An Anthropic OAuth token (sk-ant-oat01…, e.g. CLAUDE_CODE_OAUTH_TOKEN) is not an API key. Sent with an ordinary body, a current model answers 429 rate_limit_error "Error" — the same status and shape as an exhausted quota, so the endpoint looks broken at random instead of misconfigured. `oauth on` per endpoint puts Claude Code's system prompt in place, and only for endpoints that ask for it. The client's own system prompt is kept: on /v1/messages as further blocks after the marker (cache_control intact), on /v1/chat/completions as its own user message before the first turn — there the system content must be the marker alone. Measured against api.anthropic.com, each case repeated: body /v1/messages /v1/chat/completions no system 429 429 system = <marker> 200 200 system = [<marker>, <text>] 200 429 system = [<text>, <marker>] 429 429 The gating is model-dependent: retired names such as claude-haiku-4-5-20251001 answer without the marker and prove nothing. claude-sonnet-5-5, claude-haiku-5-5, claude-opus-5 and claude-opus-4-8 are gated. The marker matches byte for byte — a missing final period or a trailing newline is worth the same as no marker at all. Verified: full suite PASS, 574 OK, 0 failures. Against the live API through junction with a real subscription token: 200 on claude-sonnet-5-5 for /v1/messages (client system prompt applied, answer "Paris") and for /v1/chat/completions; streaming with a tool call works; the same request with `oauth off` still gets 429 upstream, which is the counter-proof that the option is what changes the outcome. Token B in ~/toktok is dead independently of this (403 oauth_not_allowed_for_organization). The stub's new STUB_BODY_FILE writes request bodies verbatim; a structural check (is the marker the first block) cannot be done from a header.
591 lines
27 KiB
C
591 lines
27 KiB
C
/* tests/stub.c — OpenAI-compatible stub endpoint for the test suite.
|
|
*
|
|
* stub <port> <name> [--fail] [--delay SECONDS] [--tls CERT KEY]
|
|
* [--fail-n N] [--deny-auth SUBSTR]
|
|
*
|
|
* --retry-after N puts "Retry-After: N" into every forced 503/429, so a test can check
|
|
* that junction waits as long as the provider asked instead of its own backoff.
|
|
* --retry-after-date OFF sends the same value as an HTTP date (now + OFF seconds), the
|
|
* other form RFC 7231 allows — with a negative OFF it is a date in the past.
|
|
* --fail always answers 503 (an endpoint that is up but will not serve)
|
|
* --delay waits that long before answering (to exercise "still_working")
|
|
* --fail-n answers 503 for the first N requests, then serves — the counter lives in
|
|
* $STUB_STATE, so it survives the fork per connection and the test can prove
|
|
* that a 5xx is retried on the same endpoint instead of failing over
|
|
* --deny-auth answers 429 when the Authorization header contains SUBSTR — the way to
|
|
* check that junction rotates to the next key of a pool
|
|
*
|
|
* The stub echoes what it received in response headers (X-Stub-*) so the tests can
|
|
* prove header passthrough and body integrity, including after chunked decoding.
|
|
*/
|
|
#define _POSIX_C_SOURCE 200809L
|
|
|
|
#include "../src/conn.h"
|
|
|
|
#include <arpa/inet.h>
|
|
#include <netinet/in.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <strings.h>
|
|
#include <signal.h>
|
|
#include <fcntl.h>
|
|
#include <sys/file.h>
|
|
#include <sys/socket.h>
|
|
#include <time.h>
|
|
#include <unistd.h>
|
|
#include <sys/wait.h>
|
|
|
|
/* header value of `name` in a request head, or NULL */
|
|
static int count_header(const char *head, const char *name)
|
|
{
|
|
size_t n = strlen(name);
|
|
int count = 0;
|
|
for (const char *p = head; *p; p++)
|
|
if (!strncasecmp(p, name, n) && p[n] == ':') count++;
|
|
return count;
|
|
}
|
|
|
|
static const char *find_header(const char *head, const char *name, char *out, size_t outlen)
|
|
{
|
|
size_t nlen = strlen(name);
|
|
for (const char *p = head; *p; ) {
|
|
const char *eol = strstr(p, "\r\n");
|
|
if (!eol) break;
|
|
if ((size_t)(eol - p) > nlen && !strncasecmp(p, name, nlen) && p[nlen] == ':') {
|
|
const char *v = p + nlen + 1;
|
|
while (v < eol && (*v == ' ' || *v == '\t')) v++;
|
|
size_t vl = (size_t)(eol - v);
|
|
if (vl >= outlen) vl = outlen - 1;
|
|
memcpy(out, v, vl);
|
|
out[vl] = '\0';
|
|
return out;
|
|
}
|
|
p = eol + 2;
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
/* Copy a JSON string field from the body. Enough for the tests: the value is plain
|
|
* ASCII and has no escapes. */
|
|
static void find_json_string(const char *body, const char *key, char *out, size_t outlen)
|
|
{
|
|
out[0] = '\0';
|
|
char pat[64];
|
|
snprintf(pat, sizeof pat, "\"%s\"", key);
|
|
const char *p = strstr(body, pat);
|
|
if (!p) return;
|
|
p += strlen(pat);
|
|
while (*p == ':' || *p == ' ' || *p == '\t') p++;
|
|
if (*p != '"') return;
|
|
p++;
|
|
size_t i = 0;
|
|
while (*p && *p != '"' && i < outlen - 1) out[i++] = *p++;
|
|
out[i] = '\0';
|
|
}
|
|
|
|
/* A JSON number field, enough for tests ("n":2). */
|
|
static long find_json_int(const char *body, const char *key)
|
|
{
|
|
char pat[64];
|
|
snprintf(pat, sizeof pat, "\"%s\"", key);
|
|
const char *p = strstr(body, pat);
|
|
if (!p) return -1;
|
|
p += strlen(pat);
|
|
while (*p == ':' || *p == ' ' || *p == '\t') p++;
|
|
if (*p < '0' || *p > '9') return -1;
|
|
return strtol(p, NULL, 10);
|
|
}
|
|
|
|
/* Zählt Anfragen über Prozessgrenzen hinweg — der Stub forkt je Verbindung, ein
|
|
* Zähler im Speicher des Vaters wäre für das Kind unsichtbar. Die Datei kommt aus
|
|
* $STUB_STATE; ohne sie zählt niemand und --fail-n bleibt wirkungslos. */
|
|
static int request_serial(void)
|
|
{
|
|
const char *path = getenv("STUB_STATE");
|
|
if (!path || !*path) return 0;
|
|
int fd = open(path, O_RDWR | O_CREAT, 0600);
|
|
if (fd < 0) return 0;
|
|
if (flock(fd, LOCK_EX) != 0) { close(fd); return 0; }
|
|
char b[32] = "";
|
|
ssize_t got = read(fd, b, sizeof b - 1);
|
|
int seen = (got > 0) ? atoi(b) : 0;
|
|
seen++;
|
|
snprintf(b, sizeof b, "%d\n", seen);
|
|
if (lseek(fd, 0, SEEK_SET) == 0 && ftruncate(fd, 0) == 0) {
|
|
ssize_t w = write(fd, b, strlen(b));
|
|
(void)w;
|
|
}
|
|
flock(fd, LOCK_UN);
|
|
close(fd);
|
|
return seen;
|
|
}
|
|
|
|
int main(int argc, char **argv)
|
|
{
|
|
if (argc < 3) {
|
|
fprintf(stderr, "usage: stub <port> <name> [--fail] [--delay SECONDS] [--fail-n N] [--deny-auth SUBSTR]\n");
|
|
return 2;
|
|
}
|
|
int port = atoi(argv[1]);
|
|
const char *name = argv[2];
|
|
int fail = 0;
|
|
double delay = 0;
|
|
int fail_n = 0;
|
|
int forced_status = 0;
|
|
int retry_after = 0;
|
|
int retry_after_date = 0;
|
|
int has_retry_date = 0;
|
|
int sse_mode = 0;
|
|
const char *deny_auth = "";
|
|
const char *cert = NULL, *key = NULL;
|
|
for (int i = 3; i < argc; i++) {
|
|
if (!strcmp(argv[i], "--fail")) fail = 1;
|
|
else if (!strcmp(argv[i], "--sse")) sse_mode = 1;
|
|
else if (!strcmp(argv[i], "--sse-cap")) sse_mode = 2;
|
|
else if (!strcmp(argv[i], "--sse-no-te")) sse_mode = 3;
|
|
else if (!strcmp(argv[i], "--delay") && i + 1 < argc) delay = atof(argv[++i]);
|
|
else if (!strcmp(argv[i], "--fail-n") && i + 1 < argc) fail_n = atoi(argv[++i]);
|
|
else if (!strcmp(argv[i], "--status") && i + 1 < argc) forced_status = atoi(argv[++i]);
|
|
else if (!strcmp(argv[i], "--deny-auth") && i + 1 < argc) deny_auth = argv[++i];
|
|
else if (!strcmp(argv[i], "--retry-after") && i + 1 < argc) retry_after = atoi(argv[++i]);
|
|
else if (!strcmp(argv[i], "--retry-after-date") && i + 1 < argc) {
|
|
retry_after_date = atoi(argv[++i]);
|
|
has_retry_date = 1;
|
|
}
|
|
else if (!strcmp(argv[i], "--tls") && i + 2 < argc) { cert = argv[++i]; key = argv[++i]; }
|
|
}
|
|
const char *answers_env = getenv("STUB_ANSWERS");
|
|
const char *tools_env = getenv("STUB_TOOLS");
|
|
|
|
char tlserr[256];
|
|
if (cert && j_tls_server_start(cert, key, tlserr, sizeof tlserr)) {
|
|
fprintf(stderr, "stub tls: %s\n", tlserr);
|
|
return 1;
|
|
}
|
|
|
|
int lfd = socket(AF_INET, SOCK_STREAM, 0);
|
|
int one = 1;
|
|
setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
|
|
struct sockaddr_in addr;
|
|
memset(&addr, 0, sizeof addr);
|
|
addr.sin_family = AF_INET;
|
|
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
|
addr.sin_port = htons((unsigned short)port);
|
|
if (bind(lfd, (struct sockaddr *)&addr, sizeof addr) || listen(lfd, 16)) {
|
|
perror("bind/listen");
|
|
return 1;
|
|
}
|
|
fprintf(stderr, "stub %s on %d%s\n", name, port, fail ? " (failing)" : "");
|
|
|
|
signal(SIGCHLD, SIG_IGN); /* one fork per connection, reaped by the kernel */
|
|
for (;;) {
|
|
int cfd = accept(lfd, NULL, NULL);
|
|
if (cfd < 0) continue;
|
|
/* A real model server answers several requests at once; a serial stub would
|
|
* make the router look serialised when it is not. */
|
|
pid_t child = fork();
|
|
if (child > 0) { close(cfd); continue; }
|
|
if (child < 0) { close(cfd); continue; }
|
|
/* Das Kind schließt das Hör-Socket. Sonst hält eine Verbindung, die nie
|
|
* fertig wird (Client weg, TLS-Handshake hängt), ein Kind am Leben, und
|
|
* mit ihm den Port — der Testlauf ist beendet, :9443 aber weiter belegt,
|
|
* und der nächste Lauf verweigert mit "port busy" die Arbeit. */
|
|
close(lfd);
|
|
j_conn client = J_CONN_INIT;
|
|
char aerr[256];
|
|
if (cert) {
|
|
if (j_tls_server_accept(&client, cfd, aerr, sizeof aerr)) {
|
|
fprintf(stderr, "stub tls accept: %s\n", aerr);
|
|
close(cfd);
|
|
/* Kein Hör-Socket mehr im Kind: jedes `continue` wäre eine
|
|
* Endlosschleife um accept() mit EBADF und 100 % CPU. */
|
|
_exit(0);
|
|
}
|
|
} else {
|
|
client.fd = cfd;
|
|
}
|
|
client.role = "stub";
|
|
|
|
char req[131072];
|
|
size_t used = 0;
|
|
ssize_t n;
|
|
char ioerr[192];
|
|
while (used < sizeof req - 1 && (n = j_conn_read(&client, req + used,
|
|
sizeof req - 1 - used,
|
|
ioerr, sizeof ioerr)) > 0) {
|
|
used += (size_t)n;
|
|
req[used] = '\0';
|
|
if (strstr(req, "\r\n\r\n")) break;
|
|
}
|
|
if (used == 0) { j_conn_close(&client); _exit(0); }
|
|
req[used] = '\0';
|
|
|
|
/* Zwei künstliche Fehler, ohne die sich Retry und Schlüsselrotation nicht
|
|
* nachweisen lassen: ein 503 für die ersten N Anfragen und ein 429 für einen
|
|
* bestimmten Schlüssel. */
|
|
char authhdr[256] = "";
|
|
find_header(req, "Authorization", authhdr, sizeof authhdr);
|
|
int forced = 0;
|
|
/* Nur Chat-Anfragen zählen: junction holt beim Start GET /v1/models, und diese
|
|
* eine Anfrage darf das Fehlerkontingent des Tests nicht verbrauchen. */
|
|
int counts = !strncmp(req, "POST", 4) && strstr(req, "/chat/completions");
|
|
int serial = 0, have_serial = 0;
|
|
if (counts && (fail_n > 0 || (answers_env && *answers_env))) {
|
|
serial = request_serial();
|
|
have_serial = 1;
|
|
}
|
|
if (forced_status > 0 && counts) forced = forced_status;
|
|
else if (fail_n > 0 && counts && have_serial && serial <= fail_n) forced = 503;
|
|
else if (deny_auth[0] && strstr(authhdr, deny_auth)) forced = 429;
|
|
|
|
/* STUB_ANSWERS="first|second|third": the n-th chat request answers with
|
|
* the n-th entry (the last entry repeats). This is how the self-review
|
|
* test sees a different answer on every round. */
|
|
char selected_answer[1024] = "";
|
|
if (answers_env && *answers_env && counts && have_serial) {
|
|
const char *q = answers_env;
|
|
int idx = 1;
|
|
for (;;) {
|
|
const char *bar = strchr(q, '|');
|
|
size_t len = bar ? (size_t)(bar - q) : strlen(q);
|
|
if (idx == serial) {
|
|
if (len >= sizeof selected_answer) len = sizeof selected_answer - 1;
|
|
memcpy(selected_answer, q, len);
|
|
selected_answer[len] = '\0';
|
|
break;
|
|
}
|
|
if (!bar) {
|
|
if (len >= sizeof selected_answer) len = sizeof selected_answer - 1;
|
|
memcpy(selected_answer, q, len);
|
|
selected_answer[len] = '\0';
|
|
break;
|
|
}
|
|
q = bar + 1;
|
|
idx++;
|
|
}
|
|
}
|
|
|
|
char *head_end = strstr(req, "\r\n\r\n");
|
|
size_t head_len = head_end ? (size_t)(head_end + 4 - req) : used;
|
|
char cl[32];
|
|
long content_length = 0;
|
|
if (find_header(req, "Content-Length", cl, sizeof cl)) content_length = strtol(cl, NULL, 10);
|
|
|
|
while ((long)(used - head_len) < content_length && used < sizeof req - 1) {
|
|
n = j_conn_read(&client, req + used, sizeof req - 1 - used, ioerr, sizeof ioerr);
|
|
if (n <= 0) break;
|
|
used += (size_t)n;
|
|
}
|
|
req[used] = '\0';
|
|
long body_len = (long)used - (long)head_len;
|
|
if (body_len < 0) body_len = 0;
|
|
|
|
/* A strict provider rejects stream_options on a non-streaming request.
|
|
* junction must strip it before forcing stream:false for a review. */
|
|
const char *reject_so = getenv("STUB_REJECT_STREAM_OPTIONS");
|
|
if (reject_so && *reject_so && counts &&
|
|
strstr(req + head_len, "\"stream_options\""))
|
|
forced = 400;
|
|
/* A judge call carries cache_control when the rule asks for it. This lets
|
|
* a test fail the judge while the worker (same endpoint) still serves. */
|
|
const char *fail_cache = getenv("STUB_FAIL_CACHE");
|
|
if (fail_cache && *fail_cache && counts &&
|
|
strstr(req + head_len, "\"cache_control\""))
|
|
forced = 503;
|
|
|
|
if (delay > 0) {
|
|
struct timespec ts = { (time_t)delay, (time_t)((delay - (time_t)delay) * 1e9) };
|
|
nanosleep(&ts, NULL);
|
|
}
|
|
|
|
/* STUB_BODY_FILE=<path>: write the request body verbatim. A test that has to
|
|
* check JSON *structure* (is the marker the first system block, did the
|
|
* client's prompt survive) cannot do it from a header, and dumping the whole
|
|
* body into a header would break on a real prompt. Append, so a test can see
|
|
* every request of one run. */
|
|
const char *body_file = getenv("STUB_BODY_FILE");
|
|
if (body_file && *body_file && body_len > 0) {
|
|
int bfd = open(body_file, O_WRONLY | O_CREAT | O_APPEND, 0600);
|
|
if (bfd >= 0) {
|
|
if (flock(bfd, LOCK_EX) == 0) {
|
|
(void)!write(bfd, req + head_len, (size_t)body_len);
|
|
(void)!write(bfd, "\n", 1);
|
|
}
|
|
close(bfd);
|
|
}
|
|
}
|
|
|
|
char custom[256] = "", static_hdr[256] = "", fwd[256] = "", accept[128] = "";
|
|
char effort[64] = "", thinking[64] = "", xapi[128] = "", av[64] = "";
|
|
/* the model field as it arrived, so the tests can see a rewrite (and a
|
|
* rewrite that broke the JSON would show up as a name with junk attached) */
|
|
char model[128] = "";
|
|
const char *mk = strstr(req, "\"model\"");
|
|
if (mk) {
|
|
const char *q = strchr(mk, ':');
|
|
if (q) {
|
|
q++;
|
|
while (*q == ' ' || *q == '\t') q++;
|
|
if (*q == '"') {
|
|
const char *e = strchr(++q, '"');
|
|
if (e) {
|
|
size_t ml = (size_t)(e - q);
|
|
if (ml >= sizeof model) ml = sizeof model - 1;
|
|
memcpy(model, q, ml);
|
|
model[ml] = '\0';
|
|
}
|
|
}
|
|
}
|
|
}
|
|
char reasoning[64] = "";
|
|
find_json_string(req + head_len, "reasoning_effort", reasoning, sizeof reasoning);
|
|
find_json_string(req + head_len, "effort", effort, sizeof effort);
|
|
find_json_string(req + head_len, "type", thinking, sizeof thinking);
|
|
int has_reasoning = strstr(req + head_len, "\"reasoning\"") != NULL;
|
|
/* A judge turn carries a cache_control marker so the provider can reuse
|
|
* the conversation prefix. The test reads this header. */
|
|
int has_cache_control = strstr(req + head_len, "\"cache_control\"") != NULL;
|
|
int has_review = strstr(req + head_len, "Review your previous answer") != NULL;
|
|
int has_prev = 0;
|
|
if (answers_env && *answers_env && counts && have_serial && serial > 1) {
|
|
const char *q = answers_env;
|
|
int idx = 1;
|
|
for (;;) {
|
|
const char *bar = strchr(q, '|');
|
|
size_t len = bar ? (size_t)(bar - q) : strlen(q);
|
|
if (idx == serial - 1) {
|
|
char prev[1024];
|
|
if (len >= sizeof prev) len = sizeof prev - 1;
|
|
memcpy(prev, q, len);
|
|
prev[len] = '\0';
|
|
has_prev = strstr(req + head_len, prev) != NULL;
|
|
break;
|
|
}
|
|
if (!bar) break;
|
|
q = bar + 1;
|
|
idx++;
|
|
}
|
|
}
|
|
find_header(req, "X-Custom", custom, sizeof custom);
|
|
find_header(req, "X-Static", static_hdr, sizeof static_hdr);
|
|
find_header(req, "X-Forwarded-For", fwd, sizeof fwd);
|
|
find_header(req, "Accept-Encoding", accept, sizeof accept);
|
|
find_header(req, "x-api-key", xapi, sizeof xapi);
|
|
find_header(req, "anthropic-version", av, sizeof av);
|
|
int av_count = count_header(req, "anthropic-version");
|
|
|
|
char many[4096] = "";
|
|
const char *many_env = getenv("STUB_MANY_HEADERS");
|
|
if (many_env && *many_env) {
|
|
long count = strtol(many_env, NULL, 10);
|
|
size_t mo = 0;
|
|
for (long i = 0; i < count && mo + 48 < sizeof many; i++)
|
|
mo += (size_t)snprintf(many + mo, sizeof many - mo,
|
|
"X-Stub-Many-%ld: v\r\n", i);
|
|
}
|
|
const char *bad_env = getenv("STUB_BAD_HEADER");
|
|
const char *bad_header = (bad_env && *bad_env)
|
|
? "X-Stub-Bad: a\001b\r\n" : "";
|
|
|
|
char body[8192];
|
|
if (forced) {
|
|
/* Retry-After: standardmäßig 0 — der Stub weiß nicht, wie lange ein echtes
|
|
* Kontingent braucht; die 0 macht klar, dass sofort weiterversucht werden
|
|
* darf. Mit --retry-after N sagt er eine Zahl, damit der Test prüfen kann,
|
|
* dass junction genau so lange wartet. */
|
|
const char *b = (forced == 429) ? "{\"error\":\"rate limited\"}"
|
|
: (forced == 400) ? "{\"error\":\"bad request from stub\"}"
|
|
: "{\"error\":\"not serving yet\"}";
|
|
char ra[64];
|
|
if (has_retry_date) {
|
|
time_t when = time(NULL) + retry_after_date;
|
|
struct tm g;
|
|
gmtime_r(&when, &g);
|
|
strftime(ra, sizeof ra, "%a, %d %b %Y %H:%M:%S GMT", &g);
|
|
} else {
|
|
snprintf(ra, sizeof ra, "%d", retry_after);
|
|
}
|
|
snprintf(body, sizeof body,
|
|
"HTTP/1.1 %d %s\r\nContent-Type: application/json\r\nRetry-After: %s\r\n"
|
|
"Content-Length: %zu\r\nConnection: close\r\n\r\n%s",
|
|
forced, (forced == 429) ? "Too Many Requests"
|
|
: (forced == 400) ? "Bad Request" : "Service Unavailable",
|
|
ra, strlen(b), b);
|
|
} else if (fail) {
|
|
const char *b = "{\"error\":\"not serving\"}";
|
|
snprintf(body, sizeof body,
|
|
"HTTP/1.1 503 Service Unavailable\r\nContent-Type: application/json\r\n"
|
|
"Content-Length: %zu\r\nConnection: close\r\n\r\n%s", strlen(b), b);
|
|
} else if (!strncmp(req, "POST", 4) && strstr(req, "/api/show")) {
|
|
/* Zweite Quelle für Grenzen: die eigene API eines Endpunkts.
|
|
* ollama.com veröffentlicht dort model_info["<arch>.context_length"]. */
|
|
const char *show = getenv("STUB_SHOW_CTX");
|
|
char b[256];
|
|
snprintf(b, sizeof b,
|
|
"{\"model_info\":{\"%s.context_length\":%ld},\"details\":{\"family\":\"%s\"}}",
|
|
name, show ? strtol(show, NULL, 10) : 0L, name);
|
|
snprintf(body, sizeof body,
|
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
|
|
"Content-Length: %zu\r\nConnection: close\r\n\r\n%s", strlen(b), b);
|
|
} else if (!strncmp(req, "GET", 3)) {
|
|
/* Ein Endpunkt, der Grenzen veröffentlicht: nur so lässt sich prüfen, dass
|
|
* junction die Modellzahl der Endpunktzahl vorzieht. STUB_CTX/STUB_OUT. */
|
|
char b[2048];
|
|
const char *ectx = getenv("STUB_CTX");
|
|
const char *eout = getenv("STUB_OUT");
|
|
const char *list = getenv("STUB_MODELS");
|
|
if (list && *list) {
|
|
/* Eine Liste mit mehreren IDs, damit die Modell-Politik etwas zu
|
|
* filtern hat: STUB_MODELS="foo,bar,ma/bla". */
|
|
size_t bo = 0;
|
|
int first = 1;
|
|
bo += (size_t)snprintf(b + bo, sizeof b - bo,
|
|
"{\"object\":\"list\",\"data\":[");
|
|
const char *p = list;
|
|
while (*p && bo + 128 < sizeof b) {
|
|
const char *comma = strchr(p, ',');
|
|
size_t l = comma ? (size_t)(comma - p) : strlen(p);
|
|
if (ectx && *ectx)
|
|
bo += (size_t)snprintf(b + bo, sizeof b - bo,
|
|
"%s{\"id\":\"%.*s\",\"limit\":"
|
|
"{\"context\":%ld,\"output\":%ld}}",
|
|
first ? "" : ",", (int)l, p,
|
|
strtol(ectx, NULL, 10),
|
|
eout ? strtol(eout, NULL, 10) : 0L);
|
|
else
|
|
bo += (size_t)snprintf(b + bo, sizeof b - bo,
|
|
"%s{\"id\":\"%.*s\"}",
|
|
first ? "" : ",", (int)l, p);
|
|
first = 0;
|
|
if (!comma) break;
|
|
p = comma + 1;
|
|
}
|
|
snprintf(b + bo, sizeof b - bo, "]}");
|
|
} else if (ectx && *ectx)
|
|
snprintf(b, sizeof b,
|
|
"{\"object\":\"list\",\"data\":[{\"id\":\"%s\",\"limit\":"
|
|
"{\"context\":%ld,\"output\":%ld}}]}",
|
|
name, strtol(ectx, NULL, 10), eout ? strtol(eout, NULL, 10) : 0L);
|
|
else
|
|
snprintf(b, sizeof b, "{\"object\":\"list\",\"data\":[{\"id\":\"%s\"}]}", name);
|
|
snprintf(body, sizeof body,
|
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
|
|
"Content-Length: %zu\r\nX-Stub-Name: %s\r\nX-Stub-Body-Len: %ld\r\n"
|
|
"X-Stub-Accept: %s\r\n"
|
|
"Connection: close\r\n\r\n%s", strlen(b), name, body_len, accept, b);
|
|
} else {
|
|
char b[4096];
|
|
if (tools_env && *tools_env) {
|
|
long ntools = strtol(tools_env, NULL, 10);
|
|
char calls[2048];
|
|
size_t co = 0;
|
|
|
|
if (ntools < 1) ntools = 1;
|
|
if (ntools > 8) ntools = 8;
|
|
calls[0] = '\0';
|
|
for (long t = 0; t < ntools; t++) {
|
|
int w = snprintf(calls + co, sizeof calls - co,
|
|
"%s{\"id\":\"call_%ld\",\"type\":\"function\","
|
|
"\"function\":{\"name\":\"doit%ld\","
|
|
"\"arguments\":\"{}\"}}",
|
|
t ? "," : "", t + 1, t + 1);
|
|
if (w < 0 || (size_t)w >= sizeof calls - co) break;
|
|
co += (size_t)w;
|
|
}
|
|
snprintf(b, sizeof b,
|
|
"{\"id\":\"stub\",\"model\":\"%s\",\"choices\":[{\"index\":0,"
|
|
"\"message\":{\"role\":\"assistant\",\"content\":null,"
|
|
"\"tool_calls\":[%s]},"
|
|
"\"finish_reason\":\"tool_calls\"}]}",
|
|
name, calls);
|
|
} else {
|
|
char default_answer[256];
|
|
snprintf(default_answer, sizeof default_answer, "served by %s", name);
|
|
const char *ans = selected_answer[0] ? selected_answer : default_answer;
|
|
const char *content_array = getenv("STUB_CONTENT_ARRAY");
|
|
const char *null_tools = getenv("STUB_NULL_TOOLS");
|
|
const char *tc_null = (null_tools && *null_tools)
|
|
? ",\"tool_calls\":null" : "";
|
|
char content[1280];
|
|
if (content_array && *content_array)
|
|
snprintf(content, sizeof content,
|
|
"[{\"type\":\"text\",\"text\":\"%s\"}]", ans);
|
|
else
|
|
snprintf(content, sizeof content, "\"%s\"", ans);
|
|
/* Honour the client's n so a test can prove that several choices
|
|
* pass through unreviewed. */
|
|
long choices = find_json_int(req + head_len, "n");
|
|
if (choices < 1) choices = 1;
|
|
if (choices > 4) choices = 4;
|
|
size_t bo = 0;
|
|
int wrote = snprintf(b, sizeof b,
|
|
"{\"id\":\"stub\",\"model\":\"%s\",\"choices\":[",
|
|
name);
|
|
if (wrote > 0) bo = (size_t)wrote;
|
|
for (long c = 0; c < choices; c++) {
|
|
if (bo >= sizeof b) break;
|
|
wrote = snprintf(b + bo, sizeof b - bo,
|
|
"%s{\"index\":%ld,\"message\":{\"role\":\"assistant\","
|
|
"\"content\":%s%s}}",
|
|
c ? "," : "", c, content, tc_null);
|
|
if (wrote < 0 || (size_t)wrote >= sizeof b - bo) {
|
|
bo = sizeof b - 1;
|
|
break;
|
|
}
|
|
bo += (size_t)wrote;
|
|
}
|
|
const char *usage_env = getenv("STUB_USAGE");
|
|
const char *usage = (usage_env && *usage_env)
|
|
? ",\"usage\":{\"prompt_tokens\":1200,"
|
|
"\"completion_tokens\":300,"
|
|
"\"prompt_tokens_details\":{\"cached_tokens\":0}}"
|
|
: "";
|
|
if (bo < sizeof b - 2)
|
|
snprintf(b + bo, sizeof b - bo, "]%s}", usage);
|
|
}
|
|
if (sse_mode) {
|
|
const char *e1 = "data: {\"stub\":\"one\"}\n\n";
|
|
const char *e2 = "data: {\"stub\":\"two\"}\n\n";
|
|
int off = snprintf(body, sizeof body,
|
|
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n"
|
|
"Cache-Control: no-cache\r\n%sConnection: close\r\n\r\n",
|
|
sse_mode == 1 ? "Transfer-Encoding: chunked\r\n" :
|
|
sse_mode == 2 ? "Transfer-Encoding: Chunked\r\n" : "");
|
|
if (off > 0 && (size_t)off < sizeof body) {
|
|
off += snprintf(body + off, sizeof body - (size_t)off,
|
|
"%zx\r\n%s\r\n", strlen(e1), e1);
|
|
off += snprintf(body + off, sizeof body - (size_t)off,
|
|
"%zx\r\n%s\r\n", strlen(e2), e2);
|
|
snprintf(body + off, sizeof body - (size_t)off, "0\r\n\r\n");
|
|
}
|
|
} else
|
|
snprintf(body, sizeof body,
|
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
|
|
"Content-Length: %zu\r\n"
|
|
"X-Stub-Name: %s\r\nX-Stub-Body-Len: %ld\r\n"
|
|
"X-Stub-Custom: %s\r\nX-Stub-Static: %s\r\nX-Stub-Xff: %s\r\n"
|
|
"X-Stub-Model: %s\r\nX-Stub-Auth: %s\r\nX-Stub-Reasoning: %s\r\n"
|
|
"X-Stub-Accept: %s\r\n"
|
|
"X-Stub-Effort: %s\r\nX-Stub-Effort-Set: %d\r\n"
|
|
"X-Stub-Thinking: %s\r\nX-Stub-Has-Reasoning: %d\r\n"
|
|
"X-Stub-Cache-Control: %d\r\n"
|
|
"X-Stub-Review: %d\r\nX-Stub-Prev: %d\r\n"
|
|
"X-Stub-XApi-Key: %s\r\n"
|
|
"X-Stub-Anthropic-Version: %s\r\n"
|
|
"X-Stub-Anthropic-Versions: %d\r\n"
|
|
"%s%s"
|
|
"Connection: close\r\n\r\n%s",
|
|
strlen(b), name, body_len, custom, static_hdr, fwd, model, authhdr,
|
|
reasoning, accept, effort, effort[0] ? 1 : 0, thinking,
|
|
has_reasoning ? 1 : 0, has_cache_control ? 1 : 0,
|
|
has_review ? 1 : 0, has_prev ? 1 : 0,
|
|
xapi, av, av_count, bad_header, many, b);
|
|
}
|
|
if (j_conn_write(&client, body, strlen(body), ioerr, sizeof ioerr) < 0)
|
|
fprintf(stderr, "stub write failed: %s\n", ioerr);
|
|
j_conn_close(&client);
|
|
_exit(0);
|
|
}
|
|
}
|