import dataclasses import json import pathlib import sys import typing from claude_code.model_catalog import catalog_models from loop_claude.effects import Effects, say from failure import Failure from loop_claude.stop import needs_human, needs_terminal, Stop from loop_claude.paths import Paths from file_writes import replace_json @dataclasses.dataclass(frozen=True) class Models: judge: str worker: str def get_or_ask_models(project_key: str, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> Models | Stop: judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL") if judge and worker: return Models(judge, worker) chosen = get_or_ask_model(project_key, paths, effects) if isinstance(chosen, Stop): return chosen return Models(judge or chosen, worker or chosen) def get_or_ask_model(project_key: str, paths: Paths, effects: Effects) -> str | Stop: saved = paths.models_file models = read_models_file(saved) if isinstance(models, Stop): return models if kept := models.get(project_key): return kept chosen = ask_for_model(project_key, saved, paths.model_catalog, effects) if isinstance(chosen, Stop): return chosen # Reread: another loop may have saved its project while this one waited on the human. models = read_models_file(saved) if isinstance(models, Stop): return models if failure := replace_json(saved, {**models, project_key: chosen}, indent="\t", sort_keys=True): return Stop(1, f"could not save the model in {saved}: {failure.reason}") say(f"{project_key} runs on {chosen}", effects) return chosen def read_models_file(saved: pathlib.Path) -> dict[str, str] | Stop: try: with open(saved, encoding="utf-8") as handle: models = json.load(handle) except FileNotFoundError: return {} except (OSError, ValueError) as failure: return Stop(1, f"could not read {saved}: {getattr(failure, 'strerror', None) or failure}") if not isinstance(models, dict) or not all(isinstance(chosen, str) and chosen for chosen in models.values()): return Stop(1, f"could not read {saved}: not an object mapping projects to model names") return models def ask_for_model(project_key: str, saved: pathlib.Path, folder: pathlib.Path, effects: Effects) -> str | Stop: if stop := needs_terminal(f"pick {project_key}'s model, or merge {{\"{project_key}\": \"\"}} into {saved}", effects.on_terminal()): return stop offered = catalog_models(folder) choices = [f" {number}. {label} ({model_id})" for number, (model_id, label) in enumerate(offered, 1)] or [f" no model catalog cached in {folder}"] say("\n".join([f"\nThe model to run {project_key} on, saved in {saved}:", *choices]), effects) while True: try: answer = effects.input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ") except EOFError: print(file=sys.stderr) # Ends the prompt's line. It isn't a message, so it gets no time. return needs_human(f"pick {project_key}'s model", "the input ended") picked = model_picked(answer, offered) if isinstance(picked, Failure): say(picked.reason, effects) elif picked: return picked def model_picked(answer: str, offered: list[tuple[str, object]]) -> str | Failure | None: """The model the answer picks, a Failure naming the numbers to pick from, or None to ask again.""" answer = answer.strip() if not answer: return None if not (offered and answer.isdecimal()): return answer if 1 <= int(answer) <= len(offered): return offered[int(answer) - 1][0] return Failure(f"pick 1 to {len(offered)}")