use crate::{resolve_gateway, GatewayOptions};
use serde_json::{json, Value};
const PROVIDER: &str = "agent_commander_gateway";
const PREFIX: &str = "agent_commander_gateway/";
pub fn config_variable(tool: &str, gateway: Option<&GatewayOptions>) -> Option<&'static str> {
gateway?;
match tool {
"agent" => Some("LINK_ASSISTANT_AGENT_CONFIG_CONTENT"),
"opencode" => Some("OPENCODE_CONFIG_CONTENT"),
_ => None,
}
}
pub fn model(
tool: &str,
gateway: Option<&GatewayOptions>,
model: Option<&str>,
) -> Result<Option<String>, String> {
if config_variable(tool, gateway).is_none() {
return Ok(model.map(str::to_owned));
}
let id = model
.map(|id| id.strip_prefix(PREFIX).unwrap_or(id))
.filter(|id| !id.trim().is_empty())
.ok_or_else(|| format!("The API gateway for \"{tool}\" needs a model (--model)."))?;
Ok(Some(format!("{PREFIX}{id}")))
}
pub fn prepare(
tool: &str,
gateway: Option<&GatewayOptions>,
selected_model: Option<&str>,
env: &mut Vec<(String, String)>,
) -> Result<Option<String>, String> {
let (Some(variable), Some(gateway)) = (config_variable(tool, gateway), gateway) else {
return Ok(selected_model.map(str::to_owned));
};
let index = env.iter().position(|(name, _)| name == variable);
let existing = index.map_or("", |index| env[index].1.trim());
let invalid = || format!("{variable} must contain a JSON configuration object");
let mut config: Value = if existing.is_empty() {
json!({})
} else {
serde_json::from_str(existing).map_err(|_| invalid())?
};
if !config.is_object() || config.get("provider").is_some_and(|p| !p.is_object()) {
return Err(invalid());
}
let mapped = model(
tool,
Some(gateway),
selected_model.or_else(|| config["model"].as_str()),
)?
.expect("compatible gateway model");
let id = &mapped[PREFIX.len()..];
let (base_url, token_env) = resolve_gateway(gateway, tool)?;
let provider = &mut config["provider"][PROVIDER];
if provider.is_null() {
*provider = json!({});
}
if !provider.is_object()
|| provider.get("options").is_some_and(|p| !p.is_object())
|| provider.get("models").is_some_and(|p| !p.is_object())
{
return Err(invalid());
}
provider["npm"] = json!("@ai-sdk/openai-compatible");
provider["options"]["baseURL"] = json!(base_url);
provider["options"]["apiKey"] = if tool == "agent" {
json!(env
.iter()
.find(|(name, _)| name == &token_env)
.map(|(_, token)| token))
} else {
json!(format!("{{env:{token_env}}}"))
};
if provider["models"].get(id).is_none() {
provider["models"][id] = json!({});
}
if let Some(enabled) = config
.get_mut("enabled_providers")
.and_then(Value::as_array_mut)
{
if !enabled.iter().any(|id| id == PROVIDER) {
enabled.push(json!(PROVIDER));
}
}
if let Some(disabled) = config
.get_mut("disabled_providers")
.and_then(Value::as_array_mut)
{
disabled.retain(|id| id != PROVIDER);
}
if let Some(index) = index {
env[index].1 = config.to_string();
} else {
env.push((variable.to_owned(), config.to_string()));
}
Ok(Some(mapped))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn provider_lists_are_optional() {
let gateway = GatewayOptions::with_router("https://router.example", "ROUTER_TOKEN");
let mut env = vec![("ROUTER_TOKEN".into(), "synthetic-token".into())];
prepare("opencode", Some(&gateway), Some("vendor/model"), &mut env).unwrap();
let (_, config) = env
.iter()
.find(|(name, _)| name == "OPENCODE_CONFIG_CONTENT")
.unwrap();
let config: Value = serde_json::from_str(config).unwrap();
assert!(config.get("enabled_providers").is_none());
assert!(config.get("disabled_providers").is_none());
}
}