Coverage for src/ai_shell/defaults.py: 97%

409 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-17 21:40 +0000

1"""Constants and configuration builders for augint-shell. 

2 

3Encodes all docker-compose.yml configuration as Python, so no compose file is needed. 

4""" 

5 

6from __future__ import annotations 

7 

8import json 

9import logging 

10import os 

11import re 

12from hashlib import sha1 

13from pathlib import Path 

14from typing import TYPE_CHECKING 

15 

16import yaml 

17 

18if TYPE_CHECKING: 

19 from collections.abc import Callable, Mapping 

20 

21 from docker.types import Mount 

22 

23logger = logging.getLogger(__name__) 

24 

25# ============================================================================= 

26# Image defaults 

27# ============================================================================= 

28DEFAULT_IMAGE = "svange/augint-shell" 

29CONTAINER_PREFIX = "augint-shell" 

30SHM_SIZE = "2g" 

31 

32# ============================================================================= 

33# Volume names (prefixed to avoid collisions) 

34# ============================================================================= 

35UV_CACHE_VOLUME = "augint-shell-uv-cache" 

36GH_CONFIG_VOLUME = "augint-shell-gh-config" 

37 

38# Prefix for shared named volumes that back isolated home configs (e.g. 

39# ~/.claude, ~/.codex). One volume per config dir, shared across all projects 

40# on the host, so tool state persists in Docker instead of the host home dir. 

41HOME_CONFIG_VOLUME_PREFIX = "augint-shell-home-" 

42 

43# Home configs that are single files rather than directories. A named volume 

44# can only back a directory, so these can't be volume-isolated; when named in 

45# the isolate set their host bind is dropped instead (config stays 

46# container-local). 

47_SINGLE_FILE_HOME_CONFIGS = frozenset({".claude.json", ".gitconfig", ".zapierrc"}) 

48 

49 

50def home_config_volume_name(config_name: str) -> str: 

51 """Shared named-volume name backing an isolated home config directory. 

52 

53 ``.claude`` -> ``augint-shell-home-claude``. The volume is shared across 

54 all projects on the host (mirroring how the host ``~/.claude`` bind is 

55 shared today), so a single Claude/codex config persists in Docker instead 

56 of being written into the host home directory. 

57 """ 

58 return f"{HOME_CONFIG_VOLUME_PREFIX}{_sanitize_name(config_name.lstrip('.').lower())}" 

59 

60 

61def uv_venv_path(repo_name: str) -> str: 

62 """Return the ``UV_PROJECT_ENVIRONMENT`` path for a repo.""" 

63 return f"/root/.cache/uv/venvs/{repo_name}" 

64 

65 

66NPM_CACHE_VOLUME = "augint-shell-npm-cache" 

67NODE_MODULES_VOLUME_PREFIX = "augint-shell-node-modules-" 

68 

69 

70def node_modules_volume_name( 

71 repo_name: str, 

72 subpath: str | None = None, 

73) -> str: 

74 """Per-project named volume that overlays a node_modules directory. 

75 

76 Mirrors the UV venv-isolation scheme so the container's Linux node_modules 

77 never collides with the host's (e.g. Windows-built) node_modules in the 

78 bind-mounted project directory. 

79 

80 When *subpath* is given (e.g. ``"apps/web"``), a sanitized slug plus a 

81 short hash of the exact path is appended so monorepos can isolate each 

82 workspace's node_modules independently. The hash keeps paths that flatten 

83 to the same slug (``packages/foo/bar`` and ``packages/foo-bar``) on 

84 different volumes. 

85 """ 

86 suffix = repo_name 

87 if subpath: 

88 normalized = subpath.strip("/").lower() 

89 # nosemgrep: python.lang.security.insecure-hash-algorithms.insecure-hash-algorithm-sha1 

90 digest = sha1(normalized.encode("utf-8"), usedforsecurity=False).hexdigest()[:8] 

91 suffix = f"{suffix}-{_sanitize_name(normalized)}-{digest}" 

92 return f"{NODE_MODULES_VOLUME_PREFIX}{suffix}" 

93 

94 

95COMPOSER_CACHE_VOLUME = "augint-shell-composer-cache" 

96PNPM_STORE_VOLUME = "augint-shell-pnpm-store" 

97# T3 Code: per-project data dir (~/.t3 holds the server DB, pairing sessions 

98# and the T3 Connect credential) plus a shared cache for the managed 

99# cloudflared binary so only the first project pays for the download. 

100T3_HOME_VOLUME_PREFIX = "augint-shell-t3-" 

101T3_TOOLS_VOLUME = "augint-shell-t3-tools" 

102T3_HOME_PATH = "/root/.t3" 

103T3_TOOLS_PATH = "/root/.t3/tools" 

104VENDOR_VOLUME_PREFIX = "augint-shell-vendor-" 

105 

106 

107def vendor_volume_name(repo_name: str) -> str: 

108 """Per-project named volume that overlays composer's ``vendor/`` directory. 

109 

110 Same rationale as :func:`node_modules_volume_name`: ``vendor/`` on a 

111 drvfs/9p bind mount is slow, and overlaying keeps the container's 

112 Linux-built vendor tree separate from whatever the host has. 

113 """ 

114 return f"{VENDOR_VOLUME_PREFIX}{repo_name}" 

115 

116 

117def t3_home_volume_name(project_dir: Path, project_name: str | None = None) -> str: 

118 """Per-project named volume backing ``~/.t3`` inside the dev container. 

119 

120 A T3 Code environment *is* its data directory: the sqlite state, the 

121 pairing sessions and the T3 Connect credential all live there. Since each 

122 project gets its own container, each also gets its own environment — a 

123 shared volume would mean several containers writing one sqlite file while 

124 listing projects that only exist in one of them. The host's own ``~/.t3`` 

125 is deliberately not bind-mounted so a desktop T3 Code install and the 

126 container servers never share a database. 

127 """ 

128 return f"{T3_HOME_VOLUME_PREFIX}{unique_project_name(project_dir, project_name)}" 

129 

130 

131PRE_COMMIT_CACHE_VOLUME = "augint-shell-pre-commit-cache" 

132PRE_COMMIT_CACHE_PATH = "/root/.cache/pre-commit-container" 

133OLLAMA_DATA_VOLUME = "augint-shell-ollama-data" 

134WEBUI_DATA_VOLUME = "augint-shell-webui-data" 

135N8N_DATA_VOLUME = "augint-shell-n8n-data" 

136WHISPER_DATA_VOLUME = "augint-shell-whisper-cache" 

137VOICE_AGENT_DATA_VOLUME = "augint-shell-voice-agent-data" 

138COMFYUI_DATA_VOLUME = "augint-shell-comfyui-data" 

139 

140# ============================================================================= 

141# LLM defaults 

142# ============================================================================= 

143OLLAMA_IMAGE = "ollama/ollama" 

144WEBUI_IMAGE = "ghcr.io/open-webui/open-webui:main" 

145KOKORO_IMAGE_CPU = "ghcr.io/remsky/kokoro-fastapi-cpu:latest" 

146KOKORO_IMAGE_GPU = "ghcr.io/remsky/kokoro-fastapi-gpu:latest" 

147N8N_IMAGE = "docker.n8n.io/n8nio/n8n" 

148WHISPER_IMAGE_CPU = "ghcr.io/speaches-ai/speaches:latest-cpu" 

149WHISPER_IMAGE_GPU = "ghcr.io/speaches-ai/speaches:latest-cuda" 

150# Voice-agent image is built locally from docker/voice-agent/ on first 

151# ensure call. Not pulled. The local tag keeps `images.get` fast once built. 

152VOICE_AGENT_IMAGE = "augint-shell/voice-agent:local" 

153# ComfyUI: ai-dock/comfyui is actively maintained and exposes PROVISIONING_SCRIPT 

154# which we use to download FLUX.1-dev + SDXL on first boot. GPU-only (no CPU variant). 

155COMFYUI_IMAGE = "ghcr.io/ai-dock/comfyui:latest-cuda" 

156# Model slots (RTX 4090-sized, validated April 2026). Primary = best available for 

157# the role; secondary = best uncensored alternative. See README "Local LLM stack" 

158# and the generated .ai-shell.yaml for per-slot rationale and caveats. 

159DEFAULT_PRIMARY_CHAT_MODEL = "qwen3.5:27b" 

160DEFAULT_SECONDARY_CHAT_MODEL = "huihui_ai/qwen3.5-abliterated:27b" 

161DEFAULT_PRIMARY_CODING_MODEL = "qwen3-coder:30b-a3b-q4_K_M" 

162DEFAULT_SECONDARY_CODING_MODEL = "huihui_ai/qwen3-coder-abliterated:30b-a3b-instruct-q4_K_M" 

163DEFAULT_EXTRA_MODELS: list[str] = [ 

164 "qwen3.5:9b", # ~6.6 GB mid-range chat, fast + capable 

165 "devstral:24b", # ~15 GB Mistral agentic coding, dense 24B 

166] 

167DEFAULT_CONTEXT_SIZE = 32768 

168DEFAULT_OLLAMA_PORT = 11434 

169DEFAULT_WEBUI_PORT = 3000 

170DEFAULT_KOKORO_PORT = 8880 

171DEFAULT_N8N_PORT = 5678 

172DEFAULT_WHISPER_PORT = 8001 

173DEFAULT_WHISPER_MODEL = "Systran/faster-distil-whisper-large-v3" 

174DEFAULT_VOICE_AGENT_PORT = 8010 

175DEFAULT_COMFYUI_PORT = 8188 

176DEFAULT_KOKORO_VOICE = "af_bella" 

177# T3 Code server port inside the dev container (t3's own default). It is in 

178# DEFAULT_DEV_PORTS so every dev container publishes it, which is what lets a 

179# phone or the desktop app pair with the in-container server over the LAN. 

180T3_CONTAINER_PORT = 3773 

181# Metro / Expo dev server port inside the dev container (Expo's own default). 

182# The tunnel path does not need it published — ngrok dials out from the 

183# container — but publishing it lets a host browser reach Metro and 

184# `expo start --web`. 

185EXPO_METRO_PORT = 8081 

186DEFAULT_DEV_PORTS = [ 

187 3000, 

188 3773, 

189 4096, 

190 4200, 

191 5000, 

192 5173, 

193 5678, 

194 8000, 

195 8080, 

196 8081, 

197 8888, 

198 19432, 

199 31415, 

200] 

201 

202# Deterministic dev port mapping (avoids Chrome debug range 40000-60000) 

203DEV_PORT_RANGE_START = 10000 

204DEV_PORT_RANGE_SIZE = 30000 # 10000-39999 

205 

206# ============================================================================= 

207# Bedrock defaults 

208# ============================================================================= 

209DEFAULT_BEDROCK_MODEL = "us.anthropic.claude-sonnet-4-20250514-v1:0" 

210 

211# ============================================================================= 

212# Ollama GPU defaults 

213# ============================================================================= 

214OLLAMA_VRAM_BUFFER_BYTES = 1 * 1024**3 # 1 GiB safety buffer reserved as overhead 

215OLLAMA_CPU_SHARES = 1024 # Docker CPU scheduling priority (default 0 = fair-share) 

216 

217# ============================================================================= 

218# Container names 

219# ============================================================================= 

220OLLAMA_CONTAINER = "augint-shell-ollama" 

221WEBUI_CONTAINER = "augint-shell-webui" 

222KOKORO_CONTAINER = "augint-shell-kokoro" 

223N8N_CONTAINER = "augint-shell-n8n" 

224WHISPER_CONTAINER = "augint-shell-whisper" 

225VOICE_AGENT_CONTAINER = "augint-shell-voice-agent" 

226COMFYUI_CONTAINER = "augint-shell-comfyui" 

227 

228# ============================================================================= 

229# Docker network 

230# ============================================================================= 

231LLM_NETWORK = "augint-shell-llm" 

232 

233 

234def _sanitize_name(name: str) -> str: 

235 """Convert an arbitrary string into a Docker-safe slug.""" 

236 name = re.sub(r"[^a-z0-9-]", "-", name) 

237 name = re.sub(r"-+", "-", name) 

238 return name.strip("-") or "project" 

239 

240 

241def sanitize_project_name(path: Path) -> str: 

242 """Derive a safe project slug from a directory basename.""" 

243 return _sanitize_name(path.resolve().name.lower()) 

244 

245 

246def unique_project_name(path: Path, project_name: str | None = None) -> str: 

247 """Build a path-stable project identifier for container naming. 

248 

249 The basename remains human-readable while a short path hash prevents 

250 collisions between repos with the same leaf directory name. 

251 """ 

252 slug = _sanitize_name((project_name or path.resolve().name).lower()) 

253 # nosemgrep: python.lang.security.insecure-hash-algorithms.insecure-hash-algorithm-sha1 

254 digest = sha1(str(path.resolve()).encode("utf-8"), usedforsecurity=False).hexdigest()[:8] 

255 return f"{slug}-{digest}" 

256 

257 

258def dev_container_name(project_name: str, project_dir: Path | None = None) -> str: 

259 """Build the dev container name for a project. 

260 

261 When *project_dir* is provided, the full resolved path is folded into the 

262 name to avoid collisions across nested repo layouts. Without it, the legacy 

263 basename-only format is preserved for compatibility. 

264 """ 

265 if project_dir is None: 

266 return f"{CONTAINER_PREFIX}-{project_name}-dev" 

267 return f"{CONTAINER_PREFIX}-{unique_project_name(project_dir, project_name)}-dev" 

268 

269 

270# Salted re-hash attempts per port before giving up. Each attempt is an 

271# independent draw from 30000 slots, so exhaustion means the host is 

272# rejecting essentially the whole range. 

273DEV_PORT_MAX_ATTEMPTS = 64 

274 

275 

276def project_dev_port_map( 

277 project_dir: Path, 

278 dev_ports: list[int], 

279 project_name: str | None = None, 

280 is_available: Callable[[int], bool] | None = None, 

281) -> dict[int, int]: 

282 """Map each container port to a unique, stable per-project host port. 

283 

284 Uses the same project identity as container naming (unique_project_name) 

285 combined with each container port to produce deterministic host ports in 

286 the 10000-39999 range. Different projects get different host ports for 

287 the same container port, so multiple projects can run simultaneously. 

288 

289 A candidate slot is rejected when it is already taken by another port in 

290 this map or when *is_available* (e.g. a host test-bind probe) refuses it. 

291 Rejected candidates are re-hashed with a salt counter rather than probed 

292 linearly: host-side reservations (Windows winnat excluded port ranges) 

293 are contiguous blocks, so adjacent slots tend to fail together while a 

294 re-hash jumps elsewhere in the range. Assignment runs in ascending 

295 container-port order so the result is deterministic, and an unsalted 

296 first attempt keeps existing assignments stable for the common case. 

297 """ 

298 slug = unique_project_name(project_dir, project_name) 

299 assigned: dict[int, int] = {} 

300 used: set[int] = set() 

301 for port in sorted(set(dev_ports)): 

302 for salt in range(DEV_PORT_MAX_ATTEMPTS): 

303 key = f"{slug}:{port}" if salt == 0 else f"{slug}:{port}:{salt}" 

304 # nosemgrep: python.lang.security.insecure-hash-algorithms.insecure-hash-algorithm-sha1 

305 digest = sha1(key.encode(), usedforsecurity=False).hexdigest() 

306 candidate = DEV_PORT_RANGE_START + (int(digest[:8], 16) % DEV_PORT_RANGE_SIZE) 

307 if candidate not in used and (is_available is None or is_available(candidate)): 

308 break 

309 else: 

310 raise RuntimeError( 

311 f"Could not find a free host port for container port {port} " 

312 f"after {DEV_PORT_MAX_ATTEMPTS} attempts in range " 

313 f"{DEV_PORT_RANGE_START}-{DEV_PORT_RANGE_START + DEV_PORT_RANGE_SIZE - 1}. " 

314 "The host is rejecting nearly all bind attempts — check firewall " 

315 "or reserved port configuration." 

316 ) 

317 assigned[port] = candidate 

318 used.add(candidate) 

319 return assigned 

320 

321 

322def project_dev_port( 

323 project_dir: Path, 

324 container_port: int, 

325 project_name: str | None = None, 

326 dev_ports: list[int] | None = None, 

327) -> int: 

328 """Host port for one container port, consistent with project_dev_port_map. 

329 

330 *dev_ports* must be the full port set the container was created with — 

331 collision resolution depends on it. Defaults to DEFAULT_DEV_PORTS. 

332 """ 

333 ports = list(dev_ports) if dev_ports is not None else list(DEFAULT_DEV_PORTS) 

334 if container_port not in ports: 

335 ports.append(container_port) 

336 return project_dev_port_map(project_dir, ports, project_name)[container_port] 

337 

338 

339def _as_str_list(value: object) -> list[str]: 

340 """Coerce a JSON/YAML scalar-or-list into a list of strings.""" 

341 if isinstance(value, str): 

342 return [value] 

343 if isinstance(value, list): 

344 return [str(item) for item in value if isinstance(item, (str, int, float))] 

345 return [] 

346 

347 

348def workspace_node_modules_globs(project_dir: Path) -> list[str]: 

349 """Workspace package globs a project declares, relative to *project_dir*. 

350 

351 Reads ``pnpm-workspace.yaml`` (``packages:``) and ``package.json`` 

352 (``workspaces``, either a list or ``{"packages": [...]}``). Negated 

353 patterns (``!**/test/**``) and the root itself are dropped. The result 

354 feeds :func:`build_dev_mounts`, which overlays a container-local volume on 

355 each matching package's ``node_modules``. 

356 """ 

357 patterns: list[str] = [] 

358 

359 pnpm_workspace = project_dir / "pnpm-workspace.yaml" 

360 if pnpm_workspace.is_file(): 

361 try: 

362 data = yaml.safe_load(pnpm_workspace.read_text(encoding="utf-8")) or {} 

363 except (OSError, yaml.YAMLError) as exc: 

364 logger.warning("Could not read %s: %s", pnpm_workspace, exc) 

365 data = {} 

366 if isinstance(data, dict): 

367 patterns.extend(_as_str_list(data.get("packages"))) 

368 

369 package_json = project_dir / "package.json" 

370 if package_json.is_file(): 

371 try: 

372 pkg = json.loads(package_json.read_text(encoding="utf-8")) 

373 except (OSError, ValueError) as exc: 

374 logger.warning("Could not read %s: %s", package_json, exc) 

375 pkg = {} 

376 workspaces = pkg.get("workspaces") if isinstance(pkg, dict) else None 

377 if isinstance(workspaces, dict): 

378 workspaces = workspaces.get("packages") 

379 patterns.extend(_as_str_list(workspaces)) 

380 

381 cleaned: list[str] = [] 

382 for raw in patterns: 

383 pattern = raw.strip().replace("\\", "/") 

384 if pattern.startswith("./"): 

385 pattern = pattern[2:] 

386 pattern = pattern.rstrip("/") 

387 if not pattern or pattern == "." or pattern.startswith("!"): 

388 continue 

389 if pattern not in cleaned: 

390 cleaned.append(pattern) 

391 return cleaned 

392 

393 

394def build_dev_mounts( 

395 project_dir: Path, 

396 project_name: str, 

397 extra_node_modules_paths: list[str] | None = None, 

398 isolate_home_paths: set[str] | None = None, 

399) -> list[Mount]: 

400 """Build the full mount list matching docker-compose.yml dev service. 

401 

402 Required mounts are always included. Optional mounts are skipped 

403 if the source path doesn't exist on the host. 

404 

405 *extra_node_modules_paths* is a list of glob patterns relative to 

406 *project_dir*. Each glob match (that is a directory) gets its own named 

407 volume overlaid at ``{match}/node_modules`` inside the container, so each 

408 workspace in a monorepo isolates its Linux node_modules from the host 

409 bind mount the same way the root overlay does. Workspace globs declared in 

410 ``pnpm-workspace.yaml`` or ``package.json`` ``workspaces`` are picked up 

411 automatically (see :func:`workspace_node_modules_globs`); the explicit 

412 list is for layouts those files don't describe. 

413 

414 *isolate_home_paths* is a set of home-config basenames (e.g. ``.claude``) 

415 that should be backed by a shared named volume instead of a host bind mount, 

416 so nothing is written into the host home directory. The volume persists 

417 across container recreations and is shared across projects. Single-file 

418 configs (``.claude.json`` etc.) can't be volume-backed; when named — or, for 

419 ``.claude.json``, when ``.claude`` is isolated — their host bind is dropped 

420 and the config stays container-local. 

421 

422 ``.codex`` is **always** isolated (added to the isolate set unconditionally), 

423 regardless of *isolate_home_paths*: its OAuth ``auth.json`` uses single-use 

424 refresh tokens, so sharing one file between host and container breaks auth. 

425 """ 

426 from docker.types import Mount 

427 

428 mounts: list[Mount] = [] 

429 home = Path.home() 

430 

431 # Required: project directory (rw, delegated) 

432 mounts.append( 

433 Mount( 

434 target=f"/root/projects/{project_name}", 

435 source=str(project_dir.resolve()), 

436 type="bind", 

437 read_only=False, 

438 consistency="delegated", 

439 ) 

440 ) 

441 

442 # Ensure directories that tools need for persistent config exist on the 

443 # host so bind mounts aren't silently skipped. 

444 for d in ( 

445 ".pi", 

446 ".augint", 

447 ".plannotator", 

448 ".expo", 

449 ".agents", 

450 ".config/opencode", 

451 ".local/share/opencode", 

452 ): 

453 (home / d).mkdir(parents=True, exist_ok=True) 

454 

455 # Zapier CLI auth is a single JSON file; pre-create it so the bind mount 

456 # exists and `zapier login` inside the container persists across 

457 # container recreations (mirrors the .claude.json single-file bind). 

458 zapierrc = home / ".zapierrc" 

459 if not zapierrc.exists(): 

460 zapierrc.write_text("{}\n") 

461 

462 # Optional bind mounts — skip if source doesn't exist 

463 # Note: ~/.config is deliberately NOT mounted as a whole because it 

464 # shadows /root/.config/starship.toml in the image and exposes unrelated 

465 # host desktop credentials; ~/.config/gh and ~/.config/opencode are mounted 

466 # explicitly. 

467 optional_binds: list[tuple[Path, str, bool]] = [ 

468 # .codex is always isolated to a named volume (see the isolate set 

469 # below); this host path is never bind-mounted. 

470 (home / ".codex", "/root/.codex", False), 

471 (home / ".claude", "/root/.claude", False), 

472 (home / ".claude.json", "/root/.claude.json", False), 

473 (home / ".pi", "/root/.pi", False), 

474 (home / ".augint", "/root/.augint", False), 

475 (home / ".plannotator", "/root/.plannotator", False), 

476 (home / ".agents", "/root/.agents", False), 

477 # OpenCode persistent config and state directories 

478 (home / ".config" / "opencode", "/root/.config/opencode", False), 

479 (home / ".local" / "share" / "opencode", "/root/.local/share/opencode", False), 

480 # Expo/EAS share ~/.expo for the auth session (state.json) and the 

481 # ngrok config, so binding it keeps `expo login` across recreations. 

482 (home / ".expo", "/root/.expo", False), 

483 (home / ".zapierrc", "/root/.zapierrc", False), 

484 (home / ".ssh", "/root/.ssh", True), 

485 (home / ".gitconfig", "/root/.gitconfig.windows", True), 

486 (home / ".aws", "/root/.aws", False), 

487 ] 

488 

489 # .codex holds a single-use-refresh-token OAuth session; sharing one 

490 # auth.json between the host and container causes intermittent 401s and 

491 # cross-`logout` (openai/codex #15410, #15502, #22577; OpenAI's own guidance 

492 # is one auth.json per machine). Always back it with a container-local named 

493 # volume instead of the host bind, so host ~/.codex is never touched. 

494 isolate = (isolate_home_paths or set()) | {".codex"} 

495 for source, target, read_only in optional_binds: 

496 name = source.name 

497 

498 # Isolation: back the config with a shared named volume instead of a 

499 # host bind, so nothing is written into the host home directory. 

500 if name in isolate or f".{name}" in isolate: 

501 if name in _SINGLE_FILE_HOME_CONFIGS: 

502 # A named volume can't back a single file — drop the bind so 

503 # the host file is never touched (config stays container-local). 

504 logger.debug("Isolating single-file home config (not persisted): %s", name) 

505 continue 

506 vol_name = "opencode-data" if target == "/root/.local/share/opencode" else name 

507 mounts.append( 

508 Mount( 

509 target=target, 

510 source=home_config_volume_name(vol_name), 

511 type="volume", 

512 ) 

513 ) 

514 continue 

515 

516 # Keep ~/.claude.json off the host whenever ~/.claude is isolated. 

517 if name == ".claude.json" and ".claude" in isolate: 

518 logger.debug("Isolating .claude.json alongside isolated .claude (not persisted)") 

519 continue 

520 

521 if source.exists(): 

522 mounts.append( 

523 Mount( 

524 target=target, 

525 source=str(source), 

526 type="bind", 

527 read_only=read_only, 

528 ) 

529 ) 

530 else: 

531 logger.debug("Skipping optional mount (not found): %s", source) 

532 

533 # gh CLI config: bind-mount the host path when found (Linux/Mac/WSL2), 

534 # otherwise use a named volume so auth persists across container recreations 

535 # (needed on Windows where gh stores tokens in keyring, not a file). 

536 gh_config = _find_gh_config_dir() 

537 if gh_config is not None: 

538 mounts.append( 

539 Mount( 

540 target="/root/.config/gh", 

541 source=str(gh_config), 

542 type="bind", 

543 read_only=False, 

544 ) 

545 ) 

546 else: 

547 mounts.append( 

548 Mount( 

549 target="/root/.config/gh", 

550 source=GH_CONFIG_VOLUME, 

551 type="volume", 

552 ) 

553 ) 

554 

555 # Optional: Docker socket 

556 docker_sock = Path("/var/run/docker.sock") 

557 if docker_sock.exists(): 

558 mounts.append( 

559 Mount( 

560 target="/var/run/docker.sock", 

561 source=str(docker_sock), 

562 type="bind", 

563 read_only=True, 

564 ) 

565 ) 

566 

567 # Named volume: uv cache (shared across all projects) 

568 mounts.append( 

569 Mount( 

570 target="/root/.cache/uv", 

571 source=UV_CACHE_VOLUME, 

572 type="volume", 

573 ) 

574 ) 

575 

576 # Named volume: npm cache (shared across all projects) 

577 mounts.append( 

578 Mount( 

579 target="/root/.npm", 

580 source=NPM_CACHE_VOLUME, 

581 type="volume", 

582 ) 

583 ) 

584 

585 # Named volume: composer cache (shared across all projects). Without it 

586 # composer re-downloads every package on container recreation. 

587 mounts.append( 

588 Mount( 

589 target="/root/.cache/composer", 

590 source=COMPOSER_CACHE_VOLUME, 

591 type="volume", 

592 ) 

593 ) 

594 

595 # Named volume: pnpm content-addressable store (shared across all 

596 # projects). Corepack's pnpm is container-local otherwise, so every 

597 # container rebuild is a cold install; the npm cache doesn't help pnpm. 

598 mounts.append( 

599 Mount( 

600 target="/root/.local/share/pnpm", 

601 source=PNPM_STORE_VOLUME, 

602 type="volume", 

603 ) 

604 ) 

605 

606 # Per-project named volume: T3 Code data dir (~/.t3). Keeps the server 

607 # database, paired devices and the T3 Connect credential across container 

608 # recreations without ever touching the host's own ~/.t3. 

609 mounts.append( 

610 Mount( 

611 target=T3_HOME_PATH, 

612 source=t3_home_volume_name(project_dir, project_name), 

613 type="volume", 

614 ) 

615 ) 

616 

617 # Shared named volume nested inside it: the managed cloudflared binary T3 

618 # Connect downloads (~35 MB). Shared so only the first project pays. 

619 mounts.append( 

620 Mount( 

621 target=T3_TOOLS_PATH, 

622 source=T3_TOOLS_VOLUME, 

623 type="volume", 

624 ) 

625 ) 

626 

627 # Named volume: pre-commit cache (shared across all projects). 

628 # Isolates the container's hook environments from the Windows host's 

629 # ~/.cache/pre-commit so the two installs don't clobber each other. 

630 mounts.append( 

631 Mount( 

632 target=PRE_COMMIT_CACHE_PATH, 

633 source=PRE_COMMIT_CACHE_VOLUME, 

634 type="volume", 

635 ) 

636 ) 

637 

638 # Per-project named volume overlaying node_modules. Without this the 

639 # container's Linux `npm ci` would write into the bind-mounted host 

640 # project dir and collide with host-built (e.g. Windows) node_modules. 

641 # npm has no equivalent of UV_PROJECT_ENVIRONMENT, so we isolate at the 

642 # mount layer instead. Host node_modules underneath stays untouched. 

643 mounts.append( 

644 Mount( 

645 target=f"/root/projects/{project_name}/node_modules", 

646 source=node_modules_volume_name(project_name), 

647 type="volume", 

648 ) 

649 ) 

650 

651 # Per-project named volume overlaying composer's vendor/ — the exact 

652 # node_modules rationale applies verbatim. Conditional on composer.json 

653 # so non-PHP projects don't grow an empty vendor/ dir on the host. 

654 if (project_dir / "composer.json").is_file(): 

655 mounts.append( 

656 Mount( 

657 target=f"/root/projects/{project_name}/vendor", 

658 source=vendor_volume_name(project_name), 

659 type="volume", 

660 ) 

661 ) 

662 

663 # Monorepo workspaces: overlay an isolated named volume on each matched 

664 # workspace's node_modules so per-app installs (npm/pnpm/yarn workspaces) 

665 # land in container-only storage rather than the host bind mount. 

666 # 

667 # Declared workspaces are overlaid automatically. pnpm in particular links 

668 # every workspace package's node_modules into the root virtual store, so a 

669 # Linux-made layout left on the host bind mount makes the Windows pnpm 

670 # reinstall from scratch, and vice versa: the two installs keep deleting 

671 # each other. Only directories holding a package.json count as workspace 

672 # packages (pnpm's own rule), which also keeps Docker from creating empty 

673 # node_modules dirs on the host for other glob matches. 

674 project_root = project_dir.resolve() 

675 seen_targets: set[str] = {f"/root/projects/{project_name}/node_modules"} 

676 patterns: list[tuple[str, bool]] = [ 

677 (pattern, True) for pattern in workspace_node_modules_globs(project_root) 

678 ] 

679 patterns.extend((pattern, False) for pattern in extra_node_modules_paths or []) 

680 for pattern, packages_only in patterns: 

681 for match in sorted(project_root.glob(pattern)): 

682 if not match.is_dir(): 

683 continue 

684 if packages_only and not (match / "package.json").is_file(): 

685 continue 

686 try: 

687 rel = match.relative_to(project_root) 

688 except ValueError: 

689 continue 

690 rel_posix = rel.as_posix() 

691 target = f"/root/projects/{project_name}/{rel_posix}/node_modules" 

692 if target in seen_targets: 

693 continue 

694 seen_targets.add(target) 

695 mounts.append( 

696 Mount( 

697 target=target, 

698 source=node_modules_volume_name(project_name, subpath=rel_posix), 

699 type="volume", 

700 ) 

701 ) 

702 

703 return mounts 

704 

705 

706def podman_cli_host(environ: Mapping[str, str]) -> str | None: 

707 """``CONTAINER_HOST`` to set so Podman's CLI talks to the service ``DOCKER_HOST`` names. 

708 

709 On a rootless Podman host the ``docker`` command is Podman's own CLI 

710 (``podman-docker``), which ignores ``DOCKER_HOST`` and runs containers 

711 itself. ai-shell creates the dev container through the API on the 

712 socket, inside the user's Podman service, and then runs ``docker exec`` 

713 as a subprocess: the CLI performs that exec from the terminal's own 

714 cgroup, and the kernel refuses to move a process into the service's 

715 cgroup subtree ("writing cgroup.procs: Permission denied: OCI permission 

716 denied"). ``CONTAINER_HOST`` turns on Podman's remote mode, so the exec 

717 runs in the service too. Returns ``None`` when ``DOCKER_HOST`` is not a 

718 Podman socket or the user already chose a connection. 

719 """ 

720 if environ.get("CONTAINER_HOST") or environ.get("CONTAINER_CONNECTION"): 

721 return None 

722 host = (environ.get("DOCKER_HOST") or "").strip() 

723 if not host.startswith("unix://") or "podman" not in host: 

724 return None 

725 return host 

726 

727 

728def docker_tcp_fallback_host() -> str | None: 

729 """DOCKER_HOST value for dev containers when no Unix socket exists to mount. 

730 

731 On Windows hosts there is no /var/run/docker.sock for build_dev_mounts to 

732 bind-mount, but Docker Desktop can expose the daemon on localhost:2375 

733 ("Expose daemon on tcp://localhost:2375 without TLS"). When that endpoint 

734 is reachable, containers reach the same daemon via host.docker.internal — 

735 return the DOCKER_HOST value to inject. Returns None when the socket 

736 mount already covers Docker access or no tcp endpoint is listening. 

737 """ 

738 import socket 

739 

740 if Path("/var/run/docker.sock").exists(): 

741 return None 

742 try: 

743 with socket.create_connection(("localhost", 2375), timeout=1): 

744 pass 

745 except OSError: 

746 return None 

747 return "tcp://host.docker.internal:2375" 

748 

749 

750def _find_gh_config_dir() -> Path | None: 

751 """Find the gh CLI config directory. 

752 

753 Checks the standard Linux/Mac path (~/.config/gh) first, then falls back 

754 to the Windows APPDATA path for WSL2 environments where gh is installed on 

755 the Windows side (%APPDATA%\\GitHub CLI\\). 

756 """ 

757 linux_path = Path.home() / ".config" / "gh" 

758 if linux_path.exists(): 

759 return linux_path 

760 

761 # WSL2 fallback: APPDATA is set as a Windows path (e.g. C:\Users\foo\AppData\Roaming) 

762 appdata = os.environ.get("APPDATA", "") 

763 if appdata and ":" in appdata: 

764 drive, rest = appdata.split(":", 1) 

765 wsl_appdata = Path(f"/mnt/{drive.lower()}{rest.replace(chr(92), '/')}") 

766 windows_path = wsl_appdata / "GitHub CLI" 

767 if windows_path.exists(): 

768 return windows_path 

769 

770 return None 

771 

772 

773def _load_layered_dotenv( 

774 project_dir: Path | None = None, 

775 env_file: Path | None = None, 

776) -> dict[str, str | None]: 

777 """Load layered .env files. 

778 

779 ``~/.augint/.env`` always loads (global augint suite config). The project 

780 ``./.env`` and explicit *env_file* only load when *env_file* is given 

781 (i.e. user passed ``--env`` on the CLI). Later layers override earlier 

782 ones. 

783 """ 

784 from dotenv import dotenv_values 

785 

786 layers: dict[str, str | None] = {} 

787 

788 global_path = Path.home() / ".augint" / ".env" 

789 if global_path.is_file(): 

790 layers.update(dotenv_values(global_path)) 

791 

792 if env_file is None: 

793 return layers 

794 

795 if project_dir is not None: 

796 project_path = project_dir / ".env" 

797 if project_path.is_file() and project_path.resolve() != env_file.resolve(): 

798 layers.update(dotenv_values(project_path)) 

799 

800 if env_file.is_file(): 

801 layers.update(dotenv_values(env_file)) 

802 

803 return layers 

804 

805 

806_SHARED_ENV_PASSTHROUGH = ( 

807 "ANTHROPIC_API_KEY", 

808 "OPENAI_API_KEY", 

809 "AWS_BEARER_TOKEN_BEDROCK", 

810 "BEDROCK_API_KEY", 

811 "PRIMARY_CHAT_MODEL", 

812 "SECONDARY_CHAT_MODEL", 

813 "PRIMARY_CODING_MODEL", 

814 "SECONDARY_CODING_MODEL", 

815 "CONTEXT_SIZE", 

816 "OLLAMA_PORT", 

817 "WEBUI_PORT", 

818 "KOKORO_PORT", 

819 "WHISPER_PORT", 

820 "N8N_PORT", 

821 "COMFYUI_PORT", 

822 "OPENCODE_SERVER_PASSWORD", 

823 "OPENCODE_SERVER_USERNAME", 

824 "PI_STUDIO_HOST", 

825) 

826 

827 

828# Claude Code multi-account switching. Tokens (from ``claude setup-token``) are 

829# stored in .env as ``CLAUDE_CODE_OAUTH_TOKEN_{ACCOUNT}``; the selected one is 

830# injected as ``CLAUDE_CODE_OAUTH_TOKEN``. The reserved account name 

831# ``default`` injects no token, so the ``~/.claude`` login is used. 

832CLAUDE_OAUTH_TOKEN_VAR = "CLAUDE_CODE_OAUTH_TOKEN" 

833CLAUDE_ACCOUNT_TOKEN_PREFIX = f"{CLAUDE_OAUTH_TOKEN_VAR}_" 

834CLAUDE_DEFAULT_ACCOUNT = "default" 

835# Claude Code prefers these over CLAUDE_CODE_OAUTH_TOKEN. They must be removed 

836# from the claude process when an account is selected, or the selection is 

837# silently ignored. 

838CLAUDE_AUTH_OVERRIDE_VARS = ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN") 

839 

840# Login profiles. A setup-token / CLAUDE_CODE_OAUTH_TOKEN can only make model 

841# requests, so ``claude remote-control`` refuses it; Remote Control needs a 

842# full ``claude auth login``. Each such account gets its own CLAUDE_CONFIG_DIR 

843# (Claude Code's documented multi-account mechanism) under ~/.augint, which is 

844# already bind-mounted at /root/.augint, so the login, settings and session 

845# history of that account live in ~/.augint/claude-accounts/<name>/ and 

846# survive container recreation without touching ~/.claude. 

847CLAUDE_CONFIG_DIR_VAR = "CLAUDE_CONFIG_DIR" 

848CLAUDE_ACCOUNTS_DIR_NAME = "claude-accounts" 

849CLAUDE_ACCOUNTS_CONTAINER_ROOT = f"/root/.augint/{CLAUDE_ACCOUNTS_DIR_NAME}" 

850# Every credential Claude Code ranks above a `claude auth login`. All of them 

851# must be absent from a Remote Control process or the server refuses to start. 

852CLAUDE_REMOTE_CONTROL_UNSET_VARS = (*CLAUDE_AUTH_OVERRIDE_VARS, CLAUDE_OAUTH_TOKEN_VAR) 

853 

854 

855def claude_account_slug(account: str) -> str: 

856 """Directory-safe form of an account name (``My_Org`` -> ``my-org``).""" 

857 return _sanitize_name(account.lower().replace("_", "-")) 

858 

859 

860def claude_account_login_dir(account: str) -> Path: 

861 """Host directory that holds the login profile for *account*.""" 

862 return Path.home() / ".augint" / CLAUDE_ACCOUNTS_DIR_NAME / claude_account_slug(account) 

863 

864 

865def claude_account_config_dir(account: str) -> str: 

866 """Container path of the login profile for *account* (``CLAUDE_CONFIG_DIR``).""" 

867 return f"{CLAUDE_ACCOUNTS_CONTAINER_ROOT}/{claude_account_slug(account)}" 

868 

869 

870# Written into a new login profile so the user's own ~/.claude/CLAUDE.md 

871# applies there too. Claude Code expands ``@path`` imports in user-scope 

872# memory files without an approval dialog, and ~/.claude is bind-mounted at 

873# /root/.claude, so one file stays the source of truth instead of a copy. 

874CLAUDE_LOGIN_PROFILE_MEMORY = ( 

875 "# Shared user instructions\n" 

876 "\n" 

877 "This login profile imports the host user's own Claude Code memory file\n" 

878 "through the ~/.claude bind mount. Edit or delete this file to give the\n" 

879 "account its own instructions instead.\n" 

880 "\n" 

881 "@/root/.claude/CLAUDE.md\n" 

882) 

883 

884 

885def seed_claude_login_profile(login_dir: Path) -> bool: 

886 """Give a new login profile the user's ``~/.claude/CLAUDE.md`` via an import. 

887 

888 A login profile is a separate ``CLAUDE_CONFIG_DIR``, so Claude never reads 

889 ``~/.claude/CLAUDE.md`` in it. Only written when the profile has no 

890 ``CLAUDE.md`` yet and the host has one, so an account can diverge later by 

891 editing its own file. Returns True when the file was written. 

892 """ 

893 target = login_dir / "CLAUDE.md" 

894 if target.exists() or not (Path.home() / ".claude" / "CLAUDE.md").is_file(): 

895 return False 

896 target.write_text(CLAUDE_LOGIN_PROFILE_MEMORY, encoding="utf-8") 

897 return True 

898 

899 

900def list_claude_login_accounts() -> list[str]: 

901 """Return the account names that have a login profile directory.""" 

902 root = Path.home() / ".augint" / CLAUDE_ACCOUNTS_DIR_NAME 

903 if not root.is_dir(): 

904 return [] 

905 return sorted(p.name for p in root.iterdir() if p.is_dir()) 

906 

907 

908def claude_account_token_var(account: str) -> str: 

909 """Return the .env key that holds the OAuth token for *account*.""" 

910 return CLAUDE_ACCOUNT_TOKEN_PREFIX + account.upper().replace("-", "_") 

911 

912 

913def list_claude_accounts( 

914 project_dir: Path | None = None, 

915 env_file: Path | None = None, 

916) -> list[str]: 

917 """Return the Claude account names defined in the layered .env files.""" 

918 dotenv = _load_layered_dotenv(project_dir, env_file=env_file) 

919 return sorted( 

920 key[len(CLAUDE_ACCOUNT_TOKEN_PREFIX) :].lower() 

921 for key, value in dotenv.items() 

922 if key.startswith(CLAUDE_ACCOUNT_TOKEN_PREFIX) and value 

923 ) 

924 

925 

926def list_all_claude_accounts( 

927 project_dir: Path | None = None, 

928 env_file: Path | None = None, 

929) -> list[str]: 

930 """Token accounts and login-profile accounts, deduplicated and sorted.""" 

931 names: dict[str, str] = {} 

932 for name in [*list_claude_accounts(project_dir, env_file), *list_claude_login_accounts()]: 

933 names.setdefault(claude_account_slug(name), name) 

934 return sorted(names.values()) 

935 

936 

937def build_dev_environment( 

938 extra_env: dict[str, str] | None = None, 

939 project_dir: Path | None = None, 

940 *, 

941 project_name: str = "", 

942 bedrock: bool = False, 

943 aws_profile: str = "", 

944 aws_region: str = "", 

945 bedrock_profile: str = "", 

946 bedrock_region: str = "", 

947 bedrock_model: str = "", 

948 openai_profile: str = "", 

949 claude_account: str = "", 

950 claude_login: bool = False, 

951 env_file: Path | None = None, 

952) -> dict[str, str]: 

953 """Build environment variables matching docker-compose.yml dev service. 

954 

955 ``~/.augint/.env`` always loads (global augint suite config). The project 

956 ``./.env`` only loads when *env_file* is given (``--env`` on the CLI); 

957 when loaded, **all** of its keys flow through to the container. 

958 

959 Priority (highest wins): extra_env > CLI flags > ``./.env`` (when ``--env``) 

960 > ``~/.augint/.env`` > host ``os.environ`` (allowlisted) > defaults. 

961 

962 GitHub auth defaults to SSO via the ``~/.config/gh`` bind mount. To use a 

963 PAT instead, put ``GH_TOKEN`` in ``.env`` and pass ``--env``. 

964 

965 When *bedrock* is True, ``CLAUDE_CODE_USE_BEDROCK=1`` is injected and 

966 *bedrock_profile* (if set) overrides ``AWS_PROFILE`` so the LLM provider 

967 authenticates with the correct AWS account. 

968 

969 When *openai_profile* is set, the suffixed env vars 

970 ``OPENAI_API_KEY_{NAME}`` and ``OPENAI_ORG_ID_{NAME}`` are resolved from 

971 ``.env`` and injected as ``OPENAI_API_KEY`` / ``OPENAI_ORG_ID``. 

972 

973 When *claude_account* is set (and is not ``default``), the token in 

974 ``CLAUDE_CODE_OAUTH_TOKEN_{NAME}`` is injected as ``CLAUDE_CODE_OAUTH_TOKEN`` 

975 and ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` are left out. The 

976 suffixed per-account tokens are never passed through to the container. 

977 

978 When *claude_login* is True, or the account has no token in ``.env``, 

979 the account's login profile is used instead: ``CLAUDE_CONFIG_DIR`` points 

980 at ``~/.augint/claude-accounts/{name}`` and every credential that would 

981 outrank the login is left out. The host directory is created on demand so 

982 any arbitrary ``--account <name>`` works without pre-configuration. 

983 """ 

984 dotenv = _load_layered_dotenv(project_dir, env_file=env_file) 

985 

986 def _resolve(key: str, default: str = "") -> str: 

987 """Resolve a value: .env > os.environ > default.""" 

988 dotenv_val = dotenv.get(key) 

989 if dotenv_val is not None and dotenv_val != "": 

990 return dotenv_val 

991 return os.environ.get(key, default) 

992 

993 _CONTAINER_BASE_PATH = ( 

994 "/root/.local/bin:/root/.opencode/bin:" 

995 "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" 

996 ) 

997 

998 env: dict[str, str] = { 

999 "PATH": _CONTAINER_BASE_PATH, 

1000 "AWS_PROFILE": aws_profile or _resolve("AWS_PROFILE"), 

1001 "AWS_REGION": aws_region or _resolve("AWS_REGION", "us-east-1"), 

1002 "AWS_PAGER": "", 

1003 "HUSKY": "0", 

1004 "IS_SANDBOX": "1", 

1005 "PRE_COMMIT_HOME": PRE_COMMIT_CACHE_PATH, 

1006 "PI_STUDIO_HOST": "0.0.0.0", # nosec B104 

1007 "PLANNOTATOR_REMOTE": "1", 

1008 "PLANNOTATOR_PORT": "19432", 

1009 "PLANNOTATOR_BROWSER": "echo", 

1010 } 

1011 

1012 # Mirror AWS_REGION to AWS_DEFAULT_REGION so both Node.js SDK paths resolve 

1013 env["AWS_DEFAULT_REGION"] = env["AWS_REGION"] 

1014 

1015 # Isolate UV venvs per-project within the shared cache volume. 

1016 # Overrides Dockerfile default of /root/.cache/uv/venvs/project. 

1017 if project_name: 

1018 env["UV_PROJECT_ENVIRONMENT"] = uv_venv_path(project_name) 

1019 

1020 if bedrock: 

1021 env["CLAUDE_CODE_USE_BEDROCK"] = "1" 

1022 if bedrock_profile: 

1023 env["AWS_PROFILE"] = bedrock_profile 

1024 resolved_bedrock_region = ( 

1025 bedrock_region or _resolve("AWS_BEDROCK_REGION") or env["AWS_REGION"] 

1026 ) 

1027 if resolved_bedrock_region != env["AWS_REGION"]: 

1028 env["AWS_REGION"] = resolved_bedrock_region 

1029 env["AWS_DEFAULT_REGION"] = resolved_bedrock_region 

1030 if bedrock_model: 

1031 env["ANTHROPIC_MODEL"] = bedrock_model 

1032 

1033 if openai_profile: 

1034 suffix = openai_profile.upper() 

1035 key_var = f"OPENAI_API_KEY_{suffix}" 

1036 api_key = dotenv.get(key_var) 

1037 if not api_key: 

1038 raise ValueError( 

1039 f"OpenAI profile '{openai_profile}' requires {key_var} in " 

1040 "~/.augint/.env, or pass --env to load it from ./.env" 

1041 ) 

1042 env["OPENAI_API_KEY"] = api_key 

1043 org_var = f"OPENAI_ORG_ID_{suffix}" 

1044 org_id = dotenv.get(org_var) 

1045 if org_id: 

1046 env["OPENAI_ORG_ID"] = org_id 

1047 

1048 excluded: set[str] = set() 

1049 if claude_account and claude_account.lower() != CLAUDE_DEFAULT_ACCOUNT: 

1050 if bedrock: 

1051 raise ValueError( 

1052 f"Claude account '{claude_account}' cannot be combined with Bedrock " 

1053 "(--aws or claude.provider: aws)" 

1054 ) 

1055 token_var = claude_account_token_var(claude_account) 

1056 token = dotenv.get(token_var) 

1057 if claude_login or not token: 

1058 login_dir = claude_account_login_dir(claude_account) 

1059 login_dir.mkdir(parents=True, exist_ok=True) 

1060 seed_claude_login_profile(login_dir) 

1061 env[CLAUDE_CONFIG_DIR_VAR] = claude_account_config_dir(claude_account) 

1062 excluded.update(CLAUDE_REMOTE_CONTROL_UNSET_VARS) 

1063 else: 

1064 env[CLAUDE_OAUTH_TOKEN_VAR] = token 

1065 excluded.update(CLAUDE_AUTH_OVERRIDE_VARS) 

1066 

1067 for var in _SHARED_ENV_PASSTHROUGH: 

1068 val = _resolve(var) 

1069 if val and var not in excluded: 

1070 env[var] = val 

1071 

1072 # Pass through every var loaded from .env, except keys already populated 

1073 # above (which preserves CLI-flag wins for AWS_PROFILE etc.) and the 

1074 # per-account Claude tokens (only the selected one is injected). 

1075 for key, value in dotenv.items(): 

1076 if ( 

1077 value is not None 

1078 and value != "" 

1079 and key not in env 

1080 and key not in excluded 

1081 and not key.startswith(CLAUDE_ACCOUNT_TOKEN_PREFIX) 

1082 ): 

1083 env[key] = value 

1084 

1085 if extra_env: 

1086 env.update(extra_env) 

1087 

1088 # Mirror AWS_BEARER_TOKEN_BEDROCK <-> BEDROCK_API_KEY so OpenCode and SDKs 

1089 # expecting either variable name work out of the box. 

1090 if env.get("AWS_BEARER_TOKEN_BEDROCK") and not env.get("BEDROCK_API_KEY"): 

1091 env["BEDROCK_API_KEY"] = env["AWS_BEARER_TOKEN_BEDROCK"] 

1092 elif env.get("BEDROCK_API_KEY") and not env.get("AWS_BEARER_TOKEN_BEDROCK"): 

1093 env["AWS_BEARER_TOKEN_BEDROCK"] = env["BEDROCK_API_KEY"] 

1094 

1095 return env 

1096 

1097 

1098def _resolve_env(dotenv: dict[str, str | None], key: str, default: str = "") -> str: 

1099 """Resolve a value: dotenv > os.environ > default.""" 

1100 dotenv_val = dotenv.get(key) 

1101 if dotenv_val is not None and dotenv_val != "": 

1102 return dotenv_val 

1103 return os.environ.get(key, default) 

1104 

1105 

1106def build_n8n_environment( 

1107 env_file: Path | None = None, 

1108 *, 

1109 aws_profile: str = "", 

1110 aws_region: str = "", 

1111) -> dict[str, str]: 

1112 """Build environment variables for the n8n workflow automation container. 

1113 

1114 Loads layered .env files (``~/.augint/.env`` then *env_file*), 

1115 then falls back to host environment variables. 

1116 

1117 Service discovery URLs use internal Docker network hostnames so n8n 

1118 workflows can reference them via ``{{ $env.OLLAMA_BASE_URL }}`` etc. 

1119 """ 

1120 dotenv = _load_layered_dotenv(env_file=env_file) 

1121 

1122 env: dict[str, str] = { 

1123 # Disable secure-cookie so the UI works over plain http://localhost. 

1124 "N8N_SECURE_COOKIE": "false", 

1125 # Service discovery (internal Docker network URLs). 

1126 "OLLAMA_BASE_URL": f"http://{OLLAMA_CONTAINER}:11434", 

1127 "KOKORO_BASE_URL": f"http://{KOKORO_CONTAINER}:8880", 

1128 "WHISPER_BASE_URL": f"http://{WHISPER_CONTAINER}:8000", 

1129 "VOICE_AGENT_BASE_URL": f"http://{VOICE_AGENT_CONTAINER}:8000", 

1130 "WEBUI_BASE_URL": f"http://{WEBUI_CONTAINER}:8080", 

1131 "COMFYUI_BASE_URL": f"http://{COMFYUI_CONTAINER}:8188", 

1132 } 

1133 

1134 # AWS credentials 

1135 aws_prof = aws_profile or _resolve_env(dotenv, "AWS_PROFILE") 

1136 aws_reg = aws_region or _resolve_env(dotenv, "AWS_REGION", "us-east-1") 

1137 if aws_prof: 

1138 env["AWS_PROFILE"] = aws_prof 

1139 env["AWS_REGION"] = aws_reg 

1140 env["AWS_DEFAULT_REGION"] = aws_reg 

1141 

1142 # API keys — only include when non-empty. 

1143 for key in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY"): 

1144 val = _resolve_env(dotenv, key) 

1145 if val: 

1146 env[key] = val 

1147 

1148 if env_file is not None: 

1149 gh_token = _resolve_env(dotenv, "GH_TOKEN") 

1150 if gh_token: 

1151 env["GH_TOKEN"] = gh_token 

1152 env["GITHUB_TOKEN"] = gh_token 

1153 env["GITHUB_MODELS_BASE_URL"] = "https://models.inference.ai.azure.com" 

1154 

1155 return env 

1156 

1157 

1158def build_n8n_mounts( 

1159 workflow_dir: Path | None = None, 

1160) -> list[Mount]: 

1161 """Build the mount list for the n8n container. 

1162 

1163 n8n runs as user ``node`` (UID 1000). Credential directories are mounted 

1164 read-only under ``/home/node/`` so the AWS and GitHub CLIs resolve auth 

1165 the same way the dev container does. 

1166 """ 

1167 from docker.types import Mount 

1168 

1169 home = Path.home() 

1170 

1171 mounts: list[Mount] = [ 

1172 # Persistent data (workflows, credentials DB, settings). 

1173 Mount( 

1174 target="/home/node/.n8n", 

1175 source=N8N_DATA_VOLUME, 

1176 type="volume", 

1177 ), 

1178 ] 

1179 

1180 # Optional credential bind mounts (read-only). 

1181 aws_dir = home / ".aws" 

1182 if aws_dir.exists(): 

1183 mounts.append( 

1184 Mount( 

1185 target="/home/node/.aws", 

1186 source=str(aws_dir), 

1187 type="bind", 

1188 read_only=True, 

1189 ) 

1190 ) 

1191 else: 

1192 logger.debug("Skipping n8n AWS mount (not found): %s", aws_dir) 

1193 

1194 gh_config = _find_gh_config_dir() 

1195 if gh_config is not None: 

1196 mounts.append( 

1197 Mount( 

1198 target="/home/node/.config/gh", 

1199 source=str(gh_config), 

1200 type="bind", 

1201 read_only=True, 

1202 ) 

1203 ) 

1204 

1205 # Starter workflow templates (read-only bind mount). 

1206 if workflow_dir is not None and workflow_dir.is_dir(): 

1207 mounts.append( 

1208 Mount( 

1209 target="/workflows", 

1210 source=str(workflow_dir), 

1211 type="bind", 

1212 read_only=True, 

1213 ) 

1214 ) 

1215 

1216 return mounts