688 lines
26 KiB
Python
688 lines
26 KiB
Python
"""Configuration loading and defaults."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import math
|
|
import os
|
|
import tomllib
|
|
from dataclasses import dataclass, field, replace
|
|
from pathlib import Path
|
|
from typing import Any, Mapping
|
|
from urllib.parse import urlsplit
|
|
|
|
from .utils import atomic_write_json
|
|
|
|
DEFAULT_BASE_URL = "https://opencode.ai/inference/go/openai/v1"
|
|
DEFAULT_MODEL = "deepseek-v4.1-flash"
|
|
DEFAULT_INTELLIGENCE = {
|
|
"low": "glm-5.3-flash",
|
|
"medium": "deepseek-v4.1-flash",
|
|
"high": "deepseek-v4-pro",
|
|
}
|
|
CONFIG_FILENAME = ".airouter.toml"
|
|
GLOBAL_CONFIG = Path.home() / ".config" / "airouter" / "config.toml"
|
|
GLOBAL_PROVIDERS = Path.home() / ".config" / "airouter" / "providers.json"
|
|
|
|
|
|
class ConfigError(RuntimeError):
|
|
pass
|
|
|
|
|
|
def _validate_base_url(value: str, *, field_name: str = "base_url", allow_empty: bool = True) -> str:
|
|
if not isinstance(value, str):
|
|
raise ConfigError(f"{field_name} должен быть строкой")
|
|
value = value.strip().rstrip("/")
|
|
if not value:
|
|
if allow_empty:
|
|
return ""
|
|
raise ConfigError(f"{field_name} не может быть пустым")
|
|
try:
|
|
parsed = urlsplit(value)
|
|
hostname = parsed.hostname
|
|
# Accessing port also validates malformed/non-numeric ports.
|
|
parsed.port
|
|
except ValueError as exc:
|
|
raise ConfigError(f"Некорректный {field_name}: {value!r}") from exc
|
|
if parsed.scheme not in {"http", "https"} or not hostname:
|
|
raise ConfigError(f"{field_name} должен быть полным HTTP(S) URL: {value!r}")
|
|
return value
|
|
|
|
|
|
def _validate_retries(value: Any, *, field_name: str = "max_retries") -> int:
|
|
if isinstance(value, bool) or (isinstance(value, float) and not value.is_integer()):
|
|
raise ConfigError(f"{field_name} должен быть целым числом не меньше 1")
|
|
try:
|
|
result = int(value)
|
|
except (TypeError, ValueError) as exc:
|
|
raise ConfigError(f"{field_name} должен быть целым числом не меньше 1") from exc
|
|
if result < 1:
|
|
raise ConfigError(f"{field_name} должен быть целым числом не меньше 1")
|
|
return result
|
|
|
|
|
|
def _validate_timeout(value: Any, *, field_name: str = "request_timeout") -> float:
|
|
try:
|
|
result = float(value)
|
|
except (TypeError, ValueError) as exc:
|
|
raise ConfigError(f"{field_name} должен быть положительным числом") from exc
|
|
if not math.isfinite(result) or result <= 0:
|
|
raise ConfigError(f"{field_name} должен быть положительным числом")
|
|
return result
|
|
|
|
|
|
@dataclass
|
|
class ProviderConfig:
|
|
base_url: str = DEFAULT_BASE_URL
|
|
token: str | None = field(default=None, repr=False)
|
|
token_env: str | None = None
|
|
auto_auth: bool = True
|
|
max_retries: int = 3
|
|
request_timeout: float = 600.0
|
|
|
|
def __post_init__(self) -> None:
|
|
self.base_url = _validate_base_url(
|
|
self.base_url, field_name="provider.base_url", allow_empty=False
|
|
)
|
|
self.max_retries = _validate_retries(self.max_retries, field_name="provider.max_retries")
|
|
self.request_timeout = _validate_timeout(
|
|
self.request_timeout, field_name="provider.request_timeout"
|
|
)
|
|
|
|
|
|
@dataclass
|
|
class ProviderProfile:
|
|
id: str
|
|
name: str
|
|
kind: str = "openai"
|
|
base_url: str = ""
|
|
token: str | None = field(default=None, repr=False)
|
|
token_env: str | None = None
|
|
auto_auth: bool = False
|
|
enabled: bool = True
|
|
max_retries: int = 3
|
|
request_timeout: float = 600.0
|
|
default_model: str = ""
|
|
models: list[str] = field(default_factory=list)
|
|
|
|
def __post_init__(self) -> None:
|
|
if not isinstance(self.id, str) or not self.id.strip() or "/" in self.id:
|
|
raise ConfigError("provider id должен быть непустой строкой без символа '/'")
|
|
self.id = self.id.strip()
|
|
if not isinstance(self.name, str) or not self.name.strip():
|
|
raise ConfigError(f"providers.{self.id}.name должен быть непустой строкой")
|
|
if not isinstance(self.kind, str) or not self.kind.strip():
|
|
raise ConfigError(f"providers.{self.id}.kind должен быть непустой строкой")
|
|
self.kind = self.kind.strip()
|
|
self.base_url = _validate_base_url(
|
|
self.base_url, field_name=f"providers.{self.id}.base_url"
|
|
)
|
|
self.max_retries = _validate_retries(
|
|
self.max_retries, field_name=f"providers.{self.id}.max_retries"
|
|
)
|
|
self.request_timeout = _validate_timeout(
|
|
self.request_timeout, field_name=f"providers.{self.id}.request_timeout"
|
|
)
|
|
if not isinstance(self.models, list) or any(not isinstance(item, str) for item in self.models):
|
|
raise ConfigError(f"providers.{self.id}.models должен быть массивом строк")
|
|
self.models = list(self.models)
|
|
|
|
|
|
PROVIDER_PRESETS: dict[str, ProviderProfile] = {
|
|
"opencode": ProviderProfile(
|
|
id="opencode",
|
|
name="OpenCode",
|
|
kind="opencode",
|
|
base_url=DEFAULT_BASE_URL,
|
|
token_env="OPENCODE_API_KEY",
|
|
auto_auth=True,
|
|
),
|
|
"openai": ProviderProfile(
|
|
id="openai",
|
|
name="OpenAI",
|
|
base_url="https://api.openai.com/v1",
|
|
token_env="OPENAI_API_KEY",
|
|
),
|
|
"openrouter": ProviderProfile(
|
|
id="openrouter",
|
|
name="OpenRouter",
|
|
base_url="https://openrouter.ai/api/v1",
|
|
token_env="OPENROUTER_API_KEY",
|
|
),
|
|
"groq": ProviderProfile(
|
|
id="groq",
|
|
name="Groq",
|
|
base_url="https://api.groq.com/openai/v1",
|
|
token_env="GROQ_API_KEY",
|
|
),
|
|
"together": ProviderProfile(
|
|
id="together",
|
|
name="Together AI",
|
|
base_url="https://api.together.xyz/v1",
|
|
token_env="TOGETHER_API_KEY",
|
|
),
|
|
"deepseek": ProviderProfile(
|
|
id="deepseek",
|
|
name="DeepSeek",
|
|
base_url="https://api.deepseek.com/v1",
|
|
token_env="DEEPSEEK_API_KEY",
|
|
),
|
|
"mistral": ProviderProfile(
|
|
id="mistral",
|
|
name="Mistral AI",
|
|
base_url="https://api.mistral.ai/v1",
|
|
token_env="MISTRAL_API_KEY",
|
|
),
|
|
"ollama": ProviderProfile(
|
|
id="ollama",
|
|
name="Ollama",
|
|
base_url="http://localhost:11434/v1",
|
|
auto_auth=False,
|
|
),
|
|
"lmstudio": ProviderProfile(
|
|
id="lmstudio",
|
|
name="LM Studio",
|
|
base_url="http://localhost:1234/v1",
|
|
auto_auth=False,
|
|
),
|
|
"vllm": ProviderProfile(
|
|
id="vllm",
|
|
name="vLLM",
|
|
base_url="http://localhost:8000/v1",
|
|
auto_auth=False,
|
|
),
|
|
"llamacpp": ProviderProfile(
|
|
id="llamacpp",
|
|
name="llama.cpp",
|
|
base_url="http://localhost:8080/v1",
|
|
auto_auth=False,
|
|
),
|
|
"custom": ProviderProfile(id="custom", name="Custom", base_url="", auto_auth=False),
|
|
}
|
|
|
|
|
|
@dataclass
|
|
class LimitsConfig:
|
|
max_workers: int = 6
|
|
max_steps: int = 80
|
|
max_worker_steps: int = 60
|
|
bash_timeout: int = 180
|
|
wait_timeout: int = 900
|
|
report_max_chars: int = 12_000
|
|
tool_output_max_chars: int = 30_000
|
|
max_file_bytes: int = 2_000_000
|
|
auto_compact_tokens: int = 0
|
|
|
|
|
|
@dataclass
|
|
class UIConfig:
|
|
show_reasoning: bool = False
|
|
language: str = "ru"
|
|
max_worker_line: int = 120
|
|
animations: bool = True
|
|
|
|
|
|
@dataclass
|
|
class RoleConfig:
|
|
name: str
|
|
model: str | None = None
|
|
description: str = ""
|
|
prompt_extra: str = ""
|
|
|
|
|
|
DEFAULT_ROLES: dict[str, RoleConfig] = {
|
|
"coder": RoleConfig(
|
|
name="coder",
|
|
description="Пишет и меняет код, запускает сборку и тесты.",
|
|
prompt_extra=(
|
|
"You are a hands-on coding worker. Make the requested changes, then verify them "
|
|
"by running the relevant tests, linters, or a small smoke test."
|
|
),
|
|
),
|
|
"reviewer": RoleConfig(
|
|
name="reviewer",
|
|
description="Проверяет код и отчёт, ищет баги и риски. Не меняет файлы без явной просьбы.",
|
|
prompt_extra=(
|
|
"You are a code reviewer. Inspect the relevant files and report concrete findings "
|
|
"with file:line references. Do not edit files unless the task explicitly asks for fixes."
|
|
),
|
|
),
|
|
"tester": RoleConfig(
|
|
name="tester",
|
|
description="Пишет и запускает тесты, воспроизводит баги.",
|
|
prompt_extra=(
|
|
"You are a test engineer. Reproduce the issue, write focused tests, run them, and "
|
|
"report exactly what passed and what failed."
|
|
),
|
|
),
|
|
"researcher": RoleConfig(
|
|
name="researcher",
|
|
description="Исследует кодовую базу и документацию, отвечает на вопросы без правок.",
|
|
prompt_extra=(
|
|
"You are a codebase researcher. Read and search files to answer the question with "
|
|
"evidence. Do not modify files unless explicitly asked."
|
|
),
|
|
),
|
|
}
|
|
|
|
|
|
def _profile_from_legacy(provider: ProviderConfig) -> ProviderProfile:
|
|
is_default_url = provider.base_url.rstrip("/") == DEFAULT_BASE_URL
|
|
hostname = (urlsplit(provider.base_url).hostname or "").lower()
|
|
is_opencode = hostname == "opencode.ai" or hostname.endswith(".opencode.ai")
|
|
return ProviderProfile(
|
|
id="opencode" if is_default_url else "default",
|
|
name="OpenCode" if is_default_url else "Default",
|
|
kind="opencode" if is_opencode else "openai",
|
|
base_url=provider.base_url,
|
|
token=provider.token,
|
|
token_env=provider.token_env,
|
|
auto_auth=provider.auto_auth if is_opencode else False,
|
|
max_retries=provider.max_retries,
|
|
request_timeout=provider.request_timeout,
|
|
)
|
|
|
|
|
|
@dataclass
|
|
class Config:
|
|
provider: ProviderConfig = field(default_factory=ProviderConfig)
|
|
limits: LimitsConfig = field(default_factory=LimitsConfig)
|
|
ui: UIConfig = field(default_factory=UIConfig)
|
|
orchestrator_model: str = DEFAULT_MODEL
|
|
worker_model: str = DEFAULT_MODEL
|
|
intelligence: dict[str, str] = field(default_factory=lambda: dict(DEFAULT_INTELLIGENCE))
|
|
roles: dict[str, RoleConfig] = field(
|
|
default_factory=lambda: {
|
|
name: RoleConfig(**vars(role)) for name, role in DEFAULT_ROLES.items()
|
|
}
|
|
)
|
|
project_config_path: Path | None = None
|
|
global_config_path: Path | None = None
|
|
providers: dict[str, ProviderProfile] = field(default_factory=dict)
|
|
active_provider: str = "opencode"
|
|
orchestrator_provider: str | None = None
|
|
worker_provider: str | None = None
|
|
|
|
def __post_init__(self) -> None:
|
|
self.providers = dict(self.providers)
|
|
# Config(provider=...) predates profiles. Keep it useful for ProviderRegistry
|
|
# without requiring callers to populate both representations.
|
|
if not self.providers:
|
|
legacy = _profile_from_legacy(self.provider)
|
|
self.providers[legacy.id] = legacy
|
|
if self.active_provider == "opencode" and legacy.id == "default":
|
|
self.active_provider = "default"
|
|
elif self.active_provider in {"opencode", "default"} and not any(
|
|
provider_id in self.providers for provider_id in ("opencode", "default")
|
|
):
|
|
legacy = _profile_from_legacy(self.provider)
|
|
self.providers[legacy.id] = legacy
|
|
if legacy.id == "default":
|
|
self.active_provider = "default"
|
|
|
|
def _role_provider(self, role: str) -> str:
|
|
if role == "orchestrator" and self.orchestrator_provider:
|
|
return self.orchestrator_provider
|
|
if role == "worker" and self.worker_provider:
|
|
return self.worker_provider
|
|
return self.active_provider
|
|
|
|
def resolve_model_ref(self, model: str, role: str = "worker") -> tuple[str, str]:
|
|
"""Resolve ``provider-id/model-id`` or apply the role's default provider.
|
|
|
|
A slash alone does not make a provider prefix: the first component must
|
|
name a configured profile. This keeps namespaced model IDs intact and
|
|
lets OpenRouter references split exactly once.
|
|
"""
|
|
if not isinstance(model, str):
|
|
raise ConfigError("model должен быть строкой")
|
|
prefix, separator, bare = model.partition("/")
|
|
if separator and prefix in self.providers:
|
|
return prefix, bare
|
|
provider_id = self._role_provider(role)
|
|
if provider_id not in self.providers:
|
|
raise ConfigError(f"Неизвестный провайдер: {provider_id!r}")
|
|
return provider_id, model
|
|
|
|
def role(self, name: str) -> RoleConfig:
|
|
if name in self.roles:
|
|
return self.roles[name]
|
|
raise ConfigError(
|
|
f"Неизвестная роль воркера: {name!r}. Доступны: {', '.join(sorted(self.roles))}"
|
|
)
|
|
|
|
def role_menu(self) -> str:
|
|
return "; ".join(f"{name} — {role.description}" for name, role in self.roles.items())
|
|
|
|
|
|
def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
|
|
out = dict(base)
|
|
for key, value in override.items():
|
|
if isinstance(value, dict) and isinstance(out.get(key), dict):
|
|
out[key] = _deep_merge(out[key], value)
|
|
else:
|
|
out[key] = value
|
|
return out
|
|
|
|
|
|
def _find_project_config(cwd: Path) -> Path | None:
|
|
current = cwd.resolve()
|
|
while True:
|
|
candidate = current / CONFIG_FILENAME
|
|
if candidate.is_file():
|
|
return candidate
|
|
if current.parent == current:
|
|
return None
|
|
current = current.parent
|
|
|
|
|
|
def _read_toml(path: Path) -> dict[str, Any]:
|
|
try:
|
|
with open(path, "rb") as fh:
|
|
return tomllib.load(fh)
|
|
except FileNotFoundError:
|
|
return {}
|
|
except tomllib.TOMLDecodeError as exc:
|
|
raise ConfigError(f"Ошибка в {path}: {exc}") from exc
|
|
|
|
|
|
def _read_provider_catalog(path: Path) -> dict[str, dict[str, Any]]:
|
|
try:
|
|
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
except FileNotFoundError:
|
|
return {}
|
|
except (OSError, json.JSONDecodeError) as exc:
|
|
raise ConfigError(f"Ошибка в каталоге провайдеров {path}: {exc}") from exc
|
|
if isinstance(payload, dict) and "providers" in payload:
|
|
payload = payload["providers"]
|
|
if not isinstance(payload, dict):
|
|
raise ConfigError(f"Каталог провайдеров {path} должен содержать JSON-объект providers")
|
|
result: dict[str, dict[str, Any]] = {}
|
|
for provider_id, raw in payload.items():
|
|
if not isinstance(raw, dict):
|
|
raise ConfigError(f"providers.{provider_id} в {path} должен быть объектом")
|
|
result[str(provider_id)] = raw
|
|
return result
|
|
|
|
|
|
def _profile_from_raw(
|
|
provider_id: str,
|
|
raw: Mapping[str, Any],
|
|
base: ProviderProfile | None = None,
|
|
) -> ProviderProfile:
|
|
if not isinstance(raw, Mapping):
|
|
raise ConfigError(f"providers.{provider_id} должен быть таблицей/объектом")
|
|
current = base
|
|
if current is None:
|
|
preset = PROVIDER_PRESETS.get(provider_id)
|
|
current = replace(preset, id=provider_id) if preset else ProviderProfile(
|
|
id=provider_id, name=provider_id
|
|
)
|
|
|
|
models = raw.get("models", current.models)
|
|
if not isinstance(models, list) or any(not isinstance(item, str) for item in models):
|
|
raise ConfigError(f"providers.{provider_id}.models должен быть массивом строк")
|
|
|
|
return replace(
|
|
current,
|
|
id=provider_id,
|
|
name=str(raw.get("name", current.name)),
|
|
kind=str(raw.get("kind", current.kind)),
|
|
base_url=str(raw.get("base_url", current.base_url)),
|
|
token=raw.get("token", current.token),
|
|
token_env=raw.get("token_env", current.token_env),
|
|
auto_auth=bool(raw.get("auto_auth", current.auto_auth)),
|
|
enabled=bool(raw.get("enabled", current.enabled)),
|
|
max_retries=raw.get("max_retries", current.max_retries),
|
|
request_timeout=raw.get("request_timeout", current.request_timeout),
|
|
default_model=str(raw.get("default_model", current.default_model)),
|
|
models=list(models),
|
|
)
|
|
|
|
|
|
def save_provider_profiles(
|
|
profiles: Mapping[str, ProviderProfile], path: Path = GLOBAL_PROVIDERS
|
|
) -> None:
|
|
"""Persist provider metadata, deliberately omitting inline token values."""
|
|
serialized: dict[str, dict[str, Any]] = {}
|
|
for provider_id, profile in profiles.items():
|
|
if not isinstance(profile, ProviderProfile):
|
|
raise ConfigError(f"providers.{provider_id} должен быть ProviderProfile")
|
|
if profile.id != provider_id:
|
|
raise ConfigError(
|
|
f"Ключ провайдера {provider_id!r} не совпадает с profile.id {profile.id!r}"
|
|
)
|
|
item = {
|
|
"name": profile.name,
|
|
"kind": profile.kind,
|
|
"base_url": profile.base_url,
|
|
"token_env": profile.token_env,
|
|
"auto_auth": profile.auto_auth,
|
|
"enabled": profile.enabled,
|
|
"max_retries": profile.max_retries,
|
|
"request_timeout": profile.request_timeout,
|
|
"default_model": profile.default_model,
|
|
"models": list(profile.models),
|
|
}
|
|
serialized[provider_id] = item
|
|
atomic_write_json(Path(path), {"providers": serialized})
|
|
|
|
|
|
def load_config(
|
|
cwd: Path,
|
|
*,
|
|
config_path: Path | None = None,
|
|
base_url: str | None = None,
|
|
model: str | None = None,
|
|
worker_model: str | None = None,
|
|
) -> Config:
|
|
project_path = config_path or _find_project_config(cwd)
|
|
global_path = GLOBAL_CONFIG if GLOBAL_CONFIG.is_file() else None
|
|
|
|
data: dict[str, Any] = {}
|
|
if global_path:
|
|
data = _deep_merge(data, _read_toml(global_path))
|
|
if project_path:
|
|
if not project_path.is_file():
|
|
raise ConfigError(f"Файл конфигурации не найден: {project_path}")
|
|
data = _deep_merge(data, _read_toml(project_path))
|
|
|
|
provider_raw = data.get("provider") or {}
|
|
limits_raw = data.get("limits") or {}
|
|
ui_raw = data.get("ui") or {}
|
|
models_raw = data.get("models") or {}
|
|
intelligence_raw = data.get("intelligence") or {}
|
|
roles_raw = data.get("roles") or {}
|
|
providers_raw = data.get("providers") or {}
|
|
if not isinstance(provider_raw, dict) or not isinstance(providers_raw, dict):
|
|
raise ConfigError("provider и providers должны быть таблицами")
|
|
|
|
provider_defaults = ProviderConfig()
|
|
limits_defaults = LimitsConfig()
|
|
ui_defaults = UIConfig()
|
|
provider = ProviderConfig(
|
|
base_url=str(provider_raw.get("base_url", provider_defaults.base_url)).rstrip("/"),
|
|
token=provider_raw.get("token"),
|
|
token_env=provider_raw.get("token_env"),
|
|
auto_auth=bool(provider_raw.get("auto_auth", provider_defaults.auto_auth)),
|
|
max_retries=provider_raw.get("max_retries", provider_defaults.max_retries),
|
|
request_timeout=provider_raw.get("request_timeout", provider_defaults.request_timeout),
|
|
)
|
|
env_base = os.environ.get("AIROUTER_BASE_URL")
|
|
if base_url:
|
|
provider.base_url = _validate_base_url(
|
|
base_url, field_name="provider.base_url", allow_empty=False
|
|
)
|
|
elif env_base:
|
|
provider.base_url = _validate_base_url(
|
|
env_base, field_name="provider.base_url", allow_empty=False
|
|
)
|
|
|
|
limits = LimitsConfig(
|
|
max_workers=int(limits_raw.get("max_workers", limits_defaults.max_workers)),
|
|
max_steps=int(limits_raw.get("max_steps", limits_defaults.max_steps)),
|
|
max_worker_steps=int(limits_raw.get("max_worker_steps", limits_defaults.max_worker_steps)),
|
|
bash_timeout=int(limits_raw.get("bash_timeout", limits_defaults.bash_timeout)),
|
|
wait_timeout=int(limits_raw.get("wait_timeout", limits_defaults.wait_timeout)),
|
|
report_max_chars=int(limits_raw.get("report_max_chars", limits_defaults.report_max_chars)),
|
|
tool_output_max_chars=int(
|
|
limits_raw.get("tool_output_max_chars", limits_defaults.tool_output_max_chars)
|
|
),
|
|
max_file_bytes=int(limits_raw.get("max_file_bytes", limits_defaults.max_file_bytes)),
|
|
auto_compact_tokens=int(
|
|
limits_raw.get("auto_compact_tokens", limits_defaults.auto_compact_tokens)
|
|
),
|
|
)
|
|
ui = UIConfig(
|
|
show_reasoning=bool(ui_raw.get("show_reasoning", ui_defaults.show_reasoning)),
|
|
language=str(ui_raw.get("language", ui_defaults.language)),
|
|
max_worker_line=int(ui_raw.get("max_worker_line", ui_defaults.max_worker_line)),
|
|
animations=bool(ui_raw.get("animations", ui_defaults.animations)),
|
|
)
|
|
|
|
intelligence = dict(DEFAULT_INTELLIGENCE)
|
|
for level, level_model in intelligence_raw.items():
|
|
if level in {"low", "medium", "high"} and level_model:
|
|
intelligence[level] = str(level_model)
|
|
|
|
roles = {name: RoleConfig(**vars(role)) for name, role in DEFAULT_ROLES.items()}
|
|
for name, raw in roles_raw.items():
|
|
if not isinstance(raw, dict):
|
|
continue
|
|
base = roles.get(name, RoleConfig(name=name))
|
|
roles[name] = RoleConfig(
|
|
name=name,
|
|
model=raw.get("model", base.model),
|
|
description=str(raw.get("description", base.description)),
|
|
prompt_extra=str(raw.get("prompt_extra", base.prompt_extra)),
|
|
)
|
|
|
|
# The JSON catalog is the lowest-priority profile source. Global/project
|
|
# TOML has already been merged above and overrides it field by field.
|
|
providers: dict[str, ProviderProfile] = {}
|
|
for provider_id, raw in _read_provider_catalog(GLOBAL_PROVIDERS).items():
|
|
providers[provider_id] = _profile_from_raw(provider_id, raw)
|
|
for provider_id, raw in providers_raw.items():
|
|
provider_id = str(provider_id)
|
|
providers[provider_id] = _profile_from_raw(
|
|
provider_id, raw, providers.get(provider_id)
|
|
)
|
|
|
|
legacy = _profile_from_legacy(provider)
|
|
if legacy.id not in providers:
|
|
providers[legacy.id] = legacy
|
|
|
|
active_provider = str(data.get("active_provider", legacy.id))
|
|
orchestrator_provider = data.get("orchestrator_provider")
|
|
worker_provider = data.get("worker_provider")
|
|
orchestrator_provider = str(orchestrator_provider) if orchestrator_provider else None
|
|
worker_provider = str(worker_provider) if worker_provider else None
|
|
for field_name, provider_id in (
|
|
("active_provider", active_provider),
|
|
("orchestrator_provider", orchestrator_provider),
|
|
("worker_provider", worker_provider),
|
|
):
|
|
if provider_id is not None and provider_id not in providers:
|
|
raise ConfigError(f"Неизвестный провайдер в {field_name}: {provider_id!r}")
|
|
|
|
env_model = os.environ.get("AIROUTER_MODEL")
|
|
env_worker = os.environ.get("AIROUTER_WORKER_MODEL")
|
|
|
|
config = Config(
|
|
provider=provider,
|
|
limits=limits,
|
|
ui=ui,
|
|
orchestrator_model=str(
|
|
model or env_model or models_raw.get("orchestrator") or DEFAULT_MODEL
|
|
),
|
|
worker_model=str(
|
|
worker_model or env_worker or models_raw.get("worker") or DEFAULT_MODEL
|
|
),
|
|
intelligence=intelligence,
|
|
roles=roles,
|
|
providers=providers,
|
|
active_provider=active_provider,
|
|
orchestrator_provider=orchestrator_provider,
|
|
worker_provider=worker_provider,
|
|
project_config_path=project_path if project_path and project_path.is_file() else None,
|
|
global_config_path=global_path,
|
|
)
|
|
return config
|
|
|
|
|
|
def sample_config() -> str:
|
|
return """\
|
|
# AiRouter — конфигурация проекта.
|
|
# Глобальный конфиг: ~/.config/airouter/config.toml
|
|
# Приоритет: значения проекта переопределяют глобальные.
|
|
|
|
[provider]
|
|
# OpenCode Go. Для OpenAI-совместимого сервера укажите свой URL,
|
|
# например http://localhost:11434/v1 для Ollama.
|
|
base_url = "https://opencode.ai/inference/go/openai/v1"
|
|
# Ключ можно задать явно, но лучше через переменную окружения:
|
|
# token_env = "OPENCODE_API_KEY"
|
|
# auto_auth = true # читать токен из `opencode auth export`
|
|
|
|
[models]
|
|
# Главная модель хранит весь контекст сессии.
|
|
orchestrator = "deepseek-v4.1-flash"
|
|
# Модель воркеров по умолчанию.
|
|
worker = "deepseek-v4.1-flash"
|
|
|
|
[intelligence]
|
|
# Главная модель оценивает сложность задачи и передаёт low/medium/high
|
|
# в spawn_worker. Здесь задаётся, какая модель соответствует уровню.
|
|
low = "glm-5.3-flash"
|
|
medium = "deepseek-v4.1-flash"
|
|
high = "deepseek-v4-pro"
|
|
|
|
[limits]
|
|
max_workers = 6
|
|
max_steps = 80
|
|
max_worker_steps = 60
|
|
bash_timeout = 180
|
|
wait_timeout = 900
|
|
# Сколько символов отчёта воркера попадает в контекст главной модели.
|
|
report_max_chars = 12000
|
|
# 0 = выключено; иначе контекст автоматически сжимается при превышении.
|
|
auto_compact_tokens = 0
|
|
|
|
[ui]
|
|
show_reasoning = false
|
|
animations = true
|
|
|
|
# Именованные провайдеры. Профили из TUI хранятся в providers.json.
|
|
active_provider = "opencode"
|
|
# orchestrator_provider = "openrouter"
|
|
# worker_provider = "ollama"
|
|
|
|
[providers.ollama]
|
|
name = "Ollama"
|
|
kind = "local"
|
|
base_url = "http://localhost:11434/v1"
|
|
auto_auth = false
|
|
enabled = false
|
|
models = ["qwen3:8b"]
|
|
|
|
[providers.openrouter]
|
|
name = "OpenRouter"
|
|
base_url = "https://openrouter.ai/api/v1"
|
|
token_env = "OPENROUTER_API_KEY"
|
|
enabled = false
|
|
max_retries = 4
|
|
models = ["anthropic/claude-sonnet-4"]
|
|
|
|
# Роли можно переопределять и добавлять свои.
|
|
[roles.reviewer]
|
|
model = "glm-5.3"
|
|
description = "Проверяет код и отчёт, ищет баги и риски."
|
|
"""
|
|
|
|
|
|
def write_sample_config(path: Path, *, force: bool = False) -> Path:
|
|
if path.exists() and not force:
|
|
raise ConfigError(f"{path} уже существует. Используйте --force, чтобы перезаписать.")
|
|
path.write_text(sample_config(), encoding="utf-8")
|
|
return path
|