Coverage for src/ai_shell/opencode.py: 88%
434 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"""OpenCode configuration, Bedrock Mantle endpoints, and multi-model routing.
3Manages dynamic generation and non-destructive deep-merging of
4``~/.config/opencode/opencode.json`` for:
51. AWS Bedrock Mantle OpenAI-compatible endpoints (Commercial & GovCloud).
62. Custom OpenAI-compatible endpoints (self-hosted vLLM, SGLang, etc.).
73. Primary agent (``plan``, ``build``) and subagent (``explore``, ``general``)
8 model routing.
94. The launch environment: Claude Code compatibility off, plugins, instructions
10 and MCP servers passed in ``OPENCODE_CONFIG_CONTENT`` (no file is written).
11"""
13from __future__ import annotations
15import base64
16import datetime
17import hashlib
18import hmac
19import json
20import logging
21import os
22import re
23import secrets
24import subprocess
25from dataclasses import dataclass, field
26from pathlib import Path
27from typing import Any
28from urllib.parse import quote
30logger = logging.getLogger(__name__)
32OPENCODE_SCHEMA_URL = "https://opencode.ai/config.json"
33BEDROCK_MANTLE_PROVIDER_ID = "bedrock-mantle"
34BEDROCK_MANTLE_OPENAI_PROVIDER_ID = "bedrock-mantle-openai"
35BEDROCK_RUNTIME_PROVIDER_ID = "bedrock-runtime"
36MANTLE_PROVIDER_IDS: tuple[str, ...] = (
37 BEDROCK_MANTLE_PROVIDER_ID,
38 BEDROCK_MANTLE_OPENAI_PROVIDER_ID,
39 BEDROCK_RUNTIME_PROVIDER_ID,
40)
41# Cross-Region inference profile prefixes (``us.``, ``us-gov.``, ``global.``).
42# A model ID with one of these is served by bedrock-runtime, not bedrock-mantle.
43_INFERENCE_PROFILE_PREFIX = re.compile(r"^(us-gov|us|global|eu|apac|jp|au|ca)\.", re.IGNORECASE)
44OPENAI_COMPATIBLE_NPM = "@ai-sdk/openai-compatible"
46DEFAULT_COMMERCIAL_REGION = "us-east-1"
47DEFAULT_GOVCLOUD_REGION = "us-gov-west-1"
49DEFAULT_BEDROCK_MANTLE_PRIMARY_MODEL = "openai.gpt-5.6-terra"
50DEFAULT_BEDROCK_MANTLE_SUBAGENT_MODEL = "openai.gpt-5.6-luna"
51BEDROCK_MANTLE_DEFAULT_PRIMARY_MODEL = DEFAULT_BEDROCK_MANTLE_PRIMARY_MODEL
52BEDROCK_MANTLE_DEFAULT_SUBAGENT_MODEL = DEFAULT_BEDROCK_MANTLE_SUBAGENT_MODEL
53# Models listed in the OpenCode model picker. Mantle serves gpt-oss on /v1 and
54# GPT-5.x on /openai/v1, and Grok is served by bedrock-runtime, so each list
55# becomes its own provider.
56BEDROCK_MANTLE_DEFAULT_MODELS: tuple[str, ...] = (
57 "openai.gpt-oss-120b",
58 "openai.gpt-oss-20b",
59)
60BEDROCK_MANTLE_OPENAI_DEFAULT_MODELS: tuple[str, ...] = (
61 "openai.gpt-5.6-terra",
62 "openai.gpt-5.6-luna",
63 "openai.gpt-5.4",
64)
65# Base IDs; the Region's inference profile prefix (us. or us-gov.) is added.
66BEDROCK_RUNTIME_DEFAULT_BASE_MODELS: tuple[str, ...] = (
67 "xai.grok-4.7",
68 "xai.grok-4.6",
69)
71PRIMARY_AGENTS: tuple[str, ...] = ("plan", "build")
72SUBAGENTS: tuple[str, ...] = ("explore", "general")
74BEDROCK_BEARER_TOKEN_VAR = "AWS_BEARER_TOKEN_BEDROCK"
75BEDROCK_API_KEY_VAR = "BEDROCK_API_KEY"
76BEDROCK_TOKEN_HOST = "bedrock.amazonaws.com"
77BEDROCK_TOKEN_PREFIX = "bedrock-api-key-"
78BEDROCK_TOKEN_MAX_SECONDS = 43200 # 12 hours, the most AWS allows
80# OpenCode reads Claude Code files unless told not to: ~/.claude/CLAUDE.md,
81# a project CLAUDE.md, and skills in ~/.claude/skills, ~/.agents/skills and the
82# project's .claude/ and .agents/ directories. These flags turn all of that
83# off, so only AGENTS.md and OpenCode's own config directories are read.
84# ``opencode.claude_compat: true`` leaves them unset.
85OPENCODE_NO_CLAUDE_ENV: dict[str, str] = {
86 "OPENCODE_DISABLE_CLAUDE_CODE": "1",
87 "OPENCODE_DISABLE_EXTERNAL_SKILLS": "1",
88}
90# Plugins and instruction files every launch gets unless ``opencode.plugins``
91# or ``opencode.instructions`` is set (``[]`` turns them off). Pinned, so a new
92# upstream release changes nothing until it is bumped here.
93PLANNOTATOR_PLUGIN = "@plannotator/opencode@0.28.67"
94OPENCODE_PTY_PLUGIN = "opencode-pty@0.4.0"
95DEFAULT_OPENCODE_PLUGINS: tuple[str, ...] = (PLANNOTATOR_PLUGIN, OPENCODE_PTY_PLUGIN)
96# opencode-shell-strategy is an instruction file, not a plugin. The URL names a
97# commit, so the text cannot change under us.
98SHELL_STRATEGY_INSTRUCTIONS_URL = (
99 "https://raw.githubusercontent.com/JRedeker/opencode-shell-strategy/"
100 "1303f24df1649202834e052f1d66560ed186e413/shell_strategy.md"
101)
102DEFAULT_OPENCODE_INSTRUCTIONS: tuple[str, ...] = (SHELL_STRATEGY_INSTRUCTIONS_URL,)
103PLANNOTATOR_CONTAINER_PORT = 19432 # PLANNOTATOR_PORT in build_dev_environment
105OPENCODE_SERVER_PASSWORD_ENV = "OPENCODE_SERVER_PASSWORD"
106OPENCODE_SERVER_USERNAME_ENV = "OPENCODE_SERVER_USERNAME"
107OPENCODE_DEFAULT_USERNAME = "opencode"
110def opencode_server_password_path(home: Path | None = None) -> Path:
111 """Host file that holds the generated password for ``opencode web`` / ``serve``."""
112 return (home or Path.home()) / ".augint" / "opencode" / "server-password"
115def opencode_server_password(home: Path | None = None) -> str:
116 """The saved server password, made and saved (mode 600) on first use.
118 ``opencode web`` and ``serve`` listen on every host interface, so without a
119 password anyone who can reach the port can run the agent and its tools.
120 """
121 path = opencode_server_password_path(home)
122 if path.is_file():
123 value = path.read_text(encoding="utf-8").strip()
124 if value:
125 return value
126 value = secrets.token_urlsafe(24)
127 path.parent.mkdir(parents=True, exist_ok=True)
128 path.write_text(value + "\n", encoding="utf-8")
129 try:
130 path.chmod(0o600)
131 except OSError: # pragma: no cover - Windows ignores POSIX modes
132 pass
133 return value
136_BUILTIN_PROVIDERS = frozenset(
137 {
138 BEDROCK_MANTLE_PROVIDER_ID,
139 BEDROCK_MANTLE_OPENAI_PROVIDER_ID,
140 "ollama",
141 "openai",
142 "anthropic",
143 "amazon-bedrock",
144 "google",
145 "azure",
146 "openrouter",
147 }
148)
151@dataclass
152class CustomEndpoint:
153 """A custom OpenAI-compatible provider endpoint for OpenCode."""
155 name: str
156 base_url: str
157 api_key_env: str = ""
158 models: list[str] = field(default_factory=list)
159 display_name: str = ""
162def sanitize_provider_id(name: str) -> str:
163 """Normalize a custom endpoint name into a clean OpenCode provider ID."""
164 cleaned = re.sub(r"[^a-zA-Z0-9-]+", "-", name.strip()).strip("-")
165 return cleaned.lower() or "custom"
168def parse_endpoint_spec(spec: str, default_index: int = 1) -> CustomEndpoint:
169 """Parse a CLI ``--endpoint`` specification into a :class:`CustomEndpoint`.
171 Accepted formats:
172 - ``https://vllm.internal/v1`` (auto-named ``custom`` or ``custom-N``)
173 - ``vllm=http://host.docker.internal:8000/v1``
174 - ``vllm=http://host.docker.internal:8000/v1,model=Qwen/Qwen2.5-Coder-32B,api_key_env=VLLM_API_KEY``
175 - ``url=http://...,name=vllm,model=...,key_env=...``
176 """
177 raw = spec.strip()
178 if not raw:
179 raise ValueError("Endpoint specification cannot be empty")
181 parts = [p.strip() for p in raw.split(",") if p.strip()]
182 first = parts[0]
184 name = "custom" if default_index == 1 else f"custom-{default_index}"
185 base_url = ""
186 api_key_env = ""
187 display_name = ""
188 models: list[str] = []
190 if "://" in first:
191 eq_pos = first.find("=")
192 scheme_pos = first.find("://")
193 if eq_pos != -1 and eq_pos < scheme_pos:
194 lhs, rhs = first.split("=", 1)
195 if lhs.strip().lower() in ("url", "base_url", "baseurl"):
196 base_url = rhs.strip()
197 else:
198 name = sanitize_provider_id(lhs)
199 base_url = rhs.strip()
200 else:
201 base_url = first
202 elif "=" in first:
203 lhs, rhs = first.split("=", 1)
204 if not rhs.strip():
205 raise ValueError(f"Endpoint '{lhs.strip()}' requires a non-empty base URL")
206 raise ValueError(
207 f"Invalid endpoint specification '{spec}': base URL must start with http:// or https://"
208 )
209 else:
210 raise ValueError(
211 f"Invalid endpoint specification '{spec}': first segment must contain a URL "
212 "(e.g. 'vllm=http://host.docker.internal:8000/v1')"
213 )
215 for item in parts[1:]:
216 if "=" not in item:
217 raise ValueError(
218 f"Invalid --endpoint option '{item}' in '{spec}': expected key=value "
219 "(supported keys: name, model, api_key_env, display_name)"
220 )
221 k, v = (s.strip() for s in item.split("=", 1))
222 key_lower = k.lower()
223 if key_lower in ("name", "id", "provider"):
224 name = sanitize_provider_id(v)
225 elif key_lower in ("display_name", "title", "label"):
226 display_name = v
227 elif key_lower in ("model", "models"):
228 for m in re.split(r"[;|]", v):
229 if m.strip() and m.strip() not in models:
230 models.append(m.strip())
231 elif key_lower in ("api_key_env", "key_env", "env", "api_key"):
232 api_key_env = v
233 else:
234 raise ValueError(
235 f"Unsupported option '{k}' in '{spec}' (supported: name, model, api_key_env, display_name)"
236 )
238 if not base_url:
239 raise ValueError(f"Endpoint '{name}' requires a non-empty base URL")
241 return CustomEndpoint(
242 name=name,
243 base_url=base_url.rstrip("/"),
244 api_key_env=api_key_env,
245 models=models,
246 display_name=display_name,
247 )
250def resolve_aws_partition(partition: str = "", region: str = "") -> str:
251 """Resolve the AWS partition to ``'commercial'`` or ``'govcloud'``.
253 When *partition* is omitted, infers ``'govcloud'`` when *region* starts
254 with ``us-gov-`` and ``'commercial'`` otherwise.
255 """
256 norm = partition.strip().lower()
257 if norm in ("", "auto"):
258 if region.strip().lower().startswith("us-gov-"):
259 return "govcloud"
260 return "commercial"
261 if norm in ("commercial", "aws", "standard"):
262 return "commercial"
263 if norm in ("govcloud", "aws-us-gov", "gov", "us-gov"):
264 return "govcloud"
265 raise ValueError(
266 f"Unsupported AWS partition '{partition}': expected 'commercial' or 'govcloud'"
267 )
270def resolve_bedrock_mantle_region(region: str = "", partition: str = "") -> str:
271 """Resolve the AWS region for Bedrock Mantle endpoints.
273 Defaults cleanly to ``us-gov-west-1`` for ``govcloud`` and ``us-east-1``
274 for ``commercial``. Validates that an explicit region matches the
275 requested partition.
276 """
277 clean_region = region.strip().lower()
278 resolved_partition = resolve_aws_partition(partition, clean_region)
280 if clean_region:
281 if resolved_partition == "govcloud" and not clean_region.startswith("us-gov-"):
282 raise ValueError(
283 f"Region '{clean_region}' is not a GovCloud region (expected 'us-gov-*')"
284 )
285 if resolved_partition == "commercial" and clean_region.startswith("us-gov-"):
286 raise ValueError(
287 f"AWS partition 'commercial' cannot use GovCloud region '{clean_region}'"
288 )
289 return clean_region
291 if resolved_partition == "govcloud":
292 return DEFAULT_GOVCLOUD_REGION
293 return DEFAULT_COMMERCIAL_REGION
296def bedrock_mantle_base_url(region: str = "", partition: str = "") -> str:
297 """Construct the Bedrock Mantle base URL for most models (``/v1`` route).
299 Returns ``https://bedrock-mantle.<region>.api.aws/v1``. gpt-oss and most
300 other models are served here.
301 """
302 resolved_region = resolve_bedrock_mantle_region(region=region, partition=partition)
303 return f"https://bedrock-mantle.{resolved_region}.api.aws/v1"
306def bedrock_mantle_openai_base_url(region: str = "", partition: str = "") -> str:
307 """Construct the Bedrock Mantle base URL for OpenAI GPT models (``/openai/v1`` route).
309 Returns ``https://bedrock-mantle.<region>.api.aws/openai/v1``. AWS serves
310 GPT-5.x on this route only; a request on the wrong route is rejected with
311 "model isn't supported on this route".
312 """
313 resolved_region = resolve_bedrock_mantle_region(region=region, partition=partition)
314 return f"https://bedrock-mantle.{resolved_region}.api.aws/openai/v1"
317def bedrock_runtime_openai_base_url(region: str = "", partition: str = "") -> str:
318 """Construct the bedrock-runtime OpenAI-compatible base URL.
320 Returns ``https://bedrock-runtime.<region>.amazonaws.com/openai/v1``.
321 Grok 4.7 is served only here, through a cross-Region inference profile.
322 """
323 resolved_region = resolve_bedrock_mantle_region(region=region, partition=partition)
324 return f"https://bedrock-runtime.{resolved_region}.amazonaws.com/openai/v1"
327def inference_profile_prefix(region: str) -> str:
328 """Return the geo inference profile prefix for *region*: ``us-gov`` or ``us``."""
329 return "us-gov" if region.strip().lower().startswith("us-gov-") else "us"
332def is_mantle_openai_route_model(model_id: str) -> bool:
333 """Return True when Bedrock Mantle serves *model_id* on the ``/openai/v1`` route.
335 OpenAI GPT models (``openai.gpt-5.4``, ``openai.gpt-5.6-*``) use
336 ``/openai/v1``. The open-weight ``openai.gpt-oss-*`` models and the other
337 providers' models use ``/v1``.
338 """
339 bare = model_id.strip().lower()
340 return bare.startswith("openai.") and not bare.startswith("openai.gpt-oss")
343def is_bedrock_runtime_model(model_id: str) -> bool:
344 """Return True when ai-shell sends *model_id* to bedrock-runtime.
346 That is any inference profile ID (``us.``, ``us-gov.``, ``global.`` ...)
347 and any xAI Grok model. Grok 4.7 is not on bedrock-mantle at all, and
348 Grok 4.6 is on bedrock-mantle in us-gov-east-1 but not us-gov-west-1.
349 """
350 bare = model_id.strip().lower()
351 return bool(_INFERENCE_PROFILE_PREFIX.match(bare)) or bare.startswith("xai.")
354def mantle_provider_for_model(model_id: str) -> str:
355 """Return the OpenCode provider ID that serves the Bedrock model *model_id*."""
356 if is_bedrock_runtime_model(model_id):
357 return BEDROCK_RUNTIME_PROVIDER_ID
358 if is_mantle_openai_route_model(model_id):
359 return BEDROCK_MANTLE_OPENAI_PROVIDER_ID
360 return BEDROCK_MANTLE_PROVIDER_ID
363def with_inference_profile(model_id: str, region: str) -> str:
364 """Add the Region's geo prefix to a bare bedrock-runtime model ID."""
365 clean = model_id.strip()
366 if _INFERENCE_PROFILE_PREFIX.match(clean):
367 return clean
368 return f"{inference_profile_prefix(region)}.{clean}"
371def _bedrock_credentials_via_botocore(profile: str = "") -> tuple[str, str, str] | None:
372 """Return ``(access_key, secret_key, session_token)`` from botocore, if it is installed."""
373 try:
374 import botocore.session # type: ignore[import-not-found,import-untyped]
375 except ImportError:
376 return None
377 try:
378 session = botocore.session.Session(profile=profile or None)
379 creds = session.get_credentials()
380 if creds is None:
381 return None
382 frozen = creds.get_frozen_credentials()
383 except Exception: # noqa: BLE001 - any botocore failure means "no host credentials"
384 logger.debug("botocore could not load credentials for profile %r", profile)
385 return None
386 if not frozen.access_key or not frozen.secret_key:
387 return None
388 return frozen.access_key, frozen.secret_key, frozen.token or ""
391def _bedrock_credentials_via_aws_cli(profile: str = "") -> tuple[str, str, str] | None:
392 """Return credentials from ``aws configure export-credentials`` on the host."""
393 aws_cmd = ["aws", "configure", "export-credentials", "--format", "process"]
394 if profile:
395 aws_cmd.extend(["--profile", profile])
396 try:
397 res = subprocess.run(aws_cmd, capture_output=True, text=True, timeout=15)
398 except (OSError, subprocess.SubprocessError):
399 logger.debug("Host AWS CLI unavailable")
400 return None
401 if res.returncode != 0 or not res.stdout.strip():
402 return None
403 try:
404 data = json.loads(res.stdout)
405 except ValueError:
406 return None
407 access_key = str(data.get("AccessKeyId") or "")
408 secret_key = str(data.get("SecretAccessKey") or "")
409 if not access_key or not secret_key:
410 return None
411 return access_key, secret_key, str(data.get("SessionToken") or "")
414def _bedrock_token_in_container(container_name: str, profile: str, region: str) -> str | None:
415 """Generate the token inside the dev container with ``aws-bedrock-token-generator``."""
416 script = (
417 "import os; "
418 "from aws_bedrock_token_generator import provide_token; "
419 "print(provide_token(region=os.environ['AWS_REGION']))"
420 )
421 cmd = ["docker", "exec"]
422 if profile:
423 cmd.extend(["-e", f"AWS_PROFILE={profile}"])
424 cmd.extend(["-e", f"AWS_REGION={region}", "-e", f"AWS_DEFAULT_REGION={region}"])
425 cmd.extend([container_name, "python3", "-c", script])
426 try:
427 res = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
428 except (OSError, subprocess.SubprocessError):
429 logger.debug("In-container Bedrock token generator unavailable")
430 return None
431 if res.returncode != 0 or not res.stdout.strip():
432 return None
433 token = res.stdout.strip().splitlines()[-1].strip()
434 return token if token.startswith(BEDROCK_TOKEN_PREFIX) else None
437def generate_bedrock_bearer_token(
438 *,
439 profile: str = "",
440 region: str = "us-east-1",
441 container_name: str | None = None,
442) -> str | None:
443 """Generate a short-term Bedrock API key (bearer token) from the active AWS profile.
445 The token is the one ``aws_bedrock_token_generator.provide_token`` makes: a
446 SigV4 presigned ``CallWithBearerToken`` request for *region*. It lasts
447 12 hours, or less when the AWS session ends sooner.
449 Credential sources, in order:
450 1. botocore on the host, when it is installed.
451 2. ``aws-bedrock-token-generator`` inside the dev container (``~/.aws`` is
452 bind-mounted there, so an SSO login on the host works).
453 3. ``aws configure export-credentials`` from the host AWS CLI v2.
454 """
455 creds = _bedrock_credentials_via_botocore(profile)
456 if creds:
457 return _stdlib_sigv4_bedrock_token(
458 access_key=creds[0], secret_key=creds[1], session_token=creds[2], region=region
459 )
461 if container_name:
462 token = _bedrock_token_in_container(container_name, profile, region)
463 if token:
464 return token
466 creds = _bedrock_credentials_via_aws_cli(profile)
467 if creds:
468 return _stdlib_sigv4_bedrock_token(
469 access_key=creds[0], secret_key=creds[1], session_token=creds[2], region=region
470 )
471 return None
474def _stdlib_sigv4_bedrock_token(
475 *,
476 access_key: str,
477 secret_key: str,
478 session_token: str = "",
479 region: str = "us-east-1",
480 expires_in: int = BEDROCK_TOKEN_MAX_SECONDS,
481 now: datetime.datetime | None = None,
482) -> str:
483 """Create a short-term Bedrock API key with the Python standard library only.
485 The output is the same as ``aws_bedrock_token_generator.provide_token``
486 (version 1.1.0): a SigV4 query-signed ``POST https://bedrock.amazonaws.com/
487 ?Action=CallWithBearerToken`` for *region* with an empty body, prefixed ``bedrock-api-key-`` and suffixed ``&Version=1`` before base64.
488 """
489 if expires_in <= 0 or expires_in > BEDROCK_TOKEN_MAX_SECONDS:
490 raise ValueError("Bedrock token expiry must be between 1 second and 12 hours")
492 stamp = now or datetime.datetime.now(datetime.UTC)
493 amz_date = stamp.strftime("%Y%m%dT%H%M%SZ")
494 datestamp = stamp.strftime("%Y%m%d")
495 host = BEDROCK_TOKEN_HOST
496 service = "bedrock"
497 credential_scope = f"{datestamp}/{region}/{service}/aws4_request"
499 operation_params: list[tuple[str, str]] = [("Action", "CallWithBearerToken")]
500 auth_params: list[tuple[str, str]] = [
501 ("X-Amz-Algorithm", "AWS4-HMAC-SHA256"),
502 ("X-Amz-Credential", f"{access_key}/{credential_scope}"),
503 ("X-Amz-Date", amz_date),
504 ("X-Amz-Expires", str(expires_in)),
505 ("X-Amz-SignedHeaders", "host"),
506 ]
507 if session_token:
508 auth_params.append(("X-Amz-Security-Token", session_token))
510 def _encode(pairs: list[tuple[str, str]]) -> str:
511 return "&".join(f"{quote(k, safe='-_.~')}={quote(v, safe='-_.~')}" for k, v in pairs)
513 canonical_querystring = _encode(sorted(operation_params + auth_params))
514 canonical_request = "\n".join(
515 [
516 "POST",
517 "/",
518 canonical_querystring,
519 f"host:{host}\n",
520 "host",
521 hashlib.sha256(b"").hexdigest(),
522 ]
523 )
524 string_to_sign = "\n".join(
525 [
526 "AWS4-HMAC-SHA256",
527 amz_date,
528 credential_scope,
529 hashlib.sha256(canonical_request.encode("utf-8")).hexdigest(),
530 ]
531 )
533 def _sign(key: bytes, msg: str) -> bytes:
534 return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
536 k_date = _sign(("AWS4" + secret_key).encode("utf-8"), datestamp)
537 k_region = _sign(k_date, region)
538 k_service = _sign(k_region, service)
539 k_signing = _sign(k_service, "aws4_request")
540 signature = hmac.new(k_signing, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
542 presigned = (
543 f"{host}/?{_encode(operation_params)}&{_encode(auth_params)}"
544 f"&X-Amz-Signature={signature}&Version=1"
545 )
546 encoded = base64.b64encode(presigned.encode("utf-8")).decode("ascii")
547 return f"{BEDROCK_TOKEN_PREFIX}{encoded}"
550_generate_token_from_credentials = _stdlib_sigv4_bedrock_token
553def resolve_bedrock_bearer_token(
554 exec_env: dict[str, str],
555 *,
556 profile: str = "",
557 region: str = "us-east-1",
558 generate_if_missing: bool = True,
559 container_name: str | None = None,
560) -> str | None:
561 """Ensure ``AWS_BEARER_TOKEN_BEDROCK`` (and ``BEDROCK_API_KEY``) in *exec_env*.
563 1. Checks *exec_env* and ``os.environ`` for ``AWS_BEARER_TOKEN_BEDROCK`` or
564 ``BEDROCK_API_KEY``.
565 2. If missing and *generate_if_missing* is True, attempts to generate a
566 short-term token using the active AWS profile.
567 3. Populates both ``AWS_BEARER_TOKEN_BEDROCK`` and ``BEDROCK_API_KEY`` in
568 *exec_env* when a token is resolved.
569 """
570 token = (
571 exec_env.get(BEDROCK_BEARER_TOKEN_VAR)
572 or exec_env.get(BEDROCK_API_KEY_VAR)
573 or os.environ.get(BEDROCK_BEARER_TOKEN_VAR)
574 or os.environ.get(BEDROCK_API_KEY_VAR)
575 )
576 if not token and generate_if_missing:
577 effective_profile = profile or exec_env.get("AWS_PROFILE", "")
578 effective_region = region or exec_env.get("AWS_REGION", "us-east-1")
579 token = generate_bedrock_bearer_token(
580 profile=effective_profile,
581 region=effective_region,
582 container_name=container_name,
583 )
585 if token:
586 exec_env[BEDROCK_BEARER_TOKEN_VAR] = token
587 exec_env[BEDROCK_API_KEY_VAR] = token
588 return token
589 return None
592def _split_qualified_model(
593 model_id: str,
594 default_provider: str,
595 known_providers: set[str] | None = None,
596) -> tuple[str, str, str]:
597 """Normalize *model_id* into ``(qualified_model, provider_id, bare_model_id)``."""
598 clean = model_id.strip()
599 providers = set(_BUILTIN_PROVIDERS)
600 if known_providers:
601 providers.update(known_providers)
602 if default_provider:
603 providers.add(default_provider)
605 if "/" in clean:
606 prefix, rest = clean.split("/", 1)
607 if prefix in providers:
608 return clean, prefix, rest
610 if default_provider:
611 return f"{default_provider}/{clean}", default_provider, clean
612 return clean, "", clean
615def qualify_model_id(
616 model_id: str,
617 default_provider: str,
618 known_providers: set[str] | None = None,
619) -> str:
620 """Return ``<provider>/<model>`` for *model_id*, preserving HuggingFace ``Org/Model`` IDs."""
621 qualified, _, _ = _split_qualified_model(model_id, default_provider, known_providers)
622 return qualified
625def _route_mantle_model(
626 qualified: str, provider: str, bare: str, region: str = ""
627) -> tuple[str, str, str]:
628 """Move a Bedrock model to the provider that serves it.
630 A bedrock-runtime model also gets the Region's inference profile prefix,
631 so ``xai.grok-4.7`` becomes ``us-gov.xai.grok-4.7`` in GovCloud.
632 """
633 if provider in MANTLE_PROVIDER_IDS and bare:
634 routed = mantle_provider_for_model(bare)
635 if routed == BEDROCK_RUNTIME_PROVIDER_ID and region:
636 bare = with_inference_profile(bare, region)
637 if routed != provider or f"{routed}/{bare}" != qualified:
638 return f"{routed}/{bare}", routed, bare
639 return qualified, provider, bare
642def _drop_misrouted_mantle_models(config: dict[str, Any]) -> None:
643 """Remove Mantle model entries listed under the provider whose route rejects them.
645 Older ai-shell versions put every Mantle model under one ``bedrock-mantle``
646 provider on ``/openai/v1``. A deep merge cannot delete those entries, so
647 they are removed here.
648 """
649 providers = config.get("provider")
650 if not isinstance(providers, dict):
651 return
652 for provider_id in MANTLE_PROVIDER_IDS:
653 entry = providers.get(provider_id)
654 models = entry.get("models") if isinstance(entry, dict) else None
655 if not isinstance(models, dict):
656 continue
657 for model_id in list(models):
658 if mantle_provider_for_model(model_id) != provider_id:
659 del models[model_id]
662def deep_merge_dict(base: dict[str, Any], patch: dict[str, Any]) -> dict[str, Any]:
663 """Recursively merge *patch* into a copy of *base* without clobbering sibling keys."""
664 merged: dict[str, Any] = dict(base)
665 for key, val in patch.items():
666 if isinstance(val, dict) and isinstance(merged.get(key), dict):
667 merged[key] = deep_merge_dict(merged[key], val)
668 else:
669 merged[key] = val
670 return merged
673def build_opencode_config_patch(
674 *,
675 use_bedrock_mantle: bool = False,
676 bedrock_region: str = "",
677 aws_region: str = "",
678 aws_partition: str = "",
679 custom_endpoints: list[CustomEndpoint] | None = None,
680 primary_model: str = "",
681 subagent_model: str = "",
682 default_provider: str = "",
683) -> dict[str, Any]:
684 """Build the ``opencode.json`` configuration dictionary to merge.
686 - When Bedrock is active, configures three ``@ai-sdk/openai-compatible``
687 providers with ``{env:AWS_BEARER_TOKEN_BEDROCK}``: ``bedrock-mantle`` on
688 ``https://bedrock-mantle.<region>.api.aws/v1`` (gpt-oss and most models),
689 ``bedrock-mantle-openai`` on ``.../openai/v1`` (GPT-5.x), and
690 ``bedrock-runtime`` on ``https://bedrock-runtime.<region>.amazonaws.com/openai/v1``
691 (Grok and any inference profile ID). A model is always routed to the
692 provider that serves it.
693 - Configures each entry in *custom_endpoints* under ``provider[<name>]`` using
694 ``@ai-sdk/openai-compatible``.
695 - Routes primary agents (``plan``, ``build``) to *primary_model* and
696 subagents (``explore``, ``general``) to *subagent_model*.
697 """
698 effective_region_arg = bedrock_region or aws_region
699 mantle_active = bool(use_bedrock_mantle or bedrock_region)
701 endpoints = list(custom_endpoints or [])
702 known_providers = {ep.name for ep in endpoints}
703 if mantle_active:
704 known_providers.update(MANTLE_PROVIDER_IDS)
706 resolved_default_provider = default_provider.strip()
707 if not resolved_default_provider:
708 if mantle_active:
709 resolved_default_provider = BEDROCK_MANTLE_PROVIDER_ID
710 elif endpoints:
711 resolved_default_provider = endpoints[0].name
713 effective_primary = primary_model.strip()
714 if not effective_primary:
715 if mantle_active:
716 effective_primary = DEFAULT_BEDROCK_MANTLE_PRIMARY_MODEL
717 elif endpoints and endpoints[0].models:
718 effective_primary = endpoints[0].models[0]
720 effective_subagent = subagent_model.strip()
721 if not effective_subagent:
722 if mantle_active:
723 effective_subagent = DEFAULT_BEDROCK_MANTLE_SUBAGENT_MODEL
724 elif effective_primary:
725 effective_subagent = effective_primary
727 providers_patch: dict[str, Any] = {}
728 resolved_region = ""
730 if mantle_active:
731 resolved_region = resolve_bedrock_mantle_region(
732 region=effective_region_arg, partition=aws_partition
733 )
734 api_key = f"{{env:{BEDROCK_BEARER_TOKEN_VAR}}}"
735 providers_patch[BEDROCK_MANTLE_PROVIDER_ID] = {
736 "npm": OPENAI_COMPATIBLE_NPM,
737 "name": f"Amazon Bedrock Mantle ({resolved_region})",
738 "options": {
739 "baseURL": bedrock_mantle_base_url(region=resolved_region, partition=aws_partition),
740 "apiKey": api_key,
741 },
742 "models": {m: {"name": m} for m in BEDROCK_MANTLE_DEFAULT_MODELS},
743 }
744 providers_patch[BEDROCK_MANTLE_OPENAI_PROVIDER_ID] = {
745 "npm": OPENAI_COMPATIBLE_NPM,
746 "name": f"Amazon Bedrock Mantle OpenAI GPT ({resolved_region})",
747 "options": {
748 "baseURL": bedrock_mantle_openai_base_url(
749 region=resolved_region, partition=aws_partition
750 ),
751 "apiKey": api_key,
752 },
753 "models": {m: {"name": m} for m in BEDROCK_MANTLE_OPENAI_DEFAULT_MODELS},
754 }
755 runtime_models = [
756 with_inference_profile(m, resolved_region) for m in BEDROCK_RUNTIME_DEFAULT_BASE_MODELS
757 ]
758 providers_patch[BEDROCK_RUNTIME_PROVIDER_ID] = {
759 "npm": OPENAI_COMPATIBLE_NPM,
760 "name": f"Amazon Bedrock Runtime, Grok ({resolved_region})",
761 "options": {
762 "baseURL": bedrock_runtime_openai_base_url(
763 region=resolved_region, partition=aws_partition
764 ),
765 "apiKey": api_key,
766 },
767 "models": {m: {"name": m} for m in runtime_models},
768 }
770 for ep in endpoints:
771 options: dict[str, Any] = {"baseURL": ep.base_url}
772 if ep.api_key_env:
773 options["apiKey"] = f"{{env:{ep.api_key_env}}}"
774 ep_models: dict[str, dict[str, str]] = {m: {"name": m} for m in ep.models if m}
775 providers_patch[ep.name] = {
776 "npm": OPENAI_COMPATIBLE_NPM,
777 "name": ep.display_name or ep.name,
778 "options": options,
779 "models": ep_models,
780 }
782 patch: dict[str, Any] = {}
783 agent_patch: dict[str, Any] = {}
785 if effective_primary:
786 qual_primary, prim_prov, prim_bare = _route_mantle_model(
787 *_split_qualified_model(effective_primary, resolved_default_provider, known_providers),
788 region=resolved_region,
789 )
790 patch["model"] = qual_primary
791 for agent_name in PRIMARY_AGENTS:
792 agent_patch[agent_name] = {"model": qual_primary}
793 if prim_prov and prim_prov in providers_patch and prim_bare:
794 providers_patch[prim_prov].setdefault("models", {})[prim_bare] = {"name": prim_bare}
796 if effective_subagent:
797 qual_sub, sub_prov, sub_bare = _route_mantle_model(
798 *_split_qualified_model(effective_subagent, resolved_default_provider, known_providers),
799 region=resolved_region,
800 )
801 patch["small_model"] = qual_sub
802 for agent_name in SUBAGENTS:
803 agent_patch[agent_name] = {"model": qual_sub}
804 if sub_prov and sub_prov in providers_patch and sub_bare:
805 providers_patch[sub_prov].setdefault("models", {})[sub_bare] = {"name": sub_bare}
807 if providers_patch:
808 patch["provider"] = providers_patch
809 if agent_patch:
810 patch["agent"] = agent_patch
812 return patch
815def sync_opencode_config(
816 *,
817 config_path: Path | None = None,
818 use_bedrock_mantle: bool = False,
819 bedrock_region: str = "",
820 aws_region: str = "",
821 aws_partition: str = "",
822 custom_endpoints: list[CustomEndpoint] | None = None,
823 primary_model: str = "",
824 subagent_model: str = "",
825 default_provider: str = "",
826) -> dict[str, Any]:
827 """Deep-merge provider and agent routing settings into ``opencode.json``.
829 Never overwrites unrelated user settings (e.g. ``theme``, ``keybinds``,
830 ``mcp``, ``plugin``, or other providers/agent attributes).
832 Returns the merged configuration dict.
833 """
834 target = config_path or (Path.home() / ".config" / "opencode" / "opencode.json")
835 target.parent.mkdir(parents=True, exist_ok=True)
837 existing: dict[str, Any] = {}
838 if target.is_file():
839 try:
840 loaded = json.loads(target.read_text(encoding="utf-8"))
841 if isinstance(loaded, dict):
842 existing = loaded
843 except (OSError, json.JSONDecodeError) as exc:
844 logger.warning("Could not parse existing %s, starting fresh merge: %s", target, exc)
846 patch = build_opencode_config_patch(
847 use_bedrock_mantle=use_bedrock_mantle,
848 bedrock_region=bedrock_region,
849 aws_region=aws_region,
850 aws_partition=aws_partition,
851 custom_endpoints=custom_endpoints,
852 primary_model=primary_model,
853 subagent_model=subagent_model,
854 default_provider=default_provider,
855 )
857 merged = deep_merge_dict(existing, patch)
858 _drop_misrouted_mantle_models(merged)
859 merged.setdefault("$schema", OPENCODE_SCHEMA_URL)
860 target.write_text(json.dumps(merged, indent=2) + "\n", encoding="utf-8")
861 return merged
864def opencode_launch_env(
865 *,
866 claude_compat: bool = False,
867 plugins: list[str] | tuple[str, ...] = (),
868 instructions: list[str] | tuple[str, ...] = (),
869 mcp: dict[str, Any] | None = None,
870) -> dict[str, str]:
871 """Environment for an OpenCode launch.
873 Without *claude_compat* the Claude Code compatibility flags are set (see
874 :data:`OPENCODE_NO_CLAUDE_ENV`). *plugins*, *instructions* and *mcp* go in
875 ``OPENCODE_CONFIG_CONTENT``, which OpenCode merges over its config files:
876 plugin and instruction lists are joined, so the user's own entries stay.
877 Nothing is written to ``opencode.json`` or to the project.
878 """
879 env: dict[str, str] = {} if claude_compat else dict(OPENCODE_NO_CLAUDE_ENV)
880 content: dict[str, Any] = {}
881 if plugins:
882 content["plugin"] = list(plugins)
883 if instructions:
884 content["instructions"] = list(instructions)
885 if mcp:
886 content["mcp"] = mcp
887 if content:
888 env["OPENCODE_CONFIG_CONTENT"] = json.dumps(content, separators=(",", ":"))
889 return env
892def opencode_local_mcp(command: str, args: list[str] | tuple[str, ...] = ()) -> dict[str, Any]:
893 """An OpenCode ``mcp`` entry for a local (stdio) server."""
894 return {"type": "local", "command": [command, *args], "enabled": True}
897def _is_skills_link(path: Path, targets: tuple[tuple[str, ...], ...]) -> bool:
898 """True when *path* is a symlink whose target ends with one of *targets*."""
899 if not path.is_symlink():
900 return False
901 try:
902 parts = Path(os.readlink(path)).parts
903 except OSError:
904 return False
905 return any(parts[-len(t) :] == t for t in targets)
908def remove_skills_bridges(
909 project_dir: Path | None = None,
910 home_dir: Path | None = None,
911) -> list[Path]:
912 """Remove the skills symlinks that older ai-shell versions created.
914 Older versions linked ``~/.config/opencode/skills`` to ``~/.agents/skills``
915 or ``~/.claude/skills``, and ``<project>/.opencode/skills`` to
916 ``../.agents/skills``. OpenCode always reads its config directories, so
917 those links loaded Claude Code skills even with compatibility off. Only
918 a symlink with one of those targets is removed; a real directory, or a
919 link the user pointed elsewhere, is left alone.
921 Returns the removed paths.
922 """
923 home = home_dir or Path.home()
924 candidates: list[tuple[Path, tuple[tuple[str, ...], ...]]] = [
925 (
926 home / ".config" / "opencode" / "skills",
927 ((".agents", "skills"), (".claude", "skills")),
928 )
929 ]
930 if project_dir is not None:
931 candidates.append((project_dir / ".opencode" / "skills", (("..", ".agents", "skills"),)))
933 removed: list[Path] = []
934 for link, targets in candidates:
935 if _is_skills_link(link, targets):
936 try:
937 link.unlink()
938 removed.append(link)
939 except OSError as exc:
940 logger.debug("Could not remove %s: %s", link, exc)
941 return removed