Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "opencode-wrap"
version = "0.4.1"
version = "0.4.2"
edition = "2021"
description = "OpenAI-compatible API in front of `opencode serve`"
license = "MIT"
Expand Down
17 changes: 10 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# opencode-wrap

OpenAI-compatible HTTP API in front of `opencode serve`, using the free model
`opencode/muse-spark-1.3-contributor-free`. No `OPENCODE_API_KEY` needed —
`opencode/deepseek-v4.1-flash-free`. No `OPENCODE_API_KEY` needed —
reuses whatever auth the `opencode` CLI already has.

Targets the **OpenCode 2** server API (`/api/*`, basic auth, session-scoped
Expand Down Expand Up @@ -112,7 +112,7 @@ before starting the wrapper.
| `OPENCODE_PORT` | `4100` | Port for auto-spawned serve |
| `OPENCODE_SERVER_PASSWORD` | random per start | Basic-auth password for `opencode serve`. Required when `OPENCODE_BASE` points at a server you started yourself |
| `OPENCODE_SERVER_USERNAME` | `opencode` | Basic-auth username for `opencode serve` |
| `WRAP_MODEL` | `muse-spark-1.3-contributor-free` | Backend model |
| `WRAP_MODEL` | `deepseek-v4.1-flash-free` | Backend model |
| `WRAP_PROVIDER` | `opencode` | Backend provider |
| `WRAP_AGENT` | `build` | OpenCode agent each per-request session runs under |
| `WRAP_CWD` | `/tmp` (Unix) / `%TEMP%` (Windows) | Existing directory for spawned serve. Native bash tools run here — use an empty sandbox, not your home directory |
Expand Down Expand Up @@ -185,7 +185,7 @@ curl http://127.0.0.1:8000/health
curl http://127.0.0.1:8000/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{
"model": "opencode/muse-spark-1.3-contributor-free",
"model": "opencode/deepseek-v4.1-flash-free",
"messages": [
{
"role": "user",
Expand All @@ -201,7 +201,7 @@ Streaming:
curl -N http://127.0.0.1:8000/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{
"model": "opencode/muse-spark-1.3-contributor-free",
"model": "opencode/deepseek-v4.1-flash-free",
"stream": true,
"messages": [
{
Expand All @@ -217,12 +217,12 @@ curl -N http://127.0.0.1:8000/v1/chat/completions \
```bash
curl http://127.0.0.1:8000/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{"model":"opencode/muse-spark-1.3-contributor-free",
-d '{"model":"opencode/deepseek-v4.1-flash-free",
"messages":[{"role":"user","content":"Explain closures in one paragraph."}]}'

curl http://127.0.0.1:8000/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{"model":"opencode/muse-spark-1.3-contributor-free",
-d '{"model":"opencode/deepseek-v4.1-flash-free",
"messages":[{"role":"user","content":"Weather in Paris?"}],
"tools":[{"type":"function","function":{"name":"get_weather",
"description":"Get weather for a city",
Expand Down Expand Up @@ -251,7 +251,10 @@ curl http://127.0.0.1:8000/v1/chat/completions \
type comes from the data URI or the `Content-Type` header, falling back to
the file extension.
- Opencode-native tools (bash/read/edit) execute server-side automatically.
- Bare `muse-spark-*-contributor` aliased to `...-contributor-free`.
- Bare `muse-spark-*-contributor` aliased to `...-contributor-free` (legacy; that
family is no longer on Zen).
- `WRAP_MODEL` naming a model Zen has dropped falls back to another free model
instead of failing every request; the substitution is logged at `WARN`.
- Explicit `opencode/<id>` typos → HTTP 400 with suggestions when Zen list loads.
- Empty contentless turns retried (fresh session), not served as `stop`.
- Caller tools use instruction + `tool_call` fence parsing; returned as OpenAI
Expand Down
4 changes: 2 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl Config {
opencode_password,
opencode_password_generated,
default_model: env::var("WRAP_MODEL")
.unwrap_or_else(|_| "muse-spark-1.3-contributor-free".into()),
.unwrap_or_else(|_| "deepseek-v4.1-flash-free".into()),
default_provider: env::var("WRAP_PROVIDER").unwrap_or_else(|_| "opencode".into()),
agent: non_empty_env("WRAP_AGENT").unwrap_or_else(|| "build".into()),
wrap_cwd,
Expand Down Expand Up @@ -94,7 +94,7 @@ impl Config {
opencode_username: "opencode".into(),
opencode_password: "test-password".into(),
opencode_password_generated: true,
default_model: "muse-spark-1.3-contributor-free".into(),
default_model: "deepseek-v4.1-flash-free".into(),
default_provider: "opencode".into(),
agent: "build".into(),
wrap_cwd: "/tmp".into(),
Expand Down
82 changes: 66 additions & 16 deletions src/turn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,24 +79,48 @@ fn split_variant(id: &str) -> (String, Option<String>) {
}
}

/// Preferred stand-in when the configured default is gone from Zen.
const FALLBACK_DEFAULT_MODEL: &str = "deepseek-v4.1-flash-free";

/// The configured default when Zen still lists it, otherwise the best free
/// model Zen currently offers. Zen rotates its catalogue, so a pinned default
/// eventually disappears and every caller without an explicit model breaks.
pub fn pick_default_model(configured: &str, ids: &HashSet<String>) -> String {
let configured = resolve_model_id(configured);
if ids.is_empty() || ids.contains(&configured) {
return configured;
}
let mut free: Vec<&String> = ids.iter().filter(|id| id.ends_with("-free")).collect();
free.sort();
free.iter()
.find(|id| id.as_str() == FALLBACK_DEFAULT_MODEL)
.or_else(|| free.first())
.map(|id| (*id).clone())
.unwrap_or(configured)
}

pub async fn prepare_turn(client: &OcoClient, body: &Value) -> Result<PreparedTurn, WrapError> {
let messages = body
.get("messages")
.and_then(|m| m.as_array())
.cloned()
.unwrap_or_default();
let chat_opts = parse_chat_options(body).map_err(WrapError::from)?;
let ids = client.zen_model_ids().await;
let default_model = pick_default_model(&client.config.default_model, &ids);
if default_model != client.config.default_model {
tracing::warn!(
"[wrap] default model \"{}\" is not offered by Zen; using \"{}\"",
client.config.default_model,
default_model
);
}

let raw_req = body
.get("model")
.and_then(|m| m.as_str())
.map(|s| s.trim().to_string())
.unwrap_or_else(|| {
format!(
"{}/{}",
client.config.default_provider, client.config.default_model
)
});
.unwrap_or_else(|| format!("{}/{}", client.config.default_provider, default_model));

let explicit = raw_req.contains('/');
let (req_provider, req_id, variant) = if explicit {
Expand All @@ -113,7 +137,6 @@ pub async fn prepare_turn(client: &OcoClient, body: &Value) -> Result<PreparedTu
)
};

let ids = client.zen_model_ids().await;
let model = if ids.contains(&req_id) {
model_ref("opencode", &req_id, variant.as_deref())
} else if explicit && req_provider == "opencode" && !ids.is_empty() {
Expand Down Expand Up @@ -145,13 +168,9 @@ pub async fn prepare_turn(client: &OcoClient, body: &Value) -> Result<PreparedTu
"[wrap] virtual model \"{}\" -> backend {}/{}",
raw_req,
client.config.default_provider,
client.config.default_model
default_model
);
model_ref(
&client.config.default_provider,
&resolve_model_id(&client.config.default_model),
None,
)
model_ref(&client.config.default_provider, &default_model, None)
};

let system = messages
Expand Down Expand Up @@ -333,12 +352,12 @@ pub async fn list_models(client: &OcoClient) -> Value {
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
let ids = client.zen_model_ids().await;
let def_id = format!(
"{}/{}",
client.config.default_provider,
resolve_model_id(&client.config.default_model)
pick_default_model(&client.config.default_model, &ids)
);
let ids = client.zen_model_ids().await;
if !ids.is_empty() {
let mut sorted: Vec<_> = ids.iter().cloned().collect();
sorted.sort();
Expand Down Expand Up @@ -1053,6 +1072,37 @@ mod tests {
OcoClient::new(Config::for_tests())
}

fn ids(list: &[&str]) -> HashSet<String> {
list.iter().map(|s| s.to_string()).collect()
}

#[test]
fn default_model_kept_when_zen_still_offers_it() {
let zen = ids(&["deepseek-v4.1-flash-free", "big-pickle"]);
assert_eq!(
pick_default_model("deepseek-v4.1-flash-free", &zen),
"deepseek-v4.1-flash-free"
);
}

#[test]
fn default_model_falls_back_when_zen_drops_it() {
let zen = ids(&["big-pickle", "glm-5.3-flash-free"]);
assert_eq!(
pick_default_model("muse-spark-1.3-contributor-free", &zen),
"glm-5.3-flash-free"
);
}

#[test]
fn default_model_unchanged_without_zen_catalogue() {
let zen = HashSet::new();
assert_eq!(
pick_default_model("muse-spark-1.3-contributor-free", &zen),
"muse-spark-1.3-contributor-free"
);
}

#[tokio::test]
async fn prepare_turn_merges_developer_and_files() {
let client = test_client();
Expand Down Expand Up @@ -1086,7 +1136,7 @@ mod tests {
assert_eq!(prepared.session_body["model"]["providerID"], "opencode");
assert_eq!(
prepared.session_body["model"]["id"],
"muse-spark-1.3-contributor-free"
"deepseek-v4.1-flash-free"
);
assert_eq!(prepared.session_body["agent"], "build");
assert_eq!(prepared.model_name, "wrap/test-model");
Expand Down
Loading