An Anthropic OAuth token (sk-ant-oat01…, e.g. CLAUDE_CODE_OAUTH_TOKEN) is not an API key. Sent with an ordinary body, a current model answers 429 rate_limit_error "Error" — the same status and shape as an exhausted quota, so the endpoint looks broken at random instead of misconfigured. `oauth on` per endpoint puts Claude Code's system prompt in place, and only for endpoints that ask for it. The client's own system prompt is kept: on /v1/messages as further blocks after the marker (cache_control intact), on /v1/chat/completions as its own user message before the first turn — there the system content must be the marker alone. Measured against api.anthropic.com, each case repeated: body /v1/messages /v1/chat/completions no system 429 429 system = <marker> 200 200 system = [<marker>, <text>] 200 429 system = [<text>, <marker>] 429 429 The gating is model-dependent: retired names such as claude-haiku-4-5-20251001 answer without the marker and prove nothing. claude-sonnet-5-5, claude-haiku-5-5, claude-opus-5 and claude-opus-4-8 are gated. The marker matches byte for byte — a missing final period or a trailing newline is worth the same as no marker at all. Verified: full suite PASS, 574 OK, 0 failures. Against the live API through junction with a real subscription token: 200 on claude-sonnet-5-5 for /v1/messages (client system prompt applied, answer "Paris") and for /v1/chat/completions; streaming with a tool call works; the same request with `oauth off` still gets 429 upstream, which is the counter-proof that the option is what changes the outcome. Token B in ~/toktok is dead independently of this (403 oauth_not_allowed_for_organization). The stub's new STUB_BODY_FILE writes request bodies verbatim; a structural check (is the marker the first block) cannot be done from a header.
1151 lines
61 KiB
Markdown
1151 lines
61 KiB
Markdown
# junction
|
||
|
||
A policy router for OpenAI-compatible model endpoints. **C99 + POSIX**, plus
|
||
OpenSSL when built with TLS. No branding in the code: the only name in the sources
|
||
is `junction` (even the log prefix is a config keyword), so a product name can be
|
||
layered on later without touching logic.
|
||
|
||
`junction` sits in front of N model servers and decides **per request** which one
|
||
serves it — and what to do when none of them wants to.
|
||
|
||
Code: https://git.kropa.tech/hiddenbox/junction
|
||
|
||
## What it does
|
||
|
||
- **Ordered rules, like a firewall.** `req ... pass ...` / `block`, first match wins.
|
||
Match on model glob, path glob and required context.
|
||
- **Shell pre-hooks per endpoint.** A hook that exits non-zero means "not available
|
||
yet" — retried with backoff for a bounded time, optionally after a wake command.
|
||
- **Unreachable means offline, immediately.** A connect failure is not a retry case.
|
||
- **Honest timeouts.** Two per endpoint: *idle* ("nothing for N seconds", logged as
|
||
`still_working`) and *total*. A thinking model never looks like a hang.
|
||
- **Context-aware, without guessing.** `need` reads `max_tokens` / `max_completion_tokens`
|
||
from the request and nothing else — no character counting, no assumed default. An
|
||
endpoint whose `context` is smaller than a *declared* budget is skipped; a request
|
||
that declares nothing is passed through unsized.
|
||
- **Failover with cooldown**, and a `503` that names why each endpoint was skipped.
|
||
- **A second attempt before failover.** `429`, `408` and `5xx` are retried on the *same*
|
||
endpoint (`retry_num`, `retry_backoff`), because such a state usually clears in
|
||
seconds while the next link in the chain costs money or context. Connect failures are
|
||
explicitly not retried — "unreachable" is offline, and waiting for that is the hooks'
|
||
job. A stream that has already started is never repeated.
|
||
- **Key pools per endpoint.** `api_key_env` may stand several times; each attempt takes
|
||
the next key, so a `429` on one account is answered by trying the next one instead of
|
||
giving up the endpoint. `/status` and `/metrics` show the pool size as `keys`.
|
||
- **Prometheus `/metrics`.** The same numbers as `/status`, in the text format a scraper
|
||
reads — `junction_endpoint_up{endpoint="…"}` is 1 unless the endpoint is paused,
|
||
offline, cooling down or over its hard budget.
|
||
- **Concurrency with a queue.** One thread per connection, `max_inflight` upstream
|
||
requests at a time, the rest wait in line instead of being refused. A waiting
|
||
*streaming* caller is told why it waits — as SSE comments (`: junction: waiting for
|
||
a free slot (2 ahead of you)`), which every conformant parser ignores and a human
|
||
watching `curl` sees. The same heartbeat keeps a *thinking* model's stream alive —
|
||
every 10 s of upstream silence produces `: junction: model is still working (12s)`,
|
||
so a proxy with a 60 s read timeout does not kill a stream that is perfectly alive.
|
||
As soon as real data arrives the comments stop; nothing is buffered, nothing is
|
||
rewritten. A non-streaming caller gets nothing injected at all and keeps its real
|
||
status code.
|
||
|
||
This is bounded, not endless: `queue_timeout` caps the wait for a slot, `timeout`
|
||
caps the upstream request, and when either expires a streamer receives an error
|
||
event plus `data: [DONE]`. If the client vanishes, the next comment write fails and
|
||
the router stops waiting for a model nobody is listening to.
|
||
- **TLS both ways.** `https://` upstreams (SNI, optional chain + hostname
|
||
verification, custom CA) and an optional TLS listener — no stunnel needed.
|
||
- **Chunked transfer coding.** Chunked request bodies are decoded; chunked responses
|
||
are relayed byte for byte, so streaming (`text/event-stream`) survives untouched.
|
||
- **Response cache.** Memory-only LRU keyed on method + path + model + body, honouring
|
||
`Cache-Control: no-store/private`, bypassed by the client's `no-cache`, flushed
|
||
with one call. Streams are never cached.
|
||
- **Header passthrough.** Client headers are forwarded (hop-by-hop removed), static
|
||
headers can be added per endpoint, and `X-Forwarded-For`/`Proto` are appended.
|
||
Every response carries `X-Junction-Endpoint`, `X-Junction-Ms`, `X-Junction-Cache`.
|
||
A sampled judge adds `X-Junction-Judge`, `X-Junction-Judge-Step`,
|
||
`X-Junction-Judge-Every`, `X-Junction-Judge-Model`, `X-Junction-Judge-Served`,
|
||
and on every turn of a judged rule `X-Junction-Judge-Next/-In` plus the
|
||
`X-Junction-Judge-Next-*` fields naming the next judge.
|
||
A self-review adds `X-Junction-Review`, `X-Junction-Review-Rounds`,
|
||
`X-Junction-Review-Model`, `X-Junction-Review-Skipped`; when a review ran, a
|
||
non-streaming answer also carries `X-Junction-Review-Tokens-In/-Out` and
|
||
`X-Junction-Review-Cost-Usd` summed over all its calls. A streaming response
|
||
carries the planned judge/review in the head; a reviewed stream puts the actual
|
||
outcome and summed usage in a `junction` object in its final chunk.
|
||
|
||
A worked, annotated configuration for a mixed local/cloud setup is in
|
||
`examples/olivia.conf`; `config.example` is the same grammar, reduced to the bones.
|
||
|
||
## Build / run
|
||
|
||
```bash
|
||
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 (~2.5 min)
|
||
|
||
sudo make install # /usr/local/bin + /usr/local/share/junction
|
||
# systemd unit: packaging/junction.service — RuntimeDirectory=junction belongs in it,
|
||
# otherwise the unix control socket cannot be created after a reboot (/run is tmpfs).
|
||
./junction --config junction.conf [--port 8090]
|
||
./junction --config junction.conf --check # parse and report, bind nothing
|
||
curl -s localhost:8090/status
|
||
```
|
||
|
||
`make install` also drops the hand-written project page at
|
||
`/usr/local/share/junction/www/index.html` — one file, no build step, no external
|
||
request (no font, no script, no image). Serve that directory with whatever answers
|
||
port 80; junction itself is a router, not a web server, and does not serve it.
|
||
|
||
`--check` loads the file through the same parser and prints one line
|
||
(`config ok: N endpoints, N rules, N vkeys, listen host:port`), without binding a
|
||
port: "run it through the parser once before the restart" is a command, not a
|
||
thing to remember. `/status` is also served as `/v1/status`, `/queue` and
|
||
`/v1/queue`.
|
||
|
||
## Configuration — pf.conf style
|
||
|
||
Keyword, arguments, braces. `#` starts a comment at the beginning of a word;
|
||
inside a word it is data (`model#max`, `endpoint/model#max`). Double quotes group
|
||
words, unknown keywords are a **hard error with a line number**. Full example:
|
||
`config.example`.
|
||
|
||
```
|
||
# listen 0.0.0.0:8443 tls /etc/junction/tls/cert.pem /etc/junction/tls/key.pem
|
||
listen 0.0.0.0:8090
|
||
chars_per_token 4
|
||
default_max_tokens 4096
|
||
connect_timeout_ms 1500
|
||
offline_hold_s 20
|
||
cache_ttl 300
|
||
cache_entries 128
|
||
cache_bytes 33554432
|
||
|
||
endpoint peer1 {
|
||
base http://192.0.2.10:8081/v1
|
||
kind remote
|
||
context 64000
|
||
priority 20
|
||
timeout 600
|
||
idle_timeout 60
|
||
cooldown 120
|
||
hook /usr/local/share/junction/hooks/check-http.sh
|
||
}
|
||
|
||
endpoint workstation {
|
||
base http://192.0.2.20:8080/v1
|
||
context 128000
|
||
timeout 1800
|
||
idle_timeout 30
|
||
hook_retry 180
|
||
hook_backoff 5
|
||
wake /usr/local/share/junction/hooks/wake-wol.sh
|
||
hook /usr/local/share/junction/hooks/check-http.sh
|
||
header "X-Box: workstation"
|
||
}
|
||
|
||
endpoint cloud {
|
||
base https://api.example.com/v1
|
||
context 200000
|
||
timeout 900
|
||
idle_timeout 120
|
||
cache off
|
||
tls_verify on
|
||
api_key_env EXAMPLE_API_KEY
|
||
}
|
||
|
||
# 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
|
||
```
|
||
|
||
### Rule syntax
|
||
|
||
```
|
||
req [for <model-glob>] [path <glob>] [need >N | <N | N]
|
||
[check hooks|none] [retry <seconds>] [review N]
|
||
[judge every N <endpoint|pool> [as <model>] [cache 5m|1h|off]]...
|
||
( pass <endpoint>[,<endpoint>...] [as <model>] | block )
|
||
```
|
||
|
||
- `for` — model glob (`fnmatch`) against the model in the request body.
|
||
- `need` — the output budget the client declared (`max_tokens`/`max_completion_tokens`);
|
||
`>64000` matches a declared budget above 64k. A request without one never matches a
|
||
`need` rule: junction is a pass-through and does not invent sizes.
|
||
- `check hooks|none` — override the endpoint's hook list for this rule.
|
||
- `retry <s>` — override `hook_retry` ("wait up to N s for the box").
|
||
- `review N` — before `pass`: N hidden self-review rounds after the first answer.
|
||
Only the last answer reaches the client; tool-call answers pass through
|
||
unreviewed. See below.
|
||
- `pass a, b` — try `a`, then `b` on failure.
|
||
- `as <model>` — **after a target**, rewrite the `model` field for that target only:
|
||
`pass peer-a as "qwen3.8-flash-next-q1m", peer-b, cloud` sends the local id to the
|
||
peers and the requested id to the cloud.
|
||
- `block` — refuse with `403`.
|
||
- `judge every N <endpoint|pool> [as <model>] [cache 5m|1h|off]` — before `pass`:
|
||
at request N of a conversation that endpoint or pool gets the same body. The clause
|
||
may repeat; the counts are **cumulative inside one chain** and must be ascending.
|
||
After the last step the conversation counter starts again at 0. Example: `every 5
|
||
deepseek` then `every 10 claude` means the 5th call goes to DeepSeek, the 10th to
|
||
Claude, then the chain restarts and the 15th/20th are next. A pool member's own `as`
|
||
wins; a rule-level `as` is its fallback. The rule's normal targets stay as fallback,
|
||
so a rate-limited or offline judge still leaves the worker serving the turn. A judge
|
||
turn is never answered from junction's response cache. `cache 1h` adds an Anthropic
|
||
`cache_control` marker to the last message; the provider then caches tools, system
|
||
prompt and the conversation prefix up to that message. `5m` is cheaper to write,
|
||
`off` sends no marker. See below.
|
||
|
||
No matching rule → `503 no_matching_rule`: an unmatched request is a config gap, not
|
||
something to quietly send to a cloud.
|
||
|
||
### Sampled judge — a virtual model that escalates
|
||
|
||
A rule with an exact model name and a `judge` clause becomes a virtual model in
|
||
`/v1/models`. The client asks for the virtual name; the worker does the turns, and
|
||
the chain decides which requests go to which judge:
|
||
|
||
```
|
||
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 "/models/unsloth/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q8_K_XL.gguf"
|
||
```
|
||
|
||
The 5th call of a conversation goes to the `ds41flash` pool (DeepSeek), the 10th to
|
||
Claude Opus, then the counter resets: the 15th and 20th are next. The judge gets the
|
||
**whole** body, including every previous assistant message, so it can see what the
|
||
worker did and correct it. The count is per conversation and per rule, not global. A
|
||
conversation is identified by `x-junction-session`, `x-session-id`,
|
||
`x-conversation-id` or `x-opencode-session` if the client sends one; otherwise
|
||
junction hashes the first system and first user message, which do not change when a
|
||
turn is appended. Requests are counted, not user-visible turns: an agent turn with
|
||
three tool round-trips counts three times. Use a session header and a larger N when
|
||
that matters.
|
||
|
||
The counter table lives in RAM: 4096 conversations with least-recently-used
|
||
eviction, an hour of idle expiry, and a restart that starts every conversation at
|
||
zero. The rule's identity is its model/path globs, not its line number, so
|
||
inserting a comment or another rule above it keeps the counters with the rule.
|
||
These resets change *when* a judge runs, never whether an answer is correct.
|
||
|
||
`cache` writes an Anthropic-style `cache_control` marker on the last message.
|
||
Anthropic and gateways that translate the marker honour it. DeepSeek and other
|
||
OpenAI-compatible providers cache repeated prefixes automatically; there `cache off`
|
||
is right, and the marker would only be noise.
|
||
|
||
If the judge fails, the same request is offered to the rule's normal targets. The
|
||
fallback gets the original body, without the judge's cache marker. `/v1/models` lists
|
||
the virtual model with the smaller context of worker and judge, because the worker
|
||
still has to fit ordinary turns.
|
||
|
||
Every response of a rule with a judge announces the **next** judge, including worker
|
||
turns and the judge turn itself (meaning the one after it): `X-Junction-Judge-Next`
|
||
is the counter value at which it fires, `X-Junction-Judge-In` says how many calls
|
||
are left, and `X-Junction-Judge-Next-Target/-Model/-Step/-Every/-Cache` say which
|
||
judge it will be. Rules without a judge send none of these headers. A failed judge
|
||
still counts as its turn; the next headers then describe the next scheduled judge.
|
||
|
||
### Self-review — the worker checks itself
|
||
|
||
`review N` keeps the worker, but hides N review rounds before the answer is released:
|
||
|
||
```
|
||
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/model.
|
||
That happens N times; only the last answer is written to the client. The intermediate
|
||
answers and the review text never reach the client. The review calls are sequential on
|
||
the same endpoint and hold the same slot, so a local box sees its own prompt cache again.
|
||
|
||
- **Streaming:** the client gets SSE comments while the rounds run, then the final
|
||
answer as one final chunk plus `[DONE]`. Non-streaming waits and gets one JSON answer.
|
||
- **Tools:** an answer with `tool_calls` is passed through unreviewed; reviewing a tool
|
||
call as text would be a different request than the one the client must execute.
|
||
- **Failure:** if a review round fails, the last good answer is delivered and
|
||
`X-Junction-Review-Skipped` / the `junction` chunk names the reason. The first call
|
||
still uses the normal failover.
|
||
- **Cost:** `review 2` means three provider calls. They are visible in `/spend` and
|
||
count against the vkey budget.
|
||
- **Anchor:** every review round gets the user's request and the answer so far
|
||
again, with "keep the same question, scope and language" and "this is not a
|
||
spelling or style check" in the instruction. A long tool history otherwise
|
||
pulls the reviewer toward whatever the last tool returned instead of the
|
||
question.
|
||
- **Cache:** the original conversation prefix stays the same; only the previous answer
|
||
and the review instruction are new. DeepSeek/OpenAI-compatible providers reuse the
|
||
prefix automatically; Anthropic endpoints need their explicit marker (see `cache`).
|
||
|
||
**Per request.** The rule is the default, but one request can ask for a different
|
||
depth without editing the config:
|
||
|
||
```
|
||
curl -H 'X-Junction-Review-Rounds: 7' ... # 7 rounds, 0..12
|
||
curl -H 'X-Junction-Effort: medium' ... # off=0, low/default=4,
|
||
# medium=7, high=9, max=12
|
||
```
|
||
|
||
The explicit number wins over the effort name. Out-of-range or malformed values
|
||
fall back to the rule. `X-Junction-Review-Rounds: 0` turns the review off for
|
||
that request (one provider call, no review headers). Both headers last for one
|
||
request only and are never forwarded upstream.
|
||
|
||
### Judge/review limits and headers — one place
|
||
|
||
The clauses are safe defaults, but they have hard edges. This is the complete
|
||
list; the code lives in `src/judge.c`, `src/review.c` and `review_serve` in
|
||
`src/junction.c`.
|
||
|
||
**Judge**
|
||
|
||
- At most **4** judge steps per rule; a fifth is a config error. Counts are
|
||
ascending and cumulative inside the chain. `every 5` then `every 10` means step
|
||
0 at the 5th call and step 1 at the 10th; after step 1 the counter starts at 0
|
||
again (15th/20th next).
|
||
- The counter is per conversation **and per rule identity**. The identity is the
|
||
rule's model and path globs, not its line: inserting a comment or another rule
|
||
above it keeps the counters. A conversation is the session header when present,
|
||
otherwise the first system plus first user message (see above).
|
||
- The table is in RAM: 4096 conversations, least-recently-used eviction, one hour
|
||
of idle expiry, reset on restart, and reset after the last chain step. These
|
||
resets change *when* a judge runs, never whether an answer is correct.
|
||
- A judge failure (429, 5xx, offline, timeout) offers the same request to the
|
||
rule's normal targets. The fallback body is the original, without the judge's
|
||
`cache_control` marker. If the marker cannot be added, the judge call goes out
|
||
without it rather than failing the turn.
|
||
- A judge turn is never answered from junction's response cache.
|
||
|
||
**Review**
|
||
|
||
- `review N` in the config accepts **0–12**; `review 13` is rejected at config
|
||
load and by `rules.set`. A per-request header can raise or lower the depth
|
||
(see "Per request" above). N rounds mean **N+1** provider calls (the worker
|
||
answer plus N reviews), all billed and counted in `/spend` and the vkey budget.
|
||
- Review calls use the same endpoint and model as the worker and run
|
||
sequentially. Each review request carries at least **4096** `max_tokens` (or
|
||
`max_completion_tokens`), even when the client asked for less; the first worker
|
||
call keeps exactly the client's budget. The review path buffers, so **every**
|
||
upstream call under a `review` rule (the worker call too) is sent with
|
||
`stream:false` and without `stream_options`; the client still gets SSE frames
|
||
built from the final answer if it asked for a stream.
|
||
- The review prompt is appended to the same conversation after the worker or
|
||
previous answer. It carries the user's request and the answer so far and says
|
||
to keep the same question, scope and language; only the final answer is
|
||
written to the client, intermediate answers and the prompt never leak.
|
||
- If a review round returns the answer **verbatim**, the answer is stable: the
|
||
round is counted, the remaining rounds are skipped, and the log says
|
||
`converged=1`. A reviewer that would otherwise keep rewriting a correct answer
|
||
does not get the chance.
|
||
- Review only applies to `POST /v1/chat/completions` on OpenAI-compatible
|
||
endpoints. `kind anthropic`/`kind opencode`, other paths and non-chat requests
|
||
are forwarded unreviewed with `X-Junction-Review-Skipped: protocol`.
|
||
|
||
**What skips the review (the answer is passed through)**
|
||
|
||
| Reason (`X-Junction-Review-Skipped`) | When |
|
||
|---|---|
|
||
| `n>1` | the client asked for more than one choice; several answers cannot be reviewed as one |
|
||
| `tool_calls` | the answer carries a non-empty `tool_calls` array (`null`/`[]` is text) |
|
||
| `content_array` | the answer's `content` is an array of parts |
|
||
| `no_text` | the answer has no string content |
|
||
| `budget` | the vkey's monthly budget is spent before the next round |
|
||
| `error` | a review round failed; the last good answer is delivered |
|
||
| `body` | the review body could not be built; the original request is forwarded without review |
|
||
| `protocol` | review is not supported for this path or endpoint kind |
|
||
|
||
The original call's own provider error is **not** hidden: a 4xx/5xx from the
|
||
first call reaches the client with its status and body (JSON, or an SSE error
|
||
event when the stream head is already open). A failed *review* round is
|
||
different: it is an internal extra call, so the last good answer is delivered
|
||
instead. `X-Junction-Review-Rounds` says how many rounds actually completed.
|
||
|
||
`n>1` and `protocol` are decided before any review call. A non-streaming client
|
||
sees the reason in `X-Junction-Review-Skipped`; a streaming client's body is
|
||
forwarded untouched (no `junction` chunk), so that case is visible in the log
|
||
(`review_skipped ... reason=...`) and in the non-streaming header. The other
|
||
reasons are produced by `review_serve` and also appear as `review_skipped` in
|
||
the final SSE `junction` object; if the review body cannot be built (`body`), the
|
||
request falls back to an unreviewed forward and only the header/log names it.
|
||
|
||
**Usage, cost and disconnects**
|
||
|
||
- The top-level `usage` is the last provider call's, as the provider reported it.
|
||
The `junction` object in a non-streaming answer and in the final SSE chunk adds
|
||
`usage` (prompt/completion/cached/total) and `cost_usd` summed over the worker
|
||
and all completed review rounds; an unknown price is reported as
|
||
`cost_unknown` instead of zero. Non-streaming answers also carry
|
||
`X-Junction-Review-Tokens-In`, `-Out` and `-Cost-Usd`; `X-Junction-Ms` covers
|
||
the whole request.
|
||
- Streaming clients get a final `choices:[]` chunk with the last call's `usage`
|
||
before `[DONE]`, and only when the provider sent usage. The summed numbers are
|
||
in the `junction` object of the preceding chunk.
|
||
- A non-streaming client that disconnects while review rounds are running cannot
|
||
cancel the upstream calls that already started; they remain billed and appear
|
||
in `/spend`. Streaming clients see `: junction:` comments while rounds run; the
|
||
next failed comment write stops the wait.
|
||
|
||
**Headers**
|
||
|
||
| Header | Meaning |
|
||
|---|---|
|
||
| `X-Junction-Judge` | judge endpoint or pool name from the clause; absent when this turn is not a judge turn |
|
||
| `X-Junction-Judge-Step` | zero-based index of the step in the chain (0, 1, …) |
|
||
| `X-Junction-Judge-Every` | the N of this step |
|
||
| `X-Junction-Judge-Model` | the step's `as` model; `pool` when the pool members carry their own |
|
||
| `X-Junction-Judge-Served` | `1` only if the judge slot delivered the 2xx; `0` when the worker fallback served the turn |
|
||
| `X-Junction-Judge-Next` | counter value at which the next judge runs (e.g. `5`); present on every turn of a judged rule |
|
||
| `X-Junction-Judge-In` | calls remaining until that judge (`1` = the next call) |
|
||
| `X-Junction-Judge-Next-Step` | zero-based index of the next step in the chain |
|
||
| `X-Junction-Judge-Next-Every` | the N of the next step |
|
||
| `X-Junction-Judge-Next-Target` | endpoint or pool that will judge next |
|
||
| `X-Junction-Judge-Next-Model` | its `as` model, or `pool` when the pool members carry their own |
|
||
| `X-Junction-Judge-Next-Cache` | `off`, `5m` or `1h` for the next judge |
|
||
| `X-Junction-Tokens-In` / `-Out` | the provider's token usage of this call (non-streaming) |
|
||
| `X-Junction-Cost-Usd` | exact cost from the price table; `unknown` when a price row is missing, absent without a price table; a cache hit reports `0.000000` and zero tokens |
|
||
| `X-Junction-Review` | the configured N |
|
||
| `X-Junction-Review-Rounds` | review rounds that actually completed |
|
||
| `X-Junction-Review-Model` | the model the worker/review calls were sent as |
|
||
| `X-Junction-Review-Skipped` | the reason from the table above; absent when no skip happened |
|
||
| `X-Junction-Review-Tokens-In/-Out` | summed prompt/completion tokens over the worker and completed rounds (non-streaming, only when a review ran) |
|
||
| `X-Junction-Review-Cost-Usd` | summed known cost over those calls (non-streaming, only when a review ran and the price is known) |
|
||
|
||
Header values are sanitized: CR/LF and other control bytes become spaces, an
|
||
invalid header name is dropped, and an array full at 96 headers drops the rest.
|
||
Drops and sanitized values are logged (`headers_dropped`,
|
||
`header_control_chars`, `header_name_rejected`), so a missing header is never
|
||
silent.
|
||
|
||
### Model policy — what `/v1/models` shows and serves
|
||
|
||
```
|
||
models allow "foo" "bar" "ma/bla" "opencode-go0/*"
|
||
models deny "*-free"
|
||
```
|
||
|
||
`models allow` is a whitelist: the first allow line turns the default into "deny
|
||
everything else". A model must match at least one allow pattern (and no deny pattern)
|
||
to appear in `/v1/models` and to be accepted in a request. `models deny` wins. Patterns
|
||
are `fnmatch` globs on the model ID; a trailing `#variant` is matched without the
|
||
variant, so allowing `deepseek-v4.1-flash` also allows `deepseek-v4.1-flash#high`.
|
||
Without any `models` line nothing is filtered. This is separate from the per-vkey
|
||
`allow` glob: both must agree. To deny everything and allow a few, write only the
|
||
allow lines — an explicit `models deny "*"` would win and hide the allow list too.
|
||
`/v1/models` is fetched with `Accept-Encoding: identity` so the list stays readable
|
||
and a compressed response cannot slip past the policy; every other request keeps the
|
||
client's encoding header.
|
||
|
||
### Context fallback
|
||
|
||
A request that is too large for every target of its matching rule would normally
|
||
end in `503 no_endpoint_available` with `attempts: context context ...`. One
|
||
global pool can catch those:
|
||
|
||
```
|
||
ctx_fallback ds41flash
|
||
ctx_fallback ds41flash as "deepseek-v4.1-flash" # optional default model
|
||
```
|
||
|
||
If no target can hold `ctx + max_tokens`, junction retries the members of that
|
||
pool. Each member's own `as` wins; the model after `as` on the directive is the
|
||
fallback for members without one. `/v1/models` does not list the fallback pool —
|
||
it is a route, not an advertised model.
|
||
|
||
## Images and context limits
|
||
|
||
**An image is recognised inside `messages`, not anywhere in the body.** A request
|
||
counts as an image request when a message carries a content part whose `type` is
|
||
`image_url`, `input_image` or `image`, or when `image_url` is followed directly by an
|
||
object or a string. What does *not* count: a tool schema that merely describes a
|
||
parameter named `image_url` (every agent ships one), and a tool result that quotes an
|
||
image part as text. That distinction is the whole point — a body-wide scan turned every
|
||
agent request into an image request, and those were then routed to the vision chain,
|
||
where they failed for reasons that had nothing to do with the caller. A body without a
|
||
`messages` array falls back to the whole-body scan: better one image too many than an
|
||
image delivered to a text model.
|
||
|
||
`vision on|off` per endpoint decides who may serve it. An image request whose chain
|
||
would only reach `vision off` endpoints is refused with a `503` that names the reason,
|
||
instead of being handed to a text model that would answer with an empty message.
|
||
|
||
**Limits come from the endpoint, in two steps.** First the model list it publishes —
|
||
`limit.context` per model replaces the number in the endpoint block for that model
|
||
(`limit.output` does the same for the output budget). Endpoints that publish no limits
|
||
at all are asked again through their own API: `ollama.com` answers `/api/show` with
|
||
`model_info["<arch>.context_length"]`, which is where its real windows live. Only when
|
||
both are silent does the endpoint's `context` key apply. Nothing in that chain is
|
||
estimated, and `need` still reads only the budget the client declared.
|
||
|
||
## Retry, key pools, metrics
|
||
|
||
A `429`, `408` or `5xx` is retried on the same endpoint before the chain moves on:
|
||
|
||
```conf
|
||
retry_num 1 # additional attempts on the same endpoint (0 = never)
|
||
retry_backoff 0.5 # attempt n waits n × this many seconds
|
||
retry_max_wait 30 # ceiling for a Retry-After the provider asks for (0 = no ceiling)
|
||
```
|
||
|
||
The reason is cost, not politeness: an overloaded cloud node usually recovers in
|
||
seconds, while the next link in the chain may be a paid one or one that cannot hold the
|
||
context. What is *not* retried: connect failures (that state is `offline`, and hooks
|
||
own it), any `4xx` other than the ones named, and anything after the stream head has
|
||
reached the client.
|
||
|
||
If the provider names a `Retry-After`, that number wins over the backoff — it knows when
|
||
its quota reopens, we do not. Retrying earlier only spends the second attempt on the same
|
||
closed door. Both RFC 7231 forms are read: seconds and the HTTP date
|
||
(`Sun, 06 Nov 1994 08:49:37 GMT`, converted with the same civil-date arithmetic the
|
||
monthly rollover uses — `timegm` is not POSIX and a timezone has no business deciding a
|
||
retry). A date in the past means *now*, a `Retry-After: 0` changes nothing, and anything
|
||
unparseable is treated as silence rather than guessed at.
|
||
|
||
`retry_max_wait` (default 30 s) caps whatever comes back: an hour of waiting is not a
|
||
retry, it is an outage with an announcement. The decision is visible in the log:
|
||
`retry ... backoff_ms=2000 retry_after_s=2`.
|
||
|
||
When the **whole chain** is offline or cooling down, failing at once is the wrong
|
||
answer for a van: the uplink often returns in seconds.
|
||
|
||
```conf
|
||
offline_wait 20 # seconds a request may wait for the chain to come back (0 = never)
|
||
```
|
||
|
||
The wait happens before a queue slot is taken, so a waiting request does not occupy an
|
||
upstream place. It is bounded by `offline_wait`; after that the old behaviour applies and
|
||
the caller gets the `503` naming what each target was missing. A request whose stream has
|
||
already started never waits.
|
||
|
||
A key pool is written by repeating `api_key_env`:
|
||
|
||
```conf
|
||
endpoint cloud {
|
||
base https://api.example.com/v1
|
||
api_key_env EXAMPLE_KEY_A
|
||
api_key_env EXAMPLE_KEY_B
|
||
}
|
||
```
|
||
|
||
Each attempt takes the next key, so two accounts are two quotas: a `429` on A is
|
||
answered with B, and only when every key has failed does the endpoint count as failed.
|
||
|
||
`GET /metrics` serves the same numbers as `/status` in the Prometheus text format —
|
||
requests and retries, tokens, cost, cache, queue, compression, and per endpoint
|
||
`up`, requests, inflight, `last_ms`, offline/cooldown seconds, usage percent, pool size,
|
||
`paused` and cost. Like `/status` it is **not authenticated**.
|
||
|
||
A scraper that does not run on this host does not need to reach the model port for that:
|
||
|
||
```conf
|
||
metrics tcp 192.168.1.148:9180
|
||
```
|
||
|
||
That listener answers `GET /metrics` and nothing else — `/v1` and `/admin` stay on
|
||
`listen`, so a monitoring container can read the numbers without also being able to
|
||
pause endpoints or rewrite the configuration.
|
||
|
||
## The request log — one line per served request
|
||
|
||
`spend_log` is not only a ledger. Every request junction answers leaves one JSON line,
|
||
and that line is the only place where a single request is complete: Prometheus cannot
|
||
hold the dimension (model × endpoint × rule × cache source) and journald spreads the same
|
||
request over five event lines.
|
||
|
||
```json
|
||
{"ts":1794123456,"vkey":"hermes","model":"deepseek-v4.1-flash","endpoint":"cloud",
|
||
"status":200,"latency_ms":1840,"upstream_ms":1839,"queue_ms":0,"rule_line":120,
|
||
"cache":"miss","retries":0,"tokens_in":1200,"tokens_out":300,"tokens_cached":0,
|
||
"cost_usd":0.000720}
|
||
```
|
||
|
||
| field | meaning |
|
||
|---|---|
|
||
| `status` | what the client got — the endpoint's status, not ours |
|
||
| `latency_ms` | the whole request as the client waited for it |
|
||
| `upstream_ms` | that time minus the queue wait; derived, not measured separately |
|
||
| `queue_ms` | how long the request waited for an `max_inflight` slot |
|
||
| `rule_line` | the line of the rule that matched; `0` when no rule ran (cache hit) |
|
||
| `cache` | `off` (not cacheable), `miss` (paid), `hit` (own cache), `peer` (another instance), `joined` (waited for an identical request in flight) |
|
||
| `retries` | additional attempts of this same request, not the process total |
|
||
| `tokens_*`, `cost_usd` | the provider's numbers; a cache hit has zeros, not estimates |
|
||
|
||
A streamed answer cannot be billed after the fact, but it still gets a line — with
|
||
zeros rather than a guess. Failed requests are counted in `/metrics` and logged per
|
||
attempt in journald; the request log is for what was served, not for every try.
|
||
|
||
No exporter, no collector, no agent — the file is the interface:
|
||
|
||
```bash
|
||
# p95 latency per model over the last day
|
||
jq -r 'select(.ts > (now-86400)) | [.model, .latency_ms] | @tsv' spend.jsonl |
|
||
sort -k1,1 | awk '{a[$1]=a[$1]" "$2} END {for (m in a) print m, a[m]}'
|
||
# what the cache actually saved
|
||
jq -r '.cache' spend.jsonl | sort | uniq -c
|
||
```
|
||
|
||
`/spend` reads the same file and sums `cost_usd`, so the dashboard, the monthly budgets
|
||
and the log can never disagree.
|
||
|
||
### Price table and per-call cost
|
||
|
||
`prices <file>` loads the table once at startup. A row is
|
||
`model input cached output [offpeak=IN,OUT] [budget=USD] [requests=N/5h]`, all
|
||
prices per million tokens. The billed name is the target's `as` model; a
|
||
`#variant` suffix is a selector, not part of the name, so `deepseek-v4.1-flash#max`
|
||
uses the base `deepseek-v4.1-flash` row. An exact row for the full variant still
|
||
wins. A `-go` row is used only when the model name itself is `...-go`; the endpoint
|
||
kind does not silently change the price. The endpoint's `offpeak` window is
|
||
evaluated at request time, so `offpeak=IN,OUT` columns apply even when the endpoint
|
||
has no usage command. Chunked non-streaming bodies are dechunked before usage is
|
||
read, so they are costed too.
|
||
|
||
A non-streaming response carries `X-Junction-Tokens-In`, `X-Junction-Tokens-Out`
|
||
and, when the price is known, `X-Junction-Cost-Usd`. A reviewed answer puts the
|
||
sum over the worker and all rounds in both `X-Junction-Review-Cost-Usd` and the
|
||
general `X-Junction-Cost-Usd`, so one header is enough. An unpriced model keeps
|
||
`unknown`; without any price table the headers are not invented. A cache hit is a
|
||
call that cost nothing: it reports cost `0.000000` and zero tokens even though the
|
||
cached body still contains the provider's original usage.
|
||
|
||
A plain stream cannot be costed after the fact: its head is already on the wire and
|
||
junction does not parse usage out of an arbitrary SSE stream, so its ledger line has
|
||
zeros rather than a guess. A reviewed stream is buffered, so it carries the summed
|
||
cost in its final `junction` object. The spend log and `/spend` remain authoritative
|
||
for non-streaming calls and for reviewed streams.
|
||
|
||
## Virtual keys, limits, spend
|
||
|
||
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 |
|
||
|---|---|
|
||
| `token_env` | env var holding the key's value (never the value itself in the config) |
|
||
| `allow` | model glob; `"*"` = any |
|
||
| `endpoints` | comma list of endpoint names; omitted = any |
|
||
| `rpm` | requests per minute; the window is a hard minute, not a sliding one |
|
||
| `budget` | spend cap in USD per **calendar month** |
|
||
|
||
Two limits, two answers: over `rpm` the caller gets `429 vkey_rate_limited` with a
|
||
`Retry-After` in seconds; over `budget` it gets `403 vkey_budget_exhausted`. Both are
|
||
visible in `/status` (`vkeys[]`: `rpm`, `budget_usd`, `spent_usd`, `window_hits`,
|
||
`hits`, `denied`) and in `/metrics` (`junction_vkey_*`).
|
||
|
||
The spend comes from the spend log, one JSON line per request that reported usage:
|
||
|
||
```conf
|
||
spend_log /var/lib/junction/spend.jsonl
|
||
```
|
||
|
||
```
|
||
{"ts":1794084400,"vkey":"webui","model":"deepseek-v4.1-flash","endpoint":"cloud",
|
||
"tokens_in":1200,"tokens_out":300,"tokens_cached":1000,"cost_usd":0.000720}
|
||
```
|
||
|
||
The dashboard shows the same three things without reading the model port: a card with
|
||
every virtual key (model glob, `rpm`, budget, spend, requests, refusals), the month's
|
||
total and its per-model split, and a "Letzte Anfragen" card with the last 25 lines of
|
||
the request log — time, model, endpoint, status, milliseconds, cache source, tokens,
|
||
cost — plus p95 latency and hit ratio *for those lines*, labelled as such rather than
|
||
implied for the whole day. It asks over the control channel (`spend.get`,
|
||
`requests.tail`), the same way it asks for status and rules.
|
||
|
||
`GET /spend` answers for the ledger what `/status` answers for the process: the month's
|
||
total and its split per key and per model, `?month=YYYY-MM` for any month the file still
|
||
covers. Without a `spend_log` it says so (`404 no spend_log configured`) instead of
|
||
returning zeros that look like a month without spending.
|
||
|
||
Timestamps in the ledger are wall-clock (`time(NULL)`), not the monotonic clock the
|
||
timeouts use. That distinction cost a bug: with monotonic seconds the file said
|
||
`"ts":66841`, and after the next restart the month's spend was invisible — a budget that
|
||
forgets every restart is no budget. `/spend` is what made it visible.
|
||
|
||
At startup the keys' spent amounts are recomputed from that file for the current month.
|
||
Without it a budget would be full again after every restart, which is the one thing a
|
||
budget must not be. `/status` also keeps the in-memory numbers, so a request costs one
|
||
append, not a read of the whole ledger.
|
||
|
||
Honest about the boundary: a **vkey is accounting, not a door.** A caller that sends no
|
||
key, or a wrong one, is routed as before — restricting that would need a `require_vkey`
|
||
switch and a list of every client that currently calls without one (WebUI, Navigator,
|
||
dashboard scripts), or half the fleet stops. Until then a limit only binds callers who
|
||
were given a key.
|
||
|
||
## Guards — the policy is a script, not a keyword
|
||
|
||
junction refuses to pretend it knows what should be blocked. A guard is a command that
|
||
sees the request and decides:
|
||
|
||
```conf
|
||
guard request cmd "/usr/local/share/junction/hooks/guard.sh"
|
||
```
|
||
|
||
```
|
||
JUNCTION_PATH JUNCTION_MODEL JUNCTION_VKEY
|
||
JUNCTION_BODY_FILE (the body, in a temp file)
|
||
JUNCTION_BODY_BYTES
|
||
```
|
||
|
||
Exit 0 lets the request through; anything else refuses it with `403 guard_refused`, and
|
||
stdout becomes the reason in the body and in the log. If the script says nothing, the
|
||
refusal names its exit code (`guard_exit_3`) instead of inventing an empty reason.
|
||
|
||
Three things that are deliberate:
|
||
|
||
- **The body is a file, not stdin.** A script that reads only the first line would hang
|
||
the write into a full pipe; a file cannot deadlock.
|
||
- **The guard runs before routing**, so a refused request occupies no endpoint, no queue
|
||
slot and no upstream budget.
|
||
- **Request side only.** Inspecting the answer would mean buffering every stream, which
|
||
is the one thing this router is built not to do. When a guard is configured the guard
|
||
line appears in every request's log (`guard_pass` / `guard_refused`), and
|
||
`junction_guard_refused_total` counts the refusals.
|
||
|
||
## Keys
|
||
|
||
Global: `listen`, `connect_timeout_ms`, `offline_hold_s`, `max_body_bytes`,
|
||
`log_prefix`, `cache_ttl`, `cache_entries`, `cache_bytes`, `max_inflight`,
|
||
`queue_timeout`, `retry_num`, `retry_backoff`, `offline_wait`, `guard`, `metrics`, `spend_log`.
|
||
|
||
Endpoint:
|
||
|
||
| key | meaning |
|
||
|---|---|
|
||
| `base` | OpenAI-compatible base URL including `/v1` (`http://` or `https://`) |
|
||
| `context` | usable context window in tokens |
|
||
| `kind` | free-form label (`local`, `remote`, `cloud`) |
|
||
| `priority` | lower wins when a rule lists several |
|
||
| `timeout` | total wall clock for one request (seconds) |
|
||
| `connect_timeout_ms` | per-endpoint connect limit; 0 = the global value |
|
||
| `weight` | 1..100, how often this endpoint is chosen (default 1) |
|
||
|
||
A chain can be named once and reused, and a pool may name another pool:
|
||
|
||
pool lokal box3, box6
|
||
pool alles cloud, lokal
|
||
|
||
A pool member may also carry a model and effort for that endpoint only:
|
||
|
||
pool ds41flash opencode-go/deepseek-v4.1-flash#max, ollama0/deepseek-v4.1-flash#max
|
||
|
||
`endpoint#max` keeps the request's model and only adds the selector. A rule's
|
||
`as` stays in force for members that do not name a model.
|
||
req for "*" pass alles
|
||
|
||
| `idle_timeout` | silence before `still_working` is logged (seconds) |
|
||
| `cooldown` | rest after a failed request (seconds) |
|
||
| `hook` | shell command; exit 0 = usable, non-zero = not yet (repeatable) |
|
||
| `hook_retry` | how long to keep retrying hooks |
|
||
| `hook_backoff` | sleep between hook attempts |
|
||
| `wake` | command run once before the hook retries begin |
|
||
| `api_key_env` | env var sent as `Authorization: Bearer ...` (repeatable: a pool, tried in turn) |
|
||
| `tls_verify` | `on` (default) / `off` |
|
||
| `tls_ca` | CA bundle for a private CA (default: system store) |
|
||
| `cache` | `on` / `off` for this endpoint |
|
||
| `header` | static request header, `"Name: value"` (repeatable) |
|
||
| `vision` | `on` / `off` — can this endpoint read images? Omitted = not checked |
|
||
| `kind opencode` | the endpoint is an `opencode serve`; requests are translated |
|
||
| `kind anthropic` | native Messages API; the effort selector becomes `output_config.effort` |
|
||
| `auth_basic <user>` | HTTP Basic instead of a bearer token (opencode wants this) |
|
||
| `pass_cmd <cmd>` | stdout is the password — opencode makes a new one on every start |
|
||
| `base_cmd <cmd>` | stdout is the base URL — the background server binds a random port. The health check and the request path both use this value, not the static `base`, so a service that restarts on a new port is picked up without restarting junction |
|
||
| `oauth` | `on` / `off` — the key is a Claude subscription token, not an API key (see below) |
|
||
|
||
### Claude subscription tokens (`oauth on`)
|
||
|
||
A `CLAUDE_CODE_OAUTH_TOKEN` (`sk-ant-oat01…`) is not an API key. Anthropic accepts it
|
||
only on requests that carry Claude Code's system prompt; with an ordinary body a
|
||
current model answers `429 rate_limit_error` with the message `Error` — the same
|
||
status and the same shape a real quota exhaustion has. An endpoint that "works
|
||
sometimes" is usually this, not a limit.
|
||
|
||
`oauth on` puts that system prompt in place, and only for the endpoints that ask for
|
||
it. Which models are gated is not uniform: retired names such as
|
||
`claude-haiku-4-5-20251001` still answer without the prompt, so a test against one of
|
||
them proves nothing. `claude-sonnet-5-5`, `claude-haiku-5-5`, `claude-opus-5` and
|
||
`claude-opus-4-8` are gated (measured 2026-11-24, each case repeated).
|
||
|
||
The client's own system prompt is kept, not replaced:
|
||
|
||
* `/v1/messages` — the marker becomes the first block of `system`, the client's text
|
||
follows as further blocks, `cache_control` included.
|
||
* `/v1/chat/completions` — the system content must be the marker *alone* there, so
|
||
the client's system text moves into the conversation as a user message before the
|
||
first turn. Appending it to the marker, or adding a second block, is rejected.
|
||
|
||
The marker is matched byte for byte server-side; a missing final period or a trailing
|
||
newline is worth the same as no marker at all. Nothing is rewritten for an endpoint
|
||
without this line, and a body junction cannot parse goes upstream unchanged — the
|
||
provider then answers as it would have without junction.
|
||
|
||
With `kind opencode`, the bridge carries the client's reasoning effort into the
|
||
session: `reasoning_effort` (Chat Completions), `reasoning.effort` (Responses), an
|
||
explicit `variant`, or a `model#variant` selector become the opencode model variant,
|
||
which is where opencode stores reasoning effort. Values pass through unchanged
|
||
(`default`/`auto` mean no variant), so `#high`, `#low`, `#minimal` and `#none` work
|
||
when the model offers them. Other
|
||
generation options have no slot in the session prompt API and are not invented.
|
||
|
||
With `kind anthropic`, the native `/v1/messages` body stays intact and only the
|
||
effort selector is rewritten: `reasoning_effort`, `reasoning.effort`, `variant` or
|
||
a `model#variant` selector become `output_config.effort`. `minimal` maps to `low`,
|
||
`ultra` to `max`, and `none` becomes `thinking: {"type": "disabled"}`. A native
|
||
`output_config.effort` wins over all of them. If the client sends
|
||
`anthropic-version`, the endpoint's static version header is not added a second
|
||
time.
|
||
|
||
For every other endpoint kind the request body goes out unchanged, except for a
|
||
`model#variant` selector: it is stripped and becomes `reasoning_effort`
|
||
(`minimal`→`low`, `ultra`→`max`, `default`/`auto` means no explicit effort).
|
||
`reasoning_effort`, `reasoning.effort` and the other generation options already in
|
||
the body reach the provider as written. That is why Ollama Cloud needs no special
|
||
case: its OpenAI-compatible endpoint understands both fields.
|
||
|
||
## Hooks
|
||
|
||
Plain POSIX shell, with the request in the environment:
|
||
|
||
```
|
||
JUNCTION_BACKEND JUNCTION_BASE JUNCTION_PATH JUNCTION_MODEL
|
||
JUNCTION_NEED_TOKENS JUNCTION_ATTEMPT
|
||
```
|
||
|
||
Exit non-zero and print the reason on stdout — it lands in `/status` and in the
|
||
`503` body. Examples in `hooks/`: `check-http.sh`, `check-budget.sh`,
|
||
`wake-wol.sh`.
|
||
|
||
|
||
## MCP gateway — junction as one MCP server for all tools
|
||
|
||
junction can also *serve* MCP. Every MCP server you list in the configuration is
|
||
reached through junction, so an agent connects **once** and sees every tool,
|
||
instead of subscribing to each server separately. Same role the MCP gateway of
|
||
LiteLLM plays.
|
||
|
||
```conf
|
||
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_cache_ttl 60
|
||
```
|
||
|
||
| key | meaning |
|
||
|---|---|
|
||
| `mcp <name> url <url>` | an upstream MCP server (Streamable HTTP, JSON-RPC 2.0) |
|
||
| `mcp <name> cmd "<command>"` | an upstream MCP server spoken over stdin/stdout (spawned by junction, one quoted command) |
|
||
| `header "Name: value"` | repeated; for tokens and anything else the server wants |
|
||
| `timeout <s>` | per call; default 10 — a server that does not answer delays the tool list, it does not block it |
|
||
| `off` | keep the entry, do not use it |
|
||
| `mcp_cache_ttl <s>` | how long the aggregated tool list is kept, default 60 |
|
||
| `mcp_auth auto\|all\|off` | who may call `/mcp`: `auto` (default) lets the local machine in without a key and demands a vkey from any other address, `all` demands one everywhere, `off` turns the check off |
|
||
|
||
### Who may call `/mcp`
|
||
|
||
`/mcp` is not a model path. Through it an agent creates tasks, rewrites skills, stores
|
||
memories and edits wiki pages — it writes, it does not merely route. So the default is
|
||
`mcp_auth auto`: from `127.0.0.1` (or `::1`) no key is needed, from any other address the
|
||
caller must present a vkey that junction itself minted:
|
||
|
||
```conf
|
||
vkey "mcpclient" token_env VKEY_MCP allow "*"
|
||
mcp_auth auto
|
||
```
|
||
|
||
```sh
|
||
curl -s http://192.168.1.148:8090/mcp -X POST \
|
||
-H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
|
||
-H "Authorization: Bearer $VKEY_MCP" \
|
||
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
|
||
```
|
||
|
||
Without a key the answer is `401` with `WWW-Authenticate: Bearer` and
|
||
`{"error":"mcp_key_required"}` — not a silent refusal, so a client can tell the difference
|
||
between "no key" and "junction is down". `mcp_auth off` exists for a network you actually
|
||
trust; binding `listen 0.0.0.0` and `mcp_auth off` together means anyone on that network can
|
||
write into every store. `/status` reports the mode as `mcp_auth`.
|
||
|
||
The client talks to `http://<junction>:8090/mcp` and gets `initialize`, `ping`,
|
||
`tools/list`, `tools/call`, `prompts/list`, `prompts/get`, `resources/list` and
|
||
`resources/read`. Names are prefixed with the server name — `tasksd__task_create`,
|
||
`tasksd__summarize`, `tasksd__memory://tasks` — because two servers may well have a
|
||
tool or a prompt of the same name; the call methods split the prefix off before
|
||
forwarding, so the server sees exactly the name it published. Descriptions, input
|
||
schemas and prompt arguments are passed through untouched.
|
||
|
||
The prefix is also why a resource URI looks different at the client than at the server:
|
||
`resources/list` returns `tasksd__memory://tasks`, `resources/read` takes that prefix
|
||
away again. A URI that belongs to no configured server is refused instead of being
|
||
guessed at.
|
||
|
||
Two transports are supported. An upstream is either an HTTP endpoint or a command that
|
||
junction starts itself and speaks to over stdin/stdout:
|
||
|
||
```conf
|
||
mcp tasksd url http://127.0.0.1:8781/mcp timeout 20
|
||
mcp local cmd "python3 /srv/mcp/filesystem.py --root /data"
|
||
```
|
||
|
||
A stdio server is started on first use, `initialize` is sent once, and the process stays
|
||
alive between calls — a stdio server keeps session state, and a fresh process per call
|
||
would be a different server every time. A command that does not answer is torn down and
|
||
reported like a dead HTTP server: the other servers' tools still arrive.
|
||
|
||
What it deliberately does not do: no session cookie, no server-to-client push, no SSE
|
||
answer to a request, no `resources/subscribe` (the capability is advertised as
|
||
`subscribe: false`). A tool call is a question with one answer. Requests without an `id`
|
||
are notifications and get `202` with no body.
|
||
|
||
A server that is down or silent is skipped with a log line; the tools of the
|
||
others still arrive. Nothing is invented to fill the gap.
|
||
|
||
## Control plane
|
||
|
||
| Method | Path | Effect |
|
||
|---|---|---|
|
||
| GET | `/status` | endpoints, counters, cache stats, rules |
|
||
| GET | `/metrics` | the same counters as Prometheus text (unauthenticated, like `/status`) |
|
||
| GET | `/spend[?month=YYYY-MM]` | cost of that month from the spend log, per key and per model |
|
||
| — | `{"cmd":"spend.get","month":"YYYY-MM"}` on the control channel — the same numbers, for the dashboard |
|
||
| — | `{"cmd":"requests.tail","count":"25"}` — the last N lines of the request log (capped at 200, read from the end of the file) |
|
||
| POST | `/admin/pause/<name>` | stop routing there |
|
||
| POST | `/admin/resume/<name>` | clear pause + cooldown + offline |
|
||
| POST | `/admin/flush/cache` | drop every cached response |
|
||
|
||
`/status` also reports the queue: `inflight`, `waiting`, `max_inflight`, `timeout_s`, and
|
||
per endpoint `last_ms` plus `p95_ms` — the latter computed from a histogram and therefore
|
||
an *upper bound* of the bucket the 95 % mark falls into, `-1` when nothing has been
|
||
measured yet.
|
||
|
||
`/metrics` exports that histogram (`junction_endpoint_latency_seconds_bucket{endpoint,
|
||
le}`, `_sum`, `_count`), so `histogram_quantile(0.95, …)` works per endpoint. An average
|
||
hides exactly the requests that hurt: an endpoint answering 95 % fast and 5 % of the time
|
||
in a minute keeps a harmless mean.
|
||
|
||
Everything else is proxied to the endpoint the rules choose.
|
||
|
||
`make install` also installs `junction-wol` (C, 100 lines) for the `wake-wol.sh`
|
||
hook — building a magic packet should not need an interpreter either.
|
||
|
||
`packaging/` holds what belongs next to the binary but not inside it:
|
||
`junction.service` and `junction@.service` (the unit and the rolling-update template,
|
||
both with `RuntimeDirectory=junction…` — without it the control socket cannot be created
|
||
after a reboot), and `prometheus-junction.yml`, the alert rules for `/metrics`
|
||
(router down, endpoint unusable, heavy failover, a key near its budget, a peer cache
|
||
that answers badly, a drain that never finishes).
|
||
|
||
## Providers from the environment
|
||
|
||
A key in the environment is an endpoint. No block needs to be written for it:
|
||
|
||
| variable | endpoint | base (override) |
|
||
|---|---|---|
|
||
| `OPENCODE_GO_API_KEY` [1…8] | `opencode-go` [`1`…`8`] | `https://opencode.ai/zen/go/v1` (`OPENCODE_GO_BASE`) |
|
||
| `OLLAMA_KEY` [1…8] | `ollama` [`1`…`8`] | `https://ollama.com/v1` (`OLLAMA_BASE`) |
|
||
| `ANTHROPIC_API_KEY` or `CLAUDE_API_KEY` [1…8] | `claude` [`1`…`8`] | `https://api.anthropic.com/v1` (`CLAUDE_BASE`) |
|
||
|
||
```conf
|
||
auto_endpoints on # default; off disables the whole mechanism
|
||
```
|
||
|
||
What the file already defines wins — the automatic endpoints only fill gaps, and the
|
||
log names every one it adds (`endpoint ollama1 added from OLLAMA_KEY1 (base …)`). No
|
||
`context` is invented: limits belong to the models and come from their own list. A
|
||
config with no `endpoint` block at all is valid if the environment supplies one.
|
||
The `<PROVIDER>_BASE` override exists for a local proxy and for tests.
|
||
|
||
## One request per model
|
||
|
||
```conf
|
||
endpoint box {
|
||
base http://172.25.206.3:8080/v1
|
||
max_model_inflight 1
|
||
}
|
||
pool local box, box2, box3, box4
|
||
|
||
req for "local/*" strip "local/" pass local
|
||
```
|
||
|
||
`max_model_inflight 1` means: one request at a time **per model name** on that endpoint;
|
||
the next one waits in line 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 number is per (endpoint, model), so a pool of four boxes gives four slots.
|
||
|
||
`strip` removes a prefix before the request leaves the router: a client asks for
|
||
`local/qwen3.6-35b`, the box receives `qwen3.6-35b` — in the body, in the pricing lookup
|
||
and in the log. `strip` must stand before `pass`, because `pass` ends the line.
|
||
|
||
A request that waits for a model slot holds its `max_inflight` slot meanwhile; size
|
||
`max_inflight` to at least (models × 1) plus room, or leave it generous for a local pool.
|
||
|
||
## Is the endpoint really there?
|
||
|
||
```conf
|
||
probe_interval 20 # seconds between background checks (0 = off)
|
||
probe_timeout 3 # per check
|
||
# endpoint ... { probe off } # exclude one (sleeping box, a list that costs money)
|
||
```
|
||
|
||
A background thread asks every endpoint for its model list (`GET <base>/models`). No
|
||
answer (no TCP, no HTTP) means: offline for `offline_hold_s`, logged as `probe_offline`.
|
||
The next round asks again, and a recovered endpoint is back before any request had to
|
||
pay for the discovery (`probe_recovered`). A `4xx` counts as alive — a wrong key is a
|
||
different problem than a machine that is off.
|
||
|
||
`/status` carries `probe_ok` and `probe_age_s` per endpoint, so "the router thinks it is
|
||
down" and "the router has not looked yet" are distinguishable.
|
||
|
||
## Cluster: several instances, one port, one cache
|
||
|
||
No Redis, no etcd, no proxy in front — the cluster is two mechanisms, both optional.
|
||
|
||
**SO_REUSEPORT** (`so_reuseport on`) lets several instances bind the same address; the
|
||
kernel distributes the connections. A new instance takes traffic while the old one is
|
||
still serving.
|
||
|
||
**Drain** (`drain_timeout`, default 15 s): on `SIGTERM` junction closes the listening
|
||
socket first, finishes the requests it is already serving, and only then exits. Once
|
||
the socket is closed the kernel hands new connections to the remaining instance of the
|
||
group, so there is no window where nothing answers. A request that is still running
|
||
after `drain_timeout` is abandoned with a `drain_timeout` log line — an update must not
|
||
depend on a stuck upstream.
|
||
|
||
With a templated unit (`packaging/junction.service` copied to `junction@.service` and
|
||
one config per colour) a rolling update is two commands:
|
||
|
||
```sh
|
||
systemctl start junction@blue # new binary, same port, same rules
|
||
systemctl stop junction@green # old instance drains, then exits
|
||
```
|
||
|
||
**Shared cache** (`cache tcp`, `cache_secret_env`, `cache_peer`, `cache_peer_timeout_ms`):
|
||
every instance keeps its cache in its own memory and hands it out over a port of its
|
||
own. A node that misses locally asks its peers before it pays the provider; a node that
|
||
fills an entry pushes it to its peers. The transport is a small HTTP subset — a second
|
||
implementation does not need the binary:
|
||
|
||
```
|
||
GET /cache/<16 hex> -> 200, X-Age: <s>, then the frame
|
||
PUT /cache/<16 hex> -> 204, request body is the frame, X-TTL: <s>
|
||
GET /cache/stats -> 200, JSON: entries, bytes, hits, misses
|
||
|
||
frame = 4 byte head length, 4 byte body length (big endian), head, body
|
||
```
|
||
|
||
The head is the exact HTTP head the node would have sent, so a peer hit is served
|
||
without rebuilding anything. A hit is stored locally with the remaining TTL, so the
|
||
next caller does not ask the peer again. Fills are pushed asynchronously, at most four
|
||
at a time; a dropped push is not an error, the entry is in the local cache either way.
|
||
`X-Junction-Peer: <secret>` (from the variable named by `cache_secret_env`) guards the
|
||
port; without a secret the listener does not open at all, and the log says so.
|
||
|
||
`cache_peer_timeout_ms` (default 150) is the whole cost of a peer that accepts and then
|
||
says nothing — measured at 203 ms in the suite. Peers are a shortcut, never a
|
||
dependency: if every peer is dead, the request goes to the provider as if the mesh did
|
||
not exist.
|
||
|
||
What it is not: **no coherence protocol**. `POST /admin/flush/cache` flushes one node;
|
||
the others converge by TTL only. No TLS on the peer port — it belongs on loopback or a
|
||
trusted LAN, and the secret is the only authorization.
|
||
|
||
Counters: `/status` has `cache_peers` (peers, lookups, hits, pushes, errors) and
|
||
`draining`/`reuseport`; `/metrics` has `junction_cache_peer_lookups_total`,
|
||
`junction_cache_peer_hits_total`, `junction_cache_peer_pushes_total`,
|
||
`junction_cache_peer_errors_total`, `junction_cache_peers` and `junction_draining`.
|
||
|
||
## Known limits (v0.1, deliberately named)
|
||
|
||
- **The queue is FIFO-ish**: `max_inflight` slots go to whoever asks next; there is no
|
||
prioritisation and no fairness guarantee beyond that.
|
||
- **HTTP/1.1 only** — no HTTP/2, no h2c.
|
||
- **The cache is memory-only** and lost on restart; it does not survive `SIGHUP`.
|
||
Across instances it is shared by peers (see above), but without coherence: the only
|
||
invalidation is the TTL.
|
||
- **TLS client is verified** against the system store or `tls_ca`; there is no
|
||
certificate pinning and no client-certificate auth.
|
||
- **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.
|
||
|
||
## Tests
|
||
|
||
```bash
|
||
tests/run.sh
|
||
```
|
||
|
||
C stubs for a failing endpoint, a hook-gated one, a slow one (6 s silence), a dead
|
||
port, and a TLS peer with a self-signed cert. Checks: offline detection, cooldown and
|
||
failover, hook retry, `still_working`, block rules, catch-all, model rewrite,
|
||
`no_matching_rule`, config errors, chunked request decoding (byte-exact body),
|
||
cache miss/hit/flush/bypass, header passthrough and injection, TLS listener, https
|
||
upstream, and that certificate verification actually refuses a self-signed peer.
|
||
The suite also pins the two distinctions that are easy to get wrong: an image counts
|
||
only inside `messages` (a tool schema naming `image_url` and an escaped image part in a
|
||
tool result both stay text, while a real image part still reaches the vision chain),
|
||
and a limit published only in the endpoint's own API (`/api/show`) still beats the
|
||
number in the endpoint block. Three more cover the retry path: a `503` is retried on
|
||
the same endpoint and logged with the upstream status, a `429` on the first key of a
|
||
pool rotates to the second, and `/metrics` answers in the Prometheus text format with
|
||
`junction_endpoint_up` and the retry counter. The metrics listener is tested for the
|
||
opposite too: model traffic and `/admin` get a `404` there. For MCP the suite checks
|
||
twelve things against two fake servers: the aggregated tool list, the call going to the
|
||
right server with unchanged arguments, prompts bundled and un-prefixed on `prompts/get`,
|
||
a resource URI un-prefixed on `resources/read`, an unknown prefix refused, and a dead
|
||
server not taking the list down. A guard script is tested from both sides: one that
|
||
refuses a word it does not want (with its reason in the body and in `/metrics`), one
|
||
that exits silently (the exit code becomes the reason), and a request that passes and is
|
||
logged as `guard_pass`. `/spend` is checked against a seeded ledger: the month's total,
|
||
the split per key and model, a month with nothing in it, a malformed month, and a router
|
||
without a ledger saying exactly that. The key limits have their own
|
||
file: a `rpm 1` key is served once and then refused with `429` and a `Retry-After`, a key
|
||
whose budget the ledger already used up is refused before it routes anything, and a
|
||
priced request through a key shows up in the log file, in `/status` and in `/metrics`.
|
||
The offline wait has its own section too: with the only endpoint missing the first
|
||
request fails as before, and once the endpoint is back the next request waits out the
|
||
offline hold (measured ~2 s) and is served instead of refused.
|
||
Two more sections cover the cluster. The shared cache is tested with two instances:
|
||
node A answers a request and fills, node B answers the same request from A's cache
|
||
(`via=peer` in the log) without calling the provider at all, and keeps the entry for
|
||
the next caller; the peer port refuses a caller without the secret and with a wrong one;
|
||
a node without a secret does not open the port; and a peer that accepts but never
|
||
answers costs exactly the timeout (203 ms measured) instead of stalling the request.
|
||
The rolling update is tested for real: a second instance binds the same port while the
|
||
first serves, `SIGTERM` on the first logs `draining` and `drained` and it exits, the
|
||
second serves during and after the handover, and without `so_reuseport` the port stays
|
||
exclusive.
|
||
The request log has its own section: two served requests write exactly two lines, the
|
||
paid one carries the provider's tokens, the status, a positive latency and the matching
|
||
rule line, the cached one says `cache":"hit"` with zero tokens and no rule, and `/spend`
|
||
sums exactly what the ledger wrote. A third check would have caught a real
|
||
use-after-free: the status code must be read out of the cached head *before* the body is
|
||
sent, because another thread may replace that entry while this one is still writing —
|
||
the whole suite also runs green under AddressSanitizer.
|
||
The last section covers `Retry-After`: a stub that answers the first request with
|
||
`503` plus `Retry-After: 2` makes junction wait 2.0 s (measured) instead of its 0.2 s
|
||
backoff, the same stub saying `60` under `retry_max_wait 1` is capped at 1.0 s, an HTTP
|
||
date two seconds ahead has the same effect as the number, a date two minutes in the past
|
||
means "now" (0.2 s, just the backoff), and every decision names the provider's number in
|
||
the log line.
|
||
The latency histogram is pinned too: the `+Inf` bucket must carry the same count as the
|
||
served requests, the buckets must be monotone (Prometheus computes quantiles from
|
||
cumulative buckets — non-monotone ones produce nonsense, not an error), and `/status`
|
||
must carry a `p95_ms`.
|
||
Three sections cover the local pool, the probe and the environment: two requests for the
|
||
same model take 4 s together (one at a time), two different models take 2 s (parallel),
|
||
and the box never sees the `local/` prefix — measured on the header the stub echoes.
|
||
A dead endpoint is noticed by the background check without a request being sent to it,
|
||
a request then skips it in 1.2 ms, and it is re-admitted by the next check once it
|
||
answers again; `probe off` keeps an endpoint out of the checks entirely.
|
||
Pass = `PASS` (249 checks), including two that would have caught the two mistakes this
|
||
design invites: a serial stub making a concurrent router look serialised, and a
|
||
"waiting" comment leaking into a caller that never asked for a stream.
|
||
|
||
The suite refuses to run if a test port is already taken — a stale `junction` on
|
||
`:8105` once answered requests with someone else's config and made a good test look
|
||
broken.
|