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.
This commit is contained in:
Konrad Lother authored and Hermes committed 2026-11-23 07:52:08 +00:00
1 parent 0a6373e954
commit 6412c738bd
9 files changed
+589 -39

No files matched your search

+57
View File
@@ -101,6 +101,7 @@ void j_config_defaults(j_config *cfg)
cfg->auto_endpoints = 1;
cfg->probe_interval_s = 20.0;
cfg->probe_timeout_s = 3.0;
cfg->models_refresh_s = 300.0;
snprintf(cfg->prices_path, sizeof cfg->prices_path, "/etc/junction/prices.conf");
cfg->compress = J_COMPRESS_OFF;
cfg->compress_keep = 4;
@@ -348,6 +349,14 @@ static int global_kw(j_config *cfg, char **w, int n, int lineno, char *err, size
if (cfg->probe_timeout_s <= 0 || cfg->probe_timeout_s > 60) goto bad;
return 0;
}
if (!strcmp(k, "models_refresh")) {
/* models_refresh 300 (0 = nur beim Start)
* Der Hintergrund holt die Modelllisten und die darin genannten Preise
* regelmäßig neu; neue Modelle erscheinen damit ohne Neustart. */
if (n != 2 || as_double(w[1], &cfg->models_refresh_s)) goto bad;
if (cfg->models_refresh_s < 0 || cfg->models_refresh_s > 86400) goto bad;
return 0;
}
if (!strcmp(k, "auto_endpoints")) {
/* auto_endpoints on|off
*
@@ -538,6 +547,10 @@ static int global_kw(j_config *cfg, char **w, int n, int lineno, char *err, size
return -1;
}
snprintf(v->mcp_tools, sizeof v->mcp_tools, "%s", w[i + 1]);
} else if (!strcmp(w[i], "deny")) {
if (copy_field(v->deny, sizeof v->deny, w[i + 1], lineno,
"vkey deny glob", err, errlen))
return -1;
} else if (!strcmp(w[i], "rpm")) {
if (as_int(w[i + 1], &v->rpm) || v->rpm < 0) goto bad;
} else if (!strcmp(w[i], "budget")) {
@@ -1116,6 +1129,12 @@ int j_config_expand_rule(j_rule *r, const j_config *cfg, char *err, size_t errle
for (int p = 0; p < cfg->pool_count; p++) {
if (strcmp(cfg->pools[p].name, r->targets[t])) continue;
const j_pool *pl = &cfg->pools[p];
/* A dynamic pool has no fixed members; the request path resolves
* it from the endpoint's model list. Keep the name and mark it. */
if (pl->dynamic) {
r->target_dynamic[t] = 1;
break;
}
if (r->target_count - 1 + pl->count > J_MAX_TARGETS) {
snprintf(err, errlen,
"line %d: pool %s does not fit into rule (more than %d targets)",
@@ -1162,6 +1181,7 @@ int j_config_expand_rule(j_rule *r, const j_config *cfg, char *err, size_t errle
int found = 0;
for (int e = 0; e < cfg->endpoint_count; e++)
if (!strcmp(cfg->endpoints[e].name, r->targets[t])) { found = 1; break; }
if (!found && r->target_dynamic[t]) found = 1;
if (!found) {
snprintf(err, errlen, "line %d: rule passes to unknown endpoint '%s'",
r->line, r->targets[t]);
@@ -1312,6 +1332,30 @@ int j_config_load(const char *path, j_config *cfg, char *err, size_t errlen)
fclose(fh);
return -1;
}
/* pool <name> from <endpoint> match "<model glob>"
* A dynamic pool is not a fixed target list: every model the endpoint
* currently publishes and whose id matches the glob is a member. The
* request path snapshots it, so a refresh changes the pool without
* touching any rule. */
if (n >= 3 && !strcmp(w[2], "from")) {
if (n != 6 || strcmp(w[4], "match")) {
snprintf(err, errlen,
"line %d: pool %s: expected 'from ENDPOINT match \"GLOB\"'",
lineno, pl->name);
fclose(fh);
return -1;
}
if (copy_field(pl->from, sizeof pl->from, w[3], lineno,
"pool from endpoint", err, errlen) ||
copy_field(pl->match, sizeof pl->match, w[5], lineno,
"pool model glob", err, errlen)) {
fclose(fh);
return -1;
}
pl->dynamic = 1;
cfg->pool_count++;
continue;
}
for (int i = 2; i < n; ) {
char t[J_NAME_MAX + J_GLOB_MAX];
char target_model[J_GLOB_MAX] = "";
@@ -1577,6 +1621,19 @@ int j_config_load(const char *path, j_config *cfg, char *err, size_t errlen)
return -1;
}
}
for (int i = 0; i < cfg->pool_count; i++) {
j_pool *pl = &cfg->pools[i];
if (!pl->dynamic) continue;
int found = 0;
for (int e = 0; e < cfg->endpoint_count; e++)
if (!strcmp(cfg->endpoints[e].name, pl->from)) { found = 1; break; }
if (!found) {
snprintf(err, errlen,
"line %d: pool %s draws from unknown endpoint '%s'",
pl->line, pl->name, pl->from);
return -1;
}
}
/* Expand pools in every rule and run the same validation the live
* rules.set path uses. */
for (int i = 0; i < cfg->rule_count; i++) {
+24 -1
View File
@@ -38,7 +38,7 @@
#define J_MAX_ENDPOINTS 32
#define J_MAX_HOOKS 8
#define J_MAX_RULES 64
#define J_MAX_TARGETS 8
#define J_MAX_TARGETS 16
#define J_NAME_MAX 64
#define J_URL_MAX 512
#define J_PATH_MAX 512
@@ -69,6 +69,10 @@ typedef struct {
char name[J_NAME_MAX];
char token_env[J_NAME_MAX]; /* env var holding the virtual key itself */
char allow[J_GLOB_MAX]; /* model glob; "" = any */
/* Modelle, die dieser Schlüssel trotz allow nicht sieht und nicht anfragen
* darf. Gedacht für den Agenten selbst: sein eigener Name steht in deny, damit
* er sich nicht im Modellwähler seiner eigenen Oberfläche wiederfindet. */
char deny[J_GLOB_MAX];
char endpoints[J_URL_MAX]; /* comma list; "" = any */
/* Werkzeuge, die dieser Schlüssel über /mcp sehen und aufrufen darf:
* Komma-Liste von fnmatch-Mustern auf den vollen Namen mit Präfix,
@@ -118,6 +122,11 @@ typedef struct {
char id[J_GLOB_MAX];
long ctx; /* limit.context, 0 = unbekannt */
long out; /* limit.output, 0 = unbekannt */
/* Preise, wie der Anbieter sie in derselben Liste veröffentlicht. factor ist
* der Aufschlag der Hauptzeit (cost.multipliers[].factor); 1 = kein Aufschlag.
* 0 in has_cost = der Anbieter nennt keinen Preis. */
int has_cost;
double cost_in, cost_cached, cost_out, cost_factor;
} j_model_meta;
typedef struct {
@@ -254,6 +263,10 @@ typedef struct {
int block; /* 1 = refuse the request */
char targets[J_MAX_TARGETS][J_NAME_MAX];
/* 1 = this target is a dynamic model pool (`pool X from EP match GLOB`),
* resolved from the endpoint's current model list when the rule is used.
* The name in targets[] is the pool name until then. */
int target_dynamic[J_MAX_TARGETS];
/* Per target: the model name to send instead of the requested one. Boxes serve
* different ids ("Qwen3.8-Flash-Next" is loaded as "qwen3.8-flash-next-q1m"), so
* the rewrite belongs to the target, not to the rule. */
@@ -290,6 +303,12 @@ typedef struct {
char target_as[J_MAX_TARGETS][J_GLOB_MAX];
int count;
int line;
/* Dynamic model pool: instead of a fixed endpoint list, every model of
* `from` whose id matches the glob becomes a member, with the model id as
* its "as". Rebuilt whenever the endpoint's model list is refreshed. */
int dynamic;
char from[J_NAME_MAX];
char match[J_GLOB_MAX];
} j_pool;
/* Kürzen von Werkzeugausgaben im Anfrageweg. Standard: aus. */
@@ -364,6 +383,10 @@ typedef struct {
* weiter geprüft — ohne dass eine Anfrage dafür bezahlen muss. 0 = aus. */
double probe_interval_s;
double probe_timeout_s;
/* Wie oft der Hintergrund die Modelllisten und die darin veröffentlichten
* Preise neu holt. 0 = nur beim Start. Der Wert ist absichtlich größer als
* probe_interval: Modelllisten ändern sich nicht im Sekundentakt. */
double models_refresh_s;
/* Zeichen pro Token für die Prompt-Schätzung. 0 = aus, dann kann keine Regel eine
* ctx-Bedingung tragen. Der Wert ist eine Annahme über die Tokenisierung, keine
+69 -16
View File
@@ -127,6 +127,10 @@ static __thread int t_review_count;
static __thread int t_review_done;
static __thread char t_review_model[J_GLOB_MAX];
static __thread char t_review_skipped[32];
/* The virtual key this request arrived with, or "". The /v1/models rewrite
* happens in forward_step, which does not have the handler's vk pointer; the
* per-request thread makes this safe. */
static __thread char t_vkey_name[J_NAME_MAX];
#define STATE_LOCK() pthread_mutex_lock(&g_state_mu)
#define STATE_UNLOCK() pthread_mutex_unlock(&g_state_mu)
@@ -1953,14 +1957,14 @@ static int opencode_serve(j_conn *client, j_endpoint *ep_index_owner, const j_re
* ergänzt wird. */
char *filtered = NULL;
size_t filtered_len = 0;
if (j_models_filter_list(body, blen, &filtered, &filtered_len) == 0 && filtered) {
if (j_models_filter_list(body, blen, t_vkey_name, &filtered, &filtered_len) == 0 && filtered) {
free(body);
body = filtered;
blen = filtered_len;
}
char *patched = NULL;
size_t patched_len = 0;
if (j_models_patch_list(body, blen, &patched, &patched_len) == 0 && patched) {
if (j_models_patch_list(body, blen, t_vkey_name, &patched, &patched_len) == 0 && patched) {
free(body);
body = patched;
blen = patched_len;
@@ -2025,6 +2029,9 @@ static int first_matching_rule(const char *path, const char *model, long need,
}
}
*out = CFG.rules[i];
/* A dynamic model pool is not expanded at config time: its members are
* whatever the provider publishes right now. Resolve the copy once. */
j_rule_resolve_dynamic(out);
found = 1;
break;
}
@@ -3382,7 +3389,7 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
int changed = 0;
char *filtered = NULL;
size_t filtered_len = 0;
if (j_models_filter_list(body, body_len, &filtered, &filtered_len) == 0 && filtered) {
if (j_models_filter_list(body, body_len, t_vkey_name, &filtered, &filtered_len) == 0 && filtered) {
free(body);
body = filtered;
body_len = filtered_len;
@@ -3390,7 +3397,7 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
}
char *patched = NULL;
size_t patched_len = 0;
if (j_models_patch_list(body, body_len, &patched, &patched_len) == 0 && patched) {
if (j_models_patch_list(body, body_len, t_vkey_name, &patched, &patched_len) == 0 && patched) {
free(body);
body = patched;
body_len = patched_len;
@@ -4100,6 +4107,7 @@ static void handle_client_inner(j_conn *client)
t_review_done = 0;
t_review_model[0] = '\0';
t_review_skipped[0] = '\0';
t_vkey_name[0] = '\0';
j_req rq;
char err[512] = "";
if (read_request(client, &buf, &rq, err, sizeof err)) {
@@ -4229,6 +4237,7 @@ static void handle_client_inner(j_conn *client)
const char *bearer = auth && !strncasecmp(auth, "Bearer ", 7) ? auth + 7 : auth;
vk = vkey_lookup(&rq.hdrs, bearer);
if (vk) {
snprintf(t_vkey_name, sizeof t_vkey_name, "%s", vk->name);
/* Limits dieses Schlüssels, bevor irgendetwas Routen kostet. Das Fenster
* ist eine Minute, fest gerechnet (nicht gleitend): es soll einen Client
* bremsen, nicht auf die Millisekunde genau sein. */
@@ -4276,6 +4285,24 @@ static void handle_client_inner(j_conn *client)
send_simple(client, 403, "Forbidden", body);
goto done;
}
if (vk->deny[0] && model[0]) {
char mbase[J_GLOB_MAX];
snprintf(mbase, sizeof mbase, "%s", model);
char *hash = strchr(mbase, '#');
if (hash) *hash = '\0';
if (fnmatch(vk->deny, model, 0) == 0 ||
(mbase[0] && fnmatch(vk->deny, mbase, 0) == 0)) {
char body[512], emodel[256], evk[128];
json_escape(model, emodel, sizeof emodel);
json_escape(vk->name, evk, sizeof evk);
snprintf(body, sizeof body,
"{\"error\":\"vkey_model_not_allowed\",\"vkey\":\"%s\",\"model\":\"%s\"}",
evk, emodel);
jlog("vkey_denied", "vkey=%s model=%s (deny)", vk->name, model);
send_simple(client, 403, "Forbidden", body);
goto done;
}
}
jlog("vkey", "vkey=%s model=%s", vk->name, model);
}
}
@@ -4357,18 +4384,21 @@ static void handle_client_inner(j_conn *client)
}
if (!fits) {
const j_pool *fb = find_pool(CFG.ctx_fallback);
if (fb && fb->count > 0) {
rule_copy.target_count = fb->count;
char ft[J_MAX_TARGETS][J_NAME_MAX];
char fa[J_MAX_TARGETS][J_GLOB_MAX];
int fn = fb ? j_pool_members(fb, ft, fa, J_MAX_TARGETS) : 0;
if (fn > 0) {
rule_copy.target_count = fn;
rule_copy.check = J_CHECK_NONE;
rule_copy.balance = J_BALANCE_FIRST;
rule_copy.strip[0] = '\0';
for (int c = 0; c < fb->count; c++) {
for (int c = 0; c < fn; c++) {
snprintf(rule_copy.targets[c], sizeof rule_copy.targets[c],
"%s", fb->targets[c]);
const char *m = fb->target_as[c][0] ? fb->target_as[c]
"%.*s", (int)sizeof rule_copy.targets[c] - 1, ft[c]);
const char *m = fa[c][0] ? fa[c]
: CFG.ctx_fallback_model;
snprintf(rule_copy.target_as[c], sizeof rule_copy.target_as[c],
"%s", m);
"%.*s", (int)sizeof rule_copy.target_as[c] - 1, m);
}
jlog("ctx_fallback", "rule_line=%d ctx=%ld need=%ld pool=%s",
rule_copy.line, ctx, need, CFG.ctx_fallback);
@@ -4417,8 +4447,14 @@ static void handle_client_inner(j_conn *client)
const char *judge_as = rule->judges[step].as;
int cache = rule->judges[step].cache;
const j_pool *judge_pool = find_pool(target);
int slots = judge_pool ? judge_pool->count : 1;
if (rule_copy.target_count + slots > J_MAX_TARGETS) {
char jt[J_MAX_TARGETS][J_NAME_MAX];
char ja[J_MAX_TARGETS][J_GLOB_MAX];
int jn = judge_pool ? j_pool_members(judge_pool, jt, ja, J_MAX_TARGETS) : 0;
int slots = judge_pool ? jn : 1;
if (judge_pool && jn == 0) {
jlog("judge_skipped", "rule_line=%d reason=pool_%s_empty",
rule->line, target);
} else if (rule_copy.target_count + slots > J_MAX_TARGETS) {
jlog("judge_skipped", "rule_line=%d reason=target_limit", rule->line);
} else {
if (cache > 0 &&
@@ -4436,11 +4472,11 @@ static void handle_client_inner(j_conn *client)
rule_copy.target_as[k], sizeof rule_copy.target_as[k]);
}
if (judge_pool) {
for (int c = 0; c < judge_pool->count; c++) {
for (int c = 0; c < jn; c++) {
snprintf(rule_copy.targets[c], sizeof rule_copy.targets[c], "%.*s",
(int)sizeof rule_copy.targets[c] - 1,
judge_pool->targets[c]);
const char *m = judge_pool->target_as[c][0] ? judge_pool->target_as[c]
jt[c]);
const char *m = ja[c][0] ? ja[c]
: judge_as;
snprintf(rule_copy.target_as[c], sizeof rule_copy.target_as[c],
"%.*s", (int)sizeof rule_copy.target_as[c] - 1, m);
@@ -5108,7 +5144,23 @@ static void *probe_thread(void *unused)
static void *models_refresh_thread(void *unused)
{
(void)unused;
j_models_refresh_all();
for (;;) {
/*
* The read lock keeps config.set from swapping endpoints while the
* fetch walks them. It is a read lock: requests keep flowing. The
* refresh interval is deliberately larger than the probe interval.
*/
pthread_rwlock_rdlock(&g_config_rw);
j_models_refresh_all();
double nap = CFG.models_refresh_s;
pthread_rwlock_unlock(&g_config_rw);
if (nap <= 0) break;
double next = now_s() + nap;
while (now_s() < next) {
struct timespec ts = { 0, 200 * 1000 * 1000 };
nanosleep(&ts, NULL);
}
}
return NULL;
}
@@ -5256,6 +5308,7 @@ int main(int argc, char **argv)
pthread_detach(mt);
else
j_models_refresh_all();
jlog("models", "refresh_s=%.0f", CFG.models_refresh_s);
}
/* Neustart-Ankuendigung: nach SIGTERM bleibt der Listener noch eine kurze
+270 -18
View File
@@ -27,6 +27,7 @@
#include "config.h"
#include "models.h"
#include "price.h"
extern j_config CFG; /* der Router hält genau eine Konfiguration */
@@ -87,6 +88,35 @@ static long long_after(const char *p, const char *end)
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;
@@ -115,6 +145,8 @@ int j_models_parse(j_endpoint *ep, const char *json, size_t len)
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\"");
@@ -132,6 +164,53 @@ int j_models_parse(j_endpoint *ep, const char *json, size_t len)
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);
@@ -142,12 +221,36 @@ int j_models_parse(j_endpoint *ep, const char *json, size_t len)
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;
@@ -213,6 +316,31 @@ static int model_match(const char *pattern, const char *model, const char *base)
(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;
@@ -336,6 +464,82 @@ static const j_pool *find_pool_cfg(const char *name)
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
@@ -345,6 +549,21 @@ static long effective_limit_for_rule(const j_rule *r, const char *model, int whi
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;
@@ -358,10 +577,13 @@ static long effective_limit_for_rule(const j_rule *r, const char *model, int whi
if (!target[0]) continue;
const j_pool *jp = find_pool_cfg(target);
if (jp) {
for (int c = 0; c < jp->count; c++) {
j_endpoint *ep = find_ep(jp->targets[c]);
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 = jp->target_as[c][0] ? jp->target_as[c]
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;
@@ -450,7 +672,8 @@ static int find_data_array(const char *json, size_t len, const char **arr, const
return -1;
}
int j_models_filter_list(const char *json, size_t len, char **out, size_t *out_len)
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;
@@ -485,7 +708,8 @@ int j_models_filter_list(const char *json, size_t len, char **out, size_t *out_l
if (!string_at(v, oend + 1, id, sizeof id)) id[0] = '\0';
}
if (id[0] == '\0' || j_model_allowed(id)) {
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);
@@ -550,7 +774,8 @@ static char *cap_limits_json(const char *json, size_t len, size_t *out_len)
return out;
}
int j_models_patch_list(const char *json, size_t len, char **out, size_t *out_len)
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;
@@ -566,6 +791,7 @@ int j_models_patch_list(const char *json, size_t len, char **out, size_t *out_le
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) ||
@@ -620,6 +846,29 @@ int j_models_patch_list(const char *json, size_t len, char **out, size_t *out_le
}
/* 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++) {
@@ -655,25 +904,27 @@ void j_models_refresh_all(void)
continue;
}
/* Veröffentlicht die Liste keine Grenzen, fragt junction die eigene API des
* Endpunkts (ollama.com: /api/show). Erst ein Modell als Probe: antwortet es
* nicht, sind die übrigen Anfragen nur Wartezeit. */
* 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;
if (ep->models[0].ctx == 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';
long probe = publish_context_length(root, ep->models[0].id, ep);
if (probe > 0) {
ep->models[0].ctx = probe;
filled = 1;
for (int k = 1; k < ep->model_count; k++) {
if (ep->models[k].ctx > 0) continue;
long v = publish_context_length(root, ep->models[k].id, ep);
if (v > 0) { ep->models[k].ctx = v; filled++; }
}
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++; }
}
}
@@ -684,4 +935,5 @@ void j_models_refresh_all(void)
ep->models[k].id, ep->models[k].ctx, ep->models[k].out);
fprintf(stderr, "\n");
}
models_price_import();
}
+9 -2
View File
@@ -31,7 +31,8 @@ long j_models_rule_limit(const j_rule *r, int which);
/* Ergänzt/patcht eine OpenAI-/v1/models-JSON-Antwort um virtuelle Fallback-/Pool-
* Alias-Modelle (kleinste ctx/output über die Kette). Gibt 0 bei Erfolg zurück und
* liefert ggf. neuen Buffer in *out / *out_len (Caller freed). */
int j_models_patch_list(const char *json, size_t len, char **out, size_t *out_len);
int j_models_patch_list(const char *json, size_t len, const char *vkey_name,
char **out, size_t *out_len);
/* Modell-Politik aus `models allow` / `models deny`. 1 = erlaubt, 0 = verboten.
* Ein Suffix "#variante" wird zusätzlich ohne Variante geprüft, damit eine Freigabe
@@ -40,7 +41,13 @@ int j_model_allowed(const char *model);
/* Filtert eine OpenAI-/v1/models-JSON-Antwort auf die erlaubten IDs. Gibt 0 zurück
* und liefert einen neuen Buffer, wenn Einträge entfernt wurden; -1 heißt unverändert. */
int j_models_filter_list(const char *json, size_t len, char **out, size_t *out_len);
int j_models_filter_list(const char *json, size_t len, const char *vkey_name,
char **out, size_t *out_len);
/* Dynamic pools: snapshot the current members of a pool (static or from the
* endpoint's model list), and resolve a copied rule's dynamic targets. */
int j_pool_members(const j_pool *pl, char targets[][J_NAME_MAX],
char as[][J_GLOB_MAX], int max);
void j_rule_resolve_dynamic(j_rule *r);
/* Der Parser, getrennt, damit ein Test ihn ohne Netz prüfen kann. Gibt die Zahl
* der gelesenen Modelle zurück (0 = nichts erkannt). */
+76 -2
View File
@@ -19,6 +19,7 @@
#include "price.h"
#include <ctype.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -28,6 +29,52 @@
static j_price g_rows[J_MAX_PRICES];
static int g_count;
/* Dynamic rows come from the providers' model lists; g_rows stays the file. */
static j_price g_dyn[J_MAX_PRICES];
static int g_dyn_n;
static pthread_mutex_t g_dyn_mu = PTHREAD_MUTEX_INITIALIZER;
static j_price g_imp[J_MAX_PRICES];
static int g_imp_n;
void j_price_import_begin(void)
{
g_imp_n = 0;
}
void j_price_import_add(const char *model, double in, double cached, double out,
double factor)
{
if (!model || !*model || g_imp_n >= J_MAX_PRICES) return;
if (in <= 0.0 && out <= 0.0) return;
/* The same model is listed by several endpoints (opencode-go0/1/2 and the
* free endpoint). One price row is enough; the first one wins. */
for (int i = 0; i < g_imp_n; i++)
if (!strcmp(g_imp[i].model, model)) return;
j_price *r = &g_imp[g_imp_n];
memset(r, 0, sizeof *r);
snprintf(r->model, sizeof r->model, "%s", model);
double peak = factor > 1.0 ? factor : 1.0;
r->in = in * peak;
r->out = out * peak;
r->cached = cached > 0.0 ? cached * peak : r->in;
if (peak > 1.0) {
r->has_offpeak = 1;
r->off_in = in;
r->off_out = out;
}
g_imp_n++;
}
int j_price_import_end(void)
{
pthread_mutex_lock(&g_dyn_mu);
memcpy(g_dyn, g_imp, (size_t)g_imp_n * sizeof g_dyn[0]);
g_dyn_n = g_imp_n;
pthread_mutex_unlock(&g_dyn_mu);
return g_imp_n;
}
/* "43330/5h" -> Grenze und Fenster in Sekunden. */
static void parse_requests(const char *v, long *limit, long *window_s)
{
@@ -130,8 +177,35 @@ int j_price_lookup(const char *model, j_price *out)
}
base[b] = '\0';
const j_price *hit = price_exact(model);
if (!hit && base[0]) hit = price_exact(base);
/* A provider-published price wins; the file row still contributes the
* budget and request window, which no model list carries. */
j_price dyn;
int has_dyn = 0;
pthread_mutex_lock(&g_dyn_mu);
for (int i = 0; i < g_dyn_n; i++) {
if (strcmp(g_dyn[i].model, model) &&
(!base[0] || strcmp(g_dyn[i].model, base)))
continue;
dyn = g_dyn[i];
has_dyn = 1;
break;
}
pthread_mutex_unlock(&g_dyn_mu);
const j_price *file = price_exact(model);
if (!file && base[0]) file = price_exact(base);
if (has_dyn) {
if (file) {
dyn.budget_usd = file->budget_usd;
dyn.requests_window = file->requests_window;
dyn.window_s = file->window_s;
}
if (out) *out = dyn;
return 0;
}
const j_price *hit = file;
if (!hit) hit = price_star();
if (!hit) return -1;
if (out) *out = *hit;
+8
View File
@@ -32,4 +32,12 @@ int j_price_lookup(const char *model, j_price *out);
double j_price_cost(const char *model, long in_tokens, long cached_tokens, long out_tokens,
int offpeak);
/* Preise, die die Modellliste eines Anbieters selbst nennt. Sie werden bei jedem
* Modell-Refresh neu aufgebaut und schlagen die Datei; Budget und Anfragefenster
* aus der Datei bleiben erhalten, weil sie nicht in der Liste stehen. */
void j_price_import_begin(void);
void j_price_import_add(const char *model, double in, double cached, double out,
double factor);
int j_price_import_end(void);
#endif
+38
View File
@@ -123,3 +123,41 @@ R=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' \
-d '{"model":"baz","messages":[{"role":"user","content":"frei"}],"max_tokens":8}' \
"http://127.0.0.1:$MP3/v1/chat/completions")
contains "$R" "served by MODELS" "without models lines the model is served"
# Ein vkey darf die globale Politik verengen: deny blendet ein Modell aus der
# /v1/models-Liste aus und weist es im Anfragepfad ab. So sieht Olivia sich
# selbst nicht im Modellwaehler, obwohl alle anderen das Modell sehen.
MP4=$((PORT+307))
cat > "$TMP/model-vkey.conf" <<CFG
listen 127.0.0.1:$MP4
endpoint bag {
base http://127.0.0.1:$MPS/v1
context 64000
timeout 10
}
models allow "*"
vkey "olivia" token_env VKEY_OLIVIA_TEST allow "*" deny "baz"
req path "/v1/models" check none pass bag
req for "*" check none pass bag
CFG
VKEY_OLIVIA_TEST=testkey ./junction --config "$TMP/model-vkey.conf" \
> "$TMP/model-vkey.log" 2>&1 & PIDS+=($!)
wait_port $MP4 10
R=$(curl -s -m 10 "http://127.0.0.1:$MP4/v1/models")
contains "$R" '"id":"baz"' "a model hidden from one vkey is still listed without a key"
R=$(curl -s -m 10 -H 'Authorization: Bearer testkey' "http://127.0.0.1:$MP4/v1/models")
case "$R" in
*'"id":"baz"'*) bad "a vkey deny did not hide the model from /v1/models" ;;
*) ok "a vkey deny hides its model from /v1/models" ;;
esac
contains "$R" '"id":"foo"' "a vkey deny leaves the other models listed"
CODE=$(curl -s -m 10 -o /dev/null -w '%{http_code}' -X POST \
-H 'Authorization: Bearer testkey' -H 'Content-Type: application/json' \
-d '{"model":"baz","messages":[{"role":"user","content":"nein"}],"max_tokens":8}' \
"http://127.0.0.1:$MP4/v1/chat/completions")
if [ "$CODE" = "403" ]; then ok "a vkey deny refuses the hidden model (403)"; else bad "vkey deny request got HTTP $CODE"; fi
R=$(curl -s -m 20 -X POST -H 'Authorization: Bearer testkey' \
-H 'Content-Type: application/json' \
-d '{"model":"foo","messages":[{"role":"user","content":"ok"}],"max_tokens":8}' \
"http://127.0.0.1:$MP4/v1/chat/completions")
contains "$R" "served by MODELS" "a vkey may still call the models it can see"
+38
View File
@@ -71,3 +71,41 @@ case "$OUT" in
*"unknown endpoint"*) ok "an unknown pool or endpoint name is refused" ;;
*) bad "unknown name was not refused: $OUT" ;;
esac
# 5. Dynamischer Pool: die Mitglieder sind die Modelle, die der Endpunkt
# gerade als *-free veroeffentlicht. Kein Name steht in der Konfiguration.
DYNP=$((PORT+305))
DYNS=$((PORT+306))
STUB_MODELS="alpha-free,beta-free,gamma" STUB_CTX=1000 STUB_OUT=100 \
tests/stub $DYNS MODELS > "$TMP/dyn_stub.log" 2>&1 & PIDS+=($!)
wait_port "$DYNS" 10 || bad "the dynamic-pool model stub did not come up"
cat > "$TMP/dynamic-pool.conf" <<CFG
listen 127.0.0.1:$DYNP
probe_interval 0
models_refresh 300
endpoint bag { base http://127.0.0.1:$DYNS/v1; context 1000; timeout 10 }
pool free from bag match "*-free"
req path "/v1/models" check none pass bag
req for "dynamic" check none pass free
req for "*" check none pass bag
CFG
./junction --config "$TMP/dynamic-pool.conf" > "$TMP/dynamic-pool.log" 2>&1 &
PIDS+=($!)
wait_port "$DYNP" 10 || bad "the dynamic-pool router did not come up"
for i in $(seq 1 100); do
grep -q 'models: bag 3 Modelle' "$TMP/dynamic-pool.log" 2>/dev/null && break
sleep 0.05
done
H=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' \
-d '{"model":"dynamic","messages":[{"role":"user","content":"hi"}],"max_tokens":8}' \
"http://127.0.0.1:$DYNP/v1/chat/completions")
case "$H" in
*"X-Stub-Model: alpha-free"*|*"X-Stub-Model: beta-free"*)
ok "a dynamic pool sends one of the endpoint's *-free models" ;;
*) bad "the dynamic pool did not rewrite to a *-free model: $(printf '%s' "$H" | grep -i 'X-Stub-Model' || echo no header)" ;;
esac
case "$H" in
*"X-Stub-Model: gamma"*) bad "a model outside the glob leaked into the dynamic pool" ;;
*) ok "a model outside the glob stays out of the dynamic pool" ;;
esac