junction
A policy router for OpenAI-compatible model endpoints. It sits in front of N model servers and decides per request which one answers — and what happens when none of them wants to.
You run more than one model server: 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.
# a request arrives, junction answers client POST /v1/chat/completions model: deepseek-v4.1-flash rule for "deepseek-v4.1-flash*" pass ds41flash line 566 pool ds41flash → opencode-go0, go1, go2 round-robin sent opencode-go1 one attempt, 2.2 s client 200, answer + X-Junction-Endpoint: opencode-go1
Everything in that block was measured on a running instance, not composed for this page.
What it is
junction reads one text file of rules and picks a target per request. It tries the next one when the first fails, keeps streams intact, and says in the response headers and in /status exactly what it did.
The rule language is deliberately close to pf.conf: first match wins, an unknown keyword is 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.
Written in C99 and POSIX, about 15,200 lines of C in 30 files. OpenSSL is the only optional dependency and only needed for TLS. No runtime, no config daemon, no database.
A rule, and its neighbours
# listen 0.0.0.0:8443 tls /etc/junction/tls/cert.pem /etc/junction/tls/key.pem listen 0.0.0.0:8090 endpoint workstation { base http://192.0.2.20:8080/v1 context 128000 timeout 1800 idle_timeout 30 hook /usr/local/share/junction/hooks/check-http.sh wake /usr/local/share/junction/hooks/wake-wol.sh } endpoint cloud { base https://api.example.com/v1 context 200000 api_key_env EXAMPLE_API_KEY # repeatable: a key pool } pool ds41flash opencode-go/deepseek-v4.1-flash#max, ollama0/deepseek-v4.1-flash#max # rules — first match wins req need >64000 pass workstation, cloud req for "*coder*" retry 300 pass workstation as "Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M" req path "/v1/models" check none pass peer1 req for "blocked-*" block req for "*" pass peer1, cloud
Every clause is optional except the final pass or block. Match on model glob, path glob, the output budget the client declared, and whether the request carries an image.
| clause | meaning |
|---|---|
| req for <glob> | Model glob, matched with fnmatch against the model in the request body. |
| req path <glob> | Path glob. /v1/models usually wants a different target than the chat path. |
| need >N | <N | N | The output budget the client declared as max_tokens. junction does not count characters and does not invent a default; a request that declares nothing never matches a need rule. |
| retry <s> | Override hook_retry for this rule — how long to wait for a box to boot. |
| review N | N hidden self-review rounds after the first answer. |
| judge every N <target> | Escalate every Nth call of a conversation to a stronger judge. |
| check hooks | none | Run the endpoint's hooks for this rule, or skip them. |
| pass a, b [as M] | Try a, then b on failure. as rewrites the model name for that target only. |
| block | Refuse with 403. |
How a request is decided
A client asks for model chat with roughly 3,000 prompt tokens and a declared output budget of 4,096. 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 need >64000 pass workstation, cloud no match — 4,096 is below 64,000 req for "*" pass workstation, cloud match
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 is tried within the same request. Every response says which target answered:
X-Junction-Endpoint: opencode-go1 X-Junction-Ms: 2186 X-Junction-Cache: off X-Junction-Tokens-In: 37 X-Junction-Tokens-Out: 13 X-Junction-Cost-Usd: 0.000027
Those six header lines and their values are copied from a real response of a local instance.
When something fails
- Unreachable is offline, immediately
- A connect failure is not a retry case. The endpoint is benched for
offline_hold_sand the chain moves on, so a machine that is off does not cost every request a timeout. - Two timeouts, not one
timeoutis the total wall clock;idle_timeoutis silence. A thinking model is not a hang, and a stream that has stopped producing gets a keep-alive comment rather than a severed connection.- A second attempt before failover
429,408and5xxare retried on the same endpoint, because such a state usually clears in seconds while the next link may cost money. Connect failures are explicitly not retried, and a stream that has already started is never repeated.- The provider knows better
- A
Retry-After— seconds or an HTTP date — wins over the configured backoff, capped byretry_max_wait. An hour of waiting is not a retry, it is an outage with an announcement. - Key pools
- Repeating
api_key_envmakes a pool. Each attempt takes the next key, so two accounts are two quotas: a429on A is answered by B, and only when every key failed is the endpoint down. - The queue, not a refusal
max_inflightupstream requests at a time, the rest wait in line. A waiting streaming caller is told why it waits, as an SSE comment that every conformant parser ignores and a human watchingcurlsees.
Judge and review
Two mechanisms that spend extra calls on purpose, both declared in the rule.
Self-review — the worker checks itself
req for "qwen3.6-35b-checked" balance round-robin check none \
review 2 \
pass qwen3.6-35b as "/models/unsloth/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q8_K_XL.gguf"
The worker answers first. junction then appends that answer plus a fixed review instruction to the same conversation and sends it back to the same endpoint. That happens N times; only the last answer is written to the client. The intermediate answers and the review text never reach it.
Two details matter in practice. An answer carrying tool_calls is passed through unreviewed, because reviewing a tool call as text would be a different request than the one the client must execute. And if a round returns the answer verbatim, the answer is stable: the remaining rounds are skipped and the log says converged=1, so a reviewer that would keep rewriting a correct answer does not get the chance.
Depth is a per-request decision as well as a rule: X-Junction-Review-Rounds: 7 or X-Junction-Effort: medium asks for a different depth for one call, and X-Junction-Review-Rounds: 0 turns it off.
Sampled judge — a virtual model that escalates
req for "qwen3.6-35b-judged" balance round-robin check none \
judge every 5 ds41flash cache off \
judge every 10 claude-openai0 as "claude-opus-5-5" cache 1h \
pass qwen3.6-35b as "..."
The 5th call of a conversation goes to the ds41flash pool, the 10th to Claude Opus, then the counter resets. The judge gets the whole body, including every previous assistant message, so it can see what the worker did and correct it. A rule with a judge becomes a virtual model in /v1/models: the client asks for the virtual name, the worker does the turns.
If the judge fails, the same request is offered to the rule's normal targets, so a rate-limited judge still leaves the worker serving the turn. Every response of a judged rule also announces the next judge in X-Junction-Judge-Next and -In, so a client can see one coming.
The counter table lives in RAM: 4096 conversations, least-recently-used eviction, one hour of idle expiry. The rule's identity is its model and path globs, not its line number, so inserting a comment above it keeps the counters. These resets change when a judge runs, never whether an answer is correct.
Skipping is named, never silent
Review passes an answer through untouched when it cannot review it. The reason is always reported (X-Junction-Review-Skipped, the log, or the final SSE junction object):
| reason | when |
|---|---|
| n>1 | The client asked for several choices; they cannot be reviewed as one answer. |
| tool_calls | The answer carries a non-empty tool_calls array. |
| content_array | The answer's content is an array of parts. |
| no_text | No string content — typically a model that spent its whole budget in reasoning. |
| budget | The key's monthly budget is spent before the next round. |
| error | A review round failed; the last good answer is delivered. |
| protocol | Not an OpenAI chat path, or an endpoint kind that review does not support. |
MCP gateway
junction can also serve MCP. Every MCP server in the configuration is reached through it, so an agent connects once and sees every tool instead of subscribing to each server separately.
mcp tasksd url http://127.0.0.1:8781/mcp mcp skilld url http://127.0.0.1:8790/mcp header "Authorization: Bearer ..." timeout 20 mcp local cmd "python3 /srv/mcp/filesystem.py --root /data" mcp_cache_ttl 60
Names are prefixed with the server name — tasksd__task_create, tasksd__memory://tasks — because two servers may well publish a tool of the same name. The call methods split the prefix off again, so the server sees exactly the name it published.
Two transports: an HTTP endpoint, or a command that junction starts itself and speaks to over stdin/stdout. A stdio server is started on first use and stays alive between calls, because it keeps session state and a fresh process per call would be a different server every time.
Both kinds fail the same honest way: a server that is down or silent is skipped with a log line and the other servers' tools still arrive. Nothing is invented to fill the gap.
Who may call it
/mcp is not a model path. Through it an agent creates tasks, rewrites skills and stores memories — it writes, it does not merely route. So the default is mcp_auth auto: from loopback no key is needed, from any other address the caller must present a virtual key that junction itself minted. Without one the answer is 401 with WWW-Authenticate: Bearer, so a client can tell “no key” from “junction is down”.
Keys, budgets and the ledger
A virtual key is a token junction minted itself. The client sends it; the real upstream key never leaves the process, and the key can be pinned to a model glob and a set of endpoints.
vkey "webui" token_env VKEY_WEBUI allow "deepseek-*" endpoints "cloud,ollama1" vkey "navigator" token_env VKEY_NAVIGATOR allow "deepseek-*" rpm 30 budget 5
| field | meaning |
|---|---|
| allow | Model glob; "*" = any. Both this and the global models allow must agree. |
| endpoints | Comma list of endpoint names; omitted = any. |
| rpm | Requests per minute. Over it: 429 with Retry-After. |
| budget | Spend cap in USD per calendar month. Over it: 403 vkey_budget_exhausted. |
Spend is recomputed from the ledger at startup, so a budget is not full again after every restart — the one thing a budget must not be. And junction is honest about the boundary: a vkey is accounting, not a door. A caller that sends no key is routed as before. A limit only binds callers who were given a key.
The request log
spend_log is not only a ledger: every served request leaves one JSON line, and that line is the only place where a single request is complete.
{"ts":1795193823,"model":"deepseek-v4.1-flash","endpoint":"opencode-go1",
"status":200,"latency_ms":2523,"rule_line":533,"cache":"miss","retries":0,
"tokens_in":37,"tokens_out":13,"cost_usd":0.000027}
No exporter, no collector, no agent — the file is the interface, and /spend reads the same file so the ledger and the dashboard can never disagree. A streamed answer cannot be billed after the fact, so it gets zeros rather than a guess.
Operation
| method | path | effect |
|---|---|---|
| GET | /status | Endpoints, counters, cache, queue, rules as JSON. Also served as /v1/status, /queue, /v1/queue. |
| GET | /metrics | The same numbers in Prometheus text format, including per-endpoint latency histograms. |
| GET | /spend[?month=YYYY-MM] | Cost of that month from the ledger, per key and per model. |
| POST | /admin/pause/<name> | Stop routing there. |
| POST | /admin/resume/<name> | Clear pause, cooldown and offline. |
| POST | /admin/flush/cache | Drop every cached response. |
The latency histogram is a deliberate choice over an average: an endpoint answering 95 % fast and 5 % of the time in a minute keeps a harmless mean, and an average hides exactly the requests that hurt.
Is the endpoint really there?
A background thread asks every endpoint for its model list. No answer means offline for offline_hold_s; a recovered endpoint is back before any request had to pay for the discovery. /status carries probe_ok and probe_age_s, so “the router thinks it is down” and “the router has not looked yet” are distinguishable.
Several instances, one port, one cache
so_reuseport lets several instances bind the same address and the kernel distributes connections. On SIGTERM an instance closes its listening socket first, finishes what it is already serving, and only then exits — so a rolling update has no window where nothing answers. A shared cache lets a node that misses locally ask its peers before it pays the provider; peers are a shortcut, never a dependency, and if every peer is dead the request goes to the provider as if the mesh did not exist.
Build
make # -> ./junction, TLS auto-detected via openssl headers make J_WITH_TLS=0 # dependency-free build: http:// upstreams only make test # stub endpoints, no network, no models sudo make install # /usr/local/bin + /usr/local/share/junction ./junction --config junction.conf --check # parse, report, bind nothing ./junction --config junction.conf curl -s localhost:8090/status
--check loads the file through the same parser and prints one line — “run it through the parser once before the restart” is a command, not a thing to remember. The flags are -std=c99 -Wall -Wextra -Wpedantic -Wshadow -Wconversion.
Configuration comes from the environment too: an OPENCODE_GO_API_KEY, OLLAMA_KEY or ANTHROPIC_API_KEY in the environment is an endpoint. No block needs to be written for it, and what the file already defines wins.
Known limits, deliberately named
- HTTP/1.1 only — no HTTP/2, no h2c.
- The cache is memory-only and lost on restart. Across instances it is shared by peers, but without coherence: the only invalidation is the TTL.
- junction does not tokenise. It sees only the numbers the client writes, so a request that declares no budget is routed by its model and path alone.
- No prioritisation in the queue beyond first come, first served.
- The judge counter table is in RAM, reset on restart; that changes when a judge runs, never whether an answer is correct.
- TLS client verification uses the system store or a per-endpoint CA. There is no certificate pinning and no client-certificate auth.