phoebus_os/installer-rs/crates/phoebus-executor/src/opencode_client.rs
2026-09-29 04:58:22 -07:00

1260 lines
44 KiB
Rust

//! HTTP client and the OpenCode protocol adapter.
//!
//! OpenCode is an **agent server**, not an OpenAI-compatible model endpoint.
//! This module talks its real HTTP API (sessions and messages) over the
//! project's established transport (`curl` through [`Exec`]), so we do not
//! maintain a second handwritten HTTP parser. A [`HttpClient`] trait keeps the
//! protocol logic unit-testable with a fake, and a real TCP server can drive
//! the curl path in integration tests.
//!
//! The server API used here was verified against the shipped
//! `opencode 1.18.32`:
//!
//! * `GET /global/health` → `{healthy, version}`
//! * `GET /provider` → provider/model metadata
//! * `POST /session` → `{id}`
//! * `POST /session/{id}/message` → `{info, parts}` (synchronous reply)
//! * `POST /session/{id}/abort`, `DELETE /session/{id}`
//!
//! Only `TextPart`s of the assistant reply are accepted; tool, reasoning,
//! snapshot and user parts are ignored. The `/provider` catalog can contain a
//! `key` field upstream, so only ids and model names are ever extracted.
use std::collections::BTreeMap;
use std::io::Write;
use std::net::IpAddr;
use std::time::Duration;
use phoebus_ai::provider::{ChatRequest, ModelTransport, ProviderKind};
use phoebus_ai::AiError;
use phoebus_core::SecretString;
use crate::command::CommandSpec;
use crate::exec::Exec;
/// Which HTTP method a request uses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Method {
Get,
Post,
Delete,
}
impl Method {
fn as_str(self) -> &'static str {
match self {
Method::Get => "GET",
Method::Post => "POST",
Method::Delete => "DELETE",
}
}
}
/// A bounded HTTP request. Secrets travel in `auth`/`headers` and are injected
/// through curl's stdin configuration, never argv or logs.
#[derive(Debug, Clone)]
pub struct HttpRequest {
pub method: Method,
/// The full URL, already policy-checked by the caller.
pub url: String,
/// Non-secret headers (Content-Type, Accept, ...).
pub headers: Vec<(String, String)>,
/// Optional basic-auth password. The username is supplied separately.
pub auth: Option<SecretString>,
pub auth_user: String,
/// Request body; written to a 0600 temporary file for POST.
pub body: Option<String>,
pub timeout: Duration,
pub connect_timeout: Duration,
pub max_body: u64,
/// Pin the connection to a resolved address (`host`, `port`, `ip`) so a
/// DNS answer that changes after the policy check cannot move the target.
pub resolve: Option<(String, u16, IpAddr)>,
}
impl HttpRequest {
pub fn get(url: impl Into<String>) -> Self {
Self::new(Method::Get, url)
}
pub fn post(url: impl Into<String>, body: impl Into<String>) -> Self {
let mut req = Self::new(Method::Post, url);
req.body = Some(body.into());
req
}
pub fn delete(url: impl Into<String>) -> Self {
Self::new(Method::Delete, url)
}
fn new(method: Method, url: impl Into<String>) -> Self {
Self {
method,
url: url.into(),
headers: vec![("Accept".into(), "application/json".into())],
auth: None,
auth_user: "opencode".into(),
body: None,
timeout: Duration::from_secs(120),
connect_timeout: Duration::from_secs(15),
max_body: 4 * 1024 * 1024,
resolve: None,
}
}
}
/// A bounded HTTP response. The body is capped by [`HttpRequest::max_body`].
#[derive(Debug, Clone)]
pub struct HttpResponse {
pub status: u16,
pub body: String,
}
impl HttpResponse {
pub fn is_success(&self) -> bool {
(200..300).contains(&self.status)
}
}
/// A pluggable HTTP transport. The production implementation is curl; tests
/// supply a fake or a real local server.
pub trait HttpClient {
fn request(&self, request: &HttpRequest) -> Result<HttpResponse, AiError>;
}
/// The production transport: curl, driven through [`Exec`] so logging,
/// redaction and dry-run all apply. Credentials are written into curl's config
/// on **stdin** (hidden from argv and logs); the body travels in a 0600 temp
/// file. Redirects are disabled and the protocol is restricted to http/https.
pub struct CurlHttpClient<'a> {
exec: &'a Exec,
sandboxed: bool,
}
impl<'a> CurlHttpClient<'a> {
pub fn new(exec: &'a Exec) -> Self {
Self {
exec,
sandboxed: false,
}
}
/// Run the request inside the OS-level model sandbox (same boundary as the
/// direct provider transport). The body is inlined into the curl config on
/// stdin because the sandbox has a private `/tmp`.
pub fn sandboxed(mut self) -> Self {
self.sandboxed = true;
self
}
}
const STATUS_MARKER: &str = "__PHOEBUS_STATUS__";
impl HttpClient for CurlHttpClient<'_> {
fn request(&self, request: &HttpRequest) -> Result<HttpResponse, AiError> {
let mut temp: Option<tempfile::NamedTempFile> = None;
let data_line = if let Some(body) = &request.body {
if self.sandboxed {
// Inline the body (escaped) into the curl config: the sandbox's
// PrivateTmp would hide a temp file created here.
let escaped = body.replace('\\', "\\\\").replace('"', "\\\"");
format!("data = \"{escaped}\"\n")
} else {
let mut file = tempfile::Builder::new()
.prefix("phoebus-opencode.")
.tempfile()
.map_err(|e| AiError::Provider(format!("temp file: {e}")))?;
file.write_all(body.as_bytes())
.and_then(|_| file.flush())
.map_err(|e| AiError::Provider(format!("temp file: {e}")))?;
let line = format!("data = \"@{}\"\n", file.path().display());
temp = Some(file);
line
}
} else {
String::new()
};
let auth = match (&request.auth, request.auth_user.is_empty()) {
(Some(password), false) => {
use base64_lite::encode;
let token =
encode(format!("{}:{}", request.auth_user, password.expose()).as_bytes());
self.exec.register_secret(password);
// The derived token is what actually travels, so it must be
// redacted too: a server that echoes the Authorization header
// would otherwise leak the base64 form into the log.
self.exec.register_secret(&SecretString::new(token.clone()));
format!("header = \"Authorization: Basic {token}\"\n")
}
(Some(password), true) => {
use base64_lite::encode;
let token = encode(password.expose().as_bytes());
self.exec.register_secret(password);
self.exec.register_secret(&SecretString::new(token.clone()));
format!("header = \"Authorization: Bearer {token}\"\n")
}
_ => String::new(),
};
let mut headers = String::new();
for (name, value) in &request.headers {
headers.push_str(&format!(
"header = \"{}: {}\"\n",
sanitize_header(name),
sanitize_header(value)
));
}
let resolve = match &request.resolve {
Some((host, port, ip)) => {
let addr = match ip {
IpAddr::V4(v4) => v4.to_string(),
IpAddr::V6(v6) => format!("[{v6}]"),
};
format!("resolve = \"{host}:{port}:{addr}\"\n")
}
None => String::new(),
};
let config = format!(
"url = \"{url}\"\n\
request = \"{method}\"\n\
proto = \"=http,https\"\n\
max-redirs = 0\n\
connect-timeout = {connect}\n\
max-time = {total}\n\
max-filesize = {max}\n\
silent\nshow-error\n\
header = \"Expect:\"\n\
{headers}{auth}{resolve}{data_line}\
write-out = \"\\n{marker}%{{http_code}}\"\n",
url = request.url,
method = request.method.as_str(),
connect = request.connect_timeout.as_secs().max(1),
total = request.timeout.as_secs().max(1),
max = request.max_body,
marker = STATUS_MARKER,
);
let out = if self.sandboxed {
crate::sandbox::run(
self.exec,
"curl",
&["-sS".into(), "-K".into(), "-".into()],
config.into_bytes(),
)
.map_err(|e| AiError::Provider(format!("transport error: {e}")))?
} else {
self.exec
.run(
CommandSpec::new("ai", "OpenCode request", "curl")
.args(["-sS", "-K", "-"])
.stdin(config.into_bytes()),
)
.map_err(|e| AiError::Provider(format!("transport error: {e}")))?
};
drop(temp);
let stdout = out.stdout_lossy();
let index = stdout
.rfind(STATUS_MARKER)
.ok_or_else(|| AiError::Provider("transport response had no status".into()))?;
let status: u16 = stdout[index + STATUS_MARKER.len()..]
.trim()
.parse()
.map_err(|_| AiError::Provider("transport response had an invalid status".into()))?;
let body = stdout[..index].trim_end_matches(['\n', '\r']).to_string();
Ok(HttpResponse { status, body })
}
}
fn sanitize_header(value: &str) -> String {
value
.chars()
.filter(|c| !c.is_control() && *c != '"' && *c != '\\')
.collect()
}
/// A base64 encoder for the `Authorization: Basic` header. Kept local and tiny
/// rather than adding a dependency for one header.
mod base64_lite {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
pub fn encode(input: &[u8]) -> String {
let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
for chunk in input.chunks(3) {
let b = [
chunk[0],
*chunk.get(1).unwrap_or(&0),
*chunk.get(2).unwrap_or(&0),
];
out.push(TABLE[(b[0] >> 2) as usize] as char);
out.push(TABLE[(((b[0] & 0x03) << 4) | (b[1] >> 4)) as usize] as char);
if chunk.len() > 1 {
out.push(TABLE[(((b[1] & 0x0f) << 2) | (b[2] >> 6)) as usize] as char);
} else {
out.push('=');
}
if chunk.len() > 2 {
out.push(TABLE[(b[2] & 0x3f) as usize] as char);
} else {
out.push('=');
}
}
out
}
}
// ---------------------------------------------------------------------------
// OpenCode protocol
// ---------------------------------------------------------------------------
/// A model offered by an OpenCode provider.
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub struct ModelInfo {
pub id: String,
pub name: String,
#[serde(default)]
pub variants: Vec<String>,
}
/// A parsed model catalog entry. Never carries upstream credentials.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ProviderEntry {
pub id: String,
pub name: String,
pub models: Vec<ModelInfo>,
pub connected: bool,
}
/// The provider/model catalog, extracted without ever reading a `key` field.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Catalog {
pub providers: Vec<ProviderEntry>,
}
impl Catalog {
pub fn model_count(&self) -> usize {
self.providers.iter().map(|p| p.models.len()).sum()
}
pub fn connected_model_count(&self) -> usize {
self.providers
.iter()
.filter(|p| p.connected)
.map(|p| p.models.len())
.sum()
}
pub fn has_model(&self, provider: &str, model: &str) -> bool {
self.providers
.iter()
.any(|p| p.id == provider && p.models.iter().any(|m| m.id == model))
}
pub fn default_model(&self, provider: &str) -> Option<&str> {
self.providers
.iter()
.find(|p| p.id == provider)
.and_then(|p| p.models.first())
.map(|m| m.id.as_str())
}
}
#[derive(Debug, serde::Deserialize)]
struct ProviderCatalogBody {
#[serde(default)]
all: Vec<RawProvider>,
#[serde(default)]
connected: Vec<String>,
#[serde(default)]
default: BTreeMap<String, String>,
}
#[derive(Debug, serde::Deserialize)]
struct RawProvider {
#[serde(default)]
id: String,
#[serde(default)]
name: String,
#[serde(default)]
models: BTreeMap<String, serde_json::Value>,
}
#[derive(Debug, serde::Deserialize, Default)]
struct RawModel {
#[serde(default)]
id: String,
#[serde(default)]
name: String,
#[serde(default)]
variants: serde_json::Value,
}
fn extract_variants(val: &serde_json::Value) -> Vec<String> {
if let Some(map) = val.as_object() {
map.keys().cloned().collect()
} else if let Some(arr) = val.as_array() {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
} else {
Vec::new()
}
}
impl ProviderCatalogBody {
fn into_catalog(self) -> Catalog {
let mut defaults = self.default;
let connected: std::collections::BTreeSet<String> = self.connected.into_iter().collect();
let mut providers: Vec<ProviderEntry> = self
.all
.into_iter()
.map(|p| {
let models = p
.models
.into_iter()
.map(|(key, raw_val)| {
if let Ok(m) = serde_json::from_value::<RawModel>(raw_val) {
let id = if m.id.trim().is_empty() {
key
} else {
m.id.trim().to_string()
};
let name = if m.name.trim().is_empty() {
id.clone()
} else {
m.name.trim().to_string()
};
let mut variants = extract_variants(&m.variants);
variants.sort();
ModelInfo { id, name, variants }
} else {
ModelInfo {
id: key.clone(),
name: key,
variants: Vec::new(),
}
}
})
.collect();
ProviderEntry {
connected: connected.contains(&p.id),
id: p.id,
name: p.name,
models,
}
})
.collect();
for provider in &mut providers {
provider.models.sort_by(|a, b| a.id.cmp(&b.id));
if let Some(default) = defaults.remove(&provider.id) {
// Bubble the default model to the front so callers can pick a
// sensible default without a second request.
if let Some(pos) = provider.models.iter().position(|m| m.id == default) {
let model = provider.models.remove(pos);
provider.models.insert(0, model);
}
}
}
Catalog { providers }
}
}
/// Parse the `/provider` metadata body into a catalog without retaining any
/// credential-bearing field. A non-JSON or unexpected body is an error, never a
/// silently empty catalog.
pub fn parse_catalog(body: &str) -> Result<Catalog, AiError> {
// Require an object with an `all` array. Without this, serde's all-default
// struct would happily accept `[]` or another misleading shape and report
// an empty catalog instead of an incompatible server.
let value: serde_json::Value = serde_json::from_str(body)
.map_err(|e| AiError::Provider(format!("provider catalog was not valid JSON: {e}")))?;
if !value.is_object() || value.get("all").map(|v| v.is_array()) != Some(true) {
return Err(AiError::Provider(
"provider catalog was not the expected object".into(),
));
}
let parsed: ProviderCatalogBody = serde_json::from_value(value)
.map_err(|e| AiError::Provider(format!("provider catalog was not usable: {e}")))?;
Ok(parsed.into_catalog())
}
#[derive(Debug, serde::Deserialize)]
struct SessionBody {
#[serde(default)]
id: String,
}
#[derive(Debug, serde::Deserialize)]
struct MessageBody {
#[serde(default)]
info: MessageInfo,
#[serde(default)]
parts: Vec<Part>,
}
#[derive(Debug, serde::Deserialize, Default)]
struct MessageInfo {
#[serde(default)]
role: String,
#[serde(default)]
error: Option<serde_json::Value>,
#[serde(default)]
time: Option<MessageTime>,
}
#[derive(Debug, serde::Deserialize, Default)]
struct MessageTime {
#[serde(default)]
completed: Option<u64>,
}
#[derive(Debug, serde::Deserialize, Default)]
struct Part {
#[serde(rename = "type", default)]
kind: String,
#[serde(default)]
text: Option<String>,
#[serde(default)]
synthetic: Option<bool>,
#[serde(default)]
ignored: Option<bool>,
}
/// The accepted assistant reply: only the completed assistant text parts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssistantReply {
pub content: String,
pub completed: bool,
}
impl MessageBody {
fn into_reply(self) -> Result<AssistantReply, AiError> {
if self.info.role != "assistant" {
return Err(AiError::Provider(
"the reply was not an assistant message".into(),
));
}
if let Some(error) = &self.info.error {
// The upstream error object can echo provider text; keep only the
// error name, never a credential-bearing payload.
let name = error
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("provider error");
return Err(AiError::Provider(format!("model error: {name}")));
}
let mut content = String::new();
for part in &self.parts {
if part.kind != "text" {
continue;
}
if part.synthetic == Some(true) || part.ignored == Some(true) {
continue;
}
if let Some(text) = &part.text {
if !content.is_empty() {
content.push('\n');
}
content.push_str(text);
}
}
if content.trim().is_empty() {
return Err(AiError::Provider(
"the assistant returned no usable text".into(),
));
}
let completed = self.info.time.as_ref().and_then(|t| t.completed).is_some();
Ok(AssistantReply { content, completed })
}
}
/// A protocol client for one OpenCode server, provider and model.
pub struct OpenCodeClient<'a> {
http: &'a dyn HttpClient,
base: String,
auth: Option<SecretString>,
provider: String,
model: String,
variant: Option<String>,
timeout: Duration,
max_body: u64,
resolve: Option<(String, u16, IpAddr)>,
}
impl<'a> OpenCodeClient<'a> {
pub fn new(
http: &'a dyn HttpClient,
base: impl Into<String>,
provider: impl Into<String>,
model: impl Into<String>,
) -> Self {
Self {
http,
base: base.into(),
auth: None,
provider: provider.into(),
model: model.into(),
variant: None,
timeout: Duration::from_secs(120),
max_body: 4 * 1024 * 1024,
resolve: None,
}
}
pub fn with_auth(mut self, password: Option<SecretString>) -> Self {
self.auth = password;
self
}
pub fn with_variant(mut self, variant: impl Into<String>) -> Self {
self.variant = Some(variant.into());
self
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn with_max_body(mut self, max_body: u64) -> Self {
self.max_body = max_body;
self
}
pub fn with_resolve(mut self, resolve: Option<(String, u16, IpAddr)>) -> Self {
self.resolve = resolve;
self
}
pub fn provider(&self) -> &str {
&self.provider
}
pub fn model(&self) -> &str {
&self.model
}
fn request(&self, mut request: HttpRequest) -> Result<HttpResponse, AiError> {
request.timeout = self.timeout;
request.max_body = self.max_body;
request.auth = self.auth.clone();
request.resolve = self.resolve.clone();
self.http.request(&request)
}
fn url(&self, path: &str) -> String {
format!("{}{}", self.base.trim_end_matches('/'), path)
}
fn error_for(&self, action: &str, response: &HttpResponse) -> AiError {
let hint = match response.status {
400 => "the server rejected the request (check the model id)".to_string(),
401 => "authentication required".to_string(),
403 => "authentication rejected".to_string(),
404 => "endpoint not found (incompatible server?)".to_string(),
429 => "rate limited".to_string(),
500..=599 => "the server returned an internal error (check that the model \
exists and the provider credentials are valid)"
.to_string(),
_ => format!("HTTP {}", response.status),
};
// Name the provider:model so an invalid selection is obvious.
AiError::Provider(format!(
"OpenCode {action} failed for {}/{}: {hint}",
self.provider, self.model
))
}
/// Fetch the provider/model catalog. Uses the metadata endpoint only.
pub fn catalog(&self) -> Result<Catalog, AiError> {
let response = self.request(HttpRequest::get(self.url("/provider")))?;
if !response.is_success() {
return Err(self.error_for("provider catalog", &response));
}
parse_catalog(&response.body)
}
/// Create a fresh session bound to the selected provider/model. A unique
/// title makes ownership obvious and avoids reusing an existing session.
pub fn create_session(&self, title: &str) -> Result<String, AiError> {
// Verified against 1.18.32: despite the OpenAPI schema, a `model` field
// on session creation is rejected as BadRequest. The model is selected
// on the message instead.
let body = serde_json::json!({ "title": title }).to_string();
let mut request = HttpRequest::post(self.url("/session"), body);
request
.headers
.push(("Content-Type".into(), "application/json".into()));
let response = self.request(request)?;
if !response.is_success() {
return Err(self.error_for("session creation", &response));
}
let parsed: SessionBody = serde_json::from_str(&response.body)
.map_err(|e| AiError::Provider(format!("session response was invalid: {e}")))?;
if parsed.id.is_empty() {
return Err(AiError::Provider("session response had no id".into()));
}
Ok(parsed.id)
}
/// Send one message and return only the completed assistant reply. Tools are
/// disabled per message as defence in depth; the OS/process isolation of
/// the server is documented separately.
pub fn send_message(
&self,
session: &str,
system: &str,
user: &str,
) -> Result<AssistantReply, AiError> {
let mut model_val = serde_json::json!({
"providerID": self.provider,
"modelID": self.model,
});
if let Some(variant) = &self.variant {
let v = variant.trim();
if !v.is_empty() && v != "default" {
model_val["variant"] = serde_json::Value::String(v.to_string());
}
}
let body = serde_json::json!({
"system": system,
"model": model_val,
"tools": disabled_tools(),
"parts": [{ "type": "text", "text": user }],
})
.to_string();
let mut request = HttpRequest::post(self.url(&format!("/session/{session}/message")), body);
request
.headers
.push(("Content-Type".into(), "application/json".into()));
let response = self.request(request)?;
if !response.is_success() {
return Err(self.error_for("message", &response));
}
let parsed: MessageBody = serde_json::from_str(&response.body)
.map_err(|e| AiError::Provider(format!("message response was invalid: {e}")))?;
parsed.into_reply()
}
pub fn abort(&self, session: &str) -> Result<(), AiError> {
let response = self.request(HttpRequest::post(
self.url(&format!("/session/{session}/abort")),
"",
))?;
if response.is_success() {
Ok(())
} else {
Err(self.error_for("abort", &response))
}
}
/// Best-effort session cleanup. Errors are reported to the caller but are
/// not fatal to an otherwise valid result.
pub fn delete_session(&self, session: &str) -> Result<(), AiError> {
let response = self.request(HttpRequest::delete(
self.url(&format!("/session/{session}")),
))?;
if response.is_success() {
Ok(())
} else {
Err(self.error_for("session delete", &response))
}
}
/// Create a session, send one message, clean up, and return the reply.
/// The session is deleted on every path, so installation facts are not
/// retained longer than necessary.
pub fn one_shot(&self, system: &str, user: &str) -> Result<AssistantReply, AiError> {
let session = self.create_session("phoebus assistant (transient)")?;
let result = self.send_message(&session, system, user);
let _ = self.delete_session(&session);
result
}
}
fn disabled_tools() -> serde_json::Value {
serde_json::json!({
"bash": false, "edit": false, "write": false, "read": false,
"webfetch": false, "grep": false, "glob": false, "list": false,
"patch": false, "task": false, "todowrite": false, "todoread": false,
})
}
/// Adapts the OpenAI-shaped chat request that `complete_proposal` /
/// `complete_plan` build to the OpenCode session API. It borrows the caller's
/// [`Exec`] so logging, redaction and dry-run all apply, and returns an
/// OpenAI-shaped body because the shared `extract_content` consumes it. The
/// whole proposal/review pipeline is therefore reused unchanged.
pub struct ExecOpenCodeTransport<'a> {
exec: &'a Exec,
base: String,
provider: String,
model: String,
variant: Option<String>,
auth: Option<SecretString>,
timeout: Duration,
max_body: u64,
resolve: Option<(String, u16, IpAddr)>,
sandboxed: bool,
allow_insecure_http: bool,
}
impl<'a> ExecOpenCodeTransport<'a> {
pub fn new(
exec: &'a Exec,
base: impl Into<String>,
provider: impl Into<String>,
model: impl Into<String>,
) -> Self {
Self {
exec,
base: base.into(),
provider: provider.into(),
model: model.into(),
variant: None,
auth: None,
timeout: Duration::from_secs(120),
max_body: 4 * 1024 * 1024,
resolve: None,
sandboxed: false,
allow_insecure_http: false,
}
}
/// Run the OpenCode requests inside the same OS-level sandbox as the direct
/// provider transport (DynamicUser/ProtectHome/... via `systemd-run`).
pub fn sandboxed(mut self) -> Self {
self.sandboxed = true;
self
}
/// Permit plain `http` to a non-loopback OpenCode server (explicit opt-in).
pub fn allow_insecure_http(mut self) -> Self {
self.allow_insecure_http = true;
self
}
pub fn with_auth(mut self, password: Option<SecretString>) -> Self {
self.auth = password;
self
}
pub fn with_variant(mut self, variant: impl Into<String>) -> Self {
self.variant = Some(variant.into());
self
}
pub fn with_resolve(mut self, resolve: Option<(String, u16, IpAddr)>) -> Self {
self.resolve = resolve;
self
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn with_max_body(mut self, max_body: u64) -> Self {
self.max_body = max_body;
self
}
}
fn openai_reply(content: &str) -> String {
serde_json::json!({
"choices": [{ "message": { "content": content } }]
})
.to_string()
}
fn split_chat_request(body: &str) -> Result<(String, String), AiError> {
let request: ChatRequest = serde_json::from_str(body)
.map_err(|e| AiError::Provider(format!("chat request was invalid: {e}")))?;
let system = request
.messages
.iter()
.filter(|m| m.role == "system")
.map(|m| m.content.as_str())
.collect::<Vec<_>>()
.join("\n");
let user = request
.messages
.iter()
.filter(|m| m.role == "user")
.map(|m| m.content.as_str())
.collect::<Vec<_>>()
.join("\n");
if user.trim().is_empty() {
return Err(AiError::Provider("chat request had no user content".into()));
}
Ok((system, user))
}
impl ModelTransport for ExecOpenCodeTransport<'_> {
fn send(&self, _provider: ProviderKind, _url: &str, body: &str) -> Result<String, AiError> {
let (system, user) = split_chat_request(body)?;
// Enforce the transport policy and pin the connection to the checked
// address, so the adapter cannot be pointed at a plain-http remote.
let endpoint = crate::opencode_server::Endpoint::parse(&self.base)
.map_err(|e| AiError::Rejected(format!("invalid OpenCode endpoint: {e}")))?;
let target = endpoint.checked_target_with(self.allow_insecure_http)?;
let resolve =
self.resolve
.clone()
.or(Some((endpoint.host.clone(), endpoint.port, target.ip())));
let http = CurlHttpClient::new(self.exec);
let http = if self.sandboxed {
http.sandboxed()
} else {
http
};
let mut client = OpenCodeClient::new(&http, &self.base, &self.provider, &self.model)
.with_auth(self.auth.clone())
.with_timeout(self.timeout)
.with_max_body(self.max_body)
.with_resolve(resolve);
if let Some(variant) = &self.variant {
client = client.with_variant(variant.clone());
}
let reply = client.one_shot(&system, &user)?;
Ok(openai_reply(&reply.content))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::command::{CommandOutput, RecordingRunner};
use phoebus_core::Redactor;
use std::sync::Mutex;
#[test]
fn credentials_are_on_stdin_not_argv_and_are_redacted() {
let runner = RecordingRunner::new();
runner.set_response(
"curl",
CommandOutput {
status: 0,
success: true,
stdout: b"\n__PHOEBUS_STATUS__200".to_vec(),
stderr: Vec::new(),
duration: std::time::Duration::from_millis(1),
},
);
let dir = tempfile::tempdir().unwrap().keep();
let logger = crate::log::Logger::open(dir.join("l.log"), Redactor::new(), false);
let exec = crate::exec::Exec::new(Box::new(runner.clone()), logger, false, &dir, &dir);
let http = CurlHttpClient::new(&exec);
let mut request = HttpRequest::get("http://127.0.0.1:4096/provider");
request.auth = Some(SecretString::new("s3cret-pw"));
let response = http.request(&request).unwrap();
assert_eq!(response.status, 200);
let spec = &runner.recorded()[0];
assert_eq!(spec.program, "curl");
assert!(
!spec.args.iter().any(|a| a.contains("s3cret-pw")),
"the password must not be in argv: {:?}",
spec.args
);
let stdin = String::from_utf8(spec.stdin.clone().unwrap()).unwrap();
assert!(stdin.contains("Authorization: Basic"));
assert!(stdin.contains(&base64_lite::encode(b"opencode:s3cret-pw")));
// And it is registered for redaction.
assert_eq!(exec.redactor().redact("s3cret-pw"), "<redacted>");
// The derived base64 token is what actually travels, so an endpoint
// that echoes the Authorization header must not leak it either.
assert_eq!(
exec.redactor()
.redact(&base64_lite::encode(b"opencode:s3cret-pw")),
"<redacted>"
);
}
#[test]
fn a_sandboxed_request_runs_curl_under_systemd_run_with_the_body_inlined() {
if !crate::sandbox::available() {
eprintln!("systemd-run unavailable; sandboxed OpenCode transport not exercised here");
return;
}
let runner = RecordingRunner::new();
runner.set_response(
"systemd-run",
CommandOutput {
status: 0,
success: true,
stdout: b"\n__PHOEBUS_STATUS__200".to_vec(),
stderr: Vec::new(),
duration: std::time::Duration::from_millis(1),
},
);
let dir = tempfile::tempdir().unwrap().keep();
let logger = crate::log::Logger::open(dir.join("l.log"), Redactor::new(), false);
let exec = crate::exec::Exec::new(Box::new(runner.clone()), logger, false, &dir, &dir);
let http = CurlHttpClient::new(&exec).sandboxed();
let request = HttpRequest::post("http://127.0.0.1:4096/session", r#"{"x":"y"}"#);
let response = http.request(&request).unwrap();
assert_eq!(response.status, 200);
let spec = &runner.recorded()[0];
assert_eq!(spec.program, "systemd-run");
let stdin = String::from_utf8(spec.stdin.clone().unwrap()).unwrap();
assert!(
stdin.contains(r#"data = "{\"x\":\"y\"}""#),
"the body must be inlined into the config: {stdin}"
);
assert!(
!stdin.contains("phoebus-opencode."),
"no temp file may be used under PrivateTmp: {stdin}"
);
}
#[test]
fn a_bearer_token_is_redacted_too() {
let runner = RecordingRunner::new();
runner.set_response(
"curl",
CommandOutput {
status: 0,
success: true,
stdout: b"\n__PHOEBUS_STATUS__200".to_vec(),
stderr: Vec::new(),
duration: std::time::Duration::from_millis(1),
},
);
let dir = tempfile::tempdir().unwrap().keep();
let logger = crate::log::Logger::open(dir.join("l.log"), Redactor::new(), false);
let exec = crate::exec::Exec::new(Box::new(runner), logger, false, &dir, &dir);
let http = CurlHttpClient::new(&exec);
let mut request = HttpRequest::get("http://127.0.0.1:4096/provider");
request.auth = Some(SecretString::new("s3cret-pw"));
request.auth_user = String::new();
http.request(&request).unwrap();
assert_eq!(
exec.redactor().redact(&base64_lite::encode(b"s3cret-pw")),
"<redacted>"
);
}
#[test]
fn a_missing_status_marker_is_an_error_not_a_silent_success() {
let runner = RecordingRunner::new();
runner.set_response(
"curl",
CommandOutput {
status: 0,
success: true,
stdout: b"{}".to_vec(),
stderr: Vec::new(),
duration: std::time::Duration::from_millis(1),
},
);
let dir = tempfile::tempdir().unwrap().keep();
let logger = crate::log::Logger::open(dir.join("l.log"), Redactor::new(), false);
let exec = crate::exec::Exec::new(Box::new(runner), logger, false, &dir, &dir);
let http = CurlHttpClient::new(&exec);
assert!(http
.request(&HttpRequest::get("http://127.0.0.1:4096/x"))
.is_err());
}
/// A scripted HTTP client: pops one response per request.
struct FakeHttp {
responses: Mutex<Vec<HttpResponse>>,
requests: Mutex<Vec<HttpRequest>>,
}
impl FakeHttp {
fn new(responses: Vec<HttpResponse>) -> Self {
Self {
responses: Mutex::new(responses),
requests: Mutex::new(Vec::new()),
}
}
fn json(status: u16, body: impl Into<String>) -> HttpResponse {
HttpResponse {
status,
body: body.into(),
}
}
fn requests(&self) -> Vec<HttpRequest> {
self.requests.lock().unwrap().clone()
}
}
impl HttpClient for FakeHttp {
fn request(&self, request: &HttpRequest) -> Result<HttpResponse, AiError> {
self.requests.lock().unwrap().push(request.clone());
let mut responses = self.responses.lock().unwrap();
if responses.is_empty() {
return Err(AiError::Provider("no scripted response".into()));
}
Ok(responses.remove(0))
}
}
fn message_reply(text: &str) -> String {
serde_json::json!({
"info": { "role": "assistant", "time": { "created": 1, "completed": 2 } },
"parts": [{ "type": "text", "text": text }],
})
.to_string()
}
#[test]
fn base64_matches_known_vectors() {
assert_eq!(base64_lite::encode(b"opencode:pw"), "b3BlbmNvZGU6cHc=");
assert_eq!(base64_lite::encode(b""), "");
assert_eq!(base64_lite::encode(b"f"), "Zg==");
assert_eq!(base64_lite::encode(b"fo"), "Zm8=");
assert_eq!(base64_lite::encode(b"foo"), "Zm9v");
}
#[test]
fn catalog_never_reads_provider_keys() {
// Upstream can include a `key`; the catalog must not surface it.
let body = r#"{"all":[
{"id":"deepseek","name":"DeepSeek","key":"sk-SECRET","options":{},
"models":{"b":{},"a":{}}},
{"id":"x","name":"X","models":{}}],
"connected":["deepseek"],"default":{"deepseek":"a"}}"#;
let catalog = parse_catalog(body).unwrap();
let debug = format!("{catalog:?}");
assert!(!debug.contains("SECRET"), "catalog leaked a key: {debug}");
let ds = catalog
.providers
.iter()
.find(|p| p.id == "deepseek")
.unwrap();
assert!(ds.connected);
// The default model is bubbled to the front.
let ids: Vec<&str> = ds.models.iter().map(|m| m.id.as_str()).collect();
assert_eq!(ids, vec!["a", "b"]);
assert!(catalog.has_model("deepseek", "a"));
assert!(!catalog.has_model("deepseek", "zzz"));
}
#[test]
fn catalog_rejects_a_misleading_body() {
assert!(parse_catalog("<html>not json</html>").is_err());
assert!(parse_catalog("[]").is_err());
}
#[test]
fn one_shot_accepts_only_the_assistant_text_and_cleans_up() {
let http = FakeHttp::new(vec![
FakeHttp::json(200, r#"{"id":"ses_1"}"#),
// A user part, a tool part, a reasoning part and the assistant text.
FakeHttp::json(
200,
r#"{"info":{"role":"assistant","time":{"created":1,"completed":2}},
"parts":[
{"type":"text","text":"user echo","synthetic":true},
{"type":"tool","tool":"bash"},
{"type":"reasoning","text":"thinking"},
{"type":"text","text":"{\"version\":1}"}]}"#,
),
FakeHttp::json(200, "true"),
]);
let client = OpenCodeClient::new(&http, "http://127.0.0.1:4096", "p", "m");
let reply = client.one_shot("sys", "user").unwrap();
assert_eq!(reply.content, "{\"version\":1}");
assert!(reply.completed);
let requests = http.requests();
assert_eq!(requests.len(), 3);
assert_eq!(requests[0].method, Method::Post);
assert_eq!(requests[2].method, Method::Delete);
assert!(requests[2].url.ends_with("/session/ses_1"));
}
#[test]
fn one_shot_rejects_a_non_assistant_or_errored_reply() {
let http = FakeHttp::new(vec![
FakeHttp::json(200, r#"{"id":"ses_1"}"#),
FakeHttp::json(
200,
r#"{"info":{"role":"user"},"parts":[{"type":"text","text":"hi"}]}"#,
),
FakeHttp::json(200, "true"),
]);
let client = OpenCodeClient::new(&http, "http://127.0.0.1:4096", "p", "m");
assert!(client.one_shot("s", "u").is_err());
let http = FakeHttp::new(vec![
FakeHttp::json(200, r#"{"id":"ses_1"}"#),
FakeHttp::json(
200,
r#"{"info":{"role":"assistant","error":{"name":"ProviderAuthError","data":{"message":"bad sk-SECRET"}}},"parts":[]}"#,
),
FakeHttp::json(200, "true"),
]);
let client = OpenCodeClient::new(&http, "http://127.0.0.1:4096", "p", "m");
let err = client.one_shot("s", "u").unwrap_err().to_string();
assert!(err.contains("ProviderAuthError"), "{err}");
assert!(
!err.contains("sk-SECRET"),
"error leaked a credential: {err}"
);
}
#[test]
fn failed_inference_is_reported_not_hidden() {
let http = FakeHttp::new(vec![
FakeHttp::json(200, r#"{"id":"ses_1"}"#),
FakeHttp::json(200, r#"{"info":{"role":"assistant"},"parts":[]}"#),
]);
let client = OpenCodeClient::new(&http, "http://127.0.0.1:4096", "p", "m");
assert!(client.one_shot("s", "u").is_err());
}
#[test]
fn http_errors_are_distinguished() {
for (status, needle) in [
(401u16, "authentication required"),
(403, "authentication rejected"),
(404, "not found"),
(500, "internal error"),
] {
let http = FakeHttp::new(vec![FakeHttp::json(status, "{}")]);
let client = OpenCodeClient::new(&http, "http://127.0.0.1:4096", "p", "m");
let err = client.catalog().unwrap_err().to_string();
assert!(err.contains(needle), "status {status}: {err}");
}
}
#[test]
fn session_creation_failure_is_reported() {
let http = FakeHttp::new(vec![FakeHttp::json(500, "boom")]);
let client = OpenCodeClient::new(&http, "http://127.0.0.1:4096", "p", "m");
assert!(client.create_session("t").is_err());
// A success body with no id is also refused.
let http = FakeHttp::new(vec![FakeHttp::json(200, "{}")]);
let client = OpenCodeClient::new(&http, "http://127.0.0.1:4096", "p", "m");
assert!(client.create_session("t").is_err());
}
#[test]
fn transport_adapts_openai_request_shape() {
let http = FakeHttp::new(vec![
FakeHttp::json(200, r#"{"id":"ses_1"}"#),
FakeHttp::json(200, message_reply("{\"version\":1}")),
FakeHttp::json(200, "true"),
]);
let client = OpenCodeClient::new(&http, "http://127.0.0.1:4096", "prov", "mod");
let reply = client.one_shot("system prompt", "user prompt").unwrap();
assert_eq!(reply.content, "{\"version\":1}");
let requests = http.requests();
// requests[0] = session, requests[1] = message, requests[2] = delete
let body: serde_json::Value =
serde_json::from_str(requests[1].body.as_deref().unwrap()).unwrap();
assert_eq!(body["model"]["providerID"], "prov");
assert_eq!(body["model"]["modelID"], "mod");
assert_eq!(body["system"], "system prompt");
assert_eq!(body["tools"]["bash"], false);
assert_eq!(body["parts"][0]["type"], "text");
assert_eq!(body["parts"][0]["text"], "user prompt");
}
}