From ef0fa4366122b2f3c9a391c07d0d676d6fed2804 Mon Sep 17 00:00:00 2001 From: Hermes Date: Wed, 4 Nov 2026 21:55:32 +0000 Subject: [PATCH] =?UTF-8?q?opencode=20serve=20als=20Endpunkt=20erster=20Kl?= =?UTF-8?q?asse=20(Br=C3=BCcke=20zu=20/v1/)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit opencode spricht kein OpenAI-Protokoll, sondern eine sitzungsorientierte API (/api/session, /prompt, /model, /message). Ein Client soll davon nichts merken: kind opencode Endpunkt wird über die Brücke bedient statt blind weitergeleitet auth_basic USER HTTP Basic (opencode verlangt es, junction kannte nur Bearer) pass_cmd CMD Passwort aus einem Kommando — opencode erzeugt bei jedem Start eins base_cmd CMD Basis-URL aus einem Kommando — der Dienst bindet einen freien Port Ablauf je Anfrage: Sitzung anlegen, Modell setzen, Nachrichten zu einem Prompt zusammenfassen, auf die fertige Assistenten-Nachricht warten, Antwort in OpenAI-Form bauen, Sitzung löschen. reasoning_content wird getrennt geführt, Token-Zahlen kommen aus der Sitzung. /v1/models wird ebenfalls übersetzt (modelID statt id, sonst landen Varianten wie low/high als eigene Modelle in der Liste). Bewusste Grenzen, im README benannt: Werkzeugdefinitionen werden nicht übersetzt, und Streaming kommt als ein Stück plus [DONE], weil die Sitzungs-API keine Token-Deltas liefert. Geprüft: 10 neue Prüfungen gegen einen Nachbau des Sitzungs-API (tests/opencode.sh, tests/opencode_stub.py), 76 gesamt, keine Fehler. Am echten Dienst einmal durchgelaufen mit einem kostenlosen Modell: /v1/models 10 Modelle, Chat 200 mit Inhalt "bereit" in 4,1 s. --- Makefile | 2 +- README.md | 4 + examples/full-reference.conf | 25 ++ src/config.c | 33 ++ src/config.h | 8 + src/junction.c | 98 ++++++ src/opencode.c | 616 +++++++++++++++++++++++++++++++++++ src/opencode.h | 41 +++ tests/opencode.sh | 85 +++++ tests/opencode_stub.py | 136 ++++++++ tests/run.sh | 6 +- 11 files changed, 1052 insertions(+), 2 deletions(-) create mode 100644 src/opencode.c create mode 100644 src/opencode.h create mode 100644 tests/opencode.sh create mode 100644 tests/opencode_stub.py diff --git a/Makefile b/Makefile index 10a0fc8..cd9db82 100644 --- a/Makefile +++ b/Makefile @@ -9,7 +9,7 @@ LDFLAGS ?= PREFIX ?= /usr/local J_WITH_TLS ?= auto -SRC = src/config.c src/conn.c src/http.c src/cache.c src/junction.c +SRC = src/config.c src/conn.c src/http.c src/cache.c src/opencode.c src/junction.c OBJ = $(SRC:.c=.o) TOOLS = tools/junction-wol diff --git a/README.md b/README.md index 800889b..66eeb30 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,10 @@ Endpoint: | `cache` | `on` / `off` for this endpoint | | `header` | static request header, `"Name: value"` (repeatable) | | `vision` | `on` / `off` — can this endpoint read images? Omitted = not checked | + | `kind opencode` | the endpoint is an `opencode serve`; requests are translated | + | `auth_basic ` | HTTP Basic instead of a bearer token (opencode wants this) | + | `pass_cmd ` | stdout is the password — opencode makes a new one on every start | + | `base_cmd ` | stdout is the base URL — the background server binds a random port | ## Hooks diff --git a/examples/full-reference.conf b/examples/full-reference.conf index e880015..c8dcbc2 100644 --- a/examples/full-reference.conf +++ b/examples/full-reference.conf @@ -250,6 +250,27 @@ endpoint private-tls { cache on } +# ---------------------------------------------------------------- opencode serve +# +# opencode spricht kein OpenAI-Protokoll: seine API ist sitzungsorientiert +# (/api/session, /prompt, /model, /message). Mit `kind opencode` übersetzt junction das +# in beide Richtungen, sodass ein Client weiter /v1/chat/completions spricht. +# +# Zwei Werte kommen aus Kommandos, weil opencode sie nicht festhält: der Hintergrund- +# dienst bindet einen freien Port, und er erzeugt bei jedem Start ein neues Passwort. +endpoint opencode { + base http://127.0.0.1:4096 + kind opencode + context 200000 + timeout 600 + idle_timeout 120 + auth_basic opencode + pass_cmd /home/lotherk/.hermes/scripts/opencode_password.sh + # Nur nötig, wenn der Dienst auf einem zufälligen Port läuft: + # base_cmd "/home/lotherk/.opencode/bin/opencode service status" + cost 0.0 +} + # ---------------------------------------------------------------- Einbetter, klein und billig endpoint embed { base http://192.168.1.116:11434/v1 @@ -291,6 +312,10 @@ req path "/v1/models" check none pass cloud # Einbetter laufen lokal, egal was sonst gilt. req for "*embed*" check none pass embed +# Die freien opencode-Modelle gehen an den opencode-Endpunkt, alles andere nicht. +req for "opencode/*" pass opencode +req for "*-free" pass opencode + # Bildanfragen: immer an das Bildmodell, unabhängig vom angefragten Namen. Erst der # eigene Rechner (kostet nichts), dann die Cloud — dort mit umgeschriebenem Modellnamen. # "as" gilt für das Ziel direkt davor, nicht für die ganze Regel. diff --git a/src/config.c b/src/config.c index 1b9d893..38a7181 100644 --- a/src/config.c +++ b/src/config.c @@ -235,6 +235,39 @@ static int endpoint_kw(j_endpoint *ep, char **w, int n, int lineno, char *err, s if (!strcmp(k, "hook_retry")) { if (n != 2 || as_double(w[1], &ep->hook_retry_s)) goto bad; return 0; } if (!strcmp(k, "hook_backoff")) { if (n != 2 || as_double(w[1], &ep->hook_backoff_s)) goto bad; return 0; } if (!strcmp(k, "wake")) { if (n != 2) goto bad; snprintf(ep->wake, sizeof ep->wake, "%s", w[1]); return 0; } + if (!strcmp(k, "auth_basic")) { + /* auth_basic opencode — HTTP Basic mit diesem Benutzernamen. */ + if (n != 2) goto bad; + snprintf(ep->auth_basic_user, sizeof ep->auth_basic_user, "%s", w[1]); + return 0; + } + if (!strcmp(k, "pass_cmd")) { + /* pass_cmd "" — stdout (getrimmt) ist das Passwort. Nötig, weil + * opencode serve bei jedem Start ein neues erzeugt. */ + if (n < 2) goto bad; + char joined[J_CMD_MAX] = ""; + size_t used = 0; + for (int i = 1; i < n && used < sizeof joined - 1; i++) { + int wrote = snprintf(joined + used, sizeof joined - used, "%s%s", + i > 1 ? " " : "", w[i]); + if (wrote > 0) used += (size_t)wrote; + } + snprintf(ep->pass_cmd, sizeof ep->pass_cmd, "%s", joined); + return 0; + } + if (!strcmp(k, "base_cmd")) { + /* base_cmd "" — stdout (getrimmt) ist die Basis-URL. */ + if (n < 2) goto bad; + char joined[J_CMD_MAX] = ""; + size_t used = 0; + for (int i = 1; i < n && used < sizeof joined - 1; i++) { + int wrote = snprintf(joined + used, sizeof joined - used, "%s%s", + i > 1 ? " " : "", w[i]); + if (wrote > 0) used += (size_t)wrote; + } + snprintf(ep->base_cmd, sizeof ep->base_cmd, "%s", joined); + return 0; + } if (!strcmp(k, "api_key_env")) { if (n != 2) goto bad; snprintf(ep->api_key_env, sizeof ep->api_key_env, "%s", w[1]); return 0; } if (!strcmp(k, "usage_cmd")) { /* Command mit Argumenten: Rest der Zeile zusammenfuegen, damit Quotes optional bleiben */ diff --git a/src/config.h b/src/config.h index 6a472ac..b21fe76 100644 --- a/src/config.h +++ b/src/config.h @@ -76,6 +76,14 @@ typedef struct { int hook_count; char wake[J_CMD_MAX]; char api_key_env[J_NAME_MAX]; + /* kind opencode: HTTP Basic, wie opencode serve ihn verlangt. Der Benutzer ist fest + * "opencode", das Passwort steht in einer Datei und wird per Kommando gelesen, weil + * der Dienst bei jedem Start ein neues erzeugt. */ + char auth_basic_user[J_NAME_MAX]; + char pass_cmd[J_CMD_MAX]; + /* base darf ebenfalls aus einem Kommando kommen: der Hintergrunddienst von opencode + * bindet einen freien Port, der nur über "opencode service status" zu erfahren ist. */ + char base_cmd[J_CMD_MAX]; /* Limits. The command prints key=value pairs on one line: * percent=17.9 used_usd=10.73 budget_usd=60 reset_s=1234 diff --git a/src/junction.c b/src/junction.c index fb2fa60..32c3235 100644 --- a/src/junction.c +++ b/src/junction.c @@ -9,6 +9,7 @@ #define _POSIX_C_SOURCE 200809L #include "cache.h" +#include "opencode.h" #include "config.h" #include "conn.h" #include "http.h" @@ -525,6 +526,83 @@ static void admin(j_conn *c, const char *path) send_simple(c, 404, "Not Found", "{\"error\":\"unknown endpoint\"}"); } +/* Führt ein Kommando aus und gibt dessen getrimmte Standardausgabe zurück. + * + * Gebraucht für base_cmd und pass_cmd: opencode serve bindet einen freien Port und + * erzeugt bei jedem Start ein neues Passwort, beides ist nur über ein Kommando zu + * erfahren. Ein Cache von 60 Sekunden verhindert, dass jede Anfrage einen Prozess + * startet — häufiger als einmal pro Minute ändert sich daran nichts. + */ +static int cmd_value(int ep_index, int which, char *out, size_t outlen) +{ + static char cache_base[J_MAX_ENDPOINTS][J_URL_MAX]; + static char cache_pass[J_MAX_ENDPOINTS][J_NAME_MAX]; + static double cache_at[J_MAX_ENDPOINTS][2]; + double now = now_s(); + char *dst = which ? cache_pass[ep_index] : cache_base[ep_index]; + size_t dstlen = which ? J_NAME_MAX : J_URL_MAX; + + if (cache_at[ep_index][which] > 0 && now - cache_at[ep_index][which] < 60.0 && dst[0]) { + snprintf(out, outlen, "%s", dst); + return 0; + } + const char *cmd = which ? CFG.endpoints[ep_index].pass_cmd : CFG.endpoints[ep_index].base_cmd; + FILE *f = popen(cmd, "r"); + if (!f) return -1; + char line[1024] = ""; + size_t got = fread(line, 1, sizeof line - 1, f); + line[got] = '\0'; + pclose(f); + /* erste nicht-leere Zeile, getrimmt */ + char *p = line; + while (*p && isspace((unsigned char)*p)) p++; + char *nl = p; + while (*nl && *nl != '\n' && *nl != '\r') nl++; + *nl = '\0'; + if (!*p) return -1; + snprintf(dst, dstlen, "%s", p); + cache_at[ep_index][which] = now; + snprintf(out, outlen, "%s", p); + return 0; +} + +/* Bedient einen Endpunkt, der nicht OpenAI spricht, sondern opencode serve. + * Gibt 0 zurück, wenn die Antwort an den Client geschrieben wurde. */ +static int opencode_serve(j_conn *client, j_endpoint *ep_index_owner, const j_req *rq, + const char *model, char *err, size_t errlen) +{ + (void)ep_index_owner; + char base[J_URL_MAX], pass[J_NAME_MAX]; + if (cmd_value((int)(ep_index_owner - CFG.endpoints), 0, base, sizeof base) != 0) { + if (CFG.endpoints[ep_index_owner - CFG.endpoints].base_cmd[0]) { + snprintf(err, errlen, "opencode: base_cmd failed"); + return -1; + } + snprintf(base, sizeof base, "%s", ep_index_owner->base); + } + pass[0] = '\0'; + if (ep_index_owner->pass_cmd[0] && + cmd_value((int)(ep_index_owner - CFG.endpoints), 1, pass, sizeof pass) != 0) { + snprintf(err, errlen, "opencode: pass_cmd failed"); + return -1; + } + + char *body = NULL; + size_t blen = 0; + int rc; + if (!strncmp(rq->path, "/v1/models", 10)) + rc = j_opencode_models(base, ep_index_owner->auth_basic_user, pass, &body, &blen, + ep_index_owner->timeout_s, err, errlen); + else + rc = j_opencode_chat(base, ep_index_owner->auth_basic_user, pass, model, rq->body, + &body, &blen, ep_index_owner->timeout_s, err, errlen); + if (rc != 0) return -1; + + send_simple(client, 200, "OK", body); + free(body); + return 0; +} + /* --------------------------------------------------------------------- rules */ static int rule_matches(const j_rule *r, const char *path, const char *model, long need, long ctx, int has_image) @@ -1578,6 +1656,26 @@ static void handle_client(j_conn *client) STATE_LOCK(); ep->inflight++; STATE_UNLOCK(); + if (!strcmp(ep->kind, "opencode")) { + /* Kein OpenAI-Protokoll: die Brücke übersetzt Anfrage und Antwort. */ + int brc = opencode_serve(client, ep, &rq, rule->target_as[t][0] ? rule->target_as[t] : model, + err, sizeof err); + STATE_LOCK(); + ep->inflight--; + if (brc == 0) { + ep->ok_count++; + STATE_UNLOCK(); + if (slot_held) { slot_release(); slot_held = 0; } + jlog("served_by", "endpoint=%s bridge=opencode rule_line=%d", ep->name, rule->line); + goto done; + } + ep->fail_count++; + snprintf(ep->last_error, sizeof ep->last_error, "%s", err); + STATE_UNLOCK(); + jlog("failed", "endpoint=%s error=%s", ep->name, err); + strncat(attempts, " bridge", sizeof attempts - strlen(attempts) - 1); + continue; + } int rc = forward_step(client, ep, &rq, out_body, out_len, rule->target_as[t], model, may_cache ? "miss" : "off", started, head_sent, err, sizeof err); STATE_LOCK(); diff --git a/src/opencode.c b/src/opencode.c new file mode 100644 index 0000000..5068835 --- /dev/null +++ b/src/opencode.c @@ -0,0 +1,616 @@ +/* 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); +} diff --git a/src/opencode.h b/src/opencode.h new file mode 100644 index 0000000..350b06d --- /dev/null +++ b/src/opencode.h @@ -0,0 +1,41 @@ +/* junction/opencode.h — opencode serve as a first-class endpoint. + * + * An opencode serve speaks a session-oriented API: + * + * POST /api/session -> {"data":{"id":"ses_…"}} + * POST /api/session//model {"model":{"id":…,"providerID":…}} + * POST /api/session//prompt {"text":"…"} + * GET /api/session//message -> {"data":[{type,…},…]} + * DELETE /api/session/ + * + * There is no /v1/chat/completions. This module translates one into the other, so a + * client that speaks OpenAI never has to know it is talking to opencode. + */ +#ifndef JUNCTION_OPENCODE_H +#define JUNCTION_OPENCODE_H + +#include + +/* Runs one complete chat completion through opencode. + * + * base "http://127.0.0.1:4096" (no /v1 suffix; the paths above are absolute) + * user,pass HTTP Basic credentials; opencode accepts "opencode:" + * 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 + * out_body receives a malloc'ed OpenAI response body (caller frees) + * + * Returns 0 on success, -1 on failure with a reason in err. + */ +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); + +/* Lists the models an opencode server knows, as an OpenAI /v1/models body. + * Same ownership rules as above. */ +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); + +#endif /* JUNCTION_OPENCODE_H */ diff --git a/tests/opencode.sh b/tests/opencode.sh new file mode 100644 index 0000000..09c6a4a --- /dev/null +++ b/tests/opencode.sh @@ -0,0 +1,85 @@ +#!/bin/bash +# Wird von tests/run.sh eingebunden: die opencode-Brücke gegen einen Nachbau. +# Erwartet: $TMP, $PORT, ok/bad/contains, ./junction + +echo "== 18. opencode serve als Endpunkt (Brücke zu /v1/) ==" + +OC_PORT=$((PORT+18)) +OC_JUNC=$((PORT+19)) + +python3 tests/opencode_stub.py $OC_PORT > "$TMP/oc-stub.log" 2>&1 & +PIDS+=($!) +sleep 0.6 + +printf 'opencode:testpasswort\n' > "$TMP/oc.pass" +chmod +x "$TMP/oc.pass" +cat > "$TMP/oc.pass.sh" <<'SH' +#!/bin/sh +cat "$1" 2>/dev/null +SH +# Ein Skript, das das Passwort ausgibt — so wie im Betrieb opencode_password.sh. +printf '#!/bin/sh\necho opencode:testpasswort | cut -d: -f2\n' > "$TMP/oc.pass.sh" +chmod +x "$TMP/oc.pass.sh" + +cat > "$TMP/oc.conf" < "$TMP/oc.log" 2>&1 & +PIDS+=($!) +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" +case "$R" in + *'"id":"low"'*) bad "model variants leak into the list as models";; + *) ok "model variants do not leak into the list";; +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}' \ + "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" +contains "$R" '"reasoning_content":"kurz nachgedacht"' "reasoning is carried separately from the answer" +contains "$R" '"finish_reason":"stop"' "the finish reason is translated" +contains "$R" '"prompt_tokens":11' "the token counts are read from the session" + +# 3. Das Modell kam als provider/id an +R=$(curl -s -m 20 "http://127.0.0.1:$OC_JUNC/v1/models") +case "$R" in + *'"object":"list"'*) ok "the models call goes through the bridge, not the plain proxy";; + *) bad "the models call did not go through the bridge";; +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"}]}' \ + "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 +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" +./junction --config "$TMP/oc2.conf" > "$TMP/oc2.log" 2>&1 & +PIDS+=($!) +sleep 0.8 +R=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"x","messages":[{"role":"user","content":"hi"}]}' \ + "http://127.0.0.1:$((PORT+20))/v1/chat/completions") +contains "$R" 'no_endpoint_available' "a rejected password fails as a routing error, not a crash" diff --git a/tests/opencode_stub.py b/tests/opencode_stub.py new file mode 100644 index 0000000..2612327 --- /dev/null +++ b/tests/opencode_stub.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""Nachbau von opencode serve, gerade genug für die Brücke. + +Warum ein Nachbau und nicht der echte Dienst: ein Test, der ein fremdes Modell aufruft, +kostet Guthaben und ist nicht reproduzierbar. Dieser Nachbau antwortet deterministisch und +prüft dabei die Dinge, die die Brücke falsch machen könnte: + + - Basic-Auth muss ankommen (sonst 401, wie beim echten Dienst) + - der Modellname muss als provider/id ankommen + - die Sitzung muss am Ende gelöscht werden (der Test kann das nachsehen) + - ein Prompt muss ankommen, sonst antwortet es nie + +Port aus dem ersten Argument. +""" +import base64 +import json +import sys +from http.server import BaseHTTPRequestHandler, HTTPServer + +PORT = int(sys.argv[1]) +USER, PASS = 'opencode', 'testpasswort' +SESSIONS = {} +DELETED = [] + + +class H(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def _auth(self): + want = 'Basic ' + base64.b64encode(('%s:%s' % (USER, PASS)).encode()).decode() + return self.headers.get('Authorization') == want + + def _json(self, code, obj): + body = json.dumps(obj).encode() + self.send_response(code) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _body(self): + n = int(self.headers.get('Content-Length') or 0) + try: + return json.loads(self.rfile.read(n) or b'{}') + except Exception: + return {} + + def do_GET(self): + if not self._auth(): + return self._json(401, {'_tag': 'UnauthorizedError'}) + + if self.path == '/api/model': + return self._json(200, {'data': [ + {'id': 'glm-5.3-flash-free', 'modelID': 'glm-5.3-flash-free', + 'providerID': 'opencode', 'variants': [{'id': 'low'}, {'id': 'high'}]}, + {'id': 'beam-free', 'modelID': 'beam-free', + 'providerID': 'opencode', 'variants': []}, + ]}) + + if self.path.startswith('/api/session/') and self.path.endswith('/message'): + sid = self.path.split('/')[3] + s = SESSIONS.get(sid) + if not s: + return self._json(404, {'error': 'no session'}) + msgs = [{'id': 'msg_user', 'type': 'user', 'text': s['prompt']}] + if s.get('prompt'): + msgs.append({ + 'id': 'msg_ai', 'type': 'assistant', + 'time': {'created': 1, 'completed': 2}, + 'model': {'id': s['model'], 'providerID': 'opencode'}, + 'content': [ + {'type': 'reasoning', 'text': 'kurz nachgedacht'}, + {'type': 'text', 'text': 'ANTWORT auf: ' + s['prompt']}, + ], + 'finish': 'stop', + 'tokens': {'input': 11, 'output': 7}, + }) + return self._json(200, {'data': msgs, 'cursor': {}}) + + return self._json(404, {'error': 'unknown path'}) + + def do_POST(self): + if not self._auth(): + return self._json(401, {'_tag': 'UnauthorizedError'}) + body = self._body() + + if self.path == '/api/session': + sid = 'ses_%d' % (len(SESSIONS) + 1) + SESSIONS[sid] = {'model': None, 'prompt': None} + return self._json(200, {'data': {'id': sid}}) + + parts = self.path.strip('/').split('/') + if len(parts) == 4 and parts[0] == 'api' and parts[3] == 'model': + sid = SYSSID(SESSIONS, self) + if sid is None: + return self._json(404, {'error': 'no session'}) + m = body.get('model') or {} + SESSIONS[sid]['model'] = '%s/%s' % (m.get('providerID'), m.get('id')) + self.send_response(204) + self.end_headers() + return + + if len(parts) == 4 and parts[0] == 'api' and parts[3] == 'prompt': + sid = SYSSID(SESSIONS, self) + if sid is None: + return self._json(404, {'error': 'no session'}) + SESSIONS[sid]['prompt'] = body.get('text', '') + return self._json(200, {'data': {'id': 'msg_user', 'type': 'user'}}) + + return self._json(404, {'error': 'unknown path'}) + + def do_DELETE(self): + if not self._auth(): + return self._json(401, {'_tag': 'UnauthorizedError'}) + parts = self.path.strip('/').split('/') + if len(parts) == 3 and parts[0] == 'api' and parts[1] == 'session': + SESSIONS.pop(parts[2], None) + DELETED.append(parts[2]) + self.send_response(204) + self.end_headers() + return + return self._json(404, {'error': 'unknown path'}) + + +def SYSSID(sessions, handler): + """Sitzungs-ID aus dem Pfad /api/session//.""" + parts = handler.path.strip('/').split('/') + if len(parts) < 4 or parts[0] != 'api' or parts[1] != 'session': + return None + return parts[2] if parts[2] in sessions else None + + +if __name__ == '__main__': + print('opencode-stub auf %d' % PORT, flush=True) + HTTPServer(('127.0.0.1', PORT), H).serve_forever() diff --git a/tests/run.sh b/tests/run.sh index 5b3dc7a..461ccbd 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -20,7 +20,7 @@ contains() { case "$1" in *"$2"*) ok "$3";; *) bad "$3 (missing '$2')";; esac; } # A leftover process on a test port produces confusing failures (a stale junction can # answer requests with somebody else's config), so fail loudly and early. -for port in 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 9443 9990 9991 9992 9993 9994 9995 9996; do +for port in 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 9443 9990 9991 9992 9993 9994 9995 9996; do if ss -tln 2>/dev/null | grep -q ":$port "; then echo "port $port is busy — a leftover junction/stub is still running:" ss -tlnp 2>/dev/null | grep ":$port " | sed 's/^/ /' @@ -615,6 +615,10 @@ contains "$OUT" "bad arguments" "an impossible offpeak window is rejected" # shellcheck source=tests/ctx-vision.sh . "$(dirname "$0")/ctx-vision.sh" +# Die opencode-Brücke, gegen einen Nachbau des Sitzungs-API. +# shellcheck source=tests/opencode.sh +. "$(dirname "$0")/opencode.sh" + echo if [ "$FAILED" -eq 0 ]; then echo "PASS"; else echo "FAILURES"; fi exit "$FAILED"