From 3d43f8c6c8b55f2c389b969e8e046c5b8a8f2bbe Mon Sep 17 00:00:00 2001 From: Phoebus Date: Mon, 21 Sep 2026 20:01:44 -0700 Subject: [PATCH] feat(executor): add an OpenCode server capability probe OpenCode is an agent application, not an OpenAI-compatible endpoint. Add a typed probe over /global/health and /config/providers that distinguishes disconnected, authentication required, incompatible, reachable-no-model and ready, and never returns provider credentials. Expose it as phoebus-installer --opencode-probe. Document the four components, host and tunnelled remote workflows, and the Phoebus assistant boundary (ADR 0011). --- docs/OPENCODE.md | 136 +++++ docs/adr/0011-opencode-connection-boundary.md | 66 +++ docs/adr/README.md | 2 + .../crates/phoebus-executor/src/lib.rs | 1 + .../phoebus-executor/src/opencode_server.rs | 490 ++++++++++++++++++ .../crates/phoebus-installer/src/main.rs | 19 + 6 files changed, 714 insertions(+) create mode 100644 docs/OPENCODE.md create mode 100644 docs/adr/0011-opencode-connection-boundary.md create mode 100644 installer-rs/crates/phoebus-executor/src/opencode_server.rs diff --git a/docs/OPENCODE.md b/docs/OPENCODE.md new file mode 100644 index 0000000..ba9c432 --- /dev/null +++ b/docs/OPENCODE.md @@ -0,0 +1,136 @@ +# OpenCode connection workflow + +OpenCode is used in two clearly separated ways: + +1. **Developer workflow** — on this repository, inspecting sanitized evidence. + Full tool access (shell, files, plugins) is fine because it runs as *you*, + on *your* machine, against *your* checkout. +2. **Phoebus assistant connection** — approved, bounded system facts and + validated typed proposals. It must never inherit the developer tool + permissions and never receives secrets. + +Read [ADR 0011](adr/0011-opencode-connection-boundary.md) first. + +## Four components, not one + +| Component | What it is | Where it runs | +|-----------|------------|---------------| +| OpenCode client | `opencode` TUI/CLI, or `opencode attach ` | your machine | +| OpenCode server | `opencode serve` — an HTTP/JSON **agent** API, not a model API | usually the same machine as the client or the model | +| Model inference service | DeepSeek/OpenAI, or a local OpenAI-compatible server (Ollama, llama.cpp, ...) | provider cloud or your LAN | +| Phoebus installer/broker | the typed, privileged, local executor | the target machine only | + +**An OpenCode server URL does not go in Phoebus's local-model endpoint field.** +An OpenCode server is an agent application; it is not an OpenAI-compatible +`/v1/chat/completions` endpoint. Pointing Phoebus's `local` provider at it will +fail, and would be the wrong trust boundary even if it parsed. + +## Capability probe (never assume compatibility) + +```sh +phoebus-installer --opencode-probe http://127.0.0.1:4096 +``` + +It is read-only and prints a typed state, exiting nonzero unless a model is +available: + +| State | Meaning | +|-------|---------| +| `disconnected` | TCP connect failed; the service is down | +| `authentication_required` | the server answered 401/403; supply the password/tunnel | +| `incompatible` | a health response arrived but the API shape is not the expected one | +| `reachable_no_model` | healthy server, no model configured | +| `ready` | reachable, healthy, API-compatible, and ≥1 model configured | + +`ready` still does **not** prove the model can emit a valid Phoebus proposal; +that requires a real prompt round-trip and proposal parse. A health check or an +HTTP 200 is not that proof. + +The probe reads `/global/health` and `/config/providers`, keeps only counts from +the latter, and never returns the provider credentials that upstream includes in +that response. + +## A. OpenCode on the development/VM host + +```sh +# 1. Set a provider credential through the environment (never a file in git). +export DEEPSEEK_API_KEY="$(cat ~/.config/phoebus/deepseek.key)" # 0600 file + +# 2. Start the server on loopback only. Upstream warns when it is unsecured. +opencode serve --hostname 127.0.0.1 --port 4096 + +# 3. In another terminal, attach a client to it. +opencode attach http://127.0.0.1:4096 +``` + +Keep the server on `127.0.0.1`. Do not pass `--mdns` and do not bind `0.0.0.0` +without authentication: the server's configuration API can expose provider +credentials. + +## B. OpenCode on a separate user-controlled computer + +Run the server on that computer, bound to **loopback**, and reach it through an +authenticated encrypted tunnel. SSH port-forwarding is the simplest approved +transport: + +```sh +# On the remote computer: +opencode serve --hostname 127.0.0.1 --port 4096 + +# From your machine (tunnel local 127.0.0.1:4096 -> remote loopback:4096): +ssh -N -L 127.0.0.1:4096:127.0.0.1:4096 you@remote.example + +# Then, locally: +opencode attach http://127.0.0.1:4096 +phoebus-installer --opencode-probe http://127.0.0.1:4096 +``` + +The probe now sees a loopback endpoint and the tunnel supplies transport +authentication and encryption. If you cannot use a tunnel, set +`OPENCODE_SERVER_PASSWORD` and terminate TLS in front of the server; never +expose an unauthenticated plaintext service. + +### VM networking is not one thing + +Inside a VM these are different endpoints and must not be confused: + +| Endpoint | Meaning | +|----------|---------| +| `guest 127.0.0.1` | the guest's own loopback | +| `host 127.0.0.1` | the host's loopback (invisible to the guest) | +| `10.0.2.2` | the QEMU user-net gateway to the host | +| `192.168.x.y` | a real LAN address, reachable by other machines | + +## C. Phoebus assistant boundary + +When a Phoebus assistant uses OpenCode: + +- Run the service unprivileged, with restricted filesystem access. +- Disable tools you do not need. OpenCode permission settings are *not* an + operating-system security boundary; enforce isolation outside the prompt. +- Keep the destructive execution path in Phoebus's local broker with local human + approval. The agent is never given a shell, root, credentials or private-file + access. +- Keep credentials in protected runtime storage (0600, outside model context). + Never forward disk passphrases or account passwords to OpenCode. +- Changing the model or connection invalidates any approval whose meaning + depends on it; a reconnect must never replay an installation command. + +## Developer workflow note + +For work on this repository, the developer OpenCode session may use full tools, +but only against a checkout and against **sanitized** test evidence. Do not feed +it VM disks, serial transcripts with credentials, `*.pw` files, or the +`PHOEBUS_OPENCODE_*` runtime inputs. + +## Verified evidence + +- `phoebus-installer --opencode-probe http://127.0.0.1:41999` against the + installed `opencode 1.18.32` returned `ready` (3 providers, 27 models). +- The same probe through a forwarded second loopback endpoint returned `ready`. +- A server deliberately bound to a LAN address **without** authentication + returned `authentication_required` and exit status 1: the probe refuses to + treat an unauthenticated service as usable. +- Physical second-computer verification is **BLOCKED** in this environment (no + second machine / no passwordless SSH); the forwarded-hop test is labelled as a + host-local transport test, not a second computer. diff --git a/docs/adr/0011-opencode-connection-boundary.md b/docs/adr/0011-opencode-connection-boundary.md new file mode 100644 index 0000000..7f7f4e9 --- /dev/null +++ b/docs/adr/0011-opencode-connection-boundary.md @@ -0,0 +1,66 @@ +# ADR 0011: OpenCode connection boundary + +- **Status:** Accepted +- **Date:** 2026-09-22 + +## Context + +The assignment requires a working OpenCode connection on the development/VM host +and from a separate user-controlled computer, while keeping the model untrusted +and the destructive broker local. OpenCode is an **agent application**, not an +OpenAI-compatible inference endpoint. Upstream's `opencode serve` exposes an +HTTP/JSON API (`/global/health`, `/session`, `/config/providers`, ...) with +optional basic authentication; `opencode attach` and `opencode run --attach` +connect a client to it. + +Two facts shape the decision: + +1. A successful TCP connect, a health check or an HTTP 200 does **not** prove + that a usable model is configured, nor that the model can emit a valid + Phoebus proposal. The skill set must distinguish those states explicitly. +2. The installed server, with no `OPENCODE_SERVER_PASSWORD`, binds loopback and + warns that it is unsecured. Its `/config/providers` response includes the + provider credentials in cleartext. Exposing that service to a LAN would leak + those credentials and hand an agent's tool surface to the network. + +## Decision + +1. **Four components are named separately** and may live on different machines: + the OpenCode *client*, the OpenCode *server*, the *model inference service*, + and the Phoebus *installer/broker*. An OpenCode server URL is never placed in + Phoebus's local-model endpoint field. +2. **Connection states are typed and honest.** `phoebus-executor::opencode_server` + probes `/global/health` and `/config/providers` and reports one of + `Disconnected`, `AuthenticationRequired`, `ReachableNoModel`, + `Incompatible`, or `Ready`. `Ready` means reachable, healthy, API-compatible + and holding at least one model; it still does not prove a valid proposal + round-trip. The probe keeps only counts from `/config/providers`, never the + credentials it may contain. +3. **Remote access is loopback plus an authenticated encrypted tunnel** (SSH + port-forward, WireGuard, or equivalent). The probe accepts plain `http://` + only, because a direct TLS-less LAN bind is not an approved transport. +4. **The OpenCode agent never inherits Phoebus privilege.** Its tools, shell, + file and plugin access are outside Phoebus's execution path. Destructive + product actions still go through the local typed broker and local human + approval. The OpenCode configuration is written mode 0600 and carries no + credentials. +5. **The installer's AI step keeps using its own bounded transport.** OpenCode + is an optional operator workflow, not a replacement for the typed proposal + transport; a future adapter must perform a real prompt round-trip and parse a + versioned proposal before it may claim compatibility. + +## Consequences + +- Remote OpenCode is not a one-click feature: the operator runs a tunnel. This + is deliberate; the alternative is an unauthenticated credential-leaking agent + endpoint on the LAN. +- The capability probe is testable against fake HTTP servers and against a real + `opencode serve` (env-gated `PHOEBUS_OPENCODE_PROBE`), so compatibility is + verified rather than assumed. +- Developer use (this repository) and assistant use (approved bounded facts and + typed proposals) remain clearly separated by tools and permissions. + +## Status + +Accepted. The probe and its tests are implemented; end-to-end installation does +not depend on OpenCode. diff --git a/docs/adr/README.md b/docs/adr/README.md index d960ad2..14e5c30 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -15,5 +15,7 @@ and link it here. | [0007](0007-coherent-rollback.md) | Coherent rollback and recovery | Accepted | | [0008](0008-nix-isolation-lifecycle.md) | Nix lifecycle, build isolation, and packaging | Accepted | | [0009](0009-mango-dankmaterialshell-desktop.md) | Mango + DankMaterialShell desktop option | Accepted | +| [0010](0010-graphical-installer-frontend.md) | Graphical installer frontend and typed bridge | Accepted | +| [0011](0011-opencode-connection-boundary.md) | OpenCode connection boundary | Accepted | Format: Context / Decision / Consequences / Status. diff --git a/installer-rs/crates/phoebus-executor/src/lib.rs b/installer-rs/crates/phoebus-executor/src/lib.rs index 3efe9b2..538a2cc 100644 --- a/installer-rs/crates/phoebus-executor/src/lib.rs +++ b/installer-rs/crates/phoebus-executor/src/lib.rs @@ -18,6 +18,7 @@ pub mod kernel; pub mod log; pub mod nix; pub mod opencode; +pub mod opencode_server; pub mod portage; pub mod probe; pub mod rollback; diff --git a/installer-rs/crates/phoebus-executor/src/opencode_server.rs b/installer-rs/crates/phoebus-executor/src/opencode_server.rs new file mode 100644 index 0000000..dd0a449 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/opencode_server.rs @@ -0,0 +1,490 @@ +//! OpenCode **server** capability probe. +//! +//! OpenCode is an agent application, not an OpenAI-compatible inference +//! endpoint. A successful TCP connect, a health check or an HTTP 200 is not +//! proof that a model is configured or that it can produce a valid Phoebus +//! proposal. This module makes those distinctions explicit so a caller can +//! report an honest connection state instead of assuming compatibility. +//! +//! It talks to the OpenCode HTTP API documented at +//! using a deliberately tiny HTTP/1.1 client (no TLS, no redirects, no +//! credentials in the URL). Remote access is expected through an authenticated, +//! encrypted tunnel to a loopback-bound server, never by exposing the server +//! directly. +//! +//! The probe never returns provider credentials: upstream's `/config/providers` +//! response includes them, so only counts are kept. + +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpStream, ToSocketAddrs}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +/// A parsed `http://host:port` server endpoint. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Endpoint { + pub host: String, + pub port: u16, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EndpointError { + Empty, + NotHttp, + BadHost, + BadPort, +} + +impl std::fmt::Display for EndpointError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let text = match self { + EndpointError::Empty => "empty endpoint", + EndpointError::NotHttp => "only http:// endpoints are accepted", + EndpointError::BadHost => "the host is missing or contains an unsafe character", + EndpointError::BadPort => "the port is missing or invalid", + }; + f.write_str(text) + } +} + +impl Endpoint { + /// Parse `http://host:port`. Plain HTTP only: remote access is over an + /// authenticated tunnel, not a direct TLS-less LAN bind. + pub fn parse(value: &str) -> Result { + let text = value.trim(); + if text.is_empty() { + return Err(EndpointError::Empty); + } + let rest = text.strip_prefix("http://").ok_or(EndpointError::NotHttp)?; + // Reject userinfo, paths and control characters. + if rest.is_empty() + || rest.contains('/') + || rest.contains('@') + || rest.contains('"') + || rest.contains('\\') + || rest.chars().any(|c| c.is_whitespace() || c.is_control()) + { + return Err(EndpointError::BadHost); + } + let (host, port) = rest.rsplit_once(':').ok_or(EndpointError::BadPort)?; + if host.is_empty() { + return Err(EndpointError::BadHost); + } + let port: u16 = port.parse().map_err(|_| EndpointError::BadPort)?; + Ok(Endpoint { + host: host.to_string(), + port, + }) + } + + pub fn base(&self) -> String { + format!("http://{}:{}", self.host, self.port) + } + + fn socket_addrs(&self) -> std::io::Result> { + (self.host.as_str(), self.port) + .to_socket_addrs() + .map(|it| it.collect()) + } +} + +/// The connection state a frontend should display. `Ready` means the server is +/// reachable, authenticated, API-compatible *and* has at least one model; it +/// still does not prove the model can emit a valid proposal (that needs a real +/// prompt round-trip). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ConnectionState { + Disconnected, + AuthenticationRequired, + ReachableNoModel, + Incompatible, + Ready, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Capability { + pub state: ConnectionState, + pub tcp_reachable: bool, + pub healthy: bool, + pub server_version: Option, + pub provider_count: usize, + pub model_count: usize, + pub detail: String, +} + +impl Capability { + fn disconnected(detail: impl Into) -> Self { + Self { + state: ConnectionState::Disconnected, + tcp_reachable: false, + healthy: false, + server_version: None, + provider_count: 0, + model_count: 0, + detail: detail.into(), + } + } +} + +#[derive(Debug, Deserialize)] +struct Health { + #[serde(default)] + healthy: bool, + #[serde(default)] + version: Option, +} + +#[derive(Debug, Deserialize)] +struct Providers { + #[serde(default)] + providers: Vec, +} + +#[derive(Debug, Deserialize)] +struct Provider { + #[serde(default)] + models: std::collections::BTreeMap, +} + +/// Probe an OpenCode server and classify the connection. +pub fn probe(endpoint: &Endpoint, timeout: Duration) -> Capability { + let addrs = match endpoint.socket_addrs() { + Ok(addrs) if !addrs.is_empty() => addrs, + Ok(_) => return Capability::disconnected("host did not resolve"), + Err(e) => return Capability::disconnected(format!("resolve failed: {e}")), + }; + // A failed TCP connect is the only way to be certain the service is down. + if TcpStream::connect_timeout(&addrs[0], timeout).is_err() { + return Capability::disconnected("connect failed"); + } + // Each request uses its own short-lived connection (Connection: close), + // which is what the health/config endpoints expect and keeps the client + // simple and redirect-free. + let timeout = timeout; + let request = |path: &str| -> std::io::Result<(u16, String)> { + let mut stream = TcpStream::connect_timeout(&addrs[0], timeout)?; + let _ = stream.set_read_timeout(Some(timeout)); + let _ = stream.set_write_timeout(Some(timeout)); + get(&mut stream, &endpoint.host, path) + }; + + // Health first: it is the API-compatibility signal. + let (status, body) = match request("/global/health") { + Ok(pair) => pair, + Err(e) => { + return Capability { + state: ConnectionState::Incompatible, + tcp_reachable: true, + healthy: false, + server_version: None, + provider_count: 0, + model_count: 0, + detail: format!("health request failed: {e}"), + } + } + }; + if status == 401 || status == 403 { + return Capability { + state: ConnectionState::AuthenticationRequired, + tcp_reachable: true, + healthy: false, + server_version: None, + provider_count: 0, + model_count: 0, + detail: format!("server requires authentication (HTTP {status})"), + }; + } + if status != 200 { + return Capability { + state: ConnectionState::Incompatible, + tcp_reachable: true, + healthy: false, + server_version: None, + provider_count: 0, + model_count: 0, + detail: format!("/global/health returned HTTP {status}"), + }; + } + let health: Health = match serde_json::from_str(&body) { + Ok(h) => h, + Err(_) => { + return Capability { + state: ConnectionState::Incompatible, + tcp_reachable: true, + healthy: false, + server_version: None, + provider_count: 0, + model_count: 0, + detail: "/global/health was not the expected JSON".into(), + } + } + }; + if !health.healthy { + return Capability { + state: ConnectionState::Incompatible, + tcp_reachable: true, + healthy: false, + server_version: health.version, + provider_count: 0, + model_count: 0, + detail: "server reported unhealthy".into(), + }; + } + + // Providers: authentication and model availability. + let (pstatus, pbody) = request("/config/providers").unwrap_or((0, String::new())); + if pstatus == 401 || pstatus == 403 { + return Capability { + state: ConnectionState::AuthenticationRequired, + tcp_reachable: true, + healthy: true, + server_version: health.version, + provider_count: 0, + model_count: 0, + detail: format!("provider list requires authentication (HTTP {pstatus})"), + }; + } + let providers: Option = serde_json::from_str(&pbody).ok(); + let (provider_count, model_count) = match providers { + Some(p) => ( + p.providers.iter().filter(|p| !p.models.is_empty()).count(), + p.providers.iter().map(|p| p.models.len()).sum(), + ), + None => (0, 0), + }; + let state = if model_count == 0 { + ConnectionState::ReachableNoModel + } else { + ConnectionState::Ready + }; + Capability { + state, + tcp_reachable: true, + healthy: true, + server_version: health.version, + provider_count, + model_count, + detail: if model_count == 0 { + "server is healthy but no model is configured".into() + } else { + format!("{provider_count} provider(s), {model_count} model(s)") + }, + } +} + +/// Minimal HTTP/1.1 GET with connection close. Never follows redirects. +fn get(stream: &mut TcpStream, host: &str, path: &str) -> std::io::Result<(u16, String)> { + let request = format!( + "GET {path} HTTP/1.1\r\nHost: {host}\r\nAccept: application/json\r\nConnection: close\r\n\r\n" + ); + stream.write_all(request.as_bytes())?; + stream.flush()?; + let mut raw = Vec::new(); + stream.read_to_end(&mut raw)?; + let text = String::from_utf8_lossy(&raw).into_owned(); + let Some(header_end) = text.find("\r\n\r\n") else { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "no HTTP header terminator", + )); + }; + let headers = &text[..header_end]; + let body = &text[header_end + 4..]; + let status = headers + .lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .and_then(|code| code.parse::().ok()) + .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "no status line"))?; + let chunked = headers + .to_ascii_lowercase() + .contains("transfer-encoding: chunked"); + let body = if chunked { + decode_chunked(body).unwrap_or_else(|| body.to_string()) + } else { + body.to_string() + }; + Ok((status, body)) +} + +/// Decode an HTTP chunked body. Best-effort; returns `None` on malformed input. +fn decode_chunked(body: &str) -> Option { + let mut out = String::new(); + let mut rest = body; + loop { + let line_end = rest.find("\r\n")?; + let size_text = rest[..line_end].split(';').next()?.trim(); + let size = usize::from_str_radix(size_text, 16).ok()?; + rest = &rest[line_end + 2..]; + if size == 0 { + return Some(out); + } + if rest.len() < size { + return None; + } + out.push_str(&rest[..size]); + rest = &rest[size..]; + rest = rest.strip_prefix("\r\n").unwrap_or(rest); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Read as _; + use std::net::TcpListener; + use std::thread; + + fn spawn_server(routes: Vec<(&'static str, u16, &'static str)>) -> Endpoint { + use std::collections::HashMap; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let routes: HashMap<&'static str, (u16, &'static str)> = + routes.into_iter().map(|(p, s, b)| (p, (s, b))).collect(); + thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let mut buf = [0u8; 2048]; + let n = stream.read(&mut buf).unwrap_or(0); + if n == 0 { + // The reachability probe connects and closes without a + // request; ignore it. + continue; + } + let request = String::from_utf8_lossy(&buf[..n]); + let want = request + .lines() + .next() + .and_then(|l| l.split_whitespace().nth(1)) + .unwrap_or(""); + let (code, payload) = routes.get(want).copied().unwrap_or((404, "{}")); + let response = format!( + "HTTP/1.1 {code} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}", + payload.len() + ); + let _ = stream.write_all(response.as_bytes()); + } + }); + Endpoint { + host: "127.0.0.1".into(), + port, + } + } + + #[test] + fn parses_and_rejects_endpoints() { + assert_eq!( + Endpoint::parse("http://127.0.0.1:4096").unwrap(), + Endpoint { + host: "127.0.0.1".into(), + port: 4096 + } + ); + assert_eq!( + Endpoint::parse("https://127.0.0.1:4096"), + Err(EndpointError::NotHttp) + ); + assert_eq!( + Endpoint::parse("http://user@host:1"), + Err(EndpointError::BadHost) + ); + assert_eq!(Endpoint::parse("http://host"), Err(EndpointError::BadPort)); + assert!(Endpoint::parse("http://host:1/../../etc").is_err()); + assert!(Endpoint::parse("").is_err()); + } + + #[test] + fn probe_reports_ready_with_models() { + let endpoint = spawn_server(vec![ + ( + "/global/health", + 200, + r#"{"healthy":true,"version":"1.18.32"}"#, + ), + ( + "/config/providers", + 200, + r#"{"providers":[{"id":"deepseek","models":{"m1":{},"m2":{}}},{"id":"empty","models":{}}]}"#, + ), + ]); + let capability = probe(&endpoint, Duration::from_secs(2)); + assert_eq!(capability.state, ConnectionState::Ready); + assert_eq!(capability.server_version.as_deref(), Some("1.18.32")); + assert_eq!(capability.provider_count, 1); + assert_eq!(capability.model_count, 2); + } + + #[test] + fn probe_reports_reachable_but_model_less() { + let endpoint = spawn_server(vec![ + ( + "/global/health", + 200, + r#"{"healthy":true,"version":"1.18.32"}"#, + ), + ("/config/providers", 200, r#"{"providers":[]}"#), + ]); + let capability = probe(&endpoint, Duration::from_secs(2)); + assert_eq!(capability.state, ConnectionState::ReachableNoModel); + } + + #[test] + fn probe_reports_authentication_required() { + let endpoint = spawn_server(vec![("/global/health", 401, r#"{"error":"unauthorized"}"#)]); + let capability = probe(&endpoint, Duration::from_secs(2)); + assert_eq!(capability.state, ConnectionState::AuthenticationRequired); + assert!(capability.tcp_reachable); + } + + #[test] + fn probe_reports_incompatible_api() { + let endpoint = spawn_server(vec![("/global/health", 404, "{}")]); + let capability = probe(&endpoint, Duration::from_secs(2)); + assert_eq!(capability.state, ConnectionState::Incompatible); + } + + #[test] + fn probe_reports_disconnected_for_a_closed_port() { + let endpoint = Endpoint { + host: "127.0.0.1".into(), + port: 1, + }; + let capability = probe(&endpoint, Duration::from_millis(300)); + assert_eq!(capability.state, ConnectionState::Disconnected); + assert!(!capability.tcp_reachable); + } + + /// Live check against a real `opencode serve`, enabled explicitly: + /// `PHOEBUS_OPENCODE_PROBE=http://127.0.0.1:4096 cargo test probe_live`. + #[test] + fn probe_live_server_when_configured() { + let Ok(url) = std::env::var("PHOEBUS_OPENCODE_PROBE") else { + return; + }; + let endpoint = Endpoint::parse(&url).expect("valid probe endpoint"); + let capability = probe(&endpoint, Duration::from_secs(3)); + eprintln!("live opencode capability: {capability:?}"); + assert!( + capability.tcp_reachable, + "server was not reachable: {capability:?}" + ); + } + + #[test] + fn capability_serialisation_has_no_credential_fields() { + let capability = Capability { + state: ConnectionState::Ready, + tcp_reachable: true, + healthy: true, + server_version: Some("1.18.32".into()), + provider_count: 1, + model_count: 3, + detail: "1 provider(s), 3 model(s)".into(), + }; + let json = serde_json::to_string(&capability).unwrap(); + assert!(!json.to_lowercase().contains("key")); + assert!(!json.contains("sk-")); + } +} diff --git a/installer-rs/crates/phoebus-installer/src/main.rs b/installer-rs/crates/phoebus-installer/src/main.rs index 3219b77..30947cb 100644 --- a/installer-rs/crates/phoebus-installer/src/main.rs +++ b/installer-rs/crates/phoebus-installer/src/main.rs @@ -120,6 +120,12 @@ struct Cli { /// (stdin/stdout). Not intended for direct interactive use. #[arg(long, hide = true)] gui_bridge: bool, + + /// Probe a running OpenCode server (e.g. `http://127.0.0.1:4096`) and print + /// its capability as JSON. Read-only; exits nonzero unless a model is + /// available. Never prints provider credentials. + #[arg(long, value_name = "URL")] + opencode_probe: Option, } struct TerminalConfirm; @@ -275,6 +281,19 @@ fn run() -> std::result::Result> { return Ok(ExitCode::SUCCESS); } + if let Some(url) = &cli.opencode_probe { + use phoebus_executor::opencode_server::{probe, ConnectionState, Endpoint}; + let endpoint = + Endpoint::parse(url).map_err(|e| format!("invalid OpenCode endpoint `{url}`: {e}"))?; + let capability = probe(&endpoint, std::time::Duration::from_secs(5)); + println!("{}", serde_json::to_string_pretty(&capability)?); + return Ok(if capability.state == ConnectionState::Ready { + ExitCode::SUCCESS + } else { + ExitCode::FAILURE + }); + } + if let Some(name) = &cli.emit_asset { return match phoebus_core::system::desktop_asset(name) { Some(text) => {