opencode: Effort als Modellvariante, Antworten vollständig lesen

- reasoning_effort, reasoning.effort, variant, thinking.type=disabled und
  ein model#variant werden zur opencode-Modellvariante. Ein explizites "#"
  gewinnt gegen den Body; default/auto bedeutet keine Variante.
- Die Brücke liest assistant-Nachrichten als ganze Objekte. Die echte API
  setzt time.completed vor type; der bisherige Scan ab type verlor damit
  die fertige Antwort und lief in den Timeout.
- Tests decken alle Effort-Formen, den as-Rewrite und die Modell-Politik
  über die opencode-Brücke ab.
This commit is contained in:
Hermes committed 2026-11-15 21:26:52 +00:00
1 parent b9213c6b06
commit f94420ccc9
5 files changed
+372 -43

No files matched your search

+10
View File
@@ -445,6 +445,16 @@ Endpoint:
| `pass_cmd <cmd>` | stdout is the password — opencode makes a new one on every start |
| `base_cmd <cmd>` | stdout is the base URL — the background server binds a random port |
With `kind opencode`, the bridge carries the client's reasoning effort into the
session: `reasoning_effort` (Chat Completions), `reasoning.effort` (Responses), an
explicit `variant`, or a `model#variant` selector become the opencode model variant,
which is where opencode stores reasoning effort. Values pass through unchanged
(`default`/`auto` mean no variant), so `#high`, `#low`, `#minimal` and `#none` work
when the model offers them. Other
generation options have no slot in the session prompt API and are not invented.
For every other endpoint kind the request body goes out unchanged, so
`reasoning_effort` and the other generation options reach the provider as written.
## Hooks
Plain POSIX shell, with the request in the environment:
+243 -34
View File
@@ -19,6 +19,9 @@
* streaming wants a provider, not this bridge.
* - Each request gets its own session and deletes it afterwards, so conversation state
* lives with the caller, as it does for any OpenAI client.
* - The client's reasoning effort has a home: opencode selects it as a model variant
* ("#high"), so reasoning_effort/reasoning.effort/variant are passed through there.
* Other generation options have no slot in the session prompt API and are not faked.
*/
#include <ctype.h>
#include <stdio.h>
@@ -233,6 +236,169 @@ static long field_number(const char *json, const char *key, long dflt)
return strtol(p, NULL, 10);
}
/* ------------------------------------------------------------ request options */
/* Skip one JSON value. The request body is one object, and a flat strstr would also
* find a "reasoning_effort" quoted inside a message. This walker keeps us at the level
* where request options live. */
static int skip_value(const char **pp)
{
const char *p = *pp;
while (*p && isspace((unsigned char)*p)) p++;
if (*p == '"') {
p++;
while (*p && *p != '"') { if (*p == '\\' && p[1]) p++; p++; }
if (*p != '"') return -1;
p++;
} else if (*p == '{' || *p == '[') {
char open = *p, close = (open == '{') ? '}' : ']';
int depth = 0;
while (*p) {
if (*p == '"') {
p++;
while (*p && *p != '"') { if (*p == '\\' && p[1]) p++; p++; }
if (!*p) return -1;
p++;
} else if (*p == open) {
depth++;
p++;
} else if (*p == close) {
depth--;
p++;
if (depth == 0) break;
} else {
p++;
}
}
if (depth != 0) return -1;
} else {
while (*p && *p != ',' && *p != '}' && *p != ']' && !isspace((unsigned char)*p)) p++;
}
*pp = p;
return 0;
}
/* Parse the JSON string at *pp and advance past its closing quote. */
static int parse_string(const char **pp, char *out, size_t outlen)
{
const char *p = *pp;
if (*p != '"') return -1;
const char *s = ++p;
while (*p && *p != '"') { if (*p == '\\' && p[1]) p++; p++; }
if (*p != '"') return -1;
if (json_unescape(s, (size_t)(p - s), out, outlen) != 0) return -1;
*pp = p + 1;
return 0;
}
/* Return the value of KEY in the object at OBJ, or NULL. Only the immediate level is
* searched; nested objects and arrays are skipped as a whole. */
static const char *object_value(const char *obj, const char *key)
{
if (!obj) return NULL;
const char *p = obj;
while (*p && isspace((unsigned char)*p)) p++;
if (*p != '{') return NULL;
p++;
for (;;) {
while (*p && isspace((unsigned char)*p)) p++;
if (*p != '"') return NULL; /* "}" or malformed */
char k[64];
if (parse_string(&p, k, sizeof k) != 0) return NULL;
while (*p && isspace((unsigned char)*p)) p++;
if (*p != ':') return NULL;
p++;
while (*p && isspace((unsigned char)*p)) p++;
if (!strcmp(k, key)) return p;
if (skip_value(&p) != 0) return NULL;
while (*p && isspace((unsigned char)*p)) p++;
if (*p == ',') { p++; continue; }
return NULL;
}
}
/* Return the matching '}' for the object at OBJ (which points at '{'), or NULL.
* String contents are skipped, so braces inside a message do not count. */
static const char *match_object(const char *obj)
{
if (!obj || *obj != '{') return NULL;
int depth = 0;
for (const char *p = obj; *p; ) {
if (*p == '"') {
p++;
while (*p && *p != '"') { if (*p == '\\' && p[1]) p++; p++; }
if (*p) p++;
continue;
}
if (*p == '{') depth++;
else if (*p == '}') {
depth--;
if (depth == 0) return p;
}
p++;
}
return NULL;
}
/* A string field at the top level of the request, not inside messages. */
static int body_string(const char *body, const char *key, char *out, size_t outlen)
{
out[0] = '\0';
const char *v = object_value(body, key);
if (!v) return -1;
return parse_string(&v, out, outlen);
}
/* The client's reasoning effort, in the form opencode understands: a model variant.
* Chat Completions says "reasoning_effort", the Responses shape says reasoning.effort,
* and a client that already speaks opencode may send "variant" directly. Values pass
* through unchanged; "default"/"auto" mean the provider default, which is no variant. */
static void request_variant(const char *body, char *out, size_t outlen)
{
out[0] = '\0';
if (body_string(body, "variant", out, outlen) == 0 && out[0]) goto done;
/* A rule's "as" may replace the model name before the bridge sees it. The body
* still carries the client's selector, so its #variant survives the rewrite. */
{
char ref[512] = "";
if (body_string(body, "model", ref, sizeof ref) == 0) {
char *hash = strrchr(ref, '#');
if (hash && hash[1]) snprintf(out, outlen, "%s", hash + 1);
}
}
if (out[0]) goto done;
if (body_string(body, "reasoning_effort", out, outlen) == 0 && out[0]) goto done;
{
const char *r = object_value(body, "reasoning");
if (r && *r == '"') {
parse_string(&r, out, outlen);
} else if (r && *r == '{') {
const char *effort = object_value(r, "effort");
if (effort) parse_string(&effort, out, outlen);
}
}
if (!out[0]) {
const char *t = object_value(body, "thinking");
if (t && *t == '{') {
const char *type = object_value(t, "type");
char kind[16] = "";
if (type && parse_string(&type, kind, sizeof kind) == 0 &&
!strcmp(kind, "disabled"))
snprintf(out, outlen, "none");
}
}
done:
if (!strcmp(out, "default") || !strcmp(out, "auto")) out[0] = '\0';
}
/* ------------------------------------------------------------------ prompt building */
/* Flatten an OpenAI messages array into the single prompt text opencode expects.
@@ -443,20 +609,41 @@ static int oc_chat(const char *base, const char *user, const char *pass, const c
}
oc_resp_free(&r);
/* 2. model, if one was asked for. "provider/id" and "id" are both accepted. */
/* 2. model, if one was asked for. "provider/id" and "id" are both accepted.
* A trailing "#variant" (opencode's own selector) wins over the request body;
* otherwise the client's reasoning effort is carried as the variant. */
if (model && model[0]) {
char prov[128] = "opencode", mid[192] = "";
const char *slash = strchr(model, '/');
char ref[512];
snprintf(ref, sizeof ref, "%s", model);
char variant[64] = "";
char *hash = strrchr(ref, '#');
if (hash && hash[1]) {
snprintf(variant, sizeof variant, "%s", hash + 1);
*hash = '\0';
} else {
request_variant(req_body, variant, sizeof variant);
}
char prov[512] = "opencode", mid[512] = "";
const char *slash = strchr(ref, '/');
if (slash) {
snprintf(prov, sizeof prov, "%.*s", (int)(slash - model), model);
snprintf(prov, sizeof prov, "%.*s", (int)(slash - ref), ref);
snprintf(mid, sizeof mid, "%s", slash + 1);
} else {
snprintf(mid, sizeof mid, "%s", model);
snprintf(mid, sizeof mid, "%s", ref);
}
char eprov[256], emid[384], body[768];
char eprov[1024], emid[1024], evar[160], body[4096];
json_escape(prov, eprov, sizeof eprov);
json_escape(mid, emid, sizeof emid);
snprintf(body, sizeof body, "{\"model\":{\"id\":\"%s\",\"providerID\":\"%s\"}}", emid, eprov);
json_escape(variant, evar, sizeof evar);
if (variant[0])
snprintf(body, sizeof body,
"{\"model\":{\"id\":\"%s\",\"providerID\":\"%s\",\"variant\":\"%s\"}}",
emid, eprov, evar);
else
snprintf(body, sizeof body, "{\"model\":{\"id\":\"%s\",\"providerID\":\"%s\"}}",
emid, eprov);
char path[256];
snprintf(path, sizeof path, "/api/session/%s/model", sid);
if (http_exchange(host, port, tls, "POST", path, body, basic, timeout_s, &r, err, errlen) != 0)
@@ -519,39 +706,61 @@ static int oc_chat(const char *base, const char *user, const char *pass, const c
oc_resp_free(&r);
goto cleanup;
}
/* Take the LAST assistant message that has a completed time. */
const char *p = r.body;
while ((p = strstr(p, "\"type\"")) != NULL) {
char type[32];
if (field_string(p, "type", type, sizeof type) != 0) { p += 6; continue; }
if (strcmp(type, "assistant")) { p += 6; continue; }
/* the message object ends at the matching close brace is hard to find with
* a scan; the API puts time/tokens/finish after content, so take a window */
const char *win = p;
size_t wlen = strlen(win);
if (wlen > 200000) wlen = 200000;
char *slice = malloc(wlen + 1);
if (!slice) { p += 6; continue; }
memcpy(slice, win, wlen);
slice[wlen] = '\0';
/* Take the LAST completed assistant message that carries text. Parse
* each message as a whole object: the real API puts time.completed
* BEFORE type, so a scan starting at "type" loses the completion. */
const char *data = strstr(r.body, "\"data\"");
const char *arr = data ? strchr(data, '[') : NULL;
int found = 0;
if (arr) {
const char *p = arr;
while ((p = strchr(p, '{')) != NULL) {
const char *oend = match_object(p);
if (!oend) break;
size_t olen = (size_t)(oend - p + 1);
char *slice = malloc(olen + 1);
if (!slice) { p = oend + 1; continue; }
memcpy(slice, p, olen);
slice[olen] = '\0';
if (strstr(slice, "\"completed\"")) {
extract_answer(slice, text, sizeof text, reason, sizeof reason);
const char *f = strstr(slice, "\"finish\"");
if (f && field_string(f, "finish", fin, sizeof fin) != 0) strcpy(fin, "stop");
const char *tk = strstr(slice, "\"tokens\"");
if (tk) {
tin = field_number(tk, "input", 0);
tout = field_number(tk, "output", 0);
const char *tv = object_value(slice, "type");
char type[32] = "";
if (!tv || parse_string(&tv, type, sizeof type) != 0 ||
strcmp(type, "assistant")) {
free(slice);
p = oend + 1;
continue;
}
const char *timev = object_value(slice, "time");
const char *donev = timev ? object_value(timev, "completed") : NULL;
if (!donev) {
free(slice);
p = oend + 1;
continue;
}
char t2[65536], r2[65536];
extract_answer(slice, t2, sizeof t2, r2, sizeof r2);
if (t2[0]) {
snprintf(text, sizeof text, "%s", t2);
snprintf(reason, sizeof reason, "%s", r2);
const char *f = object_value(slice, "finish");
fin[0] = '\0';
if (f) parse_string(&f, fin, sizeof fin);
if (!fin[0]) snprintf(fin, sizeof fin, "stop");
const char *tk = object_value(slice, "tokens");
if (tk) {
tin = field_number(tk, "input", 0);
tout = field_number(tk, "output", 0);
}
found = 1;
}
free(slice);
if (text[0]) { fertig = 1; break; }
} else {
free(slice);
p = oend + 1;
}
p += 6;
}
oc_resp_free(&r);
fertig = found;
if (!fertig) {
struct timespec nap = { .tv_sec = 1, .tv_nsec = 0 };
nanosleep(&nap, NULL);
+6 -2
View File
@@ -21,8 +21,12 @@
* base "http://127.0.0.1:4096" (no /v1 suffix; the paths above are absolute)
* user,pass HTTP Basic credentials; opencode accepts "opencode:<password>"
* model the model to ask for. May be "provider/id", "id", or empty for the
* server's default.
* req_body the OpenAI request body as received
* server's default. A trailing "#variant" selects an opencode model
* variant (its reasoning-effort selector).
* req_body the OpenAI request body as received. reasoning_effort,
* reasoning.effort, variant and thinking.type=disabled are carried into
* the session model's variant; other generation options have no slot in
* the session prompt API.
* out_body receives a malloc'ed OpenAI response body (caller frees)
*
* Returns 0 on success, -1 on failure with a reason in err.
+99 -4
View File
@@ -34,6 +34,10 @@ endpoint oc {
pass_cmd "$TMP/oc.pass.sh"
}
# A model selector with "#effort" is either passed through as written (first rule) or
# rewritten by an "as" — the variant must survive both paths.
req for "deepseek-v4.1-flash#*" pass oc
req for "*#*" pass oc as "deepseek-v4.1-flash-alt"
req for "*" pass oc
CFG
@@ -43,7 +47,7 @@ sleep 0.8
# 1. Modellliste kommt als OpenAI-Liste, ohne die Varianten der Modelle
R=$(curl -s -m 20 "http://127.0.0.1:$OC_JUNC/v1/models")
contains "$R" '"id":"glm-5.3-flash-free"' "the bridge lists opencode models as an OpenAI list"
contains "$R" '"id":"deepseek-v4.1-flash"' "the bridge lists opencode models as an OpenAI list"
case "$R" in
*'"id":"low"'*) bad "model variants leak into the list as models";;
*) ok "model variants do not leak into the list";;
@@ -51,7 +55,7 @@ esac
# 2. Chat: OpenAI rein, Antwort raus
R=$(curl -s -m 40 -X POST -H 'Content-Type: application/json' \
-d '{"model":"glm-5.3-flash-free","messages":[{"role":"user","content":"hallo welt"}],"max_tokens":10}' \
-d '{"model":"deepseek-v4.1-flash","messages":[{"role":"user","content":"hallo welt"}],"max_tokens":10}' \
"http://127.0.0.1:$OC_JUNC/v1/chat/completions")
contains "$R" '"object":"chat.completion"' "a chat request becomes an OpenAI completion"
contains "$R" 'ANTWORT auf: hallo welt' "the prompt reached the session and the answer came back"
@@ -68,11 +72,102 @@ esac
# 4. Ein Systemprompt wird mitgeschickt, nicht verschluckt
R=$(curl -s -m 40 -X POST -H 'Content-Type: application/json' \
-d '{"model":"beam-free","messages":[{"role":"system","content":"sei knapp"},{"role":"user","content":"frage"}]}' \
-d '{"model":"deepseek-v4.1-flash-alt","messages":[{"role":"system","content":"sei knapp"},{"role":"user","content":"frage"}]}' \
"http://127.0.0.1:$OC_JUNC/v1/chat/completions")
contains "$R" 'System: sei knapp' "a system prompt survives into the session"
# 5. Falsches Passwort ist ein sauberer Fehler, kein Absturz
# 5. Reasoning effort des Clients kommt als opencode-Modellvariante an. opencode
# trägt "reasoningEffort" nicht im Prompt, sondern in der Variante des Modells.
OC_LAST="http://127.0.0.1:$OC_PORT/test/last"
R=$(curl -s -m 40 -u opencode:testpasswort -X POST -H 'Content-Type: application/json' \
-d '{"model":"deepseek-v4.1-flash","messages":[{"role":"user","content":"denk nach"}],"reasoning_effort":"high"}' \
"http://127.0.0.1:$OC_JUNC/v1/chat/completions")
contains "$R" '"object":"chat.completion"' "reasoning_effort request is served"
R=$(curl -s -m 10 -u opencode:testpasswort "$OC_LAST")
contains "$R" '"variant": "high"' "reasoning_effort becomes the opencode model variant"
contains "$R" '"model": "opencode/deepseek-v4.1-flash"' "the variant does not become part of the model id"
R=$(curl -s -m 40 -u opencode:testpasswort -X POST -H 'Content-Type: application/json' \
-d '{"model":"deepseek-v4.1-flash-alt","messages":[{"role":"user","content":"auch nachdenken"}],"reasoning":{"effort":"low"}}' \
"http://127.0.0.1:$OC_JUNC/v1/chat/completions")
contains "$R" '"object":"chat.completion"' "reasoning.effort request is served"
R=$(curl -s -m 10 -u opencode:testpasswort "$OC_LAST")
contains "$R" '"variant": "low"' "reasoning.effort is passed through as a variant"
R=$(curl -s -m 40 -u opencode:testpasswort -X POST -H 'Content-Type: application/json' \
-d '{"model":"deepseek-v4.1-flash-alt","messages":[{"role":"user","content":"nicht nachdenken"}],"thinking":{"type":"disabled"}}' \
"http://127.0.0.1:$OC_JUNC/v1/chat/completions")
contains "$R" '"object":"chat.completion"' "a thinking:disabled request is served"
R=$(curl -s -m 10 -u opencode:testpasswort "$OC_LAST")
contains "$R" '"variant": "none"' "thinking:disabled becomes the none variant"
R=$(curl -s -m 40 -u opencode:testpasswort -X POST -H 'Content-Type: application/json' \
-d '{"model":"deepseek-v4.1-flash#max","messages":[{"role":"user","content":"maximum"}],"reasoning_effort":"low"}' \
"http://127.0.0.1:$OC_JUNC/v1/chat/completions")
contains "$R" '"object":"chat.completion"' "a model with #variant is served"
R=$(curl -s -m 10 -u opencode:testpasswort "$OC_LAST")
contains "$R" '"variant": "max"' "the explicit #variant wins over reasoning_effort"
contains "$R" '"model": "opencode/deepseek-v4.1-flash"' "the #variant is not sent as part of the model id"
# A rule's "as" replaces the model before the bridge starts; the variant from the
# client's selector must not disappear with the old name.
R=$(curl -s -m 40 -u opencode:testpasswort -X POST -H 'Content-Type: application/json' \
-d '{"model":"anything#high","messages":[{"role":"user","content":"durch as"}],"reasoning_effort":"low"}' \
"http://127.0.0.1:$OC_JUNC/v1/chat/completions")
contains "$R" '"object":"chat.completion"' "a rewritten model with #variant is served"
R=$(curl -s -m 10 -u opencode:testpasswort "$OC_LAST")
contains "$R" '"variant": "high"' "the client's #variant survives a rule's as rewrite"
contains "$R" '"model": "opencode/deepseek-v4.1-flash-alt"' "the as target is the model that reaches opencode"
R=$(curl -s -m 40 -u opencode:testpasswort -X POST -H 'Content-Type: application/json' \
-d '{"model":"deepseek-v4.1-flash-alt","messages":[{"role":"user","content":"variant direkt"}],"variant":"medium"}' \
"http://127.0.0.1:$OC_JUNC/v1/chat/completions")
contains "$R" '"object":"chat.completion"' "an explicit variant request is served"
R=$(curl -s -m 10 -u opencode:testpasswort "$OC_LAST")
contains "$R" '"variant": "medium"' "an explicit variant is passed through unchanged"
R=$(curl -s -m 40 -u opencode:testpasswort -X POST -H 'Content-Type: application/json' \
-d '{"model":"deepseek-v4.1-flash-alt","messages":[{"role":"user","content":"ohne effort"}]}' \
"http://127.0.0.1:$OC_JUNC/v1/chat/completions")
contains "$R" '"object":"chat.completion"' "a request without effort is served"
R=$(curl -s -m 10 -u opencode:testpasswort "$OC_LAST")
contains "$R" '"variant": null' "no effort means no variant is invented"
# 6. Dieselbe Modell-Politik gilt auch für die opencode-Brücke.
OC_POLICY=$((PORT+50))
cat > "$TMP/oc.policy.conf" <<CFG
listen 127.0.0.1:$OC_POLICY
endpoint oc {
base http://127.0.0.1:$OC_PORT
kind opencode
context 200000
timeout 30
idle_timeout 10
auth_basic opencode
pass_cmd "$TMP/oc.pass.sh"
}
models allow "deepseek-v4.1-flash"
req path "/v1/models" check none pass oc
req for "*" check none pass oc
CFG
./junction --config "$TMP/oc.policy.conf" > "$TMP/oc.policy.log" 2>&1 &
PIDS+=($!)
wait_port $OC_POLICY 10
R=$(curl -s -m 20 "http://127.0.0.1:$OC_POLICY/v1/models")
contains "$R" '"id":"deepseek-v4.1-flash"' "the opencode list keeps the whitelisted model"
case "$R" in
*'"id":"deepseek-v4.1-flash-alt"'*) bad "the opencode list leaked a non-whitelisted model";;
*) ok "the opencode list hides a non-whitelisted model";;
esac
CODE=$(curl -s -m 20 -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: application/json' \
-d '{"model":"deepseek-v4.1-flash-alt","messages":[{"role":"user","content":"nein"}]}' \
"http://127.0.0.1:$OC_POLICY/v1/chat/completions")
[ "$CODE" = "403" ] && ok "the opencode path refuses a non-whitelisted model" \
|| bad "the opencode path refused with HTTP $CODE"
# 7. Falsches Passwort ist ein sauberer Fehler, kein Absturz
printf '#!/bin/sh\necho falsch\n' > "$TMP/oc.bad.sh"
chmod +x "$TMP/oc.bad.sh"
sed "s|pass_cmd .*|pass_cmd \"$TMP/oc.bad.sh\"|; s|$OC_JUNC|$((PORT+20))|" "$TMP/oc.conf" > "$TMP/oc2.conf"
+14 -3
View File
@@ -21,6 +21,9 @@ PORT = int(sys.argv[1])
USER, PASS = 'opencode', 'testpasswort'
SESSIONS = {}
DELETED = []
# What the last model switch asked for. /test/last exposes it, so a test can see that
# the client's reasoning effort arrived as an opencode variant instead of being dropped.
LAST = {}
class H(BaseHTTPRequestHandler):
@@ -50,11 +53,14 @@ class H(BaseHTTPRequestHandler):
if not self._auth():
return self._json(401, {'_tag': 'UnauthorizedError'})
if self.path == '/test/last':
return self._json(200, LAST)
if self.path == '/api/model':
return self._json(200, {'data': [
{'id': 'glm-5.3-flash-free', 'modelID': 'glm-5.3-flash-free',
{'id': 'deepseek-v4.1-flash', 'modelID': 'deepseek-v4.1-flash',
'providerID': 'opencode', 'variants': [{'id': 'low'}, {'id': 'high'}]},
{'id': 'beam-free', 'modelID': 'beam-free',
{'id': 'deepseek-v4.1-flash-alt', 'modelID': 'deepseek-v4.1-flash-alt',
'providerID': 'opencode', 'variants': []},
]})
@@ -66,8 +72,11 @@ class H(BaseHTTPRequestHandler):
msgs = [{'id': 'msg_user', 'type': 'user', 'text': s['prompt']}]
if s.get('prompt'):
msgs.append({
'id': 'msg_ai', 'type': 'assistant',
'id': 'msg_ai',
# The real API puts time BEFORE type; keep that order so a
# scanner that starts at "type" cannot see "completed".
'time': {'created': 1, 'completed': 2},
'type': 'assistant',
'model': {'id': s['model'], 'providerID': 'opencode'},
'content': [
{'type': 'reasoning', 'text': 'kurz nachgedacht'},
@@ -97,6 +106,8 @@ class H(BaseHTTPRequestHandler):
return self._json(404, {'error': 'no session'})
m = body.get('model') or {}
SESSIONS[sid]['model'] = '%s/%s' % (m.get('providerID'), m.get('id'))
LAST.clear()
LAST.update({'model': SESSIONS[sid]['model'], 'variant': m.get('variant')})
self.send_response(204)
self.end_headers()
return