/* 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. */ #include #include #include #include #include #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); } /* ------------------------------------------------------------------ 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. */ if (model && model[0]) { char prov[128] = "opencode", mid[192] = ""; const char *slash = strchr(model, '/'); if (slash) { snprintf(prov, sizeof prov, "%.*s", (int)(slash - model), model); snprintf(mid, sizeof mid, "%s", slash + 1); } else { snprintf(mid, sizeof mid, "%s", model); } char eprov[256], emid[384], body[768]; json_escape(prov, eprov, sizeof eprov); json_escape(mid, emid, sizeof emid); 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 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'; 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); } free(slice); if (text[0]) { fertig = 1; break; } } else { free(slice); } p += 6; } oc_resp_free(&r); 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); }