Files
junction/src/models.c
T
Konrad Lother 6412c738bd models: refresh from providers, import prices, dynamic model pools
The background fetch now repeats (models_refresh, default 300 s) instead of
running once at startup.  It reads the price fields the provider publishes next
to each model and merges them over prices.conf (budget/request windows from the
file survive).  Known limits survive a refresh, so ollama is not asked
/api/show for every model on every pass.

A pool can be built from a provider's current model list:

    pool free from opencode-go-free match "*-free"

Rules keep a marker and resolve the pool per request, so a model that appears
later is routable without a config reload.  Pools used as judges or ctx_fallback
resolve the same way.

Virtual keys grow a deny glob: the olivia key hides the olivia model from that
key's /v1/models and refuses it on the request path, while other keys still see
it.
2026-11-23 07:52:08 +00:00

940 lines
36 KiB
C

/*
* junction — was ein Endpunkt über seine Modelle veröffentlicht.
*
* Der Endpunkt-Block in der Konfiguration trägt genau eine Kontextzahl. Das ist
* eine Aussage über den Endpunkt, nicht über die Modelle: ein Anbieter mit drei
* Modellen hat drei Grenzen, und die Wahrheit steht in seiner Modellliste:
*
* GET <base>/models
* {"data":[{"id":"deepseek-v4.1-flash","limit":{"context":1000000,"output":384000}}]}
*
* Diese Datei holt die Liste beim Start einmal je Endpunkt und legt sie dort ab.
* Die Kontextprüfung nimmt danach die Zahl des *Modells*; die Zahl aus dem
* Endpunkt-Block bleibt der Rückfall, wenn ein Anbieter keine Liste liefert.
* Erfunden wird nichts: fehlt beides, gilt die Grenze als unbekannt und ein Ziel
* wird nicht wegen Kontext abgelehnt.
*/
#define _POSIX_C_SOURCE 200809L
#include <ctype.h>
#include <fnmatch.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "config.h"
#include "models.h"
#include "price.h"
extern j_config CFG; /* der Router hält genau eine Konfiguration */
/* Der Abruf läuft im Hintergrund, Anfragen lesen gleichzeitig. */
static pthread_mutex_t g_models_lock = PTHREAD_MUTEX_INITIALIZER;
#define J_MODELS_CMD 8192
static const char *find_in(const char *from, const char *end, const char *needle)
{
size_t n = strlen(needle);
if (from >= end) return NULL;
for (const char *p = from; p + n <= end; p++)
if (!memcmp(p, needle, n)) return p;
return NULL;
}
/* obj zeigt auf '{': liefert die passende '}', String-Inhalte werden übersprungen. */
static const char *match_brace(const char *obj, const char *end)
{
int depth = 0, instr = 0;
for (const char *p = obj; p < end; p++) {
if (instr) {
if (*p == '\\' && p + 1 < end) { p++; continue; }
if (*p == '"') instr = 0;
continue;
}
if (*p == '"') { instr = 1; continue; }
if (*p == '{') depth++;
else if (*p == '}') { if (--depth == 0) return p; }
}
return NULL;
}
/* p zeigt auf das öffnende Anführungszeichen. */
static int string_at(const char *p, const char *end, char *out, size_t outlen)
{
size_t o = 0;
if (!p || p >= end || *p != '"') return 0;
for (p++; p < end && *p && *p != '"'; p++) {
if (*p == '\\' && p + 1 < end) p++;
if (o + 1 < outlen) out[o++] = *p;
}
out[o] = '\0';
return o > 0;
}
/* p zeigt auf den Doppelpunkt nach einem Schlüssel. */
static long long_after(const char *p, const char *end)
{
if (!p || p >= end) return 0;
p++;
while (p < end && (isspace((unsigned char)*p) || *p == ':')) p++;
if (p >= end) return 0;
char *e = NULL;
long v = strtol(p, &e, 10);
if (e == p || v < 0) return 0;
return v;
}
/* The same for a price, which is a decimal and may be 0. */
static double double_after(const char *p, const char *end)
{
if (!p || p >= end) return 0.0;
p++;
while (p < end && (isspace((unsigned char)*p) || *p == ':')) p++;
if (p >= end) return 0.0;
char *e = NULL;
double v = strtod(p, &e);
if (e == p || v < 0.0) return 0.0;
return v;
}
/* Find "key": { ... } inside [from,end) and return the object, with its
* matching brace in *oend. Used for cost.text / cost.text.input / cache. */
static const char *object_after(const char *from, const char *end,
const char *key, const char **oend)
{
const char *k = find_in(from, end, key);
if (!k) return NULL;
const char *colon = find_in(k, end, ":");
const char *obj = colon ? find_in(colon, end, "{") : NULL;
if (!obj) return NULL;
const char *e = match_brace(obj, end);
if (!e) return NULL;
*oend = e;
return obj;
}
int j_models_parse(j_endpoint *ep, const char *json, size_t len)
{
const char *end = json + len;
const char *data = find_in(json, end, "\"data\"");
if (!data) return 0;
const char *p = find_in(data, end, "[");
if (!p) return 0;
j_model_meta *arr = NULL;
int n = 0, cap = 0;
const char *q = p;
while (q < end) {
const char *obj = find_in(q, end, "{");
if (!obj) break;
const char *oend = match_brace(obj, end);
if (!oend) break;
char id[J_GLOB_MAX] = "";
const char *idk = find_in(obj, oend, "\"id\"");
if (idk) {
const char *colon = find_in(idk, oend, ":");
const char *v = colon ? find_in(colon, oend, "\"") : NULL;
if (!string_at(v, oend, id, sizeof id)) id[0] = '\0';
}
if (id[0]) {
long ctx = 0, out = 0;
int has_cost = 0;
double ci = 0, cc = 0, co = 0, cf = 1;
const char *lim = find_in(obj, oend, "\"limit\"");
if (lim) {
const char *ck = find_in(lim, oend, "\"context\"");
if (ck) ctx = long_after(find_in(ck, oend, ":"), oend);
const char *ok = find_in(lim, oend, "\"output\"");
if (ok) out = long_after(find_in(ok, oend, ":"), oend);
}
/* Anthropic's model list names the same limits without the
* OpenAI "limit" wrapper: max_input_tokens and max_tokens. */
if (ctx == 0) {
const char *ck = find_in(obj, oend, "\"max_input_tokens\"");
if (ck) ctx = long_after(find_in(ck, oend, ":"), oend);
}
if (out == 0) {
const char *ok = find_in(obj, oend, "\"max_tokens\"");
if (ok) out = long_after(find_in(ok, oend, ":"), oend);
}
/*
* The same list often carries the price. opencode.com publishes
* cost.text.input.price, .input.cache.read, .output.price,
* cost.multipliers[].factor
* where the multiplier is the peak surcharge. The table in
* prices.conf was a human copy of exactly these numbers; importing
* them here means a new model is priced when it appears, not when
* somebody notices.
*/
{
const char *cend = NULL;
const char *cost = object_after(obj, oend, "\"cost\"", &cend);
if (cost) {
const char *tend = NULL;
const char *text = object_after(cost, cend, "\"text\"", &tend);
if (text) {
const char *iend = NULL;
const char *in = object_after(text, tend, "\"input\"", &iend);
if (in) {
const char *pk = find_in(in, iend, "\"price\"");
if (pk) ci = double_after(find_in(pk, iend, ":"), iend);
const char *kend = NULL;
const char *cache = object_after(in, iend, "\"cache\"", &kend);
if (cache) {
const char *rk = find_in(cache, kend, "\"read\"");
if (rk) cc = double_after(find_in(rk, kend, ":"), kend);
}
}
const char *oend2 = NULL;
const char *outobj = object_after(text, tend, "\"output\"", &oend2);
if (outobj) {
const char *pk = find_in(outobj, oend2, "\"price\"");
if (pk) co = double_after(find_in(pk, oend2, ":"), oend2);
}
}
const char *mp = find_in(cost, cend, "\"multipliers\"");
if (mp) {
const char *scan = mp;
while ((scan = find_in(scan, cend, "\"factor\"")) != NULL) {
double f = double_after(find_in(scan, cend, ":"), cend);
if (f > cf) cf = f;
scan += 8;
}
}
has_cost = (ci > 0.0 || co > 0.0);
}
}
if (n == cap) {
int ncap = cap ? cap * 2 : 16;
j_model_meta *grown = realloc(arr, (size_t)ncap * sizeof *arr);
if (!grown) { free(arr); return 0; }
arr = grown;
cap = ncap;
}
snprintf(arr[n].id, sizeof arr[n].id, "%s", id);
arr[n].ctx = ctx;
arr[n].out = out;
arr[n].has_cost = has_cost;
arr[n].cost_in = ci;
arr[n].cost_cached = cc;
arr[n].cost_out = co;
arr[n].cost_factor = cf > 0.0 ? cf : 1.0;
n++;
}
q = oend + 1;
}
pthread_mutex_lock(&g_models_lock);
/* Keep what the previous list knew about models that are still there. An
* ollama list carries no limits; without this, every refresh would ask
* /api/show for every model again (six seconds each). New models are still
* asked once, and the answer survives the next refresh. */
for (int i = 0; i < n; i++) {
for (int k = 0; k < ep->model_count; k++) {
if (strcmp(arr[i].id, ep->models[k].id)) continue;
if (arr[i].ctx == 0) arr[i].ctx = ep->models[k].ctx;
if (arr[i].out == 0) arr[i].out = ep->models[k].out;
if (!arr[i].has_cost && ep->models[k].has_cost) {
arr[i].has_cost = 1;
arr[i].cost_in = ep->models[k].cost_in;
arr[i].cost_cached = ep->models[k].cost_cached;
arr[i].cost_out = ep->models[k].cost_out;
arr[i].cost_factor = ep->models[k].cost_factor;
}
break;
}
}
free(ep->models);
ep->models = arr;
ep->model_count = n;
pthread_mutex_unlock(&g_models_lock);
return n;
}
/* CFG.max_context caps only what /v1/models publishes; the engine keeps the
* model's real limits and does not refuse a request because of it. */
static long cap_context(long lim)
{
if (lim > 0 && CFG.max_context > 0 && lim > CFG.max_context)
return CFG.max_context;
return lim;
}
long j_models_limit(const j_endpoint *ep, const char *model, int which)
{
if (!model || !*model) return 0;
long found = 0;
char base[J_GLOB_MAX];
snprintf(base, sizeof base, "%s", model);
char *hash = strchr(base, '#');
if (hash) *hash = '\0';
pthread_mutex_lock(&g_models_lock);
if (ep->models && ep->model_count > 0) {
for (int i = 0; i < ep->model_count; i++)
if (!strcmp(ep->models[i].id, model) ||
(hash && !strcmp(ep->models[i].id, base))) {
found = which ? ep->models[i].out : ep->models[i].ctx;
goto done;
}
/* Manche Anbieter führen denselben Namen kanonisch
* ("deepseek/deepseek-v4.1-flash"); ein "as" nennt oft nur den kurzen Teil. */
for (int i = 0; i < ep->model_count; i++) {
const char *slash = strrchr(ep->models[i].id, '/');
if (slash && (!strcmp(slash + 1, model) ||
(hash && !strcmp(slash + 1, base)))) {
found = which ? ep->models[i].out : ep->models[i].ctx;
break;
}
}
}
done:
pthread_mutex_unlock(&g_models_lock);
return found;
}
/* Ein Muster gegen die volle ID und, falls vorhanden, gegen die ID ohne
* "#variante" prüfen. So bleibt eine Freigabe für das Modell auch dann gültig,
* wenn der Client einen opencode-Variantenselektor anhängt. Ein Muster ohne
* Platzhalter ist ein strcmp; nur echte Globs gehen durch fnmatch. */
static int pattern_match(const char *pattern, const char *value)
{
if (!strpbrk(pattern, "*?["))
return strcmp(pattern, value) == 0;
return fnmatch(pattern, value, 0) == 0;
}
static int model_match(const char *pattern, const char *model, const char *base)
{
return pattern_match(pattern, model) ||
(base && base[0] && pattern_match(pattern, base));
}
/* A vkey may narrow the global model policy further (allow and deny). It never
* widens it: j_model_allowed() runs first everywhere. */
static const j_vkey *find_vkey_cfg(const char *name)
{
if (!name || !*name) return NULL;
for (int i = 0; i < CFG.vkey_count; i++)
if (!strcmp(CFG.vkeys[i].name, name)) return &CFG.vkeys[i];
return NULL;
}
static int vkey_model_allowed(const char *vkey_name, const char *model)
{
const j_vkey *v = find_vkey_cfg(vkey_name);
if (!v || !model || !*model) return 1;
char base[J_GLOB_MAX];
snprintf(base, sizeof base, "%s", model);
char *hash = strchr(base, '#');
if (hash) *hash = '\0';
if (v->allow[0] && !model_match(v->allow, model, base)) return 0;
if (v->deny[0] && model_match(v->deny, model, base)) return 0;
return 1;
}
int j_model_allowed(const char *model)
{
if (!model || !*model) return 1;
char base[J_GLOB_MAX];
snprintf(base, sizeof base, "%s", model);
char *hash = strchr(base, '#');
if (hash) *hash = '\0';
for (int i = 0; i < CFG.model_deny_count; i++)
if (model_match(CFG.model_deny[i], model, base)) return 0;
if (CFG.model_allow_count == 0) return 1;
for (int i = 0; i < CFG.model_allow_count; i++)
if (model_match(CFG.model_allow[i], model, base)) return 1;
return 0;
}
/* Manche Endpunkte veröffentlichen ihre Grenzen nicht in der OpenAI-Liste, sondern
* in ihrer eigenen API. ollama.com tut das: /api/show liefert
* model_info["<arch>.context_length"] — kimi-k2.6 etwa 262144, nicht 128000.
* Das ist gelesen, nicht geschätzt. Fehlt der Endpunkt, kommt 0 zurück. */
static long publish_context_length(const char *root, const char *model,
const j_endpoint *ep)
{
char cmd[J_MODELS_CMD];
int off = snprintf(cmd, sizeof cmd, "curl -sS -m 6 -X POST ");
const char *key = ep->key_env_count > 0 ? getenv(ep->api_key_env[0]) : NULL;
if (key && *key)
off += snprintf(cmd + off, sizeof cmd - (size_t)off,
"-H 'Authorization: Bearer %s' ", key);
off += snprintf(cmd + off, sizeof cmd - (size_t)off,
"-H 'Content-Type: application/json' -d '{\"model\":\"%s\"}' "
"'%s/api/show' 2>/dev/null", model, root);
if (off <= 0 || (size_t)off >= sizeof cmd) return 0;
FILE *f = popen(cmd, "r");
if (!f) return 0;
char buf[8192];
size_t len = fread(buf, 1, sizeof buf - 1, f);
pclose(f);
if (len == 0) return 0;
buf[len] = '\0';
/* "…context_length":262144 — das Feld heißt je nach Architektur anders
* ("kimi-k2.context_length", "llama.context_length"), der Schwanz ist gleich. */
const char *end = buf + len;
for (const char *p = buf; (p = find_in(p, end, "context_length")) != NULL; p += 14) {
const char *colon = find_in(p, end, ":");
if (!colon) continue;
long v = long_after(colon, end);
if (v > 0) return v;
}
return 0;
}
/* Holt <base>/models. Header und Schlüssel sind die des Endpunkts — ohne die
* antwortet ein Cloudflare-geschützter Anbieter mit 403 statt mit einer Liste. */
static int fetch_json(const j_endpoint *ep, char **out, size_t *out_len)
{
char base[J_URL_MAX];
snprintf(base, sizeof base, "%s", ep->base);
size_t bl = strlen(base);
while (bl > 0 && base[bl - 1] == '/') base[--bl] = '\0';
if (bl == 0) return -1;
char cmd[J_MODELS_CMD];
int off = snprintf(cmd, sizeof cmd, "curl -sS -m 8 ");
const char *key = ep->key_env_count > 0 ? getenv(ep->api_key_env[0]) : NULL;
if (key && *key) {
off += snprintf(cmd + off, sizeof cmd - (size_t)off,
"-H 'Authorization: Bearer %s' ", key);
}
for (int i = 0; i < ep->header_count && off > 0 && (size_t)off < sizeof cmd; i++) {
/* ein Header kann ein Anführungszeichen enthalten; das ist in der
* Konfiguration nicht vorgesehen und wird hier nicht nachgebaut */
if (strchr(ep->headers[i], '\'')) continue;
off += snprintf(cmd + off, sizeof cmd - (size_t)off, "-H '%s' ", ep->headers[i]);
}
if (off > 0 && (size_t)off < sizeof cmd)
snprintf(cmd + off, sizeof cmd - (size_t)off, "'%s/models' 2>/dev/null", base);
FILE *f = popen(cmd, "r");
if (!f) return -1;
size_t cap = 65536, len = 0;
char *buf = malloc(cap);
if (!buf) { pclose(f); return -1; }
for (;;) {
if (len + 4096 + 1 > cap) {
size_t ncap = cap * 2;
char *grown = realloc(buf, ncap);
if (!grown) { free(buf); pclose(f); return -1; }
buf = grown; cap = ncap;
}
size_t got = fread(buf + len, 1, 4096, f);
len += got;
if (got < 4096) break;
}
int status = pclose(f);
if (status != 0 || len == 0) { free(buf); return -1; }
buf[len] = '\0';
*out = buf;
*out_len = len;
return 0;
}
/* Kleine Hilfsfunktion: Endpunkt per Name. */
static j_endpoint *find_ep(const char *name)
{
for (int i = 0; i < CFG.endpoint_count; i++)
if (!strcmp(CFG.endpoints[i].name, name)) return &CFG.endpoints[i];
return NULL;
}
static const j_pool *find_pool_cfg(const char *name)
{
for (int i = 0; i < CFG.pool_count; i++)
if (!strcmp(CFG.pools[i].name, name)) return &CFG.pools[i];
return NULL;
}
/*
* Snapshot a pool. A static pool copies its configured members. A dynamic pool
* (`pool free from opencode-go-free match "*-free"`) asks the endpoint's current
* model list; each match becomes a target with the model id as its "as". The
* caller gets copies, so it can use them after the models lock is released.
*/
int j_pool_members(const j_pool *pl, char targets[][J_NAME_MAX],
char as[][J_GLOB_MAX], int max)
{
if (!pl || max <= 0) return 0;
if (!pl->dynamic) {
int n = pl->count < max ? pl->count : max;
for (int i = 0; i < n; i++) {
snprintf(targets[i], J_NAME_MAX, "%s", pl->targets[i]);
snprintf(as[i], J_GLOB_MAX, "%s", pl->target_as[i]);
}
return n;
}
j_endpoint *ep = find_ep(pl->from);
if (!ep) return 0;
int n = 0;
pthread_mutex_lock(&g_models_lock);
for (int i = 0; i < ep->model_count && n < max; i++) {
if (fnmatch(pl->match, ep->models[i].id, 0) != 0) continue;
snprintf(targets[n], J_NAME_MAX, "%s", ep->name);
snprintf(as[n], J_GLOB_MAX, "%s", ep->models[i].id);
n++;
}
pthread_mutex_unlock(&g_models_lock);
return n;
}
/*
* Replace every dynamic-pool target in a copied rule with its current members.
* Called once per request, right after the rule is copied out of the config:
* a model that appears in the provider list is then routable on the next
* request, without a config reload and without touching the shared rule.
*/
void j_rule_resolve_dynamic(j_rule *r)
{
if (!r) return;
char targets[J_MAX_TARGETS][J_NAME_MAX];
char as[J_MAX_TARGETS][J_GLOB_MAX];
int n = 0;
for (int t = 0; t < r->target_count && n < J_MAX_TARGETS; t++) {
if (!r->target_dynamic[t]) {
snprintf(targets[n], J_NAME_MAX, "%s", r->targets[t]);
snprintf(as[n], J_GLOB_MAX, "%s", r->target_as[t]);
n++;
continue;
}
const j_pool *pl = find_pool_cfg(r->targets[t]);
char mt[J_MAX_TARGETS][J_NAME_MAX];
char ma[J_MAX_TARGETS][J_GLOB_MAX];
int mn = pl ? j_pool_members(pl, mt, ma, J_MAX_TARGETS) : 0;
for (int k = 0; k < mn && n < J_MAX_TARGETS; k++) {
snprintf(targets[n], J_NAME_MAX, "%.*s",
J_NAME_MAX - 1, mt[k]);
snprintf(as[n], J_GLOB_MAX, "%.*s",
J_GLOB_MAX - 1, ma[k]);
n++;
}
}
for (int t = 0; t < n; t++) {
snprintf(r->targets[t], J_NAME_MAX, "%.*s",
J_NAME_MAX - 1, targets[t]);
snprintf(r->target_as[t], J_GLOB_MAX, "%.*s",
J_GLOB_MAX - 1, as[t]);
}
r->target_count = n;
memset(r->target_dynamic, 0, sizeof r->target_dynamic);
}
/* Grenze einer einzelnen virtuellen Regel: alle Ziele plus die Judge-Kette,
* das tatsächlich angesprochene Modell je Ziel. Für context fällt ein unbekannter
* Modellwert auf die Endpoint-Zahl zurück; für output wird nichts aus dem Kontext
* geraten — dort zählt nur, was ein Modell wirklich als Ausgabe nennt. */
static long effective_limit_for_rule(const j_rule *r, const char *model, int which)
{
long best = 0;
for (int t = 0; t < r->target_count; t++) {
if (r->target_dynamic[t]) {
const j_pool *dp = find_pool_cfg(r->targets[t]);
char dt[J_MAX_TARGETS][J_NAME_MAX];
char da[J_MAX_TARGETS][J_GLOB_MAX];
int dn = dp ? j_pool_members(dp, dt, da, J_MAX_TARGETS) : 0;
for (int k = 0; k < dn; k++) {
j_endpoint *ep = find_ep(dt[k]);
if (!ep) continue;
const char *em = da[k][0] ? da[k] : model;
long lim = j_models_limit(ep, em, which);
if (which == 0 && lim <= 0) lim = ep->context;
if (lim > 0 && (best <= 0 || lim < best)) best = lim;
}
continue;
}
j_endpoint *ep = find_ep(r->targets[t]);
if (!ep) continue;
const char *em = r->target_as[t][0] ? r->target_as[t] : model;
long lim = j_models_limit(ep, em, which);
if (which == 0 && lim <= 0) lim = ep->context;
if (lim > 0 && (best <= 0 || lim < best)) best = lim;
}
for (int j = 0; j < r->judge_count; j++) {
const char *target = r->judges[j].target;
const char *judge_as = r->judges[j].as;
if (!target[0]) continue;
const j_pool *jp = find_pool_cfg(target);
if (jp) {
char jt[J_MAX_TARGETS][J_NAME_MAX];
char ja[J_MAX_TARGETS][J_GLOB_MAX];
int jn = j_pool_members(jp, jt, ja, J_MAX_TARGETS);
for (int c = 0; c < jn; c++) {
j_endpoint *ep = find_ep(jt[c]);
if (!ep) continue;
const char *em = ja[c][0] ? ja[c]
: (judge_as[0] ? judge_as : model);
long lim = j_models_limit(ep, em, which);
if (which == 0 && lim <= 0) lim = ep->context;
if (lim > 0 && (best <= 0 || lim < best)) best = lim;
}
} else {
j_endpoint *ep = find_ep(target);
if (ep) {
const char *em = judge_as[0] ? judge_as : model;
long lim = j_models_limit(ep, em, which);
if (which == 0 && lim <= 0) lim = ep->context;
if (lim > 0 && (best <= 0 || lim < best)) best = lim;
}
}
}
return best;
}
long j_models_rule_limit(const j_rule *r, int which)
{
if (!r || !j_rule_is_virtual_chain(r)) return 0;
return effective_limit_for_rule(r, r->model_glob, which);
}
/* Effektive Grenze für einen virtuellen Modellnamen. Gibt es mehrere Regeln mit
* demselben exakten Namen, gewinnt die kleinste Grenze — die erste Regel matcht
* im Betrieb, aber die Anzeige soll nicht mehr versprechen als irgendeine davon. */
long j_models_effective_limit(const char *model, int which)
{
if (!model || !*model) return 0;
long best = 0;
int found_rule = 0;
for (int ri = 0; ri < CFG.rule_count; ri++) {
const j_rule *r = &CFG.rules[ri];
if (strcmp(r->model_glob, model) != 0) continue;
if (!j_rule_is_virtual_chain(r)) continue;
found_rule = 1;
long lim = effective_limit_for_rule(r, model, which);
if (lim > 0 && (best <= 0 || lim < best)) best = lim;
}
return found_rule ? best : 0;
}
/* Prüft grob, ob eine Modell-ID bereits im JSON vorkommt: "id":"<model>" */
static int json_has_model_id(const char *json, size_t len, const char *model)
{
char needle[256];
size_t nlen = (size_t)snprintf(needle, sizeof needle, "\"id\":\"%s\"", model);
if (nlen >= sizeof needle || len < nlen) return 0;
for (size_t i = 0; i + nlen <= len; i++) {
if (json[i] == '"' && memcmp(json + i, needle, nlen) == 0) return 1;
}
return 0;
}
/* Findet das data-Array einer OpenAI-Modellliste. arr zeigt auf '[', endarr auf ']'. */
static int find_data_array(const char *json, size_t len, const char **arr, const char **endarr)
{
const char *end = json + len;
const char *data = find_in(json, end, "\"data\"");
if (!data) return -1;
const char *a = find_in(data, end, "[");
if (!a) return -1;
int depth = 0;
for (const char *p = a; p < end; p++) {
if (*p == '"') {
p++;
while (p < end) {
if (*p == '\\' && p + 1 < end) { p += 2; continue; }
if (*p == '"') break;
p++;
}
} else if (*p == '[') {
depth++;
} else if (*p == ']') {
depth--;
if (depth == 0) {
*arr = a;
*endarr = p;
return 0;
}
}
}
return -1;
}
int j_models_filter_list(const char *json, size_t len, const char *vkey_name,
char **out, size_t *out_len)
{
*out = NULL; *out_len = 0;
if (!json || len == 0) return -1;
if (CFG.model_allow_count == 0 && CFG.model_deny_count == 0) return -1;
const char *arr = NULL, *endarr = NULL;
if (find_data_array(json, len, &arr, &endarr) != 0) return -1;
char *buf = malloc(len + 1);
if (!buf) return -1;
/* Prefix bis einschließlich '['. */
size_t o = (size_t)(arr - json) + 1;
memcpy(buf, json, o);
int kept = 0, dropped = 0;
const char *p = arr + 1;
while (p < endarr) {
while (p < endarr && (isspace((unsigned char)*p) || *p == ',')) p++;
if (p >= endarr) break;
if (*p != '{') { free(buf); return -1; } /* unbekannte Form: nicht anfassen */
const char *obj = p;
const char *oend = match_brace(obj, endarr);
if (!oend) { free(buf); return -1; }
char id[J_GLOB_MAX] = "";
const char *idk = find_in(obj, oend + 1, "\"id\"");
if (idk) {
const char *colon = find_in(idk, oend + 1, ":");
const char *v = colon ? find_in(colon, oend + 1, "\"") : NULL;
if (!string_at(v, oend + 1, id, sizeof id)) id[0] = '\0';
}
if (id[0] == '\0' || (j_model_allowed(id) &&
vkey_model_allowed(vkey_name, id))) {
if (kept) buf[o++] = ',';
size_t elen = (size_t)(oend - obj + 1);
memcpy(buf + o, obj, elen);
o += elen;
kept++;
} else {
dropped++;
}
p = oend + 1;
}
if (dropped == 0) { free(buf); return -1; }
/* Suffix ab ']' (inklusive). */
size_t tail = (size_t)(endarr - json);
memcpy(buf + o, endarr, len - tail);
o += len - tail;
buf[o] = '\0';
*out = buf;
*out_len = o;
return 0;
}
/* CFG.max_context also applies to what /v1/models publishes: a model that
* advertises more is listed with the ceiling. Returns a malloc'd copy when a
* value changed, NULL otherwise. */
static char *cap_limits_json(const char *json, size_t len, size_t *out_len)
{
if (CFG.max_context <= 0) return NULL;
char *out = malloc(len + 1);
if (!out) return NULL;
size_t i = 0, o = 0;
int changed = 0;
static const char *const keys[] = { "\"context\":", "\"output\":" };
while (i < len) {
size_t klen = 0;
int hit = -1;
if (json[i] == '"') {
for (int k = 0; k < 2; k++) {
klen = strlen(keys[k]);
if (i + klen <= len && !memcmp(json + i, keys[k], klen)) { hit = k; break; }
}
}
if (hit < 0) { out[o++] = json[i++]; continue; }
memcpy(out + o, json + i, klen); o += klen; i += klen;
while (i < len && (json[i] == ' ' || json[i] == '\t')) out[o++] = json[i++];
size_t start = i;
long v = 0;
while (i < len && json[i] >= '0' && json[i] <= '9') { v = v * 10 + (json[i] - '0'); i++; }
if (i == start) { continue; }
if (v > CFG.max_context) {
int n = snprintf(out + o, len + 1 - o, "%ld", CFG.max_context);
if (n > 0) o += (size_t)n;
changed = 1;
} else {
while (start < i) out[o++] = json[start++];
}
}
out[o] = '\0';
if (!changed) { free(out); return NULL; }
*out_len = o;
return out;
}
int j_models_patch_list(const char *json, size_t len, const char *vkey_name,
char **out, size_t *out_len)
{
*out = NULL; *out_len = 0;
if (!json || len == 0) return -1;
char *capped = cap_limits_json(json, len, &len);
if (capped) json = capped;
const char *arr = NULL, *endarr = NULL;
if (find_data_array(json, len, &arr, &endarr) != 0) { free(capped); return -1; }
/* Sammle virtuelle Ketten-Modelle */
char extra[4096]; size_t eo = 0; extra[0] = '\0';
for (int ri = 0; ri < CFG.rule_count; ri++) {
const j_rule *r = &CFG.rules[ri];
if (!j_rule_is_virtual_chain(r)) continue;
const char *name = r->model_glob;
if (!j_model_allowed(name)) continue;
if (!vkey_model_allowed(vkey_name, name)) continue;
/* The same name can appear in more than one rule (a virtual rule and a
* ctx-overflow rule). The list must contain it once. */
if (json_has_model_id(json, len, name) ||
json_has_model_id(extra, eo, name)) continue;
long ctx = j_models_effective_limit(name, 0);
long outlim = j_models_effective_limit(name, 1);
/* Kein Modell nennt eine Ausgabegrenze? Dann ist der effektive Kontext die
* sichere Obergrenze — nicht die Endpoint-Zahl eines einzelnen Ziels. */
if (outlim <= 0) outlim = ctx;
if (ctx > 0 && outlim > ctx) outlim = ctx;
/* /v1/models must not promise more than the configured ceiling. */
ctx = cap_context(ctx);
outlim = cap_context(outlim);
/* nur ergänzen, wenn wir wenigstens eine Grenze kennen */
if (ctx <= 0 && outlim <= 0) continue;
int need_comma = 0;
/* comma if array not empty */
for (const char *p = arr + 1; p < endarr; p++) { if (!isspace((unsigned char)*p)) { need_comma = 1; break; } }
/* if we already added entries, need comma; but easier handle: prepend comma if not first or array non-empty */
int first_extra = (eo == 0);
int prefix_comma = (!first_extra) || need_comma;
int n = snprintf(extra + eo, sizeof extra - eo,
"%s{\"id\":\"%s\",\"name\":\"%s\",\"object\":\"model\","
"\"owned_by\":\"junction\"",
prefix_comma ? "," : "", name, name);
if (n < 0 || (size_t)n >= sizeof extra - eo) break;
eo += (size_t)n;
if (ctx > 0 || outlim > 0) {
n = snprintf(extra + eo, sizeof extra - eo, ",\"limit\":{");
if (n > 0) eo += (size_t)n;
int wrote = 0;
if (ctx > 0) { n = snprintf(extra + eo, sizeof extra - eo, "\"context\":%ld", ctx); if (n>0){eo+=(size_t)n; wrote=1;} }
if (outlim > 0) { n = snprintf(extra + eo, sizeof extra - eo, "%s\"output\":%ld", wrote?",":"", outlim); if (n>0) eo+=(size_t)n; }
n = snprintf(extra + eo, sizeof extra - eo, "}"); if (n>0) eo+=(size_t)n;
}
n = snprintf(extra + eo, sizeof extra - eo, "}"); if (n>0) eo+=(size_t)n;
if (eo >= sizeof extra - 64) break;
}
if (eo == 0) { free(capped); return -1; }
size_t newlen = len + eo;
char *nb = malloc(newlen + 1);
if (!nb) { free(capped); return -1; }
size_t pre = (size_t)(endarr - json);
memcpy(nb, json, pre);
memcpy(nb + pre, extra, eo);
memcpy(nb + pre + eo, endarr, len - pre);
nb[newlen] = '\0';
*out = nb; *out_len = newlen;
free(capped);
return 0;
}
/* Rebuild the dynamic price rows from every model that names a price. The
* file rows stay as the fallback and keep budgets/request windows that only a
* human knows. */
static void models_price_import(void)
{
j_price_import_begin();
pthread_mutex_lock(&g_models_lock);
for (int i = 0; i < CFG.endpoint_count; i++) {
const j_endpoint *ep = &CFG.endpoints[i];
for (int k = 0; k < ep->model_count; k++) {
const j_model_meta *m = &ep->models[k];
if (!m->has_cost) continue;
j_price_import_add(m->id, m->cost_in, m->cost_cached,
m->cost_out, m->cost_factor);
}
}
pthread_mutex_unlock(&g_models_lock);
int n = j_price_import_end();
if (n > 0)
fprintf(stderr, "[%s] prices: %d model(s) from provider lists\n",
CFG.log_prefix, n);
}
void j_models_refresh_all(void)
{
for (int i = 0; i < CFG.endpoint_count; i++) {
j_endpoint *ep = &CFG.endpoints[i];
if (strncmp(ep->base, "http", 4) != 0) continue;
/* kind opencode hat keine OpenAI-Modellliste -- die baut junctions Brücke
* selbst aus der Sitzungs-API. Und wer seine Basis per Kommando holt, wird
* nicht vorher gefragt: da steht noch keine Adresse. */
if (!strcmp(ep->kind, "opencode") || ep->base_cmd[0]) continue;
char *json = NULL;
size_t len = 0;
if (fetch_json(ep, &json, &len) != 0) {
if (ep->context > 0)
fprintf(stderr, "[%s] models: %s unreachable — Kontextprüfung fällt auf die "
"Endpunktzahl %ld zurück\n", CFG.log_prefix, ep->name, ep->context);
else
fprintf(stderr, "[%s] models: %s unreachable — keine Grenze bekannt, es wird "
"nicht wegen Kontext verworfen\n", CFG.log_prefix, ep->name);
continue;
}
int n = j_models_parse(ep, json, len);
free(json);
if (n <= 0) {
if (ep->context > 0)
fprintf(stderr, "[%s] models: %s liefert keine Modellliste — Kontextprüfung "
"fällt auf die Endpunktzahl %ld zurück\n",
CFG.log_prefix, ep->name, ep->context);
else
fprintf(stderr, "[%s] models: %s liefert keine Modellliste — keine Grenze "
"bekannt, es wird nicht wegen Kontext verworfen\n",
CFG.log_prefix, ep->name);
continue;
}
/* Veröffentlicht die Liste keine Grenzen, fragt junction die eigene API des
* Endpunkts (ollama.com: /api/show). Nur eine begrenzte Zahl pro Lauf:
* drei ollama-Konten mit je 31 Modellen wären sonst neun Minuten
* /api/show, und ein Refresh, der länger als sein Intervall dauert, ist
* kein Hintergrund mehr. Was einmal geantwortet hat, bleibt erhalten. */
int filled = 0;
int unknown = 0;
for (int k = 0; k < ep->model_count; k++)
if (ep->models[k].ctx == 0) { unknown = 1; break; }
if (unknown) {
char root[J_URL_MAX];
snprintf(root, sizeof root, "%s", ep->base);
size_t rl = strlen(root);
while (rl > 0 && root[rl - 1] == '/') root[--rl] = '\0';
if (rl >= 3 && !strcmp(root + rl - 3, "/v1")) root[rl - 3] = '\0';
int budget = 8;
for (int k = 0; k < ep->model_count && budget > 0; k++) {
if (ep->models[k].ctx > 0) continue;
budget--;
long v = publish_context_length(root, ep->models[k].id, ep);
if (v > 0) { ep->models[k].ctx = v; filled++; }
}
}
fprintf(stderr, "[%s] models: %s %d Modelle%s", CFG.log_prefix, ep->name, n,
filled ? " (Grenzen aus /api/show)" : "");
for (int k = 0; k < ep->model_count && k < 3; k++)
fprintf(stderr, "%s%s ctx=%ld out=%ld", k ? "," : " ·",
ep->models[k].id, ep->models[k].ctx, ep->models[k].out);
fprintf(stderr, "\n");
}
models_price_import();
}