"""Validated, text-only calls to explicitly selected model backends.""" import json import os import shutil import signal import subprocess import tempfile import time from pathlib import Path from .spec import Model class TextBatch(Model): values: list[str] class SemanticReview(Model): findings: list[str] explanation: str def _call_cli(prompt, output_model, timeout, backend): if backend not in {"claude", "grok"}: raise ValueError(f"Unsupported model backend: {backend}") label = "Grok" if backend == "grok" else "Claude Code" executable = shutil.which(backend) if not executable: raise ValueError( f"{label} is not installed. Use a no-model recipe or install and sign in to {label}." ) schema = json.dumps(output_model.model_json_schema()) with tempfile.TemporaryDirectory(prefix="expander-model-") as work: # No project files are exposed. Each CLI gets its own text-only invocation. command = [ executable, "-p", "--output-format", "json", "--json-schema", schema, "--tools", "", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--disable-slash-commands", "--setting-sources", "", "--settings", '{"disableAllHooks":true}', "--no-session-persistence", ] if backend == "grok": prompt_file = Path(work) / "prompt.txt" prompt_file.write_text(prompt) command = [ executable, "--prompt-file", str(prompt_file), "--output-format", "json", "--json-schema", schema, "--tools", "", "--no-subagents", "--disable-web-search", "--permission-mode", "dontAsk", "--max-turns", "3", ] with ( tempfile.TemporaryFile(mode="w+") as stdout, tempfile.TemporaryFile(mode="w+") as stderr, ): process = subprocess.Popen( command, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, text=True, cwd=work, start_new_session=True, ) try: process.communicate(prompt if backend == "claude" else None, timeout=timeout) except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) process.communicate() raise ValueError(f"{label} timed out; no result was accepted") from None stdout.seek(0) raw = stdout.read(2_000_001) stderr.seek(0) error = stderr.read(4000) if len(raw) > 2_000_000: raise ValueError(f"{label} response exceeded the size limit") if process.returncode: try: failure = json.loads(raw) message = ( failure.get("result") or failure.get("error") or failure.get("errors") or failure.get("terminal_reason") ) except (json.JSONDecodeError, AttributeError): message = None raise ValueError(f"{label} failed: {message or error or raw[:1000]}") try: envelope = json.loads(raw) if envelope.get("is_error") or envelope.get("error"): raise ValueError(str(envelope.get("result", "Model request failed"))) payload = ( envelope.get("structured_output") if backend == "claude" else envelope.get("structuredOutput") ) if payload is None: payload = json.loads(envelope["result"] if backend == "claude" else envelope["text"]) result = output_model.model_validate(payload) except (KeyError, TypeError, json.JSONDecodeError) as exc: raise ValueError(f"{label} did not return valid structured output") from exc return result, envelope def call(prompt, output_model, log_dir=None, timeout=180, backend="grok", cache_dir=None): from .config import load_project_env load_project_env() started = time.monotonic() cache = cached = None if cache_dir is not None: from .generation_cache import GenerationCache cache = GenerationCache(cache_dir, prompt, output_model, backend) cached = cache.read(output_model) if cached is not None: result, envelope = cached elif backend == "gateway": from .gateway import generate result, envelope = generate(prompt, output_model, timeout) else: result, envelope = _call_cli(prompt, output_model, timeout, backend) if cache is not None and cached is None: cache.write(result, envelope) if log_dir: Path(log_dir).mkdir(parents=True, exist_ok=True) with (Path(log_dir) / "calls.jsonl").open("a") as log: log.write( json.dumps( { "backend": backend, "cache_hit": cached is not None, "request_sha256": cache.key if cache is not None else None, "model_usage": envelope.get("modelUsage"), "duration": time.monotonic() - started, "usage": envelope.get("usage"), "generation_settings": envelope.get("generation_settings"), "cost_usd": envelope.get("total_cost_usd"), "prompt": prompt, "result": result.model_dump(by_alias=True), } ) + "\n" ) return result