Resolve configured host models during native installation

Read OpenCode V2's resolved default Model.Info through its authenticated CLI API from HOME when saved profile fields are missing. Preserve valid saved models, explicit --model and unrelated settings. Record the selected stage model in the native server environment so web starters have an actual default.

Run the existing read-only model picker inside ./install when a terminal needs a choice; fail noninteractive or cancelled/incomplete setup before claiming ready or starting services. Do not parse JSONC, open login flows, create sessions or run inference. Document the one-step configuration path.

Checks: 61 mocked native installer/lifecycle tests, 8 entrypoint tests, sh -n install install.sh, git diff --check. API/schema checked against official OpenCode V2 documentation. No operator CLI/service/model calls, live install, restart, deployment or native Linux verification.
This commit is contained in:
2026-10-20 21:56:04 +01:00
parent d3c7e6e784
commit da6daa9db5
3 changed files with 218 additions and 22 deletions
+58 -11
View File
@@ -156,7 +156,7 @@ class Setup:
if not isinstance(value, str) or len(value) > 501 or "/" not in value:
return False
provider, model = value.split("/", 1)
if not provider or not model:
if not provider or not model or value in ("default/default", "provider/model"):
return False
return all(char in cls.MODEL_CHARS for char in value)
@@ -174,16 +174,45 @@ class Setup:
return {}
return data if isinstance(data, dict) else {}
def configure_harnesses(self, harness, model=""):
def opencode_default_model(self, executable):
"""Read V2's resolved Model.Info, with OpenCode's own JSONC/auth handling.
Run in HOME, not the install checkout, so a repository's model override
does not accidentally become the host installation's global default.
No login, sessions, prompts or inference are involved.
"""
try:
result = self.runner([executable, "api", "get", "/api/model/default"],
cwd=str(Path.home()), env=dict(self.environ),
capture_output=True, text=True, timeout=30)
if result.returncode or len(result.stdout or "") > 4 * 1024 * 1024:
return ""
response = json.loads(result.stdout)
data = response.get("data") if isinstance(response, dict) else None
if not isinstance(data, dict) or data.get("enabled") is not True or data.get("status") == "deprecated":
return ""
provider, model = data.get("providerID"), data.get("modelID")
if not isinstance(provider, str) or "/" in provider or not isinstance(model, str):
return ""
value = provider + "/" + model
return value if self._valid_model(value) else ""
except (OSError, ValueError, subprocess.SubprocessError):
# Never echo raw CLI output: provider discovery can include secrets.
return ""
def configure_harnesses(self, harness, model="", allow_picker=True):
"""Write host (non-Docker) profiles for the harnesses detected on PATH.
The native install launches host harnesses, so a Docker-era
``docker_directory`` must be cleared rather than kept. Models come from
the explicit ``--model`` (recorded as PIPELINES_DEFAULT_MODEL) or the
existing valid profile; they are never invented. Unrelated keys and
existing valid profile, the explicit ``--model`` (also recorded as
PIPELINES_DEFAULT_MODEL), or OpenCode's resolved host default; they are
never invented. Unrelated keys and
profiles for harnesses that are not detected are preserved, matching
harness.Save. No harness is installed, upgraded or downloaded.
"""
if model and not self._valid_model(model):
raise ValueError("Invalid --model; supply an actual PROVIDER/MODEL, not a default placeholder")
existing = self._existing_harness_config()
profiles = existing.get("profiles")
if not isinstance(profiles, dict):
@@ -198,6 +227,10 @@ class Setup:
if name == "opencode" and self._valid_model(model):
harness_model = harness_model or model
pipeline_model = pipeline_model or model
if name == "opencode" and (not harness_model or not pipeline_model):
resolved = self.opencode_default_model(harness[name])
harness_model = harness_model or resolved
pipeline_model = pipeline_model or resolved
if not harness_model or not pipeline_model:
continue
# Host mode: no docker_directory, executable is the detected host binary.
@@ -207,9 +240,21 @@ class Setup:
merged[name] = profile
configured.append(name)
if not configured:
print("Host harness profiles were not written: no valid model was found for "
+ ", ".join(order) + ". Run 'pipelines harness setup opencode --host' to configure authoring.")
return None
if allow_picker and sys.stdin.isatty():
print("No usable OpenCode default model was found. Choose the defaults below to finish ./install.")
command = [str(self.resolve_prefix() / "bin/pipelines"), "harness", "setup", "opencode",
"--host", "--executable", harness["opencode"]]
current = merged.get("opencode", {})
for field, flag in (("model", "--model"), ("pipeline_model", "--pipeline-model")):
if self._valid_model(current.get(field)):
command.extend([flag, current[field]])
result = self.runner(command, cwd=str(Path.home()), env=dict(self.environ))
if result.returncode:
raise ValueError("Model selection did not complete; native setup is not ready. Rerun ./install or supply --model PROVIDER/MODEL.")
return self.configure_harnesses(harness, model, allow_picker=False)
raise ValueError("No usable configured harness model was found; native setup is not ready. "
"Rerun ./install in a terminal to choose models, or use ./install --model PROVIDER/MODEL. "
"Existing credentials and harness settings were retained.")
# Keep a configured host default; only a stale Docker default must change.
default = existing.get("default")
if default not in configured or profiles.get(default, {}).get("docker_directory"):
@@ -615,7 +660,9 @@ class Setup:
# The native install launches host harnesses, so write host profiles for
# the detected harnesses and clear any Docker-era link. Uses only the
# explicit --model or the existing valid profile/host configuration.
self.configure_harnesses(harness, args.model or "")
harness_path = self.configure_harnesses(harness, args.model or "")
harness_config = json.loads(harness_path.read_text())
pipeline_model = harness_config["profiles"][harness_config["default"]]["pipeline_model"]
lan_ip = lan.detect_lan()
base_url = args.ntfy_url or f"http://{lan_ip}:{args.ntfy_port}"
config_path = self.write_ntfy_config(prefix, base_url, args.ntfy_port)
@@ -636,8 +683,7 @@ class Setup:
"OPENCODE_SERVER", "OPENCODE_DB"):
if self.environ.get(key):
opencode_env[key] = self.environ[key]
if args.model:
opencode_env["PIPELINES_DEFAULT_MODEL"] = args.model
opencode_env["PIPELINES_DEFAULT_MODEL"] = args.model or pipeline_model
path_value = str(prefix / "bin") + os.pathsep + self.environ.get("PATH", "")
manifest = {
"format": 1,
@@ -712,7 +758,8 @@ def arguments(argv=None):
parser.add_argument("--bind-address", default=DEFAULT_BIND_ADDRESS,
help="Unauthenticated server bind address (default 127.0.0.1; expose only the web proxy)")
parser.add_argument("--ntfy-port", type=int, default=DEFAULT_NTFY_PORT, help="ntfy listen port")
parser.add_argument("--model", help="Record an explicit default model; otherwise host OpenCode configuration is reused")
parser.add_argument("--model", help="Explicit PROVIDER/MODEL for starter defaults and missing profile fields; "
"otherwise reuse saved/default OpenCode models or choose within this installer")
role = parser.add_mutually_exclusive_group()
role.add_argument("--allow-authoring", dest="allow_authoring", action="store_true", default=None,
help="Explicitly enable pipeline publication; fresh native installs default to enabled")