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.
- letitloop-0.2.0.dist-info/METADATA +232 -0
- letitloop-0.2.0.dist-info/RECORD +175 -0
- letitloop-0.2.0.dist-info/WHEEL +5 -0
- letitloop-0.2.0.dist-info/entry_points.txt +4 -0
- letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
- letitloop-0.2.0.dist-info/top_level.txt +1 -0
- orchestrator/SKILL.md +292 -0
- orchestrator/__init__.py +151 -0
- orchestrator/anti_ouroboros.py +78 -0
- orchestrator/approval.py +139 -0
- orchestrator/ast_node_splicer.py +130 -0
- orchestrator/ast_splicer.py +94 -0
- orchestrator/audit.py +88 -0
- orchestrator/budget.py +195 -0
- orchestrator/checkpoint.py +248 -0
- orchestrator/cli.py +1971 -0
- orchestrator/codebase_introspector.py +66 -0
- orchestrator/component_slicer.py +185 -0
- orchestrator/config.py +152 -0
- orchestrator/contract.py +404 -0
- orchestrator/dag_validator.py +172 -0
- orchestrator/elasticity_governor.py +80 -0
- orchestrator/env_doctor.py +166 -0
- orchestrator/errors.py +211 -0
- orchestrator/events.py +120 -0
- orchestrator/evidence.py +203 -0
- orchestrator/exceptions.py +37 -0
- orchestrator/experimental/arena_arbiter.py +260 -0
- orchestrator/experimental/fuzz_engine.py +206 -0
- orchestrator/experimental/mutation_tester.py +382 -0
- orchestrator/failure.py +226 -0
- orchestrator/fast_sandbox.py +126 -0
- orchestrator/feasibility_gate.py +115 -0
- orchestrator/feedback.py +302 -0
- orchestrator/fixtures/__init__.py +0 -0
- orchestrator/fixtures/example_contract.json +50 -0
- orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
- orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
- orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
- orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
- orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
- orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
- orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
- orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
- orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
- orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
- orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
- orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
- orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
- orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
- orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
- orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
- orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
- orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
- orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
- orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
- orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
- orchestrator/fixtures/generated/perf-step-1.json +61 -0
- orchestrator/fixtures/generated/perf-step-2.json +62 -0
- orchestrator/fixtures/generated/perf-step-3.json +62 -0
- orchestrator/fixtures/generated/perf-step-4.json +62 -0
- orchestrator/fixtures/generated/perf-step-5.json +63 -0
- orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
- orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
- orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
- orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
- orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
- orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
- orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
- orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
- orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
- orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
- orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
- orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
- orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
- orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
- orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
- orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
- orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
- orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
- orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
- orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
- orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
- orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
- orchestrator/fixtures/run_proofs.py +299 -0
- orchestrator/fixtures/test_normalizer.py +16 -0
- orchestrator/generator.py +239 -0
- orchestrator/goal.py +245 -0
- orchestrator/handoff.py +86 -0
- orchestrator/hybrid_worker.py +840 -0
- orchestrator/impossibility.py +162 -0
- orchestrator/limits.py +60 -0
- orchestrator/live_evolution_engine.py +247 -0
- orchestrator/llm.py +291 -0
- orchestrator/local_tool_calling.py +285 -0
- orchestrator/lock.py +404 -0
- orchestrator/mcp_client.py +571 -0
- orchestrator/mcp_server.py +344 -0
- orchestrator/memory_bridge.py +182 -0
- orchestrator/metrics.py +159 -0
- orchestrator/micro_epoch.py +42 -0
- orchestrator/models.py +350 -0
- orchestrator/parsing.py +237 -0
- orchestrator/patch_applier.py +154 -0
- orchestrator/plan_preview.py +138 -0
- orchestrator/plan_quality.py +357 -0
- orchestrator/planner.py +532 -0
- orchestrator/preferences.py +115 -0
- orchestrator/preflight.py +141 -0
- orchestrator/process_guard.py +357 -0
- orchestrator/prometheus_exporter.py +207 -0
- orchestrator/prompts.py +275 -0
- orchestrator/proposal_ledger.py +194 -0
- orchestrator/provenance.py +263 -0
- orchestrator/provider_scheduler.py +394 -0
- orchestrator/qc/__init__.py +153 -0
- orchestrator/qc/aggregator.py +330 -0
- orchestrator/qc/parsing.py +287 -0
- orchestrator/qc/personas.py +242 -0
- orchestrator/qc/runner.py +569 -0
- orchestrator/qc_overrule.py +87 -0
- orchestrator/qc_review.py +282 -0
- orchestrator/quality_lenses.py +314 -0
- orchestrator/quality_plan.py +449 -0
- orchestrator/quality_plane.py +103 -0
- orchestrator/reconcile.py +191 -0
- orchestrator/replanner.py +433 -0
- orchestrator/research.py +176 -0
- orchestrator/review_artifact.py +672 -0
- orchestrator/safety.py +271 -0
- orchestrator/schemas.py +230 -0
- orchestrator/scope.py +466 -0
- orchestrator/sensory_radar.py +79 -0
- orchestrator/skill_installer.py +140 -0
- orchestrator/sse_server.py +160 -0
- orchestrator/state.py +871 -0
- orchestrator/subprocess_helper.py +131 -0
- orchestrator/supervisor/__init__.py +184 -0
- orchestrator/supervisor/_shared.py +164 -0
- orchestrator/supervisor/cleanup.py +185 -0
- orchestrator/supervisor/core.py +1680 -0
- orchestrator/supervisor/recovery.py +367 -0
- orchestrator/supervisor/reporting.py +251 -0
- orchestrator/surgical_extractor.py +119 -0
- orchestrator/telemetry.py +61 -0
- orchestrator/templates.py +268 -0
- orchestrator/token_gate.py +245 -0
- orchestrator/tui.py +649 -0
- orchestrator/verifier.py +1103 -0
- orchestrator/webhooks.py +168 -0
- orchestrator/worker.py +469 -0
- orchestrator/worker_adapters.py +815 -0
- orchestrator/worker_pool.py +121 -0
- orchestrator/worktree.py +364 -0
orchestrator/llm.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
"""Generic LLM transport layer.
|
|
2
|
+
|
|
3
|
+
Synchronous chat-completions over stdlib `urllib` — zero external dependencies.
|
|
4
|
+
|
|
5
|
+
Provider resolution is driven by the model-string prefix:
|
|
6
|
+
|
|
7
|
+
openai:<model> -> OPENAI_API_KEY -> OpenAI (or OPENAI_BASE_URL override)
|
|
8
|
+
anthropic:<model> -> ANTHROPIC_API_KEY -> Anthropic Messages API
|
|
9
|
+
gemini:<model> -> GEMINI_API_KEY -> Google Gemini (OpenAI-compatible endpoint)
|
|
10
|
+
deepseek:<model> -> DEEPSEEK_API_KEY -> DeepSeek (OpenAI-compatible)
|
|
11
|
+
any:<model> -> LLM_API_KEY -> LLM_BASE_URL (default https://api.openai.com/v1)
|
|
12
|
+
<model> -> treated as `any:` (LLM_API_KEY + LLM_BASE_URL)
|
|
13
|
+
|
|
14
|
+
`any:` is the escape hatch that makes the system work with *any* OpenAI-compatible
|
|
15
|
+
endpoint: Ollama, vLLM, LM Studio, Together, Groq, Azure OpenAI (via base URL),
|
|
16
|
+
self-hosted gateways, etc. A single key + base URL is enough.
|
|
17
|
+
|
|
18
|
+
Each provider may also be pointed elsewhere via `<PROVIDER>_BASE_URL`, e.g.
|
|
19
|
+
`OPENAI_BASE_URL=https://my-proxy.example/v1`.
|
|
20
|
+
|
|
21
|
+
The transport is deliberately small and deterministic:
|
|
22
|
+
- JSON-in/JSON-out chat completions only (no streaming, no tool calling here —
|
|
23
|
+
determinism is preserved upstream by the orchestrator layers).
|
|
24
|
+
- Hard timeout per call (default 300s), raised as `LLMError` with structured info.
|
|
25
|
+
- No API key is ever written to disk or logs; keys are read from the environment
|
|
26
|
+
at call time.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import json
|
|
32
|
+
import os
|
|
33
|
+
import time
|
|
34
|
+
import urllib.error
|
|
35
|
+
import urllib.request
|
|
36
|
+
from typing import Any, Dict, Optional
|
|
37
|
+
|
|
38
|
+
# provider -> (env key, default base url, schema)
|
|
39
|
+
PROVIDERS: Dict[str, Dict[str, Any]] = {
|
|
40
|
+
"openai": {
|
|
41
|
+
"env_key": "OPENAI_API_KEY",
|
|
42
|
+
"base_url": "https://api.openai.com/v1",
|
|
43
|
+
"schema": "openai",
|
|
44
|
+
},
|
|
45
|
+
"anthropic": {
|
|
46
|
+
"env_key": "ANTHROPIC_API_KEY",
|
|
47
|
+
"base_url": "https://api.anthropic.com/v1",
|
|
48
|
+
"schema": "anthropic",
|
|
49
|
+
},
|
|
50
|
+
"gemini": {
|
|
51
|
+
"env_key": "GEMINI_API_KEY",
|
|
52
|
+
"base_url": "https://generativelanguage.googleapis.com/v1beta/openai",
|
|
53
|
+
"schema": "openai",
|
|
54
|
+
},
|
|
55
|
+
"deepseek": {
|
|
56
|
+
"env_key": "DEEPSEEK_API_KEY",
|
|
57
|
+
"base_url": "https://api.deepseek.com/v1",
|
|
58
|
+
"schema": "openai",
|
|
59
|
+
},
|
|
60
|
+
"omniroute": {
|
|
61
|
+
"env_key": "OMNIROUTE_API_KEY",
|
|
62
|
+
"base_url": "http://localhost:8000/v1",
|
|
63
|
+
"schema": "openai",
|
|
64
|
+
},
|
|
65
|
+
"openrouter": {
|
|
66
|
+
"env_key": "OPENROUTER_API_KEY",
|
|
67
|
+
"base_url": "https://openrouter.ai/api/v1",
|
|
68
|
+
"schema": "openai",
|
|
69
|
+
},
|
|
70
|
+
"groq": {
|
|
71
|
+
"env_key": "GROQ_API_KEY",
|
|
72
|
+
"base_url": "https://api.groq.com/openai/v1",
|
|
73
|
+
"schema": "openai",
|
|
74
|
+
},
|
|
75
|
+
"ollama": {
|
|
76
|
+
"env_key": "OLLAMA_API_KEY",
|
|
77
|
+
"base_url": "http://localhost:11434/v1",
|
|
78
|
+
"schema": "openai",
|
|
79
|
+
},
|
|
80
|
+
"any": {
|
|
81
|
+
"env_key": "LLM_API_KEY",
|
|
82
|
+
"base_url": "https://api.openai.com/v1",
|
|
83
|
+
"schema": "openai",
|
|
84
|
+
},
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
DEFAULT_TIMEOUT_S = 300
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class LLMError(RuntimeError):
|
|
91
|
+
"""Raised for any transport-level failure (network, auth, rate limit, parse)."""
|
|
92
|
+
|
|
93
|
+
def __init__(self, message: str, *, provider: str = "", status: Optional[int] = None):
|
|
94
|
+
super().__init__(message)
|
|
95
|
+
self.provider = provider
|
|
96
|
+
self.status = status
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def provider_of(model: str) -> str:
|
|
100
|
+
"""Return the provider key for a model string, defaulting to 'any'."""
|
|
101
|
+
if not model:
|
|
102
|
+
return "any"
|
|
103
|
+
lowered = model.strip().lower()
|
|
104
|
+
for prefix in PROVIDERS:
|
|
105
|
+
if lowered.startswith(prefix + ":"):
|
|
106
|
+
return prefix
|
|
107
|
+
return "any"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def strip_provider(model: str) -> str:
|
|
111
|
+
"""Return the model id without its provider prefix."""
|
|
112
|
+
p = provider_of(model)
|
|
113
|
+
prefix = p + ":"
|
|
114
|
+
return model[len(prefix) :] if model.startswith(prefix) else model
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def base_url(provider: str) -> str:
|
|
118
|
+
"""Effective base URL for a provider (env override wins)."""
|
|
119
|
+
conf = PROVIDERS[provider]
|
|
120
|
+
return os.environ.get(f"{provider.upper()}_BASE_URL", conf["base_url"])
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def api_key(provider: str) -> Optional[str]:
|
|
124
|
+
"""API key for a provider, or None when not configured."""
|
|
125
|
+
conf = PROVIDERS[provider]
|
|
126
|
+
return os.environ.get(conf["env_key"]) or None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def is_configured(provider: str) -> bool:
|
|
130
|
+
"""True when the provider's API key is present in the environment."""
|
|
131
|
+
return api_key(provider) is not None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def configured_providers() -> list[str]:
|
|
135
|
+
"""All providers with a key present (used by tests/CI to decide live runs)."""
|
|
136
|
+
return [p for p in PROVIDERS if is_configured(p)]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def default_model() -> str:
|
|
140
|
+
"""Worker default model, overridable via WORKER_MODEL."""
|
|
141
|
+
from .models import ModelRegistry
|
|
142
|
+
|
|
143
|
+
return ModelRegistry.default_worker()
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def qc_model() -> str:
|
|
147
|
+
"""QC default model, overridable via QC_MODEL."""
|
|
148
|
+
from .models import ModelRegistry
|
|
149
|
+
|
|
150
|
+
return ModelRegistry.default_qc()
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def planner_model() -> str:
|
|
154
|
+
"""Planner default model, overridable via PLANNER_MODEL."""
|
|
155
|
+
if "PLANNER_MODEL" in os.environ:
|
|
156
|
+
return os.environ["PLANNER_MODEL"]
|
|
157
|
+
return default_model()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _http_json(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout_s: int) -> Dict[str, Any]:
|
|
161
|
+
if not (url.startswith("http://") or url.startswith("https://")):
|
|
162
|
+
raise LLMError(f"Unsupported URL scheme in endpoint: {url}")
|
|
163
|
+
body = json.dumps(payload).encode("utf-8")
|
|
164
|
+
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
|
165
|
+
try:
|
|
166
|
+
with urllib.request.urlopen(req, timeout=timeout_s) as resp: # nosec B310
|
|
167
|
+
raw = resp.read().decode("utf-8", errors="replace")
|
|
168
|
+
except urllib.error.HTTPError as e:
|
|
169
|
+
detail = ""
|
|
170
|
+
try:
|
|
171
|
+
detail = e.read().decode("utf-8", errors="replace")[:500]
|
|
172
|
+
from .qc_review import _redact_secrets
|
|
173
|
+
|
|
174
|
+
detail = _redact_secrets(detail)
|
|
175
|
+
except (OSError, ImportError, ValueError, AttributeError):
|
|
176
|
+
pass
|
|
177
|
+
raise LLMError(
|
|
178
|
+
f"HTTP {e.code} from provider: {detail or e.reason}",
|
|
179
|
+
provider="unknown",
|
|
180
|
+
status=e.code,
|
|
181
|
+
) from e
|
|
182
|
+
except urllib.error.URLError as e:
|
|
183
|
+
raise LLMError(f"connection failed: {e.reason}") from e
|
|
184
|
+
except TimeoutError as e:
|
|
185
|
+
raise LLMError(f"timed out after {timeout_s}s") from e
|
|
186
|
+
try:
|
|
187
|
+
return json.loads(raw)
|
|
188
|
+
except json.JSONDecodeError as e:
|
|
189
|
+
raise LLMError(f"non-JSON response: {raw[:200]!r}") from e
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def call_llm(
|
|
193
|
+
prompt: str,
|
|
194
|
+
model: str,
|
|
195
|
+
*,
|
|
196
|
+
system: Optional[str] = None,
|
|
197
|
+
max_tokens: Optional[int] = None,
|
|
198
|
+
temperature: Optional[float] = None,
|
|
199
|
+
thinking_budget: Optional[int] = None,
|
|
200
|
+
timeout_s: int = DEFAULT_TIMEOUT_S,
|
|
201
|
+
) -> Dict[str, Any]:
|
|
202
|
+
"""Call a chat model and return ``{"text": str, "usage": dict, "model": str, "provider": str}``.
|
|
203
|
+
|
|
204
|
+
Raises ``LLMError`` on any transport failure so callers can degrade deterministically.
|
|
205
|
+
Never falls back silently to unrequested external CLI tools or unauthenticated models.
|
|
206
|
+
"""
|
|
207
|
+
# Explicit CLI Adapter Routing (e.g. cli:agy, cli:antigravity)
|
|
208
|
+
if model.startswith("cli:"):
|
|
209
|
+
cli_name = model[4:].strip()
|
|
210
|
+
from .worker_adapters import WorkerRegistry
|
|
211
|
+
|
|
212
|
+
adapter = WorkerRegistry.get(cli_name)
|
|
213
|
+
if not adapter:
|
|
214
|
+
raise LLMError(f"CLI adapter '{cli_name}' is not registered in WorkerRegistry.", provider="cli")
|
|
215
|
+
if not adapter.is_available():
|
|
216
|
+
raise LLMError(f"CLI binary for '{cli_name}' is not available on system PATH.", provider="cli")
|
|
217
|
+
full_prompt = f"{system}\n\n{prompt}" if system else prompt
|
|
218
|
+
res = adapter.execute(full_prompt, os.getcwd(), f"call_llm_{cli_name}", timeout=timeout_s)
|
|
219
|
+
if res.get("exit_code") != 0 or not res.get("stdout"):
|
|
220
|
+
raise LLMError(f"CLI execution failed for '{cli_name}': {res.get('stderr')}", provider="cli")
|
|
221
|
+
return {
|
|
222
|
+
"text": res["stdout"],
|
|
223
|
+
"usage": {"prompt_tokens": len(prompt) // 4, "completion_tokens": len(res["stdout"]) // 4},
|
|
224
|
+
"model": model,
|
|
225
|
+
"provider": cli_name,
|
|
226
|
+
"elapsed_sec": 0.5,
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
provider = provider_of(model)
|
|
230
|
+
key = api_key(provider)
|
|
231
|
+
if not key:
|
|
232
|
+
raise LLMError(
|
|
233
|
+
f"provider '{provider}' is not configured: set {PROVIDERS[provider]['env_key']} "
|
|
234
|
+
f"(or pass an explicit CLI model such as 'cli:agy' / 'cli:antigravity')",
|
|
235
|
+
provider=provider,
|
|
236
|
+
)
|
|
237
|
+
model_id = strip_provider(model)
|
|
238
|
+
start = time.time()
|
|
239
|
+
|
|
240
|
+
from .models import ModelThinkingConfig
|
|
241
|
+
|
|
242
|
+
if PROVIDERS[provider]["schema"] == "anthropic":
|
|
243
|
+
headers = {
|
|
244
|
+
"x-api-key": key,
|
|
245
|
+
"anthropic-version": "2023-06-01",
|
|
246
|
+
"content-type": "application/json",
|
|
247
|
+
}
|
|
248
|
+
messages = [{"role": "user", "content": prompt}]
|
|
249
|
+
payload: Dict[str, Any] = {"model": model_id, "messages": messages, "max_tokens": max_tokens or 4096}
|
|
250
|
+
if system:
|
|
251
|
+
payload["system"] = system
|
|
252
|
+
if temperature is not None:
|
|
253
|
+
payload["temperature"] = temperature
|
|
254
|
+
ModelThinkingConfig.apply_thinking_config(model_id, provider, payload, thinking_budget=thinking_budget)
|
|
255
|
+
data = _http_json(f"{base_url(provider)}/messages", headers, payload, timeout_s)
|
|
256
|
+
try:
|
|
257
|
+
text = "".join(block.get("text", "") for block in data.get("content", []) if block.get("type") == "text")
|
|
258
|
+
except (AttributeError, TypeError):
|
|
259
|
+
text = ""
|
|
260
|
+
usage = data.get("usage", {})
|
|
261
|
+
else:
|
|
262
|
+
headers = {
|
|
263
|
+
"Authorization": f"Bearer {key}",
|
|
264
|
+
"content-type": "application/json",
|
|
265
|
+
}
|
|
266
|
+
payload: Dict[str, Any] = {
|
|
267
|
+
"model": model_id,
|
|
268
|
+
"messages": [{"role": "user", "content": prompt}],
|
|
269
|
+
"max_tokens": max_tokens or 4096,
|
|
270
|
+
}
|
|
271
|
+
if system:
|
|
272
|
+
payload["messages"].insert(0, {"role": "system", "content": system})
|
|
273
|
+
if temperature is not None:
|
|
274
|
+
payload["temperature"] = temperature
|
|
275
|
+
ModelThinkingConfig.apply_thinking_config(model_id, provider, payload, thinking_budget=thinking_budget)
|
|
276
|
+
data = _http_json(f"{base_url(provider)}/chat/completions", headers, payload, timeout_s)
|
|
277
|
+
try:
|
|
278
|
+
text = data["choices"][0]["message"]["content"] or ""
|
|
279
|
+
except (KeyError, IndexError, TypeError):
|
|
280
|
+
raise LLMError(f"unexpected provider response shape: {str(data)[:300]!r}", provider=provider)
|
|
281
|
+
usage = data.get("usage", {}) or {}
|
|
282
|
+
|
|
283
|
+
if not isinstance(text, str):
|
|
284
|
+
text = str(text)
|
|
285
|
+
return {
|
|
286
|
+
"text": text,
|
|
287
|
+
"usage": usage,
|
|
288
|
+
"model": model,
|
|
289
|
+
"provider": provider,
|
|
290
|
+
"elapsed_sec": time.time() - start,
|
|
291
|
+
}
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""Local LLM First-Class Tool Calling Adapter for letitloop.
|
|
2
|
+
|
|
3
|
+
Supports native function/tool-calling schemas for local open-weights models
|
|
4
|
+
(Qwen 2.5 Coder, DeepSeek-Coder, Llama 3.3) via Ollama, vLLM, and LM Studio.
|
|
5
|
+
Handles tool declaration, schema validation, and tool-call parsing (JSON & Hermes/Qwen tags).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import subprocess
|
|
15
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
16
|
+
|
|
17
|
+
from .contract import check_path_allowed
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
DEFAULT_COMMAND_TIMEOUT_S = 120
|
|
22
|
+
MAX_COMMAND_OUTPUT_CHARS = 8000
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ToolCallingError(Exception):
|
|
26
|
+
"""Base error for local tool calling operations."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class LocalToolRegistry:
|
|
30
|
+
"""Registry and executor for tools callable by local LLM workers."""
|
|
31
|
+
|
|
32
|
+
def __init__(self):
|
|
33
|
+
self._tools: Dict[str, Dict[str, Any]] = {}
|
|
34
|
+
self._handlers: Dict[str, Callable[..., Any]] = {}
|
|
35
|
+
|
|
36
|
+
def register(
|
|
37
|
+
self,
|
|
38
|
+
name: str,
|
|
39
|
+
description: str,
|
|
40
|
+
parameters: Dict[str, Any],
|
|
41
|
+
handler: Optional[Callable[..., Any]] = None,
|
|
42
|
+
) -> None:
|
|
43
|
+
"""Register a function tool with JSON Schema parameters."""
|
|
44
|
+
self._tools[name] = {
|
|
45
|
+
"type": "function",
|
|
46
|
+
"function": {
|
|
47
|
+
"name": name,
|
|
48
|
+
"description": description,
|
|
49
|
+
"parameters": parameters,
|
|
50
|
+
},
|
|
51
|
+
}
|
|
52
|
+
if handler:
|
|
53
|
+
self._handlers[name] = handler
|
|
54
|
+
|
|
55
|
+
def get_openai_tools(self) -> List[Dict[str, Any]]:
|
|
56
|
+
"""Return tools in OpenAI / Ollama standard tool definition format."""
|
|
57
|
+
return list(self._tools.values())
|
|
58
|
+
|
|
59
|
+
def execute_call(self, tool_name: str, arguments: Dict[str, Any]) -> Any:
|
|
60
|
+
"""Execute the registered handler for a tool call."""
|
|
61
|
+
if tool_name not in self._handlers:
|
|
62
|
+
raise ToolCallingError(f"No handler registered for tool '{tool_name}'")
|
|
63
|
+
try:
|
|
64
|
+
return self._handlers[tool_name](**arguments)
|
|
65
|
+
except Exception as e:
|
|
66
|
+
raise ToolCallingError(f"Error executing tool '{tool_name}': {e}") from e
|
|
67
|
+
|
|
68
|
+
@staticmethod
|
|
69
|
+
def parse_tool_calls(response_text: str) -> List[Dict[str, Any]]:
|
|
70
|
+
"""Extract tool calls from response text supporting:
|
|
71
|
+
1. Pure JSON tool call arrays / objects
|
|
72
|
+
2. Hermes / Qwen `<tool_call>{"name": ..., "arguments": ...}</tool_call>` tags
|
|
73
|
+
3. Markdown ```json blocks with tool calls.
|
|
74
|
+
"""
|
|
75
|
+
calls: List[Dict[str, Any]] = []
|
|
76
|
+
if not response_text:
|
|
77
|
+
return calls
|
|
78
|
+
|
|
79
|
+
# 1. Check for XML-style <tool_call> tags (Hermes / Qwen standard)
|
|
80
|
+
tag_matches = re.findall(r"<tool_call>(.*?)</tool_call>", response_text, re.DOTALL)
|
|
81
|
+
for match in tag_matches:
|
|
82
|
+
try:
|
|
83
|
+
parsed = json.loads(match.strip())
|
|
84
|
+
if isinstance(parsed, dict) and "name" in parsed:
|
|
85
|
+
calls.append(
|
|
86
|
+
{
|
|
87
|
+
"name": parsed["name"],
|
|
88
|
+
"arguments": parsed.get("arguments", parsed.get("parameters", {})),
|
|
89
|
+
}
|
|
90
|
+
)
|
|
91
|
+
except json.JSONDecodeError:
|
|
92
|
+
continue
|
|
93
|
+
|
|
94
|
+
if calls:
|
|
95
|
+
return calls
|
|
96
|
+
|
|
97
|
+
# 2. Check for markdown code fence JSON blocks
|
|
98
|
+
fence_matches = re.findall(r"```(?:json)?\s*(\{.*?\}|\[.*?\])\s*```", response_text, re.DOTALL)
|
|
99
|
+
for match in fence_matches:
|
|
100
|
+
try:
|
|
101
|
+
parsed = json.loads(match.strip())
|
|
102
|
+
if isinstance(parsed, dict) and ("name" in parsed or "tool" in parsed):
|
|
103
|
+
calls.append(
|
|
104
|
+
{
|
|
105
|
+
"name": parsed.get("name") or parsed.get("tool"),
|
|
106
|
+
"arguments": parsed.get("arguments", parsed.get("parameters", {})),
|
|
107
|
+
}
|
|
108
|
+
)
|
|
109
|
+
elif isinstance(parsed, list):
|
|
110
|
+
for item in parsed:
|
|
111
|
+
if isinstance(item, dict) and ("name" in item or "tool" in item):
|
|
112
|
+
calls.append(
|
|
113
|
+
{
|
|
114
|
+
"name": item.get("name") or item.get("tool"),
|
|
115
|
+
"arguments": item.get("arguments", item.get("parameters", {})),
|
|
116
|
+
}
|
|
117
|
+
)
|
|
118
|
+
except json.JSONDecodeError:
|
|
119
|
+
continue
|
|
120
|
+
|
|
121
|
+
if calls:
|
|
122
|
+
return calls
|
|
123
|
+
|
|
124
|
+
# 3. Direct JSON string check
|
|
125
|
+
stripped = response_text.strip()
|
|
126
|
+
if (stripped.startswith("{") and stripped.endswith("}")) or (
|
|
127
|
+
stripped.startswith("[") and stripped.endswith("]")
|
|
128
|
+
):
|
|
129
|
+
try:
|
|
130
|
+
parsed = json.loads(stripped)
|
|
131
|
+
if isinstance(parsed, dict) and "name" in parsed:
|
|
132
|
+
calls.append(
|
|
133
|
+
{
|
|
134
|
+
"name": parsed["name"],
|
|
135
|
+
"arguments": parsed.get("arguments", parsed.get("parameters", {})),
|
|
136
|
+
}
|
|
137
|
+
)
|
|
138
|
+
elif isinstance(parsed, list):
|
|
139
|
+
for item in parsed:
|
|
140
|
+
if isinstance(item, dict) and "name" in item:
|
|
141
|
+
calls.append(
|
|
142
|
+
{
|
|
143
|
+
"name": item["name"],
|
|
144
|
+
"arguments": item.get("arguments", item.get("parameters", {})),
|
|
145
|
+
}
|
|
146
|
+
)
|
|
147
|
+
except json.JSONDecodeError:
|
|
148
|
+
pass
|
|
149
|
+
|
|
150
|
+
return calls
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _scoped_resolver(workspace_root: str, contract_scope: Optional[Dict[str, Any]]) -> Callable[[str], str]:
|
|
154
|
+
"""Return a resolver that canonicalizes tool path args under workspace scope.
|
|
155
|
+
|
|
156
|
+
Uses contract.check_path_allowed (realpath + commonpath) so symlink, `..`
|
|
157
|
+
traversal, and absolute escapes are rejected before any file access.
|
|
158
|
+
"""
|
|
159
|
+
allowed = list((contract_scope or {}).get("allow", []))
|
|
160
|
+
denied = list((contract_scope or {}).get("deny", []))
|
|
161
|
+
|
|
162
|
+
def resolve(path: str) -> str:
|
|
163
|
+
ok, err = check_path_allowed(path, allowed, denied, workspace_root)
|
|
164
|
+
if not ok:
|
|
165
|
+
raise ToolCallingError(f"tool path rejected by workspace scope: {err}")
|
|
166
|
+
ws = os.path.realpath(os.path.abspath(workspace_root))
|
|
167
|
+
raw = path if os.path.isabs(path) else os.path.join(ws, path)
|
|
168
|
+
return os.path.realpath(os.path.abspath(raw))
|
|
169
|
+
|
|
170
|
+
return resolve
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def build_default_registry(workspace_root: str, contract_scope: Optional[Dict[str, Any]] = None) -> LocalToolRegistry:
|
|
174
|
+
"""Build a LocalToolRegistry with the four default sandboxed workspace tools.
|
|
175
|
+
|
|
176
|
+
Tools: read_file(path), write_file(path, content),
|
|
177
|
+
replace_lines(path, start_line, end_line, new_content), execute_command(command).
|
|
178
|
+
Path tools enforce the contract workspace scope; execute_command runs with
|
|
179
|
+
cwd=workspace_root and returns {"exit_code", "output_tail"}.
|
|
180
|
+
"""
|
|
181
|
+
scope = contract_scope or {"allow": ["."], "deny": []}
|
|
182
|
+
resolve = _scoped_resolver(workspace_root, scope)
|
|
183
|
+
registry = LocalToolRegistry()
|
|
184
|
+
|
|
185
|
+
def read_file(path: str) -> str:
|
|
186
|
+
full = resolve(path)
|
|
187
|
+
with open(full, "r", encoding="utf-8") as f:
|
|
188
|
+
return f.read()
|
|
189
|
+
|
|
190
|
+
def write_file(path: str, content: str) -> str:
|
|
191
|
+
full = resolve(path)
|
|
192
|
+
parent = os.path.dirname(full)
|
|
193
|
+
if parent:
|
|
194
|
+
os.makedirs(parent, exist_ok=True)
|
|
195
|
+
with open(full, "w", encoding="utf-8") as f:
|
|
196
|
+
f.write(content)
|
|
197
|
+
return f"wrote {len(content)} chars to {path}"
|
|
198
|
+
|
|
199
|
+
def replace_lines(path: str, start_line: int, end_line: int, new_content: str) -> str:
|
|
200
|
+
full = resolve(path)
|
|
201
|
+
with open(full, "r", encoding="utf-8") as f:
|
|
202
|
+
lines = f.readlines()
|
|
203
|
+
if start_line < 1 or end_line < start_line or end_line > len(lines):
|
|
204
|
+
raise ToolCallingError(f"invalid line range {start_line}-{end_line} for {path} ({len(lines)} lines)")
|
|
205
|
+
new_lines = new_content.splitlines(keepends=True)
|
|
206
|
+
if new_lines and not new_lines[-1].endswith("\n") and end_line < len(lines):
|
|
207
|
+
new_lines[-1] += "\n"
|
|
208
|
+
lines[start_line - 1 : end_line] = new_lines
|
|
209
|
+
with open(full, "w", encoding="utf-8") as f:
|
|
210
|
+
f.writelines(lines)
|
|
211
|
+
return f"replaced lines {start_line}-{end_line} in {path}"
|
|
212
|
+
|
|
213
|
+
def execute_command(command: str) -> Dict[str, Any]:
|
|
214
|
+
try:
|
|
215
|
+
proc = subprocess.run(
|
|
216
|
+
command,
|
|
217
|
+
shell=True, # nosec B602
|
|
218
|
+
cwd=workspace_root,
|
|
219
|
+
capture_output=True,
|
|
220
|
+
text=True,
|
|
221
|
+
timeout=DEFAULT_COMMAND_TIMEOUT_S,
|
|
222
|
+
)
|
|
223
|
+
exit_code = proc.returncode
|
|
224
|
+
output = (proc.stdout or "") + (proc.stderr or "")
|
|
225
|
+
except subprocess.TimeoutExpired:
|
|
226
|
+
exit_code = 124
|
|
227
|
+
output = f"command timed out after {DEFAULT_COMMAND_TIMEOUT_S} seconds"
|
|
228
|
+
except Exception as e:
|
|
229
|
+
exit_code = 1
|
|
230
|
+
output = f"command execution error: {e}"
|
|
231
|
+
return {"exit_code": exit_code, "output_tail": output[-MAX_COMMAND_OUTPUT_CHARS:]}
|
|
232
|
+
|
|
233
|
+
registry.register(
|
|
234
|
+
name="read_file",
|
|
235
|
+
description="Read a UTF-8 text file from the workspace.",
|
|
236
|
+
parameters={
|
|
237
|
+
"type": "object",
|
|
238
|
+
"properties": {
|
|
239
|
+
"path": {"type": "string", "description": "File path relative to the workspace root"},
|
|
240
|
+
},
|
|
241
|
+
"required": ["path"],
|
|
242
|
+
},
|
|
243
|
+
handler=read_file,
|
|
244
|
+
)
|
|
245
|
+
registry.register(
|
|
246
|
+
name="write_file",
|
|
247
|
+
description="Write (create or overwrite) a UTF-8 text file in the workspace.",
|
|
248
|
+
parameters={
|
|
249
|
+
"type": "object",
|
|
250
|
+
"properties": {
|
|
251
|
+
"path": {"type": "string", "description": "File path relative to the workspace root"},
|
|
252
|
+
"content": {"type": "string", "description": "Full file content to write"},
|
|
253
|
+
},
|
|
254
|
+
"required": ["path", "content"],
|
|
255
|
+
},
|
|
256
|
+
handler=write_file,
|
|
257
|
+
)
|
|
258
|
+
registry.register(
|
|
259
|
+
name="replace_lines",
|
|
260
|
+
description="Replace an inclusive 1-based line range in an existing workspace file.",
|
|
261
|
+
parameters={
|
|
262
|
+
"type": "object",
|
|
263
|
+
"properties": {
|
|
264
|
+
"path": {"type": "string", "description": "File path relative to the workspace root"},
|
|
265
|
+
"start_line": {"type": "integer", "description": "First line to replace (1-based, inclusive)"},
|
|
266
|
+
"end_line": {"type": "integer", "description": "Last line to replace (1-based, inclusive)"},
|
|
267
|
+
"new_content": {"type": "string", "description": "Replacement text for the line range"},
|
|
268
|
+
},
|
|
269
|
+
"required": ["path", "start_line", "end_line", "new_content"],
|
|
270
|
+
},
|
|
271
|
+
handler=replace_lines,
|
|
272
|
+
)
|
|
273
|
+
registry.register(
|
|
274
|
+
name="execute_command",
|
|
275
|
+
description="Execute a shell command inside the workspace root.",
|
|
276
|
+
parameters={
|
|
277
|
+
"type": "object",
|
|
278
|
+
"properties": {
|
|
279
|
+
"command": {"type": "string", "description": "Shell command string to execute"},
|
|
280
|
+
},
|
|
281
|
+
"required": ["command"],
|
|
282
|
+
},
|
|
283
|
+
handler=execute_command,
|
|
284
|
+
)
|
|
285
|
+
return registry
|