junction

A policy router for OpenAI-compatible model endpoints. It sits in front of N servers and decides per request which one answers — and what happens when none of them wants to.

C99POSIX no runtime dependenciessingle text config ~5,200 lines of C94 tests

What it is

You run more than one model server. Maybe a paid cloud account, two free tiers, a workstation that sleeps, a box on the LAN that is only good for small prompts. Your clients speak /v1/chat/completions and should keep doing so.

junction is the thing in between. It reads one text file of rules, picks a target per request, tries the next one when the first fails, keeps streams intact, and tells you in the response headers and in /status exactly what it did.

The rule language is deliberately close to pf.conf: first match wins, unknowns are a hard error with a line number, and there is no silent fallback to "somewhere". A request that matches no rule gets 503 no_matching_rule, because a gap in the configuration is not a routing decision.

Features

Routing

  • Per-request rules, first match wins — model glob, path glob, declared output budget, estimated prompt size, vision/text, endpoint health
  • Fallback chains: pass a, b, c — targets tried in order
  • Named pools, reusable and nestable: pool lokal box3, box6
  • Explicit refusal: block answers 403 instead of rerouting
  • Model rewrite per target: as "local-name"
  • Skip reasons named in the 503 body and in /status

Load and cost

  • Four selection modes: first, round-robin, least-usage, cost
  • Weights per endpoint, honoured by round-robin and by the cost score
  • Balance mode per rule, overriding the global one
  • Budgets soft/hard in percent, with throttle or skip
  • Usage from outside: a command prints a number, junction polls it
  • Off-peak window halves the price of a target inside it

Failure

  • Two timeouts: total, and silence — the latter emits a keep-alive comment so a thinking model is not killed
  • Per-endpoint connect timeout, separate from the global one
  • Cooldown after a failed attempt, offline hold after a refused connection — no retry storm
  • Queue instead of reject: bounded wait with a position notice
  • Hooks that decide whether a target is usable, with retry and backoff
  • Wake-on-LAN once, before the hooks are retried

Protocol

  • Streaming preserved byte for byte, including chunked framing
  • Chunked request bodies decoded, so upstreams see a length
  • opencode bridge: session-based API translated to OpenAI in both directions
  • Header injection per endpoint, plus X-Forwarded-For/Proto
  • TLS both ways, with a private CA per endpoint

Memory and context

  • Tool-output compression: deterministic, no model call, per endpoint — measured 47,088 → 2,040 bytes on a 900-line log
  • Original bytes otherwise: compression splices spans, it never re-serialises the body
  • Never touches system, user or assistant messages, nor the last N
  • Bounded everything: body size, cache bytes, inflight count

Operation

  • Virtual keys: clients get their own key, restricted to model globs and endpoint sets — the real upstream key never leaves the host
  • /status as JSON: endpoints, counters, cache, queue, rules
  • Admin API: pause, resume, flush cache
  • Response cache in memory, LRU, respecting Cache-Control
  • Strict config parsing with line numbers; --check without starting

Build

$ make
$ sudo make install          # binary, systemd unit, example config

$ junction --config /etc/junction/junction.conf --check
$ junction --config /etc/junction/junction.conf

OpenSSL is the only optional dependency, needed for TLS. Without it, junction builds as plain HTTP. The flags are -std=c99 -Wall -Wextra -Wpedantic -Wshadow -Wconversion; the tree builds clean under all of them.

How a request is decided

A client asks for model: "chat" with roughly 3,000 prompt tokens and no declared output budget. Rules are read top to bottom:

req path "/v1/models" check none pass cloud      no match - different path
req for "*embed*" check none pass embed           no match - different model
req vision pass workstation, cloud as "v"         no match - no image
req ctx <2000 pass workstation                    no match - prompt is larger
req ctx <50000 pass ollama1, cloud                match    - 3,000 is below 50,000

The matched rule lists two targets. junction asks the first; if its connection is refused, that target is marked offline for offline_hold_s and the second one is tried within the same request. Every response says which target answered:

X-Junction-Endpoint: ollama1
X-Junction-Ms: 412
X-Junction-Cache: off

Full reference configuration

Every key the parser knows, each with the reasoning behind it. Copy the file and delete the parts you do not need — not the comments.

# ============================================================================
#  junction — vollständige Referenzkonfiguration
# ============================================================================
#
# Diese Datei enthält JEDEN Schlüssel, den der Parser kennt, jeweils mit einer
# Erklärung und einem sinnvollen Wert. Sie ist zum Abschreiben gedacht: für den
# Betrieb die überflüssigen Endpunkte löschen, nicht die Erklärungen.
#
# Grammatik: Schlüsselwort, Argumente, geschweifte Klammern. `#` ist Kommentar,
# doppelte Anführungszeichen fassen Wörter zusammen. Ein unbekanntes Schlüsselwort
# ist ein harter Fehler mit Zeilennummer — es gibt keine stillen Tippfehler.
#
# Prüfen ohne zu starten:   junction --config diese-datei --check
# ============================================================================


# ---------------------------------------------------------------- Zuhörer
#
# Wohin junction lauscht. Ohne `tls` reines HTTP. Mit `tls` zwei Zertifikatspfade
# in dieser Reihenfolge: Zertifikat, Schlüssel.
#
# Loopback ist die richtige Wahl, wenn der Prozess echte Upstream-Schlüssel in
# seiner Umgebung hält — er ist dann kein offener Proxy für LAN oder VPN.
listen 127.0.0.1:8090
# listen 0.0.0.0:8443 tls /etc/junction/tls/cert.pem /etc/junction/tls/key.pem

# Präfix jeder Logzeile. Steht hier, damit im Code kein Produktname auftaucht.
log_prefix junction


# ---------------------------------------------------------------- Zeitlimits
#
# Verbindungsaufbau zum Endpunkt. Ein Fehlschlag hier heißt sofort "offline" —
# das ist kein Wiederholfall, ein nicht antwortender Rechner wird nicht besser,
# wenn man ihn zweimal fragt.
connect_timeout_ms 1500

# Wie lange ein Endpunkt nach einem Verbindungsfehler als offline gilt, bevor
# ihn der nächste Versuch wieder prüft. Sekunden.
offline_hold_s 20

# Obergrenze für einen Anfragekörper. Schutz gegen einen Client, der den Router
# als Speicher missbraucht.
max_body_bytes 67108864


# ---------------------------------------------------------------- Nebenläufigkeit
#
# Wie viele Anfragen gleichzeitig zu Upstreams unterwegs sein dürfen. Der Rest
# wartet in einer Schlange, statt abgewiesen zu werden.
max_inflight 8

# Wie lange ein Wartender höchstens in der Schlange steht, bevor er eine Antwort
# bekommt. Sekunden. Danach: Fehlerereignis, bei Streamern gefolgt von [DONE].
queue_timeout 300


# ---------------------------------------------------------------- Antwort-Cache
#
# Nur im Speicher, LRU, Schlüssel ist Methode + Pfad + Modell + Körper. Streams
# werden nie zwischengespeichert. `Cache-Control: no-store/private` des Upstreams
# und `no-cache` des Clients werden respektiert.
#
# 0 bedeutet: Cache aus. Ein Cache auf einem Router, der Modelle mit
# unterschiedlichen Temperaturen bedient, ist meist falsch — deshalb hier aus.
cache_ttl 0
cache_entries 0
cache_bytes 0


# ---------------------------------------------------------------- Prompt-Größe
#
# Zeichen pro Token für die Schätzung, die Regeln mit `ctx` benutzen. 0 (Standard) heißt:
# keine Schätzung, und eine Regel mit ctx-Bedingung wird beim Laden abgelehnt — besser ein
# Fehler als eine Regel, die still nie greift.
#
# Der Wert ist eine Annahme über die Tokenisierung, keine Messung. Base64-Bilddaten werden
# bei der Zählung übersprungen, sonst zählt ein Foto als Hunderttausend Token.
ctx_chars_per_token 4


# ---------------------------------------------------------------- Auswahlreihenfolge
#
# Wie Ziele INNERHALB einer Regel geordnet werden, wenn mehrere genannt sind:
#   first        in der Reihenfolge der Regel (reiner Failover)
#   round-robin  reihum, gleichmäßig
#   least-usage  kleinster eigener Verbrauch zuerst (Prozent des Budgets)
#   cost         Verbrauch × Preis; im Off-Peak-Fenster halbiert sich der Preis
balance cost


# ---------------------------------------------------------------- virtuelle Schlüssel
#
# Clients bekommen diese Schlüssel, nie den echten Upstream-Schlüssel. Der Wert
# steht in einer Umgebungsdatei (0600 root), hier steht nur der Name der Variable.
#
#   vkey "name" token_env VAR allow "<modell-glob>" [endpoints "a,b"]
#
# `allow` begrenzt die Modelle, `endpoints` zusätzlich die Ziele. Ein Schlüssel,
# der nur DeepSeek darf, kann keinen GPT-Aufruf auslösen, selbst wenn eine Regel
# es erlauben würde.
vkey "webui"     token_env VKEY_WEBUI     allow "deepseek-*"
vkey "navigator" token_env VKEY_NAVIGATOR allow "*" endpoints "ollama1,ollama2"
vkey "hermes"    token_env VKEY_HERMES    allow "*"


# ============================================================================
#  Endpunkte
# ============================================================================

# ---------------------------------------------------------------- Abo-Cloud
#
# Der teuerste Weg pro Anfrage, aber bezahlt: die Grenzkosten sind fast null.
# `cost` ist hier ein Vergleichsgewicht, kein Geldbetrag.
endpoint cloud {
    base https://opencode.ai/zen/go/v1
    kind cloud
    context 200000

    # Niedrigere Zahl gewinnt, wenn eine Regel mehrere Ziele ohne eigene
    # Reihenfolge nennt. Relevant nur bei balance first.
    priority 90

    # Gesamtzeit für eine Anfrage und Stille-Zeit bis "still_working" im Log
    # steht. Zwei Werte, weil ein denkendes Modell nicht hängt.
    timeout 900
    idle_timeout 120

    # Eigenes Verbindungs-Zeitlimit: dieses Ziel steht hinter einem Tunnel, ein
    # ausgefallener Aufbau soll die Kette nach 400 ms weiterreichen, nicht nach 1,5 s.
    connect_timeout_ms 400

    tls_verify on
    api_key_env OPENCODE_GO_API_KEY

    # Manche Upstreams hinter Cloudflare weisen fremde User-Agents ab (403/1010)
    # und verlangen eine Session-Kennung. header ist wiederholbar.
    header "User-Agent: Mozilla/5.0 (X11; Linux x86_64) client/1.0"
    header "x-opencode-session: ses-webui-01"

    # Verbrauch von außen messen: das Skript gibt eine Zahl aus, junction pollt sie.
    usage_cmd /usr/local/libexec/junction-usage-opencode.sh
    usage_poll 120

    # Weiche und harte Grenze in Prozent. Über soft wird gedrosselt, über hard
    # übersprungen — aber nur, wenn eine Regel noch ein anderes Ziel nennt.
    budget soft 85
    budget hard 96
    on_soft delay 2
    on_hard skip

    cost 0.1
    cache off
}

# ---------------------------------------------------------------- Guthaben-Cloud, zwei Konten
#
# Zwei Konten desselben Anbieters, je mit eigenem Monatsguthaben. Beide Endpunkte
# sind gleich aufgebaut; unterschieden werden sie nur durch Schlüssel, Verbrauchs-
# messung und Priorität.
# Gewicht: höher = häufiger. Unter round-robin bekommt ein Ziel mit Gewicht 3 drei
# Plätze in der Runde, unter cost/least-usage zählt sein Verbrauch nur ein Drittel.
endpoint ollama1 {
    weight 3
    base https://ollama.com/v1
    kind cloud
    context 128000
    priority 50
    timeout 900
    idle_timeout 120
    tls_verify on
    api_key_env OLLAMA_KEY1

    usage_cmd "/usr/local/libexec/junction-usage-ollama.sh 1"
    usage_poll 180
    budget soft 80
    budget hard 95
    on_soft delay 1
    on_hard skip

    # Fenster, in dem dieser Endpunkt billiger ist: von 18:00 bis 12:00 des
    # Folgetages. Ein Fenster, nicht zwei — "Wochenende ganztägig" lässt sich
    # damit nicht ausdrücken.
    offpeak 18:00-12:00
    cost 1.5
}

endpoint ollama2 {
    base https://ollama.com/v1
    kind cloud
    context 128000
    priority 50
    timeout 900
    idle_timeout 120
    tls_verify on
    api_key_env OLLAMA_KEY2
    usage_cmd "/usr/local/libexec/junction-usage-ollama.sh 2"
    usage_poll 180
    budget soft 80
    budget hard 95
    on_soft delay 1
    on_hard skip
    offpeak 18:00-12:00
    cost 1.5
}

# ---------------------------------------------------------------- lokaler Rechner mit Aufwecken
#
# Der interessante Fall: eine Workstation, die schläft. `wake` läuft einmal,
# bevor die Haken wiederholt werden — erst wecken, dann warten.
endpoint workstation {
    base http://192.0.2.20:8080/v1
    kind local
    context 128000
    priority 10
    timeout 1800
    idle_timeout 30

    # Haken: Exit 0 heißt benutzbar, alles andere "noch nicht". Der Grund, den
    # der Haken auf stdout schreibt, landet in /status und im 503-Körper.
    hook /usr/local/share/junction/hooks/check-http.sh

    # Wie lange insgesamt auf den Rechner gewartet wird und in welchem Abstand.
    hook_retry 180
    hook_backoff 5

    # Einmaliger Weckruf vor dem ersten Wiederholen.
    wake /usr/local/share/junction/hooks/wake-wol.sh

    # Statischer Kopfzeilen-Zusatz pro Endpunkt.
    header "X-Box: workstation"

    # Kann dieser Endpunkt Bilder? on = ja, off = nein, weglassen = keine Prüfung.
    # Ein Text-Endpunkt wird für eine Bildanfrage übersprungen, statt sie anzunehmen
    # und mit leerem Inhalt zu antworten.
    vision off

    # Ein lokaler Rechner kostet Strom, kein Geld. Kleines Gewicht, damit er im
    # Vergleich gewinnt, solange er wach ist.
    cost 0.0
    cache on
    tls_verify off
}

# ---------------------------------------------------------------- privates TLS mit eigener CA
endpoint private-tls {
    base https://llm.internal.example/v1
    kind remote
    context 32000
    priority 30
    timeout 600
    idle_timeout 90
    cooldown 120
    tls_verify on
    tls_ca /etc/junction/ca/internal-ca.pem
    api_key_env INTERNAL_KEY
    cache on
}

# ---------------------------------------------------------------- opencode serve
#
# opencode spricht kein OpenAI-Protokoll: seine API ist sitzungsorientiert
# (/api/session, /prompt, /model, /message). Mit `kind opencode` übersetzt junction das
# in beide Richtungen, sodass ein Client weiter /v1/chat/completions spricht.
#
# Zwei Werte kommen aus Kommandos, weil opencode sie nicht festhält: der Hintergrund-
# dienst bindet einen freien Port, und er erzeugt bei jedem Start ein neues Passwort.
endpoint opencode {
    base http://127.0.0.1:4096
    kind opencode
    context 200000
    timeout 600
    idle_timeout 120
    auth_basic opencode
    pass_cmd /usr/local/libexec/opencode-password.sh
    # Nur nötig, wenn der Dienst auf einem zufälligen Port läuft:
    # base_cmd "/usr/local/bin/opencode service status"
    cost 0.0
}

# ---------------------------------------------------------------- Einbetter, klein und billig
endpoint embed {
    base http://192.168.1.10:11434/v1
    kind local
    context 8192
    priority 10
    timeout 120
    idle_timeout 45
    # Nach einem Fehlschlag so viele Sekunden Pause, statt bei jeder Anfrage neu
    # in ein Timeout zu laufen.
    cooldown 30
    cache on
}


# ============================================================================
#  Regeln — erste Übereinstimmung gewinnt
# ============================================================================
#
#   req [for <modell-glob>] [path <glob>] [need >N | <N | N]
#       [check hooks|none] [retry <s>]
#       ( pass <ziel>[,<ziel>...] [as <modell>] | block )
#
# for   — Modellname aus dem Anfragekörper, fnmatch-Muster
# path  — Pfad, fnmatch-Muster
# need  — das vom Client ANGEGEBENE Ausgabebudget (max_tokens /
#         max_completion_tokens). Kein Raten, keine Zeichenzählung: eine Anfrage
#         ohne Angabe erfüllt keine need-Regel. >64000 heißt "mehr als 64k
#         angefordert"; ein Endpunkt mit kleinerem context wird dann übersprungen.
# check — haken (Standard des Endpunkts) oder none (Haken überspringen, z.B. bei
#         Modell-Listen, die auch dann sinnvoll sind, wenn nichts läuft)
# retry — Wartezeit für Haken, überschreibt hook_retry dieser Regel
# as    — schreibt das Modellfeld NUR für dieses Ziel um. Der erste Ziel bekommt
#         die lokale Kennung, der letzte die angefragte.

# Modell-Liste: kein Haken nötig, sie beantwortet auch ein schlafender Rechner.
req path "/v1/models" check none pass cloud

# Einbetter laufen lokal, egal was sonst gilt.
req for "*embed*" check none pass embed

# Die freien opencode-Modelle gehen an den opencode-Endpunkt, alles andere nicht.
req for "opencode/*" pass opencode
req for "*-free" pass opencode

# Bildanfragen: immer an das Bildmodell, unabhängig vom angefragten Namen. Erst der
# eigene Rechner (kostet nichts), dann die Cloud — dort mit umgeschriebenem Modellnamen.
# "as" gilt für das Ziel direkt davor, nicht für die ganze Regel.
req vision pass workstation, cloud as "vision-capable-model"

# Kleine Anfragen an den eigenen Rechner, mittlere an das Guthaben, große an das Abo mit
# dem großen Kontext. Reihenfolge zählt: das engste Fenster zuerst, sonst fängt das
# größere alles ab. Die Zahlen sind Politik und gehören hierher, nicht in den Code.
req ctx <2000 pass workstation
req ctx <50000 pass ollama1, cloud
req ctx >50000 pass cloud

# Große Budgets kann der lokale Rechner nicht halten — also gar nicht erst hin.
req need >64000 pass cloud, ollama1

# Ein Modell, das es nur lokal gibt, mit lokalem Namen; sonst dieselbe Anfrage
# an die Cloud weitergereicht.
req for "*coder*" retry 300 pass workstation as "qwen3.8-flash-next-q1m", cloud

# Ein Modell, das es nicht geben darf. 403, kein stilles Umleiten.
req for "blocked-*" block

# Alles Übrige: erst der wache lokale Rechner, dann die Cloud, dann Guthaben.
# Kein Treffer für eine Anfrage bedeutet 503 no_matching_rule — eine Lücke in der
# Konfiguration ist kein Fall für "irgendwohin schicken".
# Ketten einen Namen geben. Ein Pool darf auch auf einen anderen verweisen; beim Laden
# wird er aufgelöst, damit eine Regel nicht jedes Mal fünf Ziele ausschreiben muss.
pool lokal   ollama1, ollama2
pool alles   cloud, lokal

# Ein Endpunkt darf auch in einer Zeile stehen, wenn er klein ist:
#   endpoint kurz { base http://127.0.0.1:8080/v1; timeout 60 }

# Diese eine Regel will reines Failover, egal was global eingestellt ist.
req for "starr*" balance first pass workstation, cloud

req for "*" check hooks pass workstation, cloud, ollama1, ollama2


# ============================================================================
#  Steuerung zur Laufzeit
# ============================================================================
#
#   GET  /status                 Endpunkte, Zähler, Cache, Regeln, Schlange
#   POST /admin/pause/<name>     dort nicht mehr routen
#   POST /admin/resume/<name>    Pause, Abkühlung und Offline zurücksetzen
#   POST /admin/flush/cache      jeden zwischengespeicherten Antwortkörper verwerfen
#
# Alles andere wird an den Endpunkt weitergeleitet, den die Regeln wählen.
# Jede Antwort trägt X-Junction-Endpoint, X-Junction-Ms und X-Junction-Cache.

Known limits

Named on purpose. A router that hides its edges gets trusted further than it should.
LimitWhat it means in practice
one off-peak window A target can be cheaper inside a single daily time range. "All weekend" is not expressible.
flat chains A rule lists targets; a target cannot call another rule. Branching by subject matter needs more rules, not nested ones.
one process State — counters, cooldowns, cache — lives in memory. Restarting the router resets it, and there is no clustering.
estimated context Prompt size is estimated from characters per token, a number you supply. It is an assumption, not a tokenizer.
no auth beyond keys Virtual keys separate clients and limit what they may ask for. There is no user database, no quota accounting per person.
compression is not memory It shortens what is sent. It cannot bring anything back later — that needs a tool the model calls, which lives in the agent, not the router.

junction · version 0.1 · C99 and POSIX · built and tested on Debian with gcc and clang

Free software under the MIT licence. Written to be read: roughly 5,200 lines of C across twelve files, plus 1,200 lines of test scripts.