1"""Configuration loading and defaults."""
2
3from __future__ import annotations
4
5import os
6import tomllib
7from dataclasses import dataclass, field
8from pathlib import Path
9from typing import Any
10
11DEFAULT_BASE_URL = "https://opencode.ai/inference/go/openai/v1"
12DEFAULT_MODEL = "deepseek-v4.1-flash"
13DEFAULT_INTELLIGENCE = {
14 "low": "glm-5.3-flash",
15 "medium": "deepseek-v4.1-flash",
16 "high": "deepseek-v4-pro",
17}
18CONFIG_FILENAME = ".airouter.toml"
19GLOBAL_CONFIG = Path.home() / ".config" / "airouter" / "config.toml"
20
21
22class ConfigError(RuntimeError):
23 pass
24
25
26@dataclass
27class ProviderConfig:
28 base_url: str = DEFAULT_BASE_URL
29 token: str | None = None
30 token_env: str | None = None
31 auto_auth: bool = True
32 max_retries: int = 3
33 request_timeout: float = 600.0
34
35
36@dataclass
37class LimitsConfig:
38 max_workers: int = 6
39 max_steps: int = 80
40 max_worker_steps: int = 60
41 bash_timeout: int = 180
42 wait_timeout: int = 900
43 report_max_chars: int = 12_000
44 tool_output_max_chars: int = 30_000
45 max_file_bytes: int = 2_000_000
46 auto_compact_tokens: int = 0
47
48
49@dataclass
50class UIConfig:
51 show_reasoning: bool = False
52 language: str = "ru"
53 max_worker_line: int = 120
54
55
56@dataclass
57class RoleConfig:
58 name: str
59 model: str | None = None
60 description: str = ""
61 prompt_extra: str = ""
62
63
64DEFAULT_ROLES: dict[str, RoleConfig] = {
65 "coder": RoleConfig(
66 name="coder",
67 description="Пишет и меняет код, запускает сборку и тесты.",
68 prompt_extra=(
69 "You are a hands-on coding worker. Make the requested changes, then verify them "
70 "by running the relevant tests, linters, or a small smoke test."
71 ),
72 ),
73 "reviewer": RoleConfig(
74 name="reviewer",
75 description="Проверяет код и отчёт, ищет баги и риски. Не меняет файлы без явной просьбы.",
76 prompt_extra=(
77 "You are a code reviewer. Inspect the relevant files and report concrete findings "
78 "with file:line references. Do not edit files unless the task explicitly asks for fixes."
79 ),
80 ),
81 "tester": RoleConfig(
82 name="tester",
83 description="Пишет и запускает тесты, воспроизводит баги.",
84 prompt_extra=(
85 "You are a test engineer. Reproduce the issue, write focused tests, run them, and "
86 "report exactly what passed and what failed."
87 ),
88 ),
89 "researcher": RoleConfig(
90 name="researcher",
91 description="Исследует кодовую базу и документацию, отвечает на вопросы без правок.",
92 prompt_extra=(
93 "You are a codebase researcher. Read and search files to answer the question with "
94 "evidence. Do not modify files unless explicitly asked."
95 ),
96 ),
97}
98
99
100@dataclass
101class Config:
102 provider: ProviderConfig = field(default_factory=ProviderConfig)
103 limits: LimitsConfig = field(default_factory=LimitsConfig)
104 ui: UIConfig = field(default_factory=UIConfig)
105 orchestrator_model: str = DEFAULT_MODEL
106 worker_model: str = DEFAULT_MODEL
107 intelligence: dict[str, str] = field(default_factory=lambda: dict(DEFAULT_INTELLIGENCE))
108 roles: dict[str, RoleConfig] = field(
109 default_factory=lambda: {
110 name: RoleConfig(**vars(role)) for name, role in DEFAULT_ROLES.items()
111 }
112 )
113 project_config_path: Path | None = None
114 global_config_path: Path | None = None
115
116 def role(self, name: str) -> RoleConfig:
117 if name in self.roles:
118 return self.roles[name]
119 raise ConfigError(
120 f"Неизвестная роль воркера: {name!r}. Доступны: {', '.join(sorted(self.roles))}"
121 )
122
123 def role_menu(self) -> str:
124 return "; ".join(f"{name} — {role.description}" for name, role in self.roles.items())
125
126
127def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
128 out = dict(base)
129 for key, value in override.items():
130 if isinstance(value, dict) and isinstance(out.get(key), dict):
131 out[key] = _deep_merge(out[key], value)
132 else:
133 out[key] = value
134 return out
135
136
137def _find_project_config(cwd: Path) -> Path | None:
138 current = cwd.resolve()
139 while True:
140 candidate = current / CONFIG_FILENAME
141 if candidate.is_file():
142 return candidate
143 if current.parent == current:
144 return None
145 current = current.parent
146
147
148def _read_toml(path: Path) -> dict[str, Any]:
149 try:
150 with open(path, "rb") as fh:
151 return tomllib.load(fh)
152 except FileNotFoundError:
153 return {}
154 except tomllib.TOMLDecodeError as exc:
155 raise ConfigError(f"Ошибка в {path}: {exc}") from exc
156
157
158def load_config(
159 cwd: Path,
160 *,
161 config_path: Path | None = None,
162 base_url: str | None = None,
163 model: str | None = None,
164 worker_model: str | None = None,
165) -> Config:
166 project_path = config_path or _find_project_config(cwd)
167 global_path = GLOBAL_CONFIG if GLOBAL_CONFIG.is_file() else None
168
169 data: dict[str, Any] = {}
170 if global_path:
171 data = _deep_merge(data, _read_toml(global_path))
172 if project_path:
173 if not project_path.is_file():
174 raise ConfigError(f"Файл конфигурации не найден: {project_path}")
175 data = _deep_merge(data, _read_toml(project_path))
176
177 provider_raw = data.get("provider") or {}
178 limits_raw = data.get("limits") or {}
179 ui_raw = data.get("ui") or {}
180 models_raw = data.get("models") or {}
181 intelligence_raw = data.get("intelligence") or {}
182 roles_raw = data.get("roles") or {}
183
184 provider_defaults = ProviderConfig()
185 limits_defaults = LimitsConfig()
186 ui_defaults = UIConfig()
187 provider = ProviderConfig(
188 base_url=str(provider_raw.get("base_url", provider_defaults.base_url)).rstrip("/"),
189 token=provider_raw.get("token"),
190 token_env=provider_raw.get("token_env"),
191 auto_auth=bool(provider_raw.get("auto_auth", provider_defaults.auto_auth)),
192 max_retries=int(provider_raw.get("max_retries", provider_defaults.max_retries)),
193 request_timeout=float(provider_raw.get("request_timeout", provider_defaults.request_timeout)),
194 )
195 limits = LimitsConfig(
196 max_workers=int(limits_raw.get("max_workers", limits_defaults.max_workers)),
197 max_steps=int(limits_raw.get("max_steps", limits_defaults.max_steps)),
198 max_worker_steps=int(limits_raw.get("max_worker_steps", limits_defaults.max_worker_steps)),
199 bash_timeout=int(limits_raw.get("bash_timeout", limits_defaults.bash_timeout)),
200 wait_timeout=int(limits_raw.get("wait_timeout", limits_defaults.wait_timeout)),
201 report_max_chars=int(limits_raw.get("report_max_chars", limits_defaults.report_max_chars)),
202 tool_output_max_chars=int(
203 limits_raw.get("tool_output_max_chars", limits_defaults.tool_output_max_chars)
204 ),
205 max_file_bytes=int(limits_raw.get("max_file_bytes", limits_defaults.max_file_bytes)),
206 auto_compact_tokens=int(
207 limits_raw.get("auto_compact_tokens", limits_defaults.auto_compact_tokens)
208 ),
209 )
210 ui = UIConfig(
211 show_reasoning=bool(ui_raw.get("show_reasoning", ui_defaults.show_reasoning)),
212 language=str(ui_raw.get("language", ui_defaults.language)),
213 max_worker_line=int(ui_raw.get("max_worker_line", ui_defaults.max_worker_line)),
214 )
215
216 intelligence = dict(DEFAULT_INTELLIGENCE)
217 for level, model in intelligence_raw.items():
218 if level in {"low", "medium", "high"} and model:
219 intelligence[level] = str(model)
220
221 roles = {name: RoleConfig(**vars(role)) for name, role in DEFAULT_ROLES.items()}
222 for name, raw in roles_raw.items():
223 if not isinstance(raw, dict):
224 continue
225 base = roles.get(name, RoleConfig(name=name))
226 roles[name] = RoleConfig(
227 name=name,
228 model=raw.get("model", base.model),
229 description=str(raw.get("description", base.description)),
230 prompt_extra=str(raw.get("prompt_extra", base.prompt_extra)),
231 )
232
233 env_model = os.environ.get("AIROUTER_MODEL")
234 env_worker = os.environ.get("AIROUTER_WORKER_MODEL")
235 env_base = os.environ.get("AIROUTER_BASE_URL")
236
237 config = Config(
238 provider=provider,
239 limits=limits,
240 ui=ui,
241 orchestrator_model=str(
242 model or env_model or models_raw.get("orchestrator") or DEFAULT_MODEL
243 ),
244 worker_model=str(
245 worker_model or env_worker or models_raw.get("worker") or DEFAULT_MODEL
246 ),
247 intelligence=intelligence,
248 roles=roles,
249 project_config_path=project_path if project_path and project_path.is_file() else None,
250 global_config_path=global_path,
251 )
252 if base_url:
253 config.provider.base_url = base_url.rstrip("/")
254 elif env_base:
255 config.provider.base_url = env_base.rstrip("/")
256 if not config.provider.base_url:
257 raise ConfigError("provider.base_url не может быть пустым")
258 return config
259
260
261def sample_config() -> str:
262 return """\
263# AiRouter — конфигурация проекта.
264# Глобальный конфиг: ~/.config/airouter/config.toml
265# Приоритет: значения проекта переопределяют глобальные.
266
267[provider]
268# OpenCode Go. Для OpenAI-совместимого сервера укажите свой URL,
269# например http://localhost:11434/v1 для Ollama.
270base_url = "https://opencode.ai/inference/go/openai/v1"
271# Ключ можно задать явно, но лучше через переменную окружения:
272# token_env = "OPENCODE_API_KEY"
273# auto_auth = true # читать токен из `opencode auth export`
274
275[models]
276# Главная модель хранит весь контекст сессии.
277orchestrator = "deepseek-v4.1-flash"
278# Модель воркеров по умолчанию.
279worker = "deepseek-v4.1-flash"
280
281[intelligence]
282# Главная модель оценивает сложность задачи и передаёт low/medium/high
283# в spawn_worker. Здесь задаётся, какая модель соответствует уровню.
284low = "glm-5.3-flash"
285medium = "deepseek-v4.1-flash"
286high = "deepseek-v4-pro"
287
288[limits]
289max_workers = 6
290max_steps = 80
291max_worker_steps = 60
292bash_timeout = 180
293wait_timeout = 900
294# Сколько символов отчёта воркера попадает в контекст главной модели.
295report_max_chars = 12000
296# 0 = выключено; иначе контекст автоматически сжимается при превышении.
297auto_compact_tokens = 0
298
299[ui]
300show_reasoning = false
301
302# Роли можно переопределять и добавлять свои.
303[roles.reviewer]
304model = "glm-5.3"
305description = "Проверяет код и отчёт, ищет баги и риски."
306"""
307
308
309def write_sample_config(path: Path, *, force: bool = False) -> Path:
310 if path.exists() and not force:
311 raise ConfigError(f"{path} уже существует. Используйте --force, чтобы перезаписать.")
312 path.write_text(sample_config(), encoding="utf-8")
313 return path