import os import threading import time from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import Any from afk_developer import fsutil from afk_developer.recovery import RecoverySettings DEFAULT_PROJECTS_DIR = Path.home() / ".afk-developer" / "projects" DEFAULT_CONFIG_PATH = Path.home() / ".afk-developer" / "config.yml" DEFAULT_COPILOT_MODEL = "gpt-5.6-terra" class EndpointType(str, Enum): COPILOT = "copilot" OPENAI_COMPATIBLE = "openai_compatible" class LintMode(str, Enum): STRICT = "strict" BASELINE = "baseline" @dataclass(frozen=True) class EndpointProfile: """A named model endpoint without embedding a credential in configuration.""" name: str type: EndpointType base_url: str = "" api_key_ref: str = "" @dataclass(frozen=True) class RoleRoute: """The endpoint and model assigned to one AFK responsibility.""" endpoint: str model: str timeout: float = 300.0 reasoning_effort: str = "" @dataclass class SessionStats: """Mutable token/turn tracking accumulated across all API calls in a session.""" prompt_tokens: int = 0 completion_tokens: int = 0 total_tokens: int = 0 cache_read_tokens: int = 0 cache_write_tokens: int = 0 reasoning_tokens: int = 0 api_calls: int = 0 total_turns: int = 0 copilot_prompts_submitted: int = 0 copilot_usage_available: bool = False copilot_nano_aiu: float = 0.0 model_usage: dict[str, dict[str, Any]] = field(default_factory=dict) tasks_completed: int = 0 tasks_failed: int = 0 start_time: float = field(default_factory=time.time) _lock: threading.Lock = field(default_factory=threading.Lock, repr=False, compare=False) @property def copilot_ai_credits(self) -> float: """GitHub Copilot AI credits, reported in billionths by the Copilot SDK.""" return self.copilot_nano_aiu / 1_000_000_000 @property def copilot_metered_value_usd(self) -> float: """USD value of consumed AI credits; included credits may cover this usage.""" return self.copilot_ai_credits * 0.01 def add_usage(self, usage, *, model: str = "", endpoint: str = "") -> None: if usage is None: return prompt_tokens = getattr(usage, "prompt_tokens", 0) or 0 completion_tokens = getattr(usage, "completion_tokens", 0) or 0 total_tokens = getattr(usage, "total_tokens", 0) or 0 cache_read_tokens = getattr(usage, "cache_read_tokens", 0) or 0 cache_write_tokens = getattr(usage, "cache_write_tokens", 0) or 0 reasoning_tokens = getattr(usage, "reasoning_tokens", 0) or 0 api_calls = getattr(usage, "api_calls", None) if api_calls is None: # Legacy OpenAI-compatible responses do not carry this normalized field. api_calls = 1 agent_turns = getattr(usage, "agent_turns", 0) or 0 copilot_prompts = getattr(usage, "copilot_prompts_submitted", 0) or 0 copilot_nano_aiu = getattr(usage, "copilot_nano_aiu", 0.0) or 0.0 with self._lock: self.prompt_tokens += prompt_tokens self.completion_tokens += completion_tokens self.total_tokens += total_tokens self.cache_read_tokens += cache_read_tokens self.cache_write_tokens += cache_write_tokens self.reasoning_tokens += reasoning_tokens self.api_calls += api_calls self.total_turns += agent_turns self.copilot_prompts_submitted += copilot_prompts self.copilot_nano_aiu += copilot_nano_aiu self.copilot_usage_available = self.copilot_usage_available or bool( getattr(usage, "telemetry_available", False) ) model_usages = getattr(usage, "model_usages", ()) or () if model_usages: for item in model_usages: self._add_model_usage(item) elif model: self._add_model_usage( { "model": model, "endpoint": endpoint, "prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "total_tokens": total_tokens, "cache_read_tokens": cache_read_tokens, "cache_write_tokens": cache_write_tokens, "reasoning_tokens": reasoning_tokens, "api_calls": api_calls, "agent_turns": agent_turns, "copilot_nano_aiu": copilot_nano_aiu, "telemetry_available": bool(getattr(usage, "telemetry_available", False)), } ) def _add_model_usage(self, usage) -> None: def value(name, default=0): if isinstance(usage, dict): return usage.get(name, default) return getattr(usage, name, default) model = str(value("model", "unknown")) endpoint = str(value("endpoint", "")) key = f"{endpoint}:{model}" bucket = self.model_usage.setdefault( key, { "model": model, "endpoint": endpoint, "prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0, "api_calls": 0, "agent_turns": 0, "copilot_nano_aiu": 0.0, "telemetry_available": False, }, ) for name in ( "prompt_tokens", "completion_tokens", "total_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens", "api_calls", "agent_turns", "copilot_nano_aiu", ): bucket[name] += value(name, 0) or 0 bucket["telemetry_available"] = bucket["telemetry_available"] or bool( value("telemetry_available", False) ) @property def elapsed_seconds(self) -> float: return time.time() - self.start_time @property def elapsed_formatted(self) -> str: s = int(self.elapsed_seconds) if s < 60: return f"{s}s" m, s = divmod(s, 60) if m < 60: return f"{m}m {s}s" h, m = divmod(m, 60) return f"{h}h {m}m {s}s" def to_dict(self) -> dict: return { "prompt_tokens": self.prompt_tokens, "completion_tokens": self.completion_tokens, "total_tokens": self.total_tokens, "cache_read_tokens": self.cache_read_tokens, "cache_write_tokens": self.cache_write_tokens, "reasoning_tokens": self.reasoning_tokens, "api_calls": self.api_calls, "total_turns": self.total_turns, "copilot_prompts_submitted": self.copilot_prompts_submitted, "copilot_usage_available": self.copilot_usage_available, "copilot_nano_aiu": self.copilot_nano_aiu, "copilot_ai_credits": self.copilot_ai_credits, "copilot_metered_value_usd": self.copilot_metered_value_usd, "model_usage": list(self.model_usage.values()), "tasks_completed": self.tasks_completed, "tasks_failed": self.tasks_failed, "elapsed_seconds": self.elapsed_seconds, } def _load_dotenv(*extra_paths: Path) -> None: candidates = [ Path.home() / ".afk-developer" / ".env", Path(__file__).resolve().parent.parent / ".env", Path.cwd() / ".env", *extra_paths, ] seen = set() for env_path in candidates: if env_path in seen: continue seen.add(env_path) if not env_path.is_file(): continue with open(env_path) as fh: for raw in fh: line = raw.strip() if not line or line.startswith("#") or "=" not in line: continue key, _, val = line.partition("=") key = key.strip() val = val.strip().strip("\"'") if key and key not in os.environ: os.environ[key] = val @dataclass class Config: # Legacy OpenAI-compatible settings remain during the adapter migration. api_key: str = field(default_factory=lambda: os.environ.get("DEEPSEEK_API_KEY", "")) model: str = "deepseek-v4-pro" base_url: str = "https://api.deepseek.com" projects_dir: Path = DEFAULT_PROJECTS_DIR max_retries: int = 3 reflection_interval: int = 5 max_shell_timeout: int = 60 lint_mode: LintMode = LintMode.STRICT max_auto_resume_passes: int = 10 max_turns_by_effort: dict[str, int] = field( default_factory=lambda: {"small": 20, "medium": 50, "large": 80} ) summarization_window_turns: int = 12 summarization_max_context_chars: int = 300_000 discovery_progress_turn_limit: int = 8 discovery_progress_tool_limit: int = 20 git_isolation: str = "inplace" target_python: Path | None = None recovery: RecoverySettings = field(default_factory=RecoverySettings) stats: SessionStats = field(default_factory=SessionStats) endpoints: dict[str, EndpointProfile] = field(default_factory=dict) reasoner: RoleRoute = field( default_factory=lambda: RoleRoute(endpoint="copilot", model=DEFAULT_COPILOT_MODEL) ) coder: RoleRoute = field( default_factory=lambda: RoleRoute(endpoint="copilot", model=DEFAULT_COPILOT_MODEL) ) researcher: RoleRoute | None = None validator: RoleRoute | None = None foreman: RoleRoute | None = None supervisor: RoleRoute | None = None vision: RoleRoute | None = None coder_light: RoleRoute | None = None @property def is_configured(self) -> bool: return bool(self.endpoints) or bool(self.api_key) def route_for(self, role: str) -> RoleRoute: if role == "reasoner": return self.reasoner if role == "coder": return self.coder if role == "researcher": return self.researcher or self.reasoner if role == "validator": return self.validator or self.reasoner if role == "foreman": return self.foreman or self.reasoner if role == "supervisor": return self.supervisor or self.reasoner if role == "vision": return self.vision or self.reasoner if role == "coder_light": return self.coder_light or self.coder raise ValueError(f"Unknown AFK model role: {role}") def endpoint_for(self, role: str) -> EndpointProfile: route = self.route_for(role) try: return self.endpoints[route.endpoint] except KeyError as exc: raise ValueError( f"Role '{role}' references unknown endpoint '{route.endpoint}'. " "Run 'afk setup' or correct ~/.afk-developer/config.yml." ) from exc def max_turns_for(self, effort: str) -> int: """Return the per-attempt tool-calling turn budget for a task's estimated effort.""" return self.max_turns_by_effort.get(effort, self.max_turns_by_effort.get("medium", 50)) def record_usage(self, usage, *, role: str = "") -> None: """Record normalized or legacy provider usage with its configured model route.""" route = self.route_for(role) if role else None endpoint = route.endpoint if route else "" if role and route.endpoint in self.endpoints: endpoint = self.endpoint_for(role).name self.stats.add_usage( usage, model=route.model if route else "", endpoint=endpoint, ) @classmethod def from_env(cls, *dotenv_paths: Path) -> "Config": _load_dotenv(*dotenv_paths) api_key = os.environ.get("DEEPSEEK_API_KEY", "") if not api_key: api_key = os.environ.get("OPENAI_API_KEY", "") config = cls(api_key=api_key) config.endpoints = { "copilot": EndpointProfile(name="copilot", type=EndpointType.COPILOT), } if api_key: config.endpoints["deepseek"] = EndpointProfile( name="deepseek", type=EndpointType.OPENAI_COMPATIBLE, base_url=config.base_url, ) config.reasoner = RoleRoute(endpoint="deepseek", model=config.model) config.coder = config.reasoner raw = _load_user_config() if raw: _apply_user_config(config, raw) config = _apply_role_environment_overrides(config) return config def resolve_project_dir(self, project_name: str) -> Path: return self.projects_dir / project_name def _load_user_config() -> dict[str, Any]: config_path = Path(os.environ.get("AFK_CONFIG_PATH", DEFAULT_CONFIG_PATH)) if not config_path.is_file(): return {} try: import yaml except ImportError as exc: raise RuntimeError("PyYAML is required to load AFK configuration files.") from exc loaded = yaml.safe_load(config_path.read_text(encoding="utf-8")) if loaded is None: return {} if not isinstance(loaded, dict): raise ValueError(f"AFK configuration must be a mapping: {config_path}") return loaded def save_user_config(raw: dict[str, Any], path: Path | None = None) -> Path: """Atomically write the non-secret user configuration file.""" try: import yaml except ImportError as exc: raise RuntimeError("PyYAML is required to write AFK configuration files.") from exc target = path or Path(os.environ.get("AFK_CONFIG_PATH", DEFAULT_CONFIG_PATH)) target.parent.mkdir(parents=True, exist_ok=True) rendered = yaml.safe_dump(raw, sort_keys=False, allow_unicode=True) fsutil.atomic_write_text(target, rendered) return target def _apply_user_config(config: Config, raw: dict[str, Any]) -> None: endpoints_raw = raw.get("endpoints", {}) if endpoints_raw: if not isinstance(endpoints_raw, dict): raise ValueError("'endpoints' must be a mapping.") endpoints: dict[str, EndpointProfile] = {} for name, value in endpoints_raw.items(): if not isinstance(value, dict): raise ValueError(f"Endpoint '{name}' must be a mapping.") try: endpoint_type = EndpointType(value.get("type", "")) except ValueError as exc: supported = ", ".join(item.value for item in EndpointType) raise ValueError( f"Endpoint '{name}' has unsupported type. Use: {supported}." ) from exc endpoints[name] = EndpointProfile( name=name, type=endpoint_type, base_url=str(value.get("base_url", "")), api_key_ref=str(value.get("api_key_ref", "")), ) config.endpoints = endpoints roles_raw = raw.get("roles", {}) if roles_raw and not isinstance(roles_raw, dict): raise ValueError("'roles' must be a mapping.") reasoner_raw = roles_raw.get("reasoner", {}) if roles_raw else {} coder_raw = roles_raw.get("coder", {}) if roles_raw else {} config.reasoner = _parse_route("reasoner", reasoner_raw, config.reasoner) config.coder = _parse_route("coder", coder_raw, config.reasoner) for role in ("researcher", "validator", "foreman", "supervisor", "vision"): if role in roles_raw: setattr( config, role, _parse_route(role, roles_raw[role], config.reasoner), ) if "coder_light" in roles_raw: config.coder_light = _parse_route("coder_light", roles_raw["coder_light"], config.coder) if "recovery" in raw: config.recovery = RecoverySettings.from_mapping(raw["recovery"]) review_raw = raw.get("review", {}) if review_raw and not isinstance(review_raw, dict): raise ValueError("'review' must be a mapping.") if review_raw: try: config.lint_mode = LintMode(str(review_raw.get("lint_mode", config.lint_mode.value))) except ValueError as exc: supported = ", ".join(mode.value for mode in LintMode) raise ValueError(f"'review.lint_mode' must be one of: {supported}.") from exc max_passes = int(review_raw.get("max_auto_resume_passes", config.max_auto_resume_passes)) if max_passes < 1: raise ValueError("'review.max_auto_resume_passes' must be at least 1.") config.max_auto_resume_passes = max_passes execution_raw = raw.get("execution", {}) if execution_raw: if not isinstance(execution_raw, dict): raise ValueError("'execution' must be a mapping.") isolation = str(execution_raw.get("isolation", config.git_isolation)).strip().lower() if isolation not in {"inplace", "worktree"}: raise ValueError("'execution.isolation' must be 'inplace' or 'worktree'.") config.git_isolation = isolation if "target_python" in execution_raw: target_python = str(execution_raw["target_python"]).strip() if not target_python: raise ValueError("'execution.target_python' must be a non-empty path.") config.target_python = Path(target_python).expanduser() worker_raw = raw.get("worker", {}) if worker_raw: if not isinstance(worker_raw, dict): raise ValueError("'worker' must be a mapping.") turns_raw = worker_raw.get("max_turns_by_effort") if turns_raw is not None: if not isinstance(turns_raw, dict): raise ValueError("'worker.max_turns_by_effort' must be a mapping.") merged = dict(config.max_turns_by_effort) for key, value in turns_raw.items(): if key not in {"small", "medium", "large"}: raise ValueError(f"'worker.max_turns_by_effort' has unsupported key: {key}") try: parsed = int(value) except (TypeError, ValueError) as exc: raise ValueError( f"'worker.max_turns_by_effort.{key}' must be an integer." ) from exc if parsed < 1: raise ValueError(f"'worker.max_turns_by_effort.{key}' must be at least 1.") merged[key] = parsed config.max_turns_by_effort = merged if "max_shell_timeout" in worker_raw: try: shell_timeout = int(worker_raw["max_shell_timeout"]) except (TypeError, ValueError) as exc: raise ValueError("'worker.max_shell_timeout' must be an integer.") from exc if shell_timeout < 1: raise ValueError("'worker.max_shell_timeout' must be at least 1.") config.max_shell_timeout = shell_timeout if "summarization_window_turns" in worker_raw: try: window_turns = int(worker_raw["summarization_window_turns"]) except (TypeError, ValueError) as exc: raise ValueError("'worker.summarization_window_turns' must be an integer.") from exc if window_turns < 0: raise ValueError( "'worker.summarization_window_turns' must be at least 0 (0 disables it)." ) config.summarization_window_turns = window_turns if "summarization_max_context_chars" in worker_raw: try: max_context_chars = int(worker_raw["summarization_max_context_chars"]) except (TypeError, ValueError) as exc: raise ValueError( "'worker.summarization_max_context_chars' must be an integer." ) from exc if max_context_chars < 0: raise ValueError( "'worker.summarization_max_context_chars' must be at least 0 (0 disables it)." ) config.summarization_max_context_chars = max_context_chars for key in ("discovery_progress_turn_limit", "discovery_progress_tool_limit"): if key not in worker_raw: continue try: value = int(worker_raw[key]) except (TypeError, ValueError) as exc: raise ValueError(f"'worker.{key}' must be an integer.") from exc if value < 0: raise ValueError(f"'worker.{key}' must be at least 0 (0 disables it).") setattr(config, key, value) def _parse_route(name: str, raw: Any, fallback: RoleRoute) -> RoleRoute: if not raw: return fallback if not isinstance(raw, dict): raise ValueError(f"Role '{name}' must be a mapping.") endpoint = str(raw.get("endpoint", fallback.endpoint)).strip() model = str(raw.get("model", fallback.model)).strip() if not endpoint: raise ValueError(f"Role '{name}' must specify a non-empty endpoint.") if not model: raise ValueError(f"Role '{name}' must specify a non-empty model.") try: timeout = float(raw.get("timeout", fallback.timeout)) except (TypeError, ValueError) as exc: raise ValueError(f"Role '{name}' must specify a positive timeout.") from exc if timeout <= 0: raise ValueError(f"Role '{name}' must specify a positive timeout.") reasoning_effort = str(raw.get("reasoning_effort", fallback.reasoning_effort)) if reasoning_effort and reasoning_effort not in {"low", "medium", "high", "xhigh"}: raise ValueError(f"Role '{name}' has invalid reasoning_effort: {reasoning_effort}") return RoleRoute( endpoint=endpoint, model=model, timeout=timeout, reasoning_effort=reasoning_effort, ) def _apply_role_environment_overrides(config: Config) -> Config: def override(role: str, route: RoleRoute) -> RoleRoute: prefix = f"AFK_{role.upper()}_" return RoleRoute( endpoint=os.environ.get(f"{prefix}ENDPOINT", route.endpoint), model=os.environ.get(f"{prefix}MODEL", route.model), timeout=float(os.environ.get(f"{prefix}TIMEOUT", route.timeout)), reasoning_effort=os.environ.get(f"{prefix}REASONING_EFFORT", route.reasoning_effort), ) config.reasoner = override("reasoner", config.reasoner) config.coder = override("coder", config.coder) for role in ("researcher", "validator", "foreman", "supervisor", "vision", "coder_light"): prefix = f"AFK_{role.upper()}_" if any( os.environ.get(f"{prefix}{name}") is not None for name in ("ENDPOINT", "MODEL", "TIMEOUT", "REASONING_EFFORT") ): setattr(config, role, override(role, config.route_for(role))) lint_mode = os.environ.get("AFK_LINT_MODE") if lint_mode: try: config.lint_mode = LintMode(lint_mode) except ValueError as exc: supported = ", ".join(mode.value for mode in LintMode) raise ValueError(f"AFK_LINT_MODE must be one of: {supported}.") from exc git_isolation = os.environ.get("AFK_GIT_ISOLATION") if git_isolation: normalized_isolation = git_isolation.strip().lower() if normalized_isolation not in {"inplace", "worktree"}: raise ValueError("AFK_GIT_ISOLATION must be 'inplace' or 'worktree'.") config.git_isolation = normalized_isolation target_python = os.environ.get("AFK_TARGET_PYTHON") if target_python is not None: if not target_python.strip(): raise ValueError("AFK_TARGET_PYTHON must be a non-empty path.") config.target_python = Path(target_python).expanduser() max_passes = os.environ.get("AFK_MAX_AUTO_RESUME_PASSES") if max_passes: config.max_auto_resume_passes = int(max_passes) if config.max_auto_resume_passes < 1: raise ValueError("AFK_MAX_AUTO_RESUME_PASSES must be at least 1.") recovery_raw: dict[str, Any] = config.recovery.to_dict() recovery_env_names = { "AFK_RECOVERY_MODE": "mode", "AFK_SEMANTIC_REPAIR_LIMIT": "semantic_repair_limit", "AFK_RESEARCH_SUPPLEMENT_LIMIT": "research_supplement_limit", "AFK_HIGH_REASONING_REPAIR_LIMIT": "high_reasoning_repair_limit", } for environment_name, setting_name in recovery_env_names.items(): value = os.environ.get(environment_name) if value is not None: recovery_raw[setting_name] = value xhigh_requirement = os.environ.get("AFK_XHIGH_REQUIRES_EXPLICIT_ENABLE") if xhigh_requirement is not None: normalized = xhigh_requirement.strip().lower() if normalized not in {"true", "false"}: raise ValueError("AFK_XHIGH_REQUIRES_EXPLICIT_ENABLE must be true or false.") recovery_raw["xhigh_requires_explicit_enable"] = normalized == "true" config.recovery = RecoverySettings.from_mapping(recovery_raw) for role in ("reasoner", "coder", "researcher", "validator"): config.endpoint_for(role) return config