- 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.
826 lines
32 KiB
C
826 lines
32 KiB
C
/* junction/opencode.c — translate OpenAI chat into opencode sessions and back.
|
|
*
|
|
* The two protocols do not line up, and pretending they do is how a bridge becomes a
|
|
* source of silent nonsense. What this file does, plainly:
|
|
*
|
|
* in : one OpenAI request with a list of messages
|
|
* step1: create a session
|
|
* step2: set the session's model
|
|
* step3: send the conversation as ONE prompt text (opencode takes a prompt, not a
|
|
* message array — tools, roles and system prompts have no separate slot)
|
|
* step4: poll the session's messages until an assistant message reports a completion
|
|
* out : one OpenAI response carrying that assistant text
|
|
*
|
|
* Deliberate limits, stated rather than hidden:
|
|
* - Tool calling is not translated: opencode runs its own agent loop, and passing
|
|
* OpenAI tool definitions through would silently do something else.
|
|
* - Streaming is delivered as a single chunk followed by [DONE], because the session
|
|
* API reports a finished message rather than token deltas. A client that needs real
|
|
* 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>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <time.h>
|
|
|
|
#include "opencode.h"
|
|
#include "conn.h"
|
|
#include "http.h"
|
|
|
|
#define OC_MAX_HDR 8192
|
|
|
|
/* ------------------------------------------------------------------ tiny helpers */
|
|
|
|
static void die(char *err, size_t errlen, const char *msg, const char *detail)
|
|
{
|
|
if (!detail) snprintf(err, errlen, "%s", msg);
|
|
else snprintf(err, errlen, "%s: %s", msg, detail);
|
|
}
|
|
|
|
/* Split "http://host:port/whatever" into host, port and TLS flag.
|
|
* The path is deliberately dropped: the bridge builds its own absolute paths. */
|
|
static int split_base(const char *base, char *host, size_t hlen, char *port, size_t plen,
|
|
int *tls, char *err, size_t errlen)
|
|
{
|
|
const char *rest;
|
|
*tls = 0;
|
|
if (!strncmp(base, "https://", 8)) { *tls = 1; rest = base + 8; }
|
|
else if (!strncmp(base, "http://", 7)) { rest = base + 7; }
|
|
else { die(err, errlen, "opencode: base must start with http:// or https://", NULL); return -1; }
|
|
|
|
const char *slash = strchr(rest, '/');
|
|
size_t hostlen = slash ? (size_t)(slash - rest) : strlen(rest);
|
|
const char *colon = memchr(rest, ':', hostlen);
|
|
if (colon) {
|
|
snprintf(host, hlen, "%.*s", (int)(colon - rest), rest);
|
|
snprintf(port, plen, "%.*s", (int)(hostlen - (size_t)(colon - rest) - 1), colon + 1);
|
|
} else {
|
|
snprintf(host, hlen, "%.*s", (int)hostlen, rest);
|
|
snprintf(port, plen, "%s", *tls ? "443" : "80");
|
|
}
|
|
if (!host[0] || !port[0]) { die(err, errlen, "opencode: base has no host or port", NULL); return -1; }
|
|
return 0;
|
|
}
|
|
|
|
static void json_escape(const char *in, char *out, size_t outlen)
|
|
{
|
|
size_t o = 0;
|
|
for (const char *p = in; *p && o + 8 < outlen; p++) {
|
|
switch (*p) {
|
|
case '"': out[o++] = '\\'; out[o++] = '"'; break;
|
|
case '\\': out[o++] = '\\'; out[o++] = '\\'; break;
|
|
case '\n': out[o++] = '\\'; out[o++] = 'n'; break;
|
|
case '\r': out[o++] = '\\'; out[o++] = 'r'; break;
|
|
case '\t': out[o++] = '\\'; out[o++] = 't'; break;
|
|
default:
|
|
if ((unsigned char)*p < 0x20) o += (size_t)snprintf(out + o, outlen - o, "\\u%04x", *p);
|
|
else out[o++] = *p;
|
|
}
|
|
}
|
|
out[o] = '\0';
|
|
}
|
|
|
|
/* Unescape a JSON string body into out. Returns 0 on success. */
|
|
static int json_unescape(const char *in, size_t len, char *out, size_t outlen)
|
|
{
|
|
size_t o = 0;
|
|
for (size_t i = 0; i < len && o + 1 < outlen; i++) {
|
|
char c = in[i];
|
|
if (c != '\\') { out[o++] = c; continue; }
|
|
if (++i >= len) break;
|
|
switch (in[i]) {
|
|
case 'n': out[o++] = '\n'; break;
|
|
case 't': out[o++] = '\t'; break;
|
|
case 'r': out[o++] = '\r'; break;
|
|
case 'b': out[o++] = '\b'; break;
|
|
case 'f': out[o++] = '\f'; break;
|
|
case 'u': {
|
|
/* \uXXXX — we only have to survive it, not round-trip every plane. */
|
|
if (i + 4 >= len) return -1;
|
|
char hex[5] = { in[i+1], in[i+2], in[i+3], in[i+4], 0 };
|
|
long cp = strtol(hex, NULL, 16);
|
|
i += 4;
|
|
if (cp < 0x80) out[o++] = (char)cp;
|
|
else out[o++] = '?';
|
|
break;
|
|
}
|
|
case '"': out[o++] = '"'; break;
|
|
case '\\': out[o++] = '\\'; break;
|
|
case '/': out[o++] = '/'; break;
|
|
default: out[o++] = in[i];
|
|
}
|
|
}
|
|
out[o] = '\0';
|
|
return 0;
|
|
}
|
|
|
|
/* --------------------------------------------------------------- one HTTP exchange */
|
|
|
|
typedef struct {
|
|
char *body;
|
|
size_t len;
|
|
int status;
|
|
} oc_resp;
|
|
|
|
static void oc_resp_free(oc_resp *r)
|
|
{
|
|
free(r->body);
|
|
r->body = NULL;
|
|
r->len = 0;
|
|
}
|
|
|
|
static int http_exchange(const char *host, const char *port, int tls, const char *method,
|
|
const char *path, const char *body, const char *basic,
|
|
double timeout_s, oc_resp *out, char *err, size_t errlen)
|
|
{
|
|
j_conn c = J_CONN_INIT;
|
|
if (j_conn_open(&c, host, port, tls, 1, NULL, 2000.0, err, errlen) != 0) return -1;
|
|
|
|
char hdr[OC_MAX_HDR];
|
|
size_t body_len = body ? strlen(body) : 0;
|
|
int n = snprintf(hdr, sizeof hdr,
|
|
"%s %s HTTP/1.1\r\nHost: %s:%s\r\nConnection: close\r\n"
|
|
"Accept: application/json\r\n",
|
|
method, path, host, port);
|
|
if (basic && basic[0])
|
|
n += snprintf(hdr + n, sizeof hdr - (size_t)n, "Authorization: Basic %s\r\n", basic);
|
|
if (body)
|
|
n += snprintf(hdr + n, sizeof hdr - (size_t)n,
|
|
"Content-Type: application/json\r\nContent-Length: %zu\r\n", body_len);
|
|
n += snprintf(hdr + n, sizeof hdr - (size_t)n, "\r\n");
|
|
|
|
if (j_conn_write(&c, hdr, (size_t)n, err, errlen) < 0) { j_conn_close(&c); return -1; }
|
|
if (body && j_conn_write(&c, body, body_len, err, errlen) < 0) { j_conn_close(&c); return -1; }
|
|
|
|
/* Read the whole answer. opencode answers JSON without chunking for these routes. */
|
|
j_buf buf;
|
|
j_buf_init(&buf);
|
|
double deadline = (double)time(NULL) + timeout_s;
|
|
char tmp[8192];
|
|
while ((double)time(NULL) < deadline) {
|
|
ssize_t got = j_conn_read(&c, tmp, sizeof tmp, err, errlen);
|
|
if (got < 0) { j_buf_free(&buf); j_conn_close(&c); return -1; }
|
|
if (got == 0) break;
|
|
if (j_buf_reserve(&buf, buf.len + (size_t)got + 1) != 0) {
|
|
j_buf_free(&buf); j_conn_close(&c);
|
|
die(err, errlen, "opencode: out of memory", NULL);
|
|
return -1;
|
|
}
|
|
memcpy(buf.data + buf.len, tmp, (size_t)got);
|
|
buf.len += (size_t)got;
|
|
buf.data[buf.len] = '\0';
|
|
}
|
|
j_conn_close(&c);
|
|
|
|
if (!buf.data || buf.len == 0) {
|
|
j_buf_free(&buf);
|
|
die(err, errlen, "opencode: empty answer", NULL);
|
|
return -1;
|
|
}
|
|
|
|
/* Status and body split. */
|
|
char *sep = strstr(buf.data, "\r\n\r\n");
|
|
if (!sep) { j_buf_free(&buf); die(err, errlen, "opencode: malformed answer", NULL); return -1; }
|
|
out->status = 0;
|
|
if (!strncmp(buf.data, "HTTP/", 5)) {
|
|
const char *sp = strchr(buf.data, ' ');
|
|
if (sp) out->status = atoi(sp + 1);
|
|
}
|
|
size_t hdrlen = (size_t)(sep - buf.data) + 4;
|
|
out->len = buf.len - hdrlen;
|
|
out->body = malloc(out->len + 1);
|
|
if (!out->body) { j_buf_free(&buf); die(err, errlen, "opencode: out of memory", NULL); return -1; }
|
|
memcpy(out->body, buf.data + hdrlen, out->len);
|
|
out->body[out->len] = '\0';
|
|
j_buf_free(&buf);
|
|
return 0;
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ JSON poking */
|
|
|
|
/* Find a string field inside an object slice and unescape it. Returns 0 if found. */
|
|
static int field_string(const char *json, const char *key, char *out, size_t outlen)
|
|
{
|
|
char pat[64];
|
|
snprintf(pat, sizeof pat, "\"%s\"", key);
|
|
const char *p = json;
|
|
while ((p = strstr(p, pat)) != NULL) {
|
|
const char *v = p + strlen(pat);
|
|
while (*v && (*v == ':' || isspace((unsigned char)*v))) v++;
|
|
if (*v != '"') { p += strlen(pat); continue; }
|
|
const char *s = v + 1;
|
|
const char *e = s;
|
|
while (*e && *e != '"') { if (*e == '\\' && e[1]) e++; e++; }
|
|
if (*e != '"') return -1;
|
|
return json_unescape(s, (size_t)(e - s), out, outlen);
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
/* Liest ein numerisches Feld ("key": 1234) aus einem JSON-Ausschnitt. */
|
|
static long field_number(const char *json, const char *key, long dflt)
|
|
{
|
|
char pat[64];
|
|
snprintf(pat, sizeof pat, "\"%s\"", key);
|
|
const char *p = strstr(json, pat);
|
|
if (!p) return dflt;
|
|
p += strlen(pat);
|
|
while (*p && (*p == ':' || isspace((unsigned char)*p))) p++;
|
|
if (!isdigit((unsigned char)*p)) return 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.
|
|
*
|
|
* The roles that survive are kept as prefixes, because losing a system prompt changes
|
|
* the model's behaviour, and losing "assistant:" makes a history unreadable. Tool and
|
|
* image parts are dropped on purpose — the bridge does not pretend to carry them. */
|
|
static void build_prompt(const char *req_body, char *out, size_t outlen, const char **skip_reason)
|
|
{
|
|
const char *p = req_body ? strstr(req_body, "\"messages\"") : NULL;
|
|
size_t o = 0;
|
|
out[0] = '\0';
|
|
*skip_reason = NULL;
|
|
if (!p) { *skip_reason = "request has no messages"; return; }
|
|
|
|
const char *arr = strchr(p, '[');
|
|
if (!arr) { *skip_reason = "messages is not an array"; return; }
|
|
(void)arr;
|
|
|
|
/* Walk objects at this level: "role" then "content". A flat scan is enough because
|
|
* the OpenAI shape puts both inside the same object and in that order in practice;
|
|
* content may be a string or an array of parts, so arrays are handled explicitly. */
|
|
const char *q = arr;
|
|
while ((q = strstr(q, "\"role\"")) != NULL) {
|
|
char role[32] = "";
|
|
if (field_string(q, "role", role, sizeof role) != 0) { q += 6; continue; }
|
|
|
|
const char *c = strstr(q, "\"content\"");
|
|
if (!c) break;
|
|
const char *v = c + 9;
|
|
while (*v && (*v == ':' || isspace((unsigned char)*v))) v++;
|
|
|
|
char piece[16384];
|
|
piece[0] = '\0';
|
|
|
|
if (*v == '"') {
|
|
const char *s = v + 1, *e = s;
|
|
while (*e && *e != '"') { if (*e == '\\' && e[1]) e++; e++; }
|
|
json_unescape(s, (size_t)(e - s), piece, sizeof piece);
|
|
} else if (*v == '[') {
|
|
/* Array of parts: concatenate every "text" field in order. */
|
|
const char *part = v;
|
|
size_t po = 0;
|
|
while ((part = strstr(part, "\"text\"")) != NULL && po + 2 < sizeof piece) {
|
|
char t[8192];
|
|
if (field_string(part, "text", t, sizeof t) == 0) {
|
|
int wrote = snprintf(piece + po, sizeof piece - po, "%s", t);
|
|
if (wrote > 0) po += (size_t)wrote;
|
|
}
|
|
part += 6;
|
|
if (part > v && *part == ']') break;
|
|
}
|
|
if (po == 0) { q = c + 9; continue; } /* pure image part: nothing to send */
|
|
} else {
|
|
q = c + 9;
|
|
continue;
|
|
}
|
|
|
|
if (!piece[0]) { q = c + 9; continue; }
|
|
|
|
int wrote;
|
|
if (!strcmp(role, "system")) {
|
|
wrote = snprintf(out + o, outlen - o, "System: %s\n\n", piece);
|
|
} else if (!strcmp(role, "assistant")) {
|
|
wrote = snprintf(out + o, outlen - o, "Assistant: %s\n\n", piece);
|
|
} else if (!strcmp(role, "user")) {
|
|
wrote = snprintf(out + o, outlen - o, "%s\n\n", piece);
|
|
} else {
|
|
wrote = snprintf(out + o, outlen - o, "%s: %s\n\n", role, piece);
|
|
}
|
|
if (wrote > 0) o += (size_t)wrote;
|
|
if (o >= outlen - 1) break;
|
|
q = c + 9;
|
|
}
|
|
}
|
|
|
|
/* Collect the visible text of one assistant message: every content part of type "text",
|
|
* joined. Reasoning parts are kept apart — they belong in reasoning_content, not in the
|
|
* answer. */
|
|
static void extract_answer(const char *msg, char *text, size_t tlen, char *reason, size_t rlen)
|
|
{
|
|
size_t to = 0, ro = 0;
|
|
text[0] = '\0';
|
|
reason[0] = '\0';
|
|
const char *c = strstr(msg, "\"content\"");
|
|
if (!c) return;
|
|
const char *p = c;
|
|
while ((p = strstr(p, "\"type\"")) != NULL) {
|
|
char type[32] = "";
|
|
if (field_string(p, "type", type, sizeof type) != 0) { p += 6; continue; }
|
|
char body[16384];
|
|
if (field_string(p, "text", body, sizeof body) != 0) { p += 6; continue; }
|
|
if (!strcmp(type, "text")) {
|
|
int wrote = snprintf(text + to, tlen - to, "%s%s", to ? "\n" : "", body);
|
|
if (wrote > 0) to += (size_t)wrote;
|
|
} else if (!strcmp(type, "reasoning") && ro + 2 < rlen) {
|
|
int wrote = snprintf(reason + ro, rlen - ro, "%s", body);
|
|
if (wrote > 0) ro += (size_t)wrote;
|
|
}
|
|
p += 6;
|
|
}
|
|
}
|
|
|
|
/* ------------------------------------------------------------------- the calls */
|
|
|
|
static int oc_models(const char *base, const char *user, const char *pass, double timeout_s,
|
|
char **out_body, size_t *out_len, char *err, size_t errlen)
|
|
{
|
|
char host[256], port[16];
|
|
int tls;
|
|
if (split_base(base, host, sizeof host, port, sizeof port, &tls, err, errlen) != 0) return -1;
|
|
|
|
char basic[512] = "";
|
|
if (user && user[0]) {
|
|
char raw[256];
|
|
snprintf(raw, sizeof raw, "%s:%s", user, pass ? pass : "");
|
|
/* base64, because Basic auth demands it and junction only ever sent Bearer */
|
|
static const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
size_t rl = strlen(raw), o = 0;
|
|
for (size_t i = 0; i < rl; i += 3) {
|
|
unsigned v = (unsigned char)raw[i] << 16;
|
|
if (i + 1 < rl) v |= (unsigned char)raw[i+1] << 8;
|
|
if (i + 2 < rl) v |= (unsigned char)raw[i+2];
|
|
basic[o++] = b64[(v >> 18) & 63];
|
|
basic[o++] = b64[(v >> 12) & 63];
|
|
basic[o++] = (i + 1 < rl) ? b64[(v >> 6) & 63] : '=';
|
|
basic[o++] = (i + 2 < rl) ? b64[v & 63] : '=';
|
|
}
|
|
basic[o] = '\0';
|
|
}
|
|
|
|
oc_resp r = {0};
|
|
if (http_exchange(host, port, tls, "GET", "/api/model", NULL, basic, timeout_s, &r, err, errlen) != 0)
|
|
return -1;
|
|
if (r.status != 200) {
|
|
snprintf(err, errlen, "opencode: /api/model answered %d", r.status);
|
|
oc_resp_free(&r);
|
|
return -1;
|
|
}
|
|
|
|
/* Reshape {"data":[{"id":…,"ref":{…}}]} into an OpenAI model list. */
|
|
size_t cap = 4096 + r.len;
|
|
char *out = malloc(cap);
|
|
if (!out) { oc_resp_free(&r); die(err, errlen, "opencode: out of memory", NULL); return -1; }
|
|
size_t o = (size_t)snprintf(out, cap, "{\"object\":\"list\",\"data\":[");
|
|
int first = 1;
|
|
const char *p = r.body;
|
|
while ((p = strstr(p, "\"modelID\"")) != NULL) {
|
|
char id[256];
|
|
if (field_string(p, "modelID", id, sizeof id) != 0) { p += 8; continue; }
|
|
if (id[0]) {
|
|
o += (size_t)snprintf(out + o, cap - o, "%s{\"id\":\"%s\",\"object\":\"model\"}",
|
|
first ? "" : ",", id);
|
|
first = 0;
|
|
}
|
|
p += 4;
|
|
}
|
|
snprintf(out + o, cap - o, "]}");
|
|
oc_resp_free(&r);
|
|
*out_body = out;
|
|
*out_len = strlen(out);
|
|
return 0;
|
|
}
|
|
|
|
static int oc_chat(const char *base, const char *user, const char *pass, const char *model,
|
|
const char *req_body, double timeout_s, char **out_body, size_t *out_len,
|
|
char *err, size_t errlen)
|
|
{
|
|
char host[256], port[16];
|
|
int tls;
|
|
if (split_base(base, host, sizeof host, port, sizeof port, &tls, err, errlen) != 0) return -1;
|
|
|
|
char basic[512] = "";
|
|
if (user && user[0]) {
|
|
char raw[256];
|
|
snprintf(raw, sizeof raw, "%s:%s", user, pass ? pass : "");
|
|
static const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
size_t rl = strlen(raw), o = 0;
|
|
for (size_t i = 0; i < rl; i += 3) {
|
|
unsigned v = (unsigned char)raw[i] << 16;
|
|
if (i + 1 < rl) v |= (unsigned char)raw[i+1] << 8;
|
|
if (i + 2 < rl) v |= (unsigned char)raw[i+2];
|
|
basic[o++] = b64[(v >> 18) & 63];
|
|
basic[o++] = b64[(v >> 12) & 63];
|
|
basic[o++] = (i + 1 < rl) ? b64[(v >> 6) & 63] : '=';
|
|
basic[o++] = (i + 2 < rl) ? b64[v & 63] : '=';
|
|
}
|
|
basic[o] = '\0';
|
|
}
|
|
|
|
/* 1. session */
|
|
oc_resp r = {0};
|
|
if (http_exchange(host, port, tls, "POST", "/api/session",
|
|
"{\"title\":\"junction\"}", basic, timeout_s, &r, err, errlen) != 0) return -1;
|
|
if (r.status != 200) {
|
|
snprintf(err, errlen, "opencode: session create answered %d %.120s", r.status, r.body ? r.body : "");
|
|
oc_resp_free(&r);
|
|
return -1;
|
|
}
|
|
char sid[128] = "";
|
|
{
|
|
const char *d = strstr(r.body, "\"data\"");
|
|
if (!d || field_string(d, "id", sid, sizeof sid) != 0 || !sid[0]) {
|
|
oc_resp_free(&r);
|
|
die(err, errlen, "opencode: session without id", NULL);
|
|
return -1;
|
|
}
|
|
}
|
|
oc_resp_free(&r);
|
|
|
|
/* 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 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 - ref), ref);
|
|
snprintf(mid, sizeof mid, "%s", slash + 1);
|
|
} else {
|
|
snprintf(mid, sizeof mid, "%s", ref);
|
|
}
|
|
char eprov[1024], emid[1024], evar[160], body[4096];
|
|
json_escape(prov, eprov, sizeof eprov);
|
|
json_escape(mid, emid, sizeof emid);
|
|
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)
|
|
goto cleanup;
|
|
if (r.status >= 400) {
|
|
snprintf(err, errlen, "opencode: model switch answered %d", r.status);
|
|
oc_resp_free(&r);
|
|
goto cleanup;
|
|
}
|
|
oc_resp_free(&r);
|
|
}
|
|
|
|
/* 3. prompt */
|
|
{
|
|
char *prompt = malloc(262144);
|
|
if (!prompt) { die(err, errlen, "opencode: out of memory", NULL); goto cleanup; }
|
|
const char *why = NULL;
|
|
build_prompt(req_body, prompt, 262144, &why);
|
|
if (!prompt[0]) {
|
|
free(prompt);
|
|
die(err, errlen, "opencode: nothing to send", why);
|
|
goto cleanup;
|
|
}
|
|
char *esc = malloc(600000);
|
|
if (!esc) { free(prompt); die(err, errlen, "opencode: out of memory", NULL); goto cleanup; }
|
|
json_escape(prompt, esc, 600000);
|
|
char *body = malloc(620000);
|
|
if (!body) { free(prompt); free(esc); die(err, errlen, "opencode: out of memory", NULL); goto cleanup; }
|
|
snprintf(body, 620000, "{\"text\":\"%s\"}", esc);
|
|
char path[256];
|
|
snprintf(path, sizeof path, "/api/session/%s/prompt", sid);
|
|
int rc = http_exchange(host, port, tls, "POST", path, body, basic, timeout_s, &r, err, errlen);
|
|
free(prompt);
|
|
free(esc);
|
|
free(body);
|
|
if (rc != 0) goto cleanup;
|
|
if (r.status >= 400) {
|
|
snprintf(err, errlen, "opencode: prompt answered %d %.160s", r.status, r.body ? r.body : "");
|
|
oc_resp_free(&r);
|
|
goto cleanup;
|
|
}
|
|
oc_resp_free(&r);
|
|
}
|
|
|
|
/* 4. wait for the assistant message to report a completion */
|
|
{
|
|
char text[65536] = "", reason[65536] = "";
|
|
char fin[32] = "stop";
|
|
long tin = 0, tout = 0;
|
|
char path[256];
|
|
snprintf(path, sizeof path, "/api/session/%s/message", sid);
|
|
|
|
double start = (double)time(NULL);
|
|
int fertig = 0;
|
|
while (!fertig && (double)time(NULL) - start < timeout_s) {
|
|
if (http_exchange(host, port, tls, "GET", path, NULL, basic, timeout_s, &r, err, errlen) != 0)
|
|
goto cleanup;
|
|
if (r.status != 200) {
|
|
snprintf(err, errlen, "opencode: message list answered %d", r.status);
|
|
oc_resp_free(&r);
|
|
goto cleanup;
|
|
}
|
|
/* 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';
|
|
|
|
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);
|
|
p = oend + 1;
|
|
}
|
|
}
|
|
oc_resp_free(&r);
|
|
fertig = found;
|
|
if (!fertig) {
|
|
struct timespec nap = { .tv_sec = 1, .tv_nsec = 0 };
|
|
nanosleep(&nap, NULL);
|
|
}
|
|
}
|
|
if (!fertig) {
|
|
die(err, errlen, "opencode: no answer before the deadline", NULL);
|
|
goto cleanup;
|
|
}
|
|
|
|
/* 5. reshape into an OpenAI response */
|
|
char etext[140000], ereason[140000];
|
|
json_escape(text, etext, sizeof etext);
|
|
json_escape(reason, ereason, sizeof ereason);
|
|
size_t cap = strlen(etext) + strlen(ereason) + 1024;
|
|
char *out = malloc(cap);
|
|
if (!out) { die(err, errlen, "opencode: out of memory", NULL); goto cleanup; }
|
|
int n = snprintf(out, cap,
|
|
"{\"id\":\"chatcmpl-%ld\",\"object\":\"chat.completion\",\"created\":%ld,"
|
|
"\"model\":\"%s\",\"choices\":[{\"index\":0,\"message\":{\"role\":\"assistant\"",
|
|
(long)time(NULL), (long)time(NULL), model && model[0] ? model : "opencode");
|
|
if (ereason[0]) n += snprintf(out + n, cap - (size_t)n, ",\"reasoning_content\":\"%s\"", ereason);
|
|
n += snprintf(out + n, cap - (size_t)n, ",\"content\":\"%s\"},\"finish_reason\":\"%s\"}],"
|
|
"\"usage\":{\"prompt_tokens\":%ld,\"completion_tokens\":%ld,\"total_tokens\":%ld}}",
|
|
etext, fin, tin, tout, tin + tout);
|
|
*out_body = out;
|
|
*out_len = (size_t)n;
|
|
}
|
|
|
|
char del_ok[256];
|
|
snprintf(del_ok, sizeof del_ok, "/api/session/%s", sid);
|
|
if (http_exchange(host, port, tls, "DELETE", del_ok, NULL, basic, 5.0, &r, err, errlen) == 0)
|
|
oc_resp_free(&r);
|
|
return 0;
|
|
|
|
cleanup:
|
|
{
|
|
char del_fail[256];
|
|
snprintf(del_fail, sizeof del_fail, "/api/session/%s", sid);
|
|
oc_resp tmp = {0};
|
|
char e2[128];
|
|
if (http_exchange(host, port, tls, "DELETE", del_fail, NULL, basic, 5.0, &tmp, e2, sizeof e2) == 0)
|
|
oc_resp_free(&tmp);
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ public entry */
|
|
|
|
int j_opencode_chat(const char *base, const char *user, const char *pass, const char *model,
|
|
const char *req_body, char **out_body, size_t *out_len,
|
|
double timeout_s, char *err, size_t errlen)
|
|
{
|
|
return oc_chat(base, user, pass, model, req_body, timeout_s, out_body, out_len, err, errlen);
|
|
}
|
|
|
|
int j_opencode_models(const char *base, const char *user, const char *pass,
|
|
char **out_body, size_t *out_len, double timeout_s,
|
|
char *err, size_t errlen)
|
|
{
|
|
return oc_models(base, user, pass, timeout_s, out_body, out_len, err, errlen);
|
|
}
|