Coverage for src/ai_shell/config.py: 91%
368 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-17 21:40 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-17 21:40 +0000
1"""Configuration loading for ai-shell.
3Priority (highest wins): CLI flags > env vars > project config > global config > defaults.
5Global config lookup order (first match wins):
6 ~/.ai-shell.yaml > ~/.ai-shell.yml > ~/.ai-shell.toml
7 > ~/.config/ai-shell/config.yaml > ~/.config/ai-shell/config.yml > ~/.config/ai-shell/config.toml
9Project config lookup order (first match wins):
10 .ai-shell.yaml > .ai-shell.yml > .ai-shell.toml > ai-shell.toml
11"""
13from __future__ import annotations
15import logging
16import os
17import tomllib
18from dataclasses import dataclass, field
19from pathlib import Path
21import yaml
23from ai_shell.defaults import (
24 DEFAULT_COMFYUI_PORT,
25 DEFAULT_CONTEXT_SIZE,
26 DEFAULT_DEV_PORTS,
27 DEFAULT_EXTRA_MODELS,
28 DEFAULT_IMAGE,
29 DEFAULT_KOKORO_PORT,
30 DEFAULT_KOKORO_VOICE,
31 DEFAULT_N8N_PORT,
32 DEFAULT_OLLAMA_PORT,
33 DEFAULT_PRIMARY_CHAT_MODEL,
34 DEFAULT_PRIMARY_CODING_MODEL,
35 DEFAULT_SECONDARY_CHAT_MODEL,
36 DEFAULT_SECONDARY_CODING_MODEL,
37 DEFAULT_VOICE_AGENT_PORT,
38 DEFAULT_WEBUI_PORT,
39 DEFAULT_WHISPER_MODEL,
40 DEFAULT_WHISPER_PORT,
41)
42from ai_shell.opencode import CustomEndpoint, parse_endpoint_spec, sanitize_provider_id
44logger = logging.getLogger(__name__)
47@dataclass
48class VoiceAgentModelProfile:
49 """A named pair of primary + secondary chat models for the voice agent."""
51 primary: str = ""
52 secondary: str = ""
55@dataclass
56class VoiceAgentConfig:
57 """Voice-agent configuration."""
59 port: int = DEFAULT_VOICE_AGENT_PORT
60 domain: str = ""
61 profile: str = "resident"
62 profiles: dict[str, VoiceAgentModelProfile] = field(
63 default_factory=lambda: {
64 "resident": VoiceAgentModelProfile(
65 primary="qwen3.5:9b",
66 secondary="huihui_ai/qwen3.5-abliterated:9b",
67 ),
68 "swap": VoiceAgentModelProfile(
69 primary="qwen3.5:27b",
70 secondary="dolphin3:8b",
71 ),
72 }
73 )
76@dataclass
77class AiShellConfig:
78 """Configuration for ai-shell."""
80 # Container
81 image: str = DEFAULT_IMAGE
82 image_tag: str = "latest"
83 project_name: str = ""
84 project_dir: Path = field(default_factory=Path.cwd)
86 # LLM model slots. Primary = best-available; secondary = best uncensored
87 # alternative. Chat slots are routed to Open WebUI, coding slots to
88 # OpenCode. `extra_models` is a free-form list of additional
89 # Ollama tags to pull alongside the 4 slots (deduped).
90 primary_chat_model: str = DEFAULT_PRIMARY_CHAT_MODEL
91 secondary_chat_model: str = DEFAULT_SECONDARY_CHAT_MODEL
92 primary_coding_model: str = DEFAULT_PRIMARY_CODING_MODEL
93 secondary_coding_model: str = DEFAULT_SECONDARY_CODING_MODEL
94 extra_models: list[str] = field(default_factory=lambda: list(DEFAULT_EXTRA_MODELS))
95 context_size: int = DEFAULT_CONTEXT_SIZE
96 ollama_port: int = DEFAULT_OLLAMA_PORT
97 webui_port: int = DEFAULT_WEBUI_PORT
98 kokoro_port: int = DEFAULT_KOKORO_PORT
99 kokoro_voice: str = DEFAULT_KOKORO_VOICE
100 n8n_port: int = DEFAULT_N8N_PORT
101 whisper_port: int = DEFAULT_WHISPER_PORT
102 whisper_model: str = DEFAULT_WHISPER_MODEL
103 comfyui_port: int = DEFAULT_COMFYUI_PORT
105 # Voice agent (Phase 2 wires `port`; remaining fields are schema
106 # placeholders that Phases 3-6 consume — see VoiceAgentConfig).
107 voice_agent: VoiceAgentConfig = field(default_factory=VoiceAgentConfig)
109 # Extra configuration
110 extra_env: dict[str, str] = field(default_factory=dict)
111 extra_volumes: list[str] = field(default_factory=list)
112 extra_ports: list[int] = field(default_factory=list)
113 # Glob patterns (relative to project_dir) for monorepo workspace
114 # node_modules directories. Each match gets an isolated named volume.
115 node_modules_paths: list[str] = field(default_factory=list)
116 # Home-config basenames (e.g. ".claude", ".codex") to back with a shared
117 # named volume instead of a host bind mount, so tool config/state never
118 # touches the host home directory. Empty = current bind-mount behavior.
119 isolate_home_paths: list[str] = field(default_factory=list)
121 # AWS
122 ai_profile: str = "" # AWS profile for infra (sets AWS_PROFILE in container)
123 aws_region: str = "" # Override AWS_REGION
124 aws_partition: str = "" # "commercial" or "govcloud"
125 bedrock_profile: str = "" # AWS profile for Bedrock LLM API calls
126 bedrock_region: str = "" # AWS region for Bedrock (falls back to aws_region)
127 bedrock_model: str = "us.meta.llama3-3-70b-instruct-v1:0"
129 # OpenAI
130 openai_profile: str = "" # Suffixed .env key name for multi-account switching
132 # Claude options
133 claude_account: str = (
134 "" # Suffixed .env token name or login profile for multi-account switching
135 )
136 local_chrome: bool = False # Attach Chrome DevTools MCP to project-scoped host Chrome
137 chrome_proxy: str = (
138 "" # --proxy-server for every host Chrome ai-shell launches ("vpn" = own VPN)
139 )
140 skip_updates: bool = False
142 # VPN container (chrome_proxy: vpn). NordVPN over WireGuard through gluetun;
143 # the credential is NORDVPN_TOKEN in ~/.augint/.env, never config.
144 vpn_country: str = "" # gluetun SERVER_COUNTRIES; empty = any server
145 vpn_firewall: bool = True # gluetun's own firewall; turned off by itself where it cannot run
146 vpn_proxy_port: int = 8888 # loopback port of the HTTP proxy Chrome uses # When True, skip pre-launch tool freshness checks
148 # Expo. When False, a detected Expo app is not started automatically;
149 # an explicit --expo still works. --expo/--no-expo override this.
150 expo_auto: bool = True
152 # Pre-launch cache TTLs (seconds). Set to 0 to disable.
153 image_pull_cache_ttl: int = 900 # 15 min: skip docker pull if checked recently
154 bedrock_check_cache_ttl: int = 86400 # 24 h: skip Bedrock preflight if checked recently
156 # Per-tool provider and OpenCode routing
157 claude_provider: str = "" # "anthropic" (default) or "aws"
158 opencode_provider: str = (
159 "" # "ollama" (default), "aws" / "bedrock-mantle", or custom provider name
160 )
161 opencode_model: str = "" # Primary model override for plan + build agents
162 opencode_subagent_model: str = "" # Subagent model override for explore + general agents
163 opencode_endpoints: list[CustomEndpoint] = field(default_factory=list)
164 # Off by default: OpenCode then reads AGENTS.md only, never CLAUDE.md,
165 # ~/.claude or .claude/.agents skills.
166 opencode_claude_compat: bool = False
167 # None = the defaults in ai_shell.opencode; [] = none.
168 opencode_plugins: list[str] | None = None
169 opencode_instructions: list[str] | None = None
170 opencode_local_chrome: bool = False # Chrome DevTools MCP for ai-shell opencode
171 # Bedrock region for ai-shell opencode only. Kept apart from bedrock_region
172 # (Claude's) so a commercial default never reaches a GovCloud OpenCode.
173 opencode_region: str = ""
175 @property
176 def full_image(self) -> str:
177 """Return the full image reference with tag."""
178 return f"{self.image}:{self.image_tag}"
180 @property
181 def dev_ports(self) -> list[int]:
182 """Return deduplicated, sorted list of dev container ports to expose."""
183 return sorted(set(DEFAULT_DEV_PORTS + self.extra_ports))
185 @property
186 def models_to_pull(self) -> list[str]:
187 """Return the full deduped list of Ollama model tags to pull.
189 The 4 slots in order, followed by any ``extra_models``. Duplicates
190 are removed while preserving first-occurrence order.
191 """
192 ordered = [
193 self.primary_chat_model,
194 self.secondary_chat_model,
195 self.primary_coding_model,
196 self.secondary_coding_model,
197 *self.extra_models,
198 ]
199 seen: set[str] = set()
200 deduped: list[str] = []
201 for model in ordered:
202 if model and model not in seen:
203 seen.add(model)
204 deduped.append(model)
205 return deduped
208def load_config(
209 project_override: str | None = None,
210 project_dir: Path | None = None,
211) -> AiShellConfig:
212 """Load configuration from all sources.
214 Priority: CLI overrides > env vars > project toml > global toml > defaults.
215 """
216 config = AiShellConfig()
218 if project_dir:
219 config.project_dir = project_dir
221 # Load global config (~/.augint/ canonical, ~/.ai-shell.yaml legacy fallback)
222 home = Path.home()
223 for candidate in (
224 home / ".augint" / ".ai-shell.yaml",
225 home / ".ai-shell.yaml",
226 home / ".ai-shell.yml",
227 home / ".ai-shell.toml",
228 home / ".config" / "ai-shell" / "config.yaml",
229 home / ".config" / "ai-shell" / "config.yml",
230 home / ".config" / "ai-shell" / "config.toml",
231 ):
232 if candidate.exists():
233 _apply_config(config, candidate)
234 break
236 # Load project config (first match wins)
237 for name in (".ai-shell.yaml", ".ai-shell.yml", ".ai-shell.toml", "ai-shell.toml"):
238 candidate = config.project_dir / name
239 if candidate.exists():
240 _apply_config(config, candidate)
241 break
243 # Apply environment variable overrides
244 _apply_env_vars(config)
246 # Apply CLI overrides
247 if project_override:
248 config.project_name = project_override
250 # Auto-derive project name from CWD if not set
251 if not config.project_name:
252 from ai_shell.defaults import sanitize_project_name
254 config.project_name = sanitize_project_name(config.project_dir)
256 return config
259def _load_config_file(path: Path) -> dict:
260 """Load a YAML or TOML config file and return the parsed dict."""
261 suffix = path.suffix.lower()
262 if suffix in (".yaml", ".yml"):
263 with open(path, encoding="utf-8") as f:
264 return yaml.safe_load(f) or {}
265 with open(path, "rb") as f:
266 return tomllib.load(f)
269_LEGACY_LLM_KEY_HINT = {
270 "primary_model": (
271 "renamed to `primary_coding_model` (coding) or `primary_chat_model` "
272 "(chat). The new config uses 4 role-specific slots; pick the one "
273 "that matches your intent. See the generated .ai-shell.yaml for the "
274 "full layout."
275 ),
276 "fallback_model": (
277 "removed. The previous `fallback_model` was role-ambiguous. Use "
278 "`secondary_chat_model` and `secondary_coding_model` instead "
279 "(both default to the best uncensored variants). See the generated "
280 ".ai-shell.yaml for the full layout."
281 ),
282}
285def _reject_legacy_llm_keys(llm_section: dict, path: Path) -> None:
286 """Raise on deprecated `primary_model` / `fallback_model` keys.
288 These were removed when the llm config split into 4 role-specific slots
289 (primary/secondary x chat/coding). Silently aliasing them would corrupt
290 intent — e.g. the old `fallback_model` meant different things to chat and
291 coding users. Fail loudly with migration guidance.
292 """
293 bad = [k for k in _LEGACY_LLM_KEY_HINT if k in llm_section]
294 if not bad:
295 return
296 lines = [f"\nDeprecated llm key(s) found in {path}:"]
297 for key in bad:
298 lines.append(f" - `{key}`: {_LEGACY_LLM_KEY_HINT[key]}")
299 raise ValueError("\n".join(lines))
302def _apply_voice_agent_config(va: VoiceAgentConfig, data: dict) -> None:
303 """Merge a parsed ``voice_agent:`` section into a VoiceAgentConfig.
305 Only keys present in *data* override defaults; everything else keeps
306 the dataclass default. Nested sections are merged field-by-field so
307 partial user configs work.
308 """
309 if "port" in data:
310 va.port = int(data["port"])
311 if "domain" in data:
312 va.domain = str(data["domain"])
313 if "profile" in data:
314 va.profile = str(data["profile"])
315 if "profiles" in data and isinstance(data["profiles"], dict):
316 for name, entry in data["profiles"].items():
317 profile = va.profiles.get(name, VoiceAgentModelProfile())
318 if isinstance(entry, dict):
319 if "primary" in entry:
320 profile.primary = str(entry["primary"])
321 if "secondary" in entry:
322 profile.secondary = str(entry["secondary"])
323 va.profiles[name] = profile
326def _apply_config(config: AiShellConfig, path: Path) -> None:
327 """Apply settings from a YAML or TOML config file."""
328 try:
329 data = _load_config_file(path)
330 except (OSError, tomllib.TOMLDecodeError, yaml.YAMLError) as e:
331 logger.warning("Failed to load config from %s: %s", path, e)
332 return
334 logger.debug("Loading config from %s", path)
336 # [container] section
337 container = data.get("container", {})
338 if "image" in container:
339 config.image = container["image"]
340 if "image_tag" in container:
341 config.image_tag = container["image_tag"]
342 if "extra_env" in container:
343 config.extra_env.update(container["extra_env"])
344 if "extra_volumes" in container:
345 config.extra_volumes.extend(container["extra_volumes"])
346 if "ports" in container:
347 config.extra_ports.extend(int(p) for p in container["ports"])
348 if "node_modules_paths" in container:
349 config.node_modules_paths.extend(str(p) for p in container["node_modules_paths"])
350 if "isolate_home_paths" in container:
351 config.isolate_home_paths.extend(str(p) for p in container["isolate_home_paths"])
353 # [expo] section
354 expo = data.get("expo", {})
355 if "auto" in expo:
356 config.expo_auto = bool(expo["auto"])
358 # [llm] section
359 llm = data.get("llm", {})
360 _reject_legacy_llm_keys(llm, path)
361 if "primary_chat_model" in llm:
362 config.primary_chat_model = llm["primary_chat_model"]
363 if "secondary_chat_model" in llm:
364 config.secondary_chat_model = llm["secondary_chat_model"]
365 if "primary_coding_model" in llm:
366 config.primary_coding_model = llm["primary_coding_model"]
367 if "secondary_coding_model" in llm:
368 config.secondary_coding_model = llm["secondary_coding_model"]
369 if "extra_models" in llm:
370 config.extra_models = [str(m) for m in llm["extra_models"]]
371 if "context_size" in llm:
372 config.context_size = int(llm["context_size"])
373 if "ollama_port" in llm:
374 config.ollama_port = int(llm["ollama_port"])
375 if "webui_port" in llm:
376 config.webui_port = int(llm["webui_port"])
377 if "kokoro_port" in llm:
378 config.kokoro_port = int(llm["kokoro_port"])
379 if "kokoro_voice" in llm:
380 config.kokoro_voice = str(llm["kokoro_voice"])
381 if "n8n_port" in llm:
382 config.n8n_port = int(llm["n8n_port"])
383 if "whisper_port" in llm:
384 config.whisper_port = int(llm["whisper_port"])
385 if "whisper_model" in llm:
386 config.whisper_model = str(llm["whisper_model"])
387 if "comfyui_port" in llm:
388 config.comfyui_port = int(llm["comfyui_port"])
390 # [voice_agent] section (top-level, not under llm)
391 if "voice_agent" in data:
392 _apply_voice_agent_config(config.voice_agent, data["voice_agent"])
394 # [aws] section
395 aws = data.get("aws", {})
396 if "ai_profile" in aws:
397 config.ai_profile = aws["ai_profile"]
398 if "region" in aws:
399 config.aws_region = aws["region"]
400 if "partition" in aws:
401 config.aws_partition = str(aws["partition"] or "")
402 if "aws_partition" in aws:
403 config.aws_partition = str(aws["aws_partition"] or "")
404 if "bedrock_profile" in aws:
405 config.bedrock_profile = aws["bedrock_profile"]
406 if "bedrock_region" in aws:
407 config.bedrock_region = aws["bedrock_region"]
408 if "bedrock_model" in aws:
409 config.bedrock_model = aws["bedrock_model"]
411 # [openai] section
412 openai = data.get("openai", {})
413 if "profile" in openai:
414 config.openai_profile = openai["profile"]
416 # [claude] section
417 claude_sec = data.get("claude", {})
418 if "provider" in claude_sec:
419 config.claude_provider = claude_sec["provider"]
420 if "account" in claude_sec:
421 config.claude_account = str(claude_sec["account"])
422 if "local_chrome" in claude_sec:
423 config.local_chrome = bool(claude_sec["local_chrome"])
424 if "chrome_proxy" in claude_sec:
425 config.chrome_proxy = str(claude_sec["chrome_proxy"] or "")
427 # [opencode] section
428 opencode_sec = data.get("opencode", {})
429 if isinstance(opencode_sec, dict):
430 _apply_opencode_config(config, opencode_sec)
432 # [vpn] section
433 vpn = data.get("vpn", {})
434 if isinstance(vpn, dict):
435 if "country" in vpn:
436 config.vpn_country = str(vpn["country"] or "")
437 if "firewall" in vpn:
438 config.vpn_firewall = bool(vpn["firewall"])
439 if "proxy_port" in vpn:
440 config.vpn_proxy_port = int(vpn["proxy_port"])
441 if "skip_updates" in container:
442 config.skip_updates = bool(container["skip_updates"])
443 if "image_pull_cache_ttl" in container:
444 config.image_pull_cache_ttl = int(container["image_pull_cache_ttl"])
445 if "bedrock_check_cache_ttl" in aws:
446 config.bedrock_check_cache_ttl = int(aws["bedrock_check_cache_ttl"])
449def _upsert_custom_endpoint(
450 endpoints: list[CustomEndpoint],
451 new_ep: CustomEndpoint,
452) -> None:
453 """Insert or replace a CustomEndpoint by provider name."""
454 for idx, existing in enumerate(endpoints):
455 if existing.name == new_ep.name:
456 endpoints[idx] = new_ep
457 return
458 endpoints.append(new_ep)
461def _coerce_models_list(raw: object) -> list[str]:
462 """Normalize a string or list of model IDs into a list of non-empty strings."""
463 if isinstance(raw, str):
464 return [m.strip() for m in raw.split(",") if m.strip()]
465 if isinstance(raw, list):
466 return [str(m).strip() for m in raw if str(m).strip()]
467 return []
470def _parse_opencode_endpoints(raw: object) -> list[CustomEndpoint]:
471 """Parse ``opencode.endpoints`` from YAML/TOML (supports dict or list formats)."""
472 parsed: list[CustomEndpoint] = []
473 if isinstance(raw, dict):
474 for name, entry in raw.items():
475 provider_id = sanitize_provider_id(str(name))
476 if isinstance(entry, str) and entry.strip():
477 parsed.append(CustomEndpoint(name=provider_id, base_url=entry.strip()))
478 elif isinstance(entry, dict):
479 base_url = str(entry.get("base_url") or entry.get("url") or "").strip()
480 if not base_url:
481 continue
482 api_key_env = str(entry.get("api_key_env") or entry.get("key_env") or "").strip()
483 models_raw = entry.get("models") if "models" in entry else entry.get("model", [])
484 models = _coerce_models_list(models_raw)
485 display_name = str(entry.get("display_name") or "").strip()
486 parsed.append(
487 CustomEndpoint(
488 name=provider_id,
489 base_url=base_url,
490 api_key_env=api_key_env,
491 models=models,
492 display_name=display_name,
493 )
494 )
495 elif isinstance(raw, list):
496 for item in raw:
497 if isinstance(item, str) and item.strip():
498 parsed.append(parse_endpoint_spec(item))
499 elif isinstance(item, dict):
500 name = sanitize_provider_id(str(item.get("name") or "custom"))
501 base_url = str(item.get("base_url") or item.get("url") or "").strip()
502 if not base_url:
503 continue
504 api_key_env = str(item.get("api_key_env") or item.get("key_env") or "").strip()
505 models_raw = item.get("models") if "models" in item else item.get("model", [])
506 models = _coerce_models_list(models_raw)
507 display_name = str(item.get("display_name") or "").strip()
508 parsed.append(
509 CustomEndpoint(
510 name=name,
511 base_url=base_url,
512 api_key_env=api_key_env,
513 models=models,
514 display_name=display_name,
515 )
516 )
517 return parsed
520def _apply_opencode_config(config: AiShellConfig, data: dict) -> None:
521 """Apply settings from the ``opencode:`` config section."""
522 if "provider" in data:
523 config.opencode_provider = str(data["provider"] or "")
524 if "aws_partition" in data:
525 config.aws_partition = str(data["aws_partition"] or "")
526 elif "partition" in data:
527 config.aws_partition = str(data["partition"] or "")
528 if "aws_region" in data:
529 config.opencode_region = str(data["aws_region"] or "")
530 elif "region" in data:
531 config.opencode_region = str(data["region"] or "")
532 if "aws_profile" in data:
533 config.bedrock_profile = str(data["aws_profile"] or "")
534 elif "profile" in data:
535 config.bedrock_profile = str(data["profile"] or "")
536 if "model" in data:
537 config.opencode_model = str(data["model"] or "")
538 elif "primary_model" in data:
539 config.opencode_model = str(data["primary_model"] or "")
540 if "subagent_model" in data:
541 config.opencode_subagent_model = str(data["subagent_model"] or "")
542 if "endpoints" in data:
543 for ep in _parse_opencode_endpoints(data["endpoints"]):
544 _upsert_custom_endpoint(config.opencode_endpoints, ep)
545 if "claude_compat" in data:
546 config.opencode_claude_compat = bool(data["claude_compat"])
547 if "plugins" in data:
548 config.opencode_plugins = _string_list(data["plugins"])
549 if "instructions" in data:
550 config.opencode_instructions = _string_list(data["instructions"])
551 if "local_chrome" in data:
552 config.opencode_local_chrome = bool(data["local_chrome"])
555def _string_list(raw: object) -> list[str]:
556 """A config list of strings; ``None`` or an empty value is ``[]``."""
557 if raw is None or raw == "":
558 return []
559 items = raw if isinstance(raw, list) else [raw]
560 return [str(item).strip() for item in items if str(item).strip()]
563_LEGACY_ENV_VARS = {
564 "AI_SHELL_PRIMARY_MODEL": ("AI_SHELL_PRIMARY_CODING_MODEL or AI_SHELL_PRIMARY_CHAT_MODEL"),
565 "AI_SHELL_FALLBACK_MODEL": ("AI_SHELL_SECONDARY_CHAT_MODEL or AI_SHELL_SECONDARY_CODING_MODEL"),
566}
569def _apply_env_vars(config: AiShellConfig) -> None:
570 """Apply AI_SHELL_* environment variable overrides."""
571 bad_env = [k for k in _LEGACY_ENV_VARS if os.environ.get(k) is not None]
572 if bad_env:
573 lines = ["\nDeprecated AI_SHELL_* env var(s) set:"]
574 for key in bad_env:
575 lines.append(f" - {key}: use {_LEGACY_ENV_VARS[key]} instead")
576 raise ValueError("\n".join(lines))
578 env_map: dict[str, tuple[str, type]] = {
579 "AI_SHELL_IMAGE": ("image", str),
580 "AI_SHELL_IMAGE_TAG": ("image_tag", str),
581 "AI_SHELL_PROJECT": ("project_name", str),
582 "AI_SHELL_PRIMARY_CHAT_MODEL": ("primary_chat_model", str),
583 "AI_SHELL_SECONDARY_CHAT_MODEL": ("secondary_chat_model", str),
584 "AI_SHELL_PRIMARY_CODING_MODEL": ("primary_coding_model", str),
585 "AI_SHELL_SECONDARY_CODING_MODEL": ("secondary_coding_model", str),
586 "AI_SHELL_CONTEXT_SIZE": ("context_size", int),
587 "AI_SHELL_OLLAMA_PORT": ("ollama_port", int),
588 "AI_SHELL_WEBUI_PORT": ("webui_port", int),
589 "AI_SHELL_KOKORO_PORT": ("kokoro_port", int),
590 "AI_SHELL_KOKORO_VOICE": ("kokoro_voice", str),
591 "AI_SHELL_N8N_PORT": ("n8n_port", int),
592 "AI_SHELL_WHISPER_PORT": ("whisper_port", int),
593 "AI_SHELL_WHISPER_MODEL": ("whisper_model", str),
594 "AI_SHELL_COMFYUI_PORT": ("comfyui_port", int),
595 "AI_SHELL_AI_PROFILE": ("ai_profile", str),
596 "AI_SHELL_AWS_REGION": ("aws_region", str),
597 "AI_SHELL_AWS_PARTITION": ("aws_partition", str),
598 "AI_SHELL_BEDROCK_PROFILE": ("bedrock_profile", str),
599 "AI_SHELL_BEDROCK_REGION": ("bedrock_region", str),
600 "AI_SHELL_BEDROCK_MODEL": ("bedrock_model", str),
601 "AI_SHELL_OPENAI_PROFILE": ("openai_profile", str),
602 "AI_SHELL_CLAUDE_PROVIDER": ("claude_provider", str),
603 "AI_SHELL_CLAUDE_ACCOUNT": ("claude_account", str),
604 "AI_SHELL_OPENCODE_PROVIDER": ("opencode_provider", str),
605 "AI_SHELL_OPENCODE_MODEL": ("opencode_model", str),
606 "AI_SHELL_OPENCODE_SUBAGENT_MODEL": ("opencode_subagent_model", str),
607 "AI_SHELL_OPENCODE_AWS_PARTITION": ("aws_partition", str),
608 "AI_SHELL_OPENCODE_AWS_REGION": ("opencode_region", str),
609 "AI_SHELL_OPENCODE_CLAUDE_COMPAT": ("opencode_claude_compat", bool),
610 "AI_SHELL_OPENCODE_LOCAL_CHROME": ("opencode_local_chrome", bool),
611 "AI_SHELL_LOCAL_CHROME": ("local_chrome", bool),
612 "AI_SHELL_CHROME_PROXY": ("chrome_proxy", str),
613 "AI_SHELL_VPN_COUNTRY": ("vpn_country", str),
614 "AI_SHELL_VPN_FIREWALL": ("vpn_firewall", bool),
615 "AI_SHELL_VPN_PROXY_PORT": ("vpn_proxy_port", int),
616 "AI_SHELL_EXPO_AUTO": ("expo_auto", bool),
617 "AI_SHELL_SKIP_UPDATES": ("skip_updates", bool),
618 "AI_SHELL_IMAGE_PULL_CACHE_TTL": ("image_pull_cache_ttl", int),
619 "AI_SHELL_BEDROCK_CHECK_CACHE_TTL": ("bedrock_check_cache_ttl", int),
620 }
622 for env_key, (attr, type_fn) in env_map.items():
623 value = os.environ.get(env_key)
624 if value is not None:
625 if type_fn is bool:
626 coerced = value.lower() not in ("0", "false", "no", "")
627 else:
628 coerced = type_fn(value)
629 setattr(config, attr, coerced)
630 logger.debug("Config override from env: %s=%s", env_key, value)
632 # AI_SHELL_PORTS is comma-separated, extends extra_ports
633 ports_value = os.environ.get("AI_SHELL_PORTS")
634 if ports_value:
635 config.extra_ports.extend(int(p.strip()) for p in ports_value.split(",") if p.strip())
637 # AI_SHELL_ISOLATE_HOME_PATHS is comma-separated, extends isolate_home_paths
638 isolate_value = os.environ.get("AI_SHELL_ISOLATE_HOME_PATHS")
639 if isolate_value:
640 config.isolate_home_paths.extend(p.strip() for p in isolate_value.split(",") if p.strip())
642 # OpenCode custom endpoint env vars:
643 # - AI_SHELL_OPENCODE_ENDPOINT / AI_SHELL_OPENCODE_ENDPOINTS (semicolon-separated specs)
644 # - AI_SHELL_OPENCODE_CUSTOM_URL (+ optional _NAME, _KEY_ENV, _MODEL)
645 for env_key in ("AI_SHELL_OPENCODE_ENDPOINT", "AI_SHELL_OPENCODE_ENDPOINTS"):
646 raw_specs = os.environ.get(env_key, "").strip()
647 if raw_specs:
648 for spec in raw_specs.split(";"):
649 if spec.strip():
650 _upsert_custom_endpoint(
651 config.opencode_endpoints,
652 parse_endpoint_spec(spec.strip()),
653 )
655 custom_url = os.environ.get("AI_SHELL_OPENCODE_CUSTOM_URL", "").strip()
656 if custom_url:
657 custom_name = sanitize_provider_id(
658 os.environ.get("AI_SHELL_OPENCODE_CUSTOM_NAME", "custom")
659 )
660 custom_key_env = os.environ.get("AI_SHELL_OPENCODE_CUSTOM_KEY_ENV", "").strip()
661 custom_model_raw = os.environ.get("AI_SHELL_OPENCODE_CUSTOM_MODEL", "").strip()
662 custom_models = [m.strip() for m in custom_model_raw.split(",") if m.strip()]
663 _upsert_custom_endpoint(
664 config.opencode_endpoints,
665 CustomEndpoint(
666 name=custom_name,
667 base_url=custom_url,
668 api_key_env=custom_key_env,
669 models=custom_models,
670 ),
671 )
673 # Nested voice_agent overrides (flat env vars map to nested fields)
674 voice_agent_port = os.environ.get("AI_SHELL_VOICE_AGENT_PORT")
675 if voice_agent_port is not None:
676 config.voice_agent.port = int(voice_agent_port)
677 voice_agent_domain = os.environ.get("AI_SHELL_VOICE_AGENT_DOMAIN")
678 if voice_agent_domain is not None:
679 config.voice_agent.domain = voice_agent_domain
680 voice_agent_profile = os.environ.get("AI_SHELL_VOICE_AGENT_PROFILE")
681 if voice_agent_profile is not None:
682 config.voice_agent.profile = voice_agent_profile