Files
junction/config.example
lotherk e86c52b074 oauth: make Claude subscription tokens usable as endpoint keys
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.
2026-11-24 10:56:16 +00:00

280 lines
13 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# junction.conf — pf.conf-style. keyword, arguments, braces. '#' starts a comment
# at the beginning of a word; inside a word it is data (model#max).
# Double quotes group words. Unknown keywords are a hard error with a line number.
# Plain listener:
listen 0.0.0.0:8090
# ... or TLS (https clients without a proxy in front):
# listen 0.0.0.0:8443 tls /etc/junction/tls/cert.pem /etc/junction/tls/key.pem
connect_timeout_ms 1500
offline_hold_s 20
max_body_bytes 67108864
# How many upstream requests may run at once; the rest wait in line. A waiting
# streaming caller gets SSE comments explaining the wait, a plain one waits silently.
max_inflight 4
queue_timeout 300
# Retry before failover: 429/408/5xx are tried again on the SAME endpoint, because such
# a state usually clears in seconds while the next link may cost money or context.
# 0 disables it. retry_backoff is per attempt (attempt n waits n × this).
retry_num 1
retry_backoff 0.5
# The provider's Retry-After wins over the backoff (seconds or an HTTP date); this is the
# ceiling, so a "come back in an hour" does not turn a retry into an outage. 0 = none.
retry_max_wait 30
# If the WHOLE chain is offline or cooling down, wait this many seconds for it to come
# back instead of answering 503 at once (0 = never wait). The wait happens before a
# queue slot is taken, so a waiting request holds no upstream place.
# offline_wait 20
# One JSON line per request that reported usage: time, key, model, endpoint, tokens,
# cost. The per-key monthly budgets are recomputed from it at startup — without it a
# budget would be full again after every restart. Empty = no log.
# One JSON line per served request: cost for the budgets, plus status, latency,
# queue wait, rule line, cache source and retries for looking things up later.
# spend_log /var/lib/junction/spend.jsonl
# A guard sees every request before it is routed and decides: exit 0 = pass, anything
# else = 403 with the script's stdout as the reason. junction brings no policy of its
# own. The body is handed over as a file (JUNCTION_BODY_FILE), not on stdin.
# guard request cmd "/usr/local/share/junction/hooks/guard.sh"
# Response cache (memory only). ttl 0 disables it. Only complete, non-streamed 200
# answers are stored, keyed on method + path + model + body.
# Only /metrics, only read-only. A Prometheus in a container or on another host can
# scrape the numbers here without reaching the model port (and /admin) at all.
# metrics tcp 192.168.1.148:9180
# --- providers from the environment -------------------------------------------
# A key is an endpoint: OLLAMA_KEY[_N] -> ollama[N], OPENCODE_GO_API_KEY[_N] ->
# opencode-go[N], ANTHROPIC_API_KEY/_CLAUDE_API_KEY[_N] -> claude[N]. What this file
# defines wins; the mechanism only fills gaps. <PROVIDER>_BASE overrides the base.
# auto_endpoints on
# --- is it really there? ------------------------------------------------------
# Background check: every N seconds GET <base>/models. No TCP connection = offline for
# offline_hold_s, then checked again. A slow answer is not offline.
# probe_interval 20
# probe_timeout 3
# --- one request per model ----------------------------------------------------
# endpoint box { base http://172.25.206.3:8080/v1; max_model_inflight 1 }
# req for "local/*" strip "local/" pass box
# --- cluster, without a service in between -----------------------------------
# Several instances may share one port, and each may hand its cache to the others.
# mcp_auth auto|all|off
# Who may call /mcp. "auto" (default) needs no key from 127.0.0.1 and a vkey from anywhere
# else; "all" needs one everywhere; "off" disables the check (only for a trusted network).
# mcp_auth auto
# so_reuseport on
# drain_timeout 15
# cache tcp 127.0.0.1:8170
# cache_secret_env JUNCTION_CACHE_KEY
# cache_peer 127.0.0.1:8171
# cache_peer_timeout_ms 150
cache_ttl 300
cache_entries 128
cache_bytes 33554432
# --------------------------------------------------------------------- endpoints
endpoint peer1 {
base http://192.0.2.10:8081/v1
kind remote
context 64000
priority 20
timeout 600
idle_timeout 60
cooldown 120
hook /opt/junction/hooks/check-http.sh
}
endpoint peer2 {
base http://192.0.2.10:8082/v1
kind remote
context 64000
priority 20
timeout 600
idle_timeout 60
cooldown 120
hook /opt/junction/hooks/check-http.sh
}
endpoint workstation {
base http://192.0.2.20:8080/v1
kind local
context 128000
priority 10
timeout 1800
idle_timeout 30
cooldown 60
hook_retry 180
hook_backoff 5
wake /opt/junction/hooks/wake-wol.sh
hook /opt/junction/hooks/check-http.sh
hook /opt/junction/hooks/check-budget.sh
}
endpoint opencode-go {
base https://api.example.com/v1
kind opencode-go
# A fallback, not a truth: junction reads the model limits from the endpoint's own
# model list at startup (GET /models -> limit.context / limit.output). This number
# applies only when that fetch fails or the model is missing from it.
context 200000
priority 90
timeout 900
idle_timeout 120
cache off # never store opencode-go answers
api_key_env EXAMPLE_API_KEY
# A second account is a second quota: the line may be repeated. Each attempt takes
# the next key, so a 429 on the first is answered with the second instead of giving
# the endpoint up.
# api_key_env EXAMPLE_API_KEY_2
tls_verify on # off only for a self-signed internal endpoint
# tls_ca /etc/junction/tls/internal-ca.pem
header "X-Title: olivia" # static header sent with every request here
}
# An Anthropic Messages API endpoint. `kind anthropic` keeps /v1/messages native and
# rewrites reasoning_effort/reasoning.effort/variant or a model#variant selector into
# output_config.effort. A client's anthropic-version wins over the static default.
# endpoint claude {
# base https://api.anthropic.com/v1
# kind anthropic
# context 200000
# timeout 900
# idle_timeout 120
# api_key_env ANTHROPIC_API_KEY
# header "anthropic-version: 2023-06-01"
# }
# A Claude subscription token (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.
# Without that prompt a current model answers 429 rate_limit_error "Error", which is
# indistinguishable from an exhausted quota — so the endpoint looks broken at random.
# `oauth on` puts the prompt in place and keeps the client's own system text (native
# path: as further blocks; /v1/chat/completions: as a user message before the first
# turn). Nothing is rewritten without this line. See src/oauth.c for the measurements.
# endpoint claude-abo {
# base https://api.anthropic.com/v1
# kind anthropic
# oauth on
# context 200000
# timeout 900
# idle_timeout 120
# api_key_env CLAUDE_CODE_OAUTH_TOKEN
# header "anthropic-version: 2023-06-01"
# }
# --------------------------------------------------------------------------- mcp
#
# This turns junction into an MCP server itself: an agent connects to
# http://127.0.0.1:8090/mcp and sees the tools of every server listed here, with the
# server name as prefix ("tasksd__task_create"). A dead server is skipped and the other
# tools still arrive.
#
# mcp tasksd url http://127.0.0.1:8781/mcp
# mcp skilld url http://127.0.0.1:8790/mcp header "Authorization: Bearer CHANGE_ME"
# A stdio server instead of an HTTP one is one quoted command:
# mcp local cmd "python3 /srv/mcp/filesystem.py --root /data"
# mcp_cache_ttl 60
# A virtual key is a token junction mints: the client sends it, the real upstream key
# never leaves the process. allow/endpoints restrict what the key may use; rpm and
# budget (USD per calendar month) limit what it may consume. Both optional.
# vkey "webui" token_env VKEY_WEBUI allow "deepseek-*" endpoints "opencode-go,peer1" rpm 60 budget 10
# A caller without a key is routed as before - a vkey is accounting, not a door.
# --------------------------------------------------------------------- models
# A whitelist for /v1/models and for requests. The first allow line means "deny
# everything else" -- do not also write deny "*", it would win and hide the allow
# list. deny is for exceptions to a wildcard allow. Patterns are fnmatch globs on
# the model ID. A trailing #variant is matched without it, so a model's opencode
# effort selector stays usable.
# models allow "foo" "bar" "ma/bla" "opencode-go0/*"
# models deny "*-free"
# If no target of the selected rule can hold ctx + max_tokens, retry this pool.
# Pool members should name the model they expect with "as"; the optional model
# after "as" on the directive is the default for members without their own.
# ctx_fallback ds41flash
# ctx_fallback ds41flash as "deepseek-v4.1-flash"
# ------------------------------------------------------------------------- rules
# First matching rule wins. Rules may use:
# for <model-glob> need >N | <N | N path <glob>
# check hooks|none retry <seconds>
# pass <endpoint>[,<endpoint>...] [as <model>] | block
# A client that DECLARES more output than the peers can hold goes to the big box.
# 'need' reads max_tokens from the request; there is no character counting and no
# default, so a request that states nothing is not sized by guesswork.
req need >64000 pass workstation, opencode-go
# Coding work: prefer the workstation, wake it, wait up to 5 minutes for the hooks,
# and hand it the model name it actually serves.
req for "*coder*" check hooks retry 300 pass workstation as "Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M"
req for "Qwen3.8-Flash-Next*" check hooks retry 60 pass workstation, peer1, peer2
# Cheap metadata calls never need a model at all.
req path "/v1/models" check none pass peer1, peer2, opencode-go
# A virtual model with a sampled judge: every 10th request of a conversation
# goes to the judge endpoint instead of the worker. The judge comes before
# "pass"; its model is rewritten like any other target's "as". "cache 1h" asks
# Anthropic to cache tools + system + conversation prefix (needs kind remote on
# the Anthropic OpenAI-compatible endpoint, not kind anthropic):
#
# req for "qwen-judged" balance round-robin check none \
# judge every 5 ds41flash cache off \
# judge every 10 claude-openai as "claude-opus-5-5" cache 1h \
# pass peer1 as "qwen3.8"
#
# The judge clauses form a chain: the 5th call goes to the DeepSeek pool, the
# 10th to Claude, then the counter resets to 0 (15th/20th next). Counts must be
# ascending. A pool is allowed as the judge; its members keep their own "as".
# Every response of a judged rule carries X-Junction-Judge-Next (the counter
# value), X-Junction-Judge-In (calls remaining) and X-Junction-Judge-Next-Target/
# -Model/-Step/-Every/-Cache, also on worker turns — so a client can see when
# and where the next escalation happens.
# "cache" is for Anthropic-style cache_control; DeepSeek/OpenAI-compatible
# providers cache prefixes automatically, so leave it off there.
#
# Self-review keeps the worker and hides N review rounds:
#
# req for "qwen-checked" review 2 pass peer1 as "qwen3.8"
#
# The worker's first answer plus a review instruction go back to the same model
# N times; only the last answer reaches the client. Tool-call answers pass
# through unreviewed. "review 2" means three provider calls.
#
# Limits and failure behavior (full table in README, "Judge/review limits and
# headers"): at most 4 judge steps and 12 review rounds in the config (review 13
# is a config error). A request may set its own depth with X-Junction-Review-Rounds:
# N, or X-Junction-Effort: off|low|medium|high|max (0/4/7/9/12). A round that
# repeats the answer verbatim stops the loop (converged=1). Review calls carry at
# least 4096 max_tokens; the first worker call
# keeps the client's budget. n>1, content arrays, non-empty tool_calls and a
# spent vkey budget skip the remaining rounds and deliver the original or last
# good answer; X-Junction-Review-Skipped names the reason. Judge counters are
# per conversation and per rule (model/path glob), live in RAM (4096 slots, LRU
# eviction, 1 h idle expiry, reset on restart) and reset after the last chain
# step. A failing judge falls back to the worker without its cache marker; a
# first-call provider 4xx reaches the client with its own status and body.
# Optional price table: model input cached output [offpeak=IN,OUT] [budget=USD]
# A "#variant" uses the base model's row; a "-go" name uses its own row. The
# endpoint's offpeak window is evaluated per request. Non-streaming responses then
# carry X-Junction-Tokens-In/-Out and X-Junction-Cost-Usd.
# prices /home/lotherk/stack/data/junction/prices.conf
# Anything unseen is refused rather than silently sent to the opencode-go.
req for "*" block