Documentation
¶
Overview ¶
Package llmproxy is muster's LLM proxy for officer instances: an Anthropic-Messages-shaped endpoint (POST /llm/v1/messages on the connect listener, internal/api) that a routine officer instance's Claude Code points ANTHROPIC_BASE_URL at, and that forwards to one provider (OpenRouter's Anthropic-compatible POST /api/v1/messages) with the officer's key.
Per request, in order: the body is read and rebuilt from an allowlist of Anthropic Messages fields (forwardBodyFields), its `model` set to the officer's pinned model (the client's is ignored); the officer's spend this UTC day is read from the store and the request refused once it reaches the daily budget; the instance's tokens on its held item are checked against the per-item cap; the request goes upstream with the key attached; the response is relayed event by event (server-sent events are flushed as each arrives); the usage and cost the provider reported in the stream are booked to the store before the response ends, so the instance's next request sees them; and one audit record and one log line are written.
The admin's chief is the one other caller (Caller.Unbudgeted): the same allowlist, pin, key handling and metering, on the one key the route layer hands it (the server's MUSTER_AGENT_OPENROUTER_KEY, internal/api), and with no budget, no item cap and no usage row — the key's own provider-side credit limit is its cap, so a 402 is answered with the caller's KeyRemedy.
🔴 THE KEY IS ATTACHED HERE AND NOWHERE ELSE. It is never logged, never audited, never sent to the client: every byte relayed downstream is passed through redact first, a 401/403 body (and a KeyRemedy caller's 402 body) is replaced by muster's own message, and every other non-2xx body is relayed redacted. The client's own credential (its muster token) is never sent upstream.
🔴 THE MODEL PIN HOLDS BECAUSE THE BODY IS AN ALLOWLIST. OpenRouter reads routing fields in the body (fallbacks, models, provider, route, plugins, transforms) that can serve a request from a model other than the pinned one. Only the Anthropic Messages fields in forwardBodyFields go upstream; every other key is dropped. Inside `messages`, a mid-conversation `system` entry (which the provider refuses) is folded into the user turn (foldSystemMessages); nothing else in a message is changed.
🔴 COST IS THE PROVIDER'S, NOT A PRICE LIST'S. OpenRouter reports what it billed in the stream (`usage.cost` in message_delta). Billed prices have run well above list prices, so only a response that carries no cost is booked from an estimate, at deliberately pessimistic rates (EstimateUSDPerInputToken, EstimateUSDPerOutputToken), and counted as estimated.
Index ¶
- Constants
- func Day(t time.Time) time.Time
- func Refuse(w http.ResponseWriter, status int, errType, msg string)
- type Caller
- type Config
- type PGStore
- type Proxy
- func (p *Proxy) Claimed(officer string, instance int, item string)
- func (p *Proxy) ClaimedAttempt(officer string, instance int, item string, attempts int)
- func (p *Proxy) Ended(officer string, instance int, item string)
- func (p *Proxy) ItemCost(officer string, instance int, item string) (float64, bool)
- func (p *Proxy) ItemCostWhy(officer string, instance int, item string) (float64, string)
- func (p *Proxy) ServeMessages(w http.ResponseWriter, r *http.Request, c Caller)
- func (p *Proxy) Sync(officer string, holding map[int][]string, at time.Time)
- type Record
- type Store
- type Usage
Constants ¶
const ( CostNotHeld = "not_held" // the instance does not hold the item (in the meter) CostAdopted = "adopted" // adopted from HQ's claimed list (a restart): requests before it are not in it CostNotFirstClaim = "not_first_claim" // HQ's second or later claim: an earlier hold may have spent on it CostAttemptsUnknown = "attempts_unknown" // the claim carried no attempts (already-yours, or an HQ without the field) CostNoRequests = "no_requests" // no request booked: no evidence, never a 0 CostEstimated = "estimated" // a request was booked from the proxy's estimate CostInFlight = "inflight" // a request admitted under the hold is not booked yet )
Why an item's cost is not known (Proxy.ItemCostWhy), each a short id for the log line officer_complete writes when it sends no cost.
const ( EstimateUSDPerInputToken = 0.60e-6 EstimateUSDPerOutputToken = 1.20e-6 )
Pessimistic $/token for a response that reported no cost. NOT list prices: they are set above the highest billed rate observed for the pinned models, so an estimate over-books rather than under-books.
const DefaultUpstream = "https://openrouter.ai/api"
DefaultUpstream is the provider's Anthropic-compatible API base; requests go to DefaultUpstream + UpstreamPath.
const (
// MaxRequestBytes bounds a request body (a long session's whole context).
MaxRequestBytes = 32 << 20
)
Limits.
const UpstreamPath = "/v1/messages"
UpstreamPath is the one provider path the proxy calls. Claude Code calls only POST /v1/messages (with ?beta=true) against its base URL, always streamed; no count_tokens or model-list call was observed. Every other path under /llm/ is refused by the route layer.
Variables ¶
This section is empty.
Functions ¶
func Refuse ¶
func Refuse(w http.ResponseWriter, status int, errType, msg string)
Refuse writes an Anthropic-shaped error, which Claude Code shows as the turn's API error.
⚠ Status choice matters to the client: Claude Code retries 429 and 5xx with backoff (and a 401 about ten times), so a refusal that must END the turn — the budget, the item cap — is a 400, never a 429.
Types ¶
type Caller ¶
type Caller struct {
// Officer labels the caller in metrics, logs and the audit detail: the
// officer id, or "chief".
Officer string
// Instance is the routine instance's number in its pool, and
// InstanceLabel how it is named in metrics and logs (`r<n>`).
Instance int
InstanceLabel string
AgentID int64
AgentName string
Model string
DailyBudgetUSD float64
MaxTokensPerItem int64
Key string
// Unbudgeted: muster enforces NO budget and NO per-item cap for this
// caller, and keeps no usage row for it (the store is neither read nor
// written); the cap is the key's own provider-side credit limit. Usage is
// still metered in the metrics, the log line and the audit record.
//
// 🔴 IT IS A SEPARATE FIELD SO THAT ZERO VALUES STAY SAFE. A budgeted
// caller (the zero value, false) whose DailyBudgetUSD is 0 is refused on
// its first request (spent 0 >= budget 0), exactly as an officer with a
// missing budget always was: "no budget" can never be spelled as a 0.
Unbudgeted bool
// Title is the X-Title header the provider attributes the request to;
// "" is "muster officer".
Title string
// KeyRemedy is what the client is told when the provider refuses the key
// (401/403), and the log line's remedy; "" is the officer's (the operator's
// MUSTER_OFFICER_OPENROUTER_KEY_<NAME>). A caller with one is also told it
// on a 402 (a spent credit limit), which is NOT counted as a refused key;
// an officer's 402 is relayed.
KeyRemedy string
}
Caller is the agent a request is made for, with its settings: an officer routine instance (budgeted), or the chief (Unbudgeted). The route layer builds it after authenticating the agent.
type Config ¶
type Config struct {
// Upstream is the provider's API base ("" is DefaultUpstream).
Upstream string
// HTTP is the upstream transport; nil is a client that follows no
// redirect.
HTTP *http.Client
// Store keeps each officer's spend. nil is a proxy with no budget store:
// it serves Unbudgeted callers only, and a budgeted caller is refused
// (refused_store, nothing sent) because its spend cannot be read — never
// served as if it had no budget.
Store Store
// Audit receives one record per request ServeMessages answers (a
// malformed body's refusal included); nil records none.
Audit func(ctx context.Context, r Record)
Logger *log.Logger
// Now is the clock; nil is time.Now.
Now func() time.Time
}
Config is New's input.
type PGStore ¶
type PGStore struct {
// contains filtered or unexported fields
}
PGStore is Store on officer_llm_usage (migration 0075), under row-level security: ctx must act as the officer's owner (the request's principal is the calling instance's owner, which is its officer's), and the row lands under that owner. Numbers only: no column can hold a prompt, a response or a key.
type Proxy ¶
type Proxy struct {
// contains filtered or unexported fields
}
Proxy is the LLM proxy.
func (*Proxy) Claimed ¶
Claimed tells the per-item meter that instance of officer now holds item, by a claim whose HQ attempts are not known (its cost is then unknown).
func (*Proxy) ClaimedAttempt ¶ added in v0.175.0
ClaimedAttempt is Claimed by the claim HQ answered with attempts (its item's `attempts`; 0 when not known): HQ's first claim (1) is the one whose hold can know the item's cost (ItemCost).
func (*Proxy) ItemCost ¶ added in v0.175.0
ItemCost is the USD instance of officer's hold on item has booked through this proxy (the provider's reported cost of each request, as the budget books it), and whether that is KNOWN to be the item's whole proxy spend: the hold is HQ's first claim of the item, claimed through muster, has booked at least one request, none from the proxy's estimate, and none still unbooked (items). Read it while the hold lasts: Ended clears it.
func (*Proxy) ItemCostWhy ¶ added in v0.175.0
ItemCostWhy is ItemCost, with why the cost is not known instead of a bool: "" when it is known, else one of the Cost* reasons.
func (*Proxy) ServeMessages ¶
ServeMessages proxies one POST /llm/v1/messages for c.
type Record ¶
type Record struct {
Officer string
Instance string // the instance's label, `r<n>`
AgentID int64
AgentName string
Item string
RequestedModel string
Model string
Provider string
MessageID string
Status int
Result string
Input int64
Output int64
CacheRead int64
CacheWrite int64
CostUSD float64
CostEstimated bool
StopReason string
Duration time.Duration
// UpstreamError is a non-2xx provider answer's error, "<type>: <message>",
// redacted and truncated by upstreamError; "" on a 2xx.
UpstreamError string
}
Record is one request's audit record. It carries no request or response body, no header and no credential; on a provider error, only the provider's error type and message (UpstreamError), redacted and truncated.
type Store ¶
type Store interface {
// SpentToday is officer's booked USD on day, over every instance.
SpentToday(ctx context.Context, officer string, day time.Time) (float64, error)
// Book adds u (one request) to its (officer, instance, day) row.
Book(ctx context.Context, u Usage) error
}
Store persists each officer's usage per instance and UTC day, so a restart does not reset a budget.