# ============================================================================
# junction — full reference configuration
# ============================================================================
#
# This file contains EVERY key the parser knows, each with an explanation and a
# sensible value. It is meant to be copied from: for production, delete the
# endpoints you do not need, not the explanations.
#
# Grammar: keyword, arguments, braces. `#` starts a comment, double quotes group
# words. An unknown keyword is a hard error with a line number — there are no
# silent typos.
#
# Check without starting: junction --config this-file --check
# ============================================================================
# ---------------------------------------------------------------- listener
#
# Where junction listens. Plain HTTP without `tls`. With `tls`, two certificate
# paths in this order: certificate, key.
#
# Loopback is the right choice when the process holds real upstream keys in its
# environment — then it is not an open proxy for LAN or VPN.
listen 127.0.0.1:8090
# listen 0.0.0.0:8443 tls /etc/junction/tls/cert.pem /etc/junction/tls/key.pem
# Prefix of every log line. It lives here so no product name appears in the code.
log_prefix junction
# ---------------------------------------------------------------- time limits
#
# Connecting to the endpoint. A failure here means "offline" immediately — that is
# not a retry case, a machine that does not answer does not get better by asking
# twice.
connect_timeout_ms 1500
# How long an endpoint counts as offline after a connect failure, before the next
# attempt probes it again. Seconds.
offline_hold_s 20
# Upper bound for a request body. Protection against a client using the router as
# storage.
max_body_bytes 67108864
# ---------------------------------------------------------------- concurrency
#
# How many requests may be on their way to upstreams at the same time. The rest
# wait in line instead of being refused.
max_inflight 8
# How long a waiting request may stand in line before it gets an answer. Seconds.
# Afterwards: an error event, followed by [DONE] for streamers.
queue_timeout 300
# A second attempt before the chain moves on. 429/408/5xx are often over in
# seconds; the next link costs money or context instead. Connect failures are NOT
# retried (those mean offline, that is what the hooks are for), and nothing is
# retried after the streaming head has gone out. Retry-After is not evaluated.
retry_num 1
retry_backoff 0.5
# If the provider names a Retry-After (seconds or the RFC 7231 HTTP date), that wins over
# the backoff — it knows when its quota reopens. The ceiling keeps a "come back in an
# hour" from turning a retry into an outage: 0 means no ceiling. A date in the past means
# now; anything unparseable counts as silence.
retry_max_wait 30
# Whole chain offline? A request may wait this long instead of getting a 503 at
# once. In the van the uplink is often gone for seconds. Deliberately before the
# queue slot: a request that waits holds no upstream place. 0 = do not wait.
offline_wait 20
# ---------------------------------------------------------------- monitoring
#
# A second listener that answers GET /metrics and nothing else. Prometheus runs in
# a container here and cannot reach the host's loopback; instead of putting /v1 and
# /admin on the network, there is exactly this one read-only port.
metrics tcp 192.168.1.148:9180
# ---------------------------------------------------------------- providers from env
#
# A key in the environment is an endpoint, so that a host with three provider keys needs
# no endpoint block at all:
#
# OPENCODE_GO_API_KEY[1..8] -> opencode-go, opencode-go1 … (OPENCODE_GO_BASE)
# OLLAMA_KEY[1..8] -> ollama, ollama1 … (OLLAMA_BASE)
# ANTHROPIC_API_KEY | CLAUDE_API_KEY [1..8]
# -> claude, claude1 … (CLAUDE_BASE)
#
# The file always wins: an endpoint with the same name is not touched. No `context` is
# invented — limits belong to the models and come from their own list. The base override
# exists for a local proxy and for tests.
auto_endpoints on
# ---------------------------------------------------------------- liveness
#
# A background thread asks every endpoint for its model list (GET /models). No TCP
# connection means offline for offline_hold_s; the next round asks again, so a returning
# endpoint is back before any request had to pay for the discovery. A slow answer is not
# offline: only a missing connection counts. `probe off` in an endpoint block keeps that
# endpoint out of the checks (a box that sleeps on purpose).
probe_interval 20
probe_timeout 3
# ---------------------------------------------------------------- one request per model
#
# max_model_inflight 1 means: one request at a time per MODEL on this endpoint. The next
# one waits instead of pushing a box that holds the model in memory into swap. Different
# models are different slots — four models are four parallel requests. The limit is per
# (endpoint, model), so a pool of four boxes gives four slots.
#
# endpoint box {
# base http://172.25.206.3:8080/v1
# timeout 600
# max_model_inflight 1
# }
#
# `strip` takes a prefix off the model before the request leaves the router: a client asks
# for local/qwen3.6-35b, the box receives qwen3.6-35b. It must stand before `pass`,
# because `pass` ends the line.
#
# req for "local/*" strip "local/" pass box
# ---------------------------------------------------------------- cluster
#
# Several instances on one port and one cache shared between them — no Redis, no
# etcd, no proxy in front. Both halves are optional and independent.
#
# so_reuseport: the kernel distributes the connections over the instances that bound
# the same address. A new instance takes traffic while the old one still serves.
#
# drain_timeout: on SIGTERM the listening socket is closed first, the running requests
# are finished, then the process exits. A request still running after this many seconds
# is abandoned (logged as drain_timeout) — an update must not hang on an upstream.
# mcp_auth auto|all|off
# /mcp is not a model path: through it an agent writes tasks, skills, memories and wiki
# pages. "auto" (the default) lets the local machine in without a key and demands a vkey
# from any other address. "all" demands one everywhere (useful to prove the check works),
# "off" disables it — do not pair "off" with a listen address the whole network reaches.
mcp_auth auto
so_reuseport on
drain_timeout 15
# The cache peer port of THIS instance. It answers three paths and nothing else:
# GET /cache/<16 hex> a cached response (head and body, framed)
# PUT /cache/<16 hex> store one (pushed by another instance)
# GET /cache/stats its own counters
# Without cache_secret_env this port does not open at all: an unprotected peer port on
# a LAN is a way to read responses you never paid for, and to fill someone's memory.
cache tcp 127.0.0.1:8170
cache_secret_env JUNCTION_CACHE_KEY
# The other instances, asked on a local miss and pushed to on a fill. Repeated line per
# peer. cache_peer_timeout_ms is the entire cost of a peer that accepts and then says
# nothing; 150 ms is a LAN round trip with room to spare.
cache_peer 127.0.0.1:8171
cache_peer_timeout_ms 150
# ---------------------------------------------------------------- guard
#
# A command that sees every request before it is routed: exit 0 = let it through,
# anything else = 403 with stdout as the reason. junction brings no content rule of
# its own. The body arrives as a file (JUNCTION_BODY_FILE), not on stdin — a script
# that reads only part of it would otherwise hang writing into a full pipe.
#
# Only the request is inspected. Inspecting the answer would mean buffering every
# stream — exactly what this router does not do.
#
# guard request cmd "/home/lotherk/.hermes/scripts/guard.sh"
# ---------------------------------------------------------------- response cache
#
# Memory only, LRU, key is method + path + model + body. Streams are never cached.
# The upstream's `Cache-Control: no-store/private` and the client's `no-cache` are
# respected.
#
# 0 means: cache off. A cache on a router that serves models at different
# temperatures is usually wrong — hence off here.
cache_ttl 0
cache_entries 0
cache_bytes 0
# Only cache requests whose answer is predictable: temperature 0, or an embedder
# (the same text always gives the same vector). Caching an answer with temperature
# 0.7 would hand the second caller someone else's answer — that is not a saving,
# it is a wrong answer.
cache_deterministic_only on
# ---------------------------------------------------------------- prompt size
#
# Characters per token for the estimate that `ctx` rules use. 0 (default) means: no
# estimate, and a rule with a ctx condition is refused at load time — an error beats
# a rule that silently never matches.
#
# The value is an assumption about tokenisation, not a measurement. Base64 image
# data is skipped when counting, otherwise a photo counts as a hundred thousand
# tokens.
ctx_chars_per_token 4
# ---------------------------------------------------------------- selection order
#
# How targets INSIDE one rule are ordered when several are named:
# first in the order of the rule (plain failover)
# round-robin in turns, evenly
# least-usage smallest own consumption first (percent of budget)
# cost consumption × price; in the off-peak window the price halves
balance cost
# ---------------------------------------------------------------- virtual keys
#
# Clients get these keys, never the real upstream key. The value lives in an
# environment file (0600 root); here stands only the name of the variable.
#
# vkey "name" token_env VAR allow "" [endpoints "a,b"] [rpm N] [budget USD]
#
# `allow` limits the models, `endpoints` additionally the targets. A key that may
# only use DeepSeek cannot trigger a GPT call, even if a rule would allow it.
#
# rpm and budget limit the consumption of ONE client (not the provider's): above rpm
# junction answers 429 with Retry-After, above budget 403. The budget is per calendar
# month and is recomputed from the spend log at startup — without that it would be
# full again after every restart.
vkey "webui" token_env VKEY_WEBUI allow "deepseek-*" rpm 60 budget 10
vkey "navigator" token_env VKEY_NAVIGATOR allow "*" endpoints "ollama1,ollama2" rpm 30 budget 5
vkey "hermes" token_env VKEY_HERMES allow "*"
# One JSON line per served request — the ledger and the request log in the same file.
# Without it there is no monthly figure, no budget that survives a restart, and no way
# to answer "why was that request slow" without grepping five journald lines.
#
# ts, vkey, model, endpoint, status, latency_ms, upstream_ms, queue_ms, rule_line,
# cache (off|miss|hit|peer|joined), retries, tokens_in/out/cached, cost_usd
#
# A cache hit writes zeros for tokens and cost, not estimates; a streamed answer writes a
# line as well (zeros are honest, a guess is not). Failed attempts are not in here —
# they are in journald and in /metrics.
spend_log /var/lib/junction/spend.jsonl
# ============================================================================
# Endpoints
# ============================================================================
# ---------------------------------------------------------------- subscription opencode-go
#
# The most expensive path per request, but already paid for: the marginal cost is
# nearly zero. `cost` here is a comparison weight, not a sum of money.
endpoint opencode-go {
base https://opencode.ai/zen/go/v1
kind opencode-go
context 200000
# Lower number wins when a rule names several targets without an order of its
# own. Only relevant with balance first.
priority 90
# Total time for one request and the silence until "still_working" appears in
# the log. Two values, because a thinking model is not hanging.
timeout 900
idle_timeout 120
# Its own connect limit: this target sits behind a tunnel, a failed connect
# should pass the chain on after 400 ms, not after 1.5 s.
connect_timeout_ms 400
tls_verify on
api_key_env OPENCODE_GO_API_KEY
# Some upstreams behind Cloudflare refuse foreign user agents (403/1010) and
# want a session id. header may be repeated.
header "User-Agent: Mozilla/5.0 (X11; Linux x86_64) Olivia-UI/1.0"
header "x-opencode-session: ses-olivia-webui"
# Measure consumption from outside: the script prints one number, junction
# polls it.
usage_cmd /home/lotherk/.hermes/scripts/junction_usage_opencode.sh
usage_poll 120
# Soft and hard limit in percent. Above soft the request is slowed, above hard
# the endpoint is skipped — but only when a rule names another target.
budget soft 85
budget hard 96
on_soft delay 2
on_hard skip
cost 0.1
cache off
}
# ---------------------------------------------------------------- credit opencode-go, two accounts
#
# Two accounts of the same provider, each with its own monthly credit. Both
# endpoints look alike; they differ only in key, usage measurement and priority.
# Weight: higher = more often. Under round-robin a target with weight 3 gets three
# slots in the round; under cost/least-usage its consumption counts one third.
endpoint ollama1 {
weight 3
base https://ollama.com/v1
kind opencode-go
context 128000
priority 50
timeout 900
idle_timeout 120
tls_verify on
api_key_env OLLAMA_KEY1
usage_cmd "/home/lotherk/.hermes/scripts/junction_usage_ollama.sh 1"
usage_poll 180
budget soft 80
budget hard 95
on_soft delay 1
on_hard skip
# Window in which this endpoint is cheaper: from 18:00 to 12:00 of the following
# day. One window, not two — "all weekend" cannot be expressed with it.
offpeak 18:00-12:00
cost 1.5
}
endpoint ollama2 {
base https://ollama.com/v1
kind opencode-go
# Two accounts as two endpoints: that keeps the quota per account visible
# (usage_cmd 1 vs. 2). As one endpoint with two api_key_env lines junction would
# rotate to the second account on a 429, but usage_cmd and /api/show would only
# run with the first key — the second account's quota would stay invisible.
context 128000
priority 50
timeout 900
idle_timeout 120
tls_verify on
api_key_env OLLAMA_KEY2
usage_cmd "/home/lotherk/.hermes/scripts/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
}
# ---------------------------------------------------------------- local machine with wake-up
#
# The interesting case: a workstation that sleeps. `wake` runs once before the hooks
# are repeated — wake first, then wait.
endpoint workstation {
base http://192.0.2.20:8080/v1
kind local
context 128000
priority 10
timeout 1800
idle_timeout 30
# Hook: exit 0 means usable, anything else "not yet". The reason the hook prints
# on stdout lands in /status and in the 503 body.
hook /usr/local/share/junction/hooks/check-http.sh
# How long to wait for the machine in total, and at what interval.
hook_retry 180
hook_backoff 5
# One wake-up call before the first repeat.
wake /usr/local/share/junction/hooks/wake-wol.sh
# Static header addition per endpoint.
header "X-Box: workstation"
# Can this endpoint read images? on = yes, off = no, omit = no check.
# A text endpoint is skipped for an image request instead of accepting it and
# answering with empty content.
vision off
# A local machine costs electricity, not money. Small weight so it wins the
# comparison while it is awake.
cost 0.0
cache on
tls_verify off
}
# ---------------------------------------------------------------- private TLS with its own 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 does not speak the OpenAI protocol: its API is session-oriented
# (/api/session, /prompt, /model, /message). With `kind opencode` junction translates
# in both directions, so a client keeps speaking /v1/chat/completions.
#
# Two values come from commands because opencode does not pin them: the background
# service binds a free port, and it creates a new password on every start.
endpoint opencode {
base http://127.0.0.1:4096
kind opencode
context 200000
timeout 600
idle_timeout 120
auth_basic opencode
pass_cmd /home/lotherk/.hermes/scripts/opencode_password.sh
# Only needed when the service runs on a random port:
# base_cmd "/home/lotherk/.opencode/bin/opencode service status"
cost 0.0
}
# ---------------------------------------------------------------- embedder, small and cheap
endpoint embed {
base http://192.168.1.116:11434/v1
kind local
context 8192
priority 10
timeout 120
idle_timeout 45
# After a failure, pause this many seconds instead of running into a timeout
# again on every request.
cooldown 30
cache on
}
# ============================================================================
# Rules — first match wins
# ============================================================================
#
# req [for ] [path ] [need >N | ]
# ( pass [,...] [as ] | block )
#
# for — model name from the request body, fnmatch pattern
# path — path, fnmatch pattern
# need — the output budget the client DECLARES (max_tokens /
# max_completion_tokens). No guessing, no character counting: a request
# that states nothing matches no need rule. >64000 means "more than 64k
# requested"; an endpoint with a smaller context is then skipped.
# check — hooks (the endpoint's default) or none (skip hooks, e.g. for model
# lists that make sense even when nothing is running)
# retry — wait time for hooks, overrides this rule's hook_retry
# as — rewrites the model field ONLY for that target. The first target gets the
# local id, the last the requested one.
# Model list: no hook needed, a sleeping machine answers it too.
req path "/v1/models" check none pass opencode-go
# Embedders run locally, no matter what else applies.
req for "*embed*" check none pass embed
# The free opencode models go to the opencode endpoint, nothing else does.
req for "opencode/*" pass opencode
req for "*-free" pass opencode
# Image requests: always to the image model, independent of the requested name.
# First the own machine (costs nothing), then the opencode-go — there with a rewritten
# model name. "as" applies to the target directly before it, not to the whole rule.
req vision pass workstation, opencode-go as "vision-capable-model"
# Small requests to the own machine, medium ones to the credit account, large ones to
# the subscription with the big context. Order matters: narrowest window first,
# otherwise the larger one catches everything. The numbers are policy and belong
# here, not in the code.
req ctx <2000 pass workstation
req ctx <50000 pass ollama1, opencode-go
req ctx >50000 pass opencode-go
# Large budgets cannot be held by the local machine — so do not send them there.
req need >64000 pass opencode-go, ollama1
# A model that only exists locally, with a local name; otherwise the same request is
# passed on to the opencode-go.
req for "*coder*" retry 300 pass workstation as "qwen3.8-flash-next-q1m", opencode-go
# A model that must not exist. 403, not a silent redirect.
req for "blocked-*" block
# Everything else: first the awake local machine, then the opencode-go, then credits.
# No match for a request means 503 no_matching_rule — a gap in the configuration is
# not a case for "send it somewhere".
# Give chains a name. A pool may point at another pool; it is resolved at load time,
# so a rule does not have to spell out five targets every time.
pool lokal ollama1, ollama2
pool alles opencode-go, lokal
# An endpoint may also fit on one line when it is small:
# endpoint kurz { base http://127.0.0.1:8080/v1; timeout 60 }
# This one rule wants plain failover, whatever the global setting is.
req for "starr*" balance first pass workstation, opencode-go
req for "*" check hooks pass workstation, opencode-go, ollama1, ollama2
# ============================================================================
# Control at runtime
# ============================================================================
#
# GET /status endpoints, counters, cache, rules, queue
# GET /metrics the same numbers as Prometheus text
# GET /spend[?month=YYYY-MM] cost per key and model, from the spend log
# POST /admin/pause/ stop routing there
# POST /admin/resume/ clear pause, cooldown and offline
# POST /admin/flush/cache drop every cached response body
#
# Everything else is forwarded to the endpoint the rules choose.
# Every response carries X-Junction-Endpoint, X-Junction-Ms and X-Junction-Cache.