llmproxy

package
v0.222.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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.

View Source
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.

View Source
const DefaultUpstream = "https://openrouter.ai/api"

DefaultUpstream is the provider's Anthropic-compatible API base; requests go to DefaultUpstream + UpstreamPath.

View Source
const (
	// MaxRequestBytes bounds a request body (a long session's whole context).
	MaxRequestBytes = 32 << 20
)

Limits.

View Source
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 Day

func Day(t time.Time) time.Time

Day is the UTC day t falls on, as the store keys it.

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
	// Pool is the officer pool the instance is in (`routine` or
	// `judgement`): each pool has its own budget, usage rows and meter.
	Pool string
	// Instance is the instance's number in its pool, and InstanceLabel how
	// it is named in metrics and logs (`r<n>` routine, `<n>` judgement).
	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 (migrations 0075, and 0110 for its per-pool key), 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.

func NewPGStore

func NewPGStore(pool *pgxpool.Pool) *PGStore

NewPGStore is Store over pool.

func (*PGStore) Book

func (s *PGStore) Book(ctx context.Context, u Usage) error

Book implements Store: one statement, so two concurrent requests never lose a count.

func (*PGStore) SpentToday

func (s *PGStore) SpentToday(ctx context.Context, officer, pool string, day time.Time) (float64, error)

SpentToday implements Store.

type Proxy

type Proxy struct {
	// contains filtered or unexported fields
}

Proxy is the LLM proxy.

func New

func New(cfg Config) (*Proxy, error)

New builds a Proxy.

func (*Proxy) Claimed

func (p *Proxy) Claimed(officer, pool string, instance int, item string)

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

func (p *Proxy) ClaimedAttempt(officer, pool string, instance int, item string, attempts int)

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) Ended

func (p *Proxy) Ended(officer, pool string, instance int, item string)

Ended tells the per-item meter that instance of officer no longer holds item.

func (*Proxy) ItemCost added in v0.175.0

func (p *Proxy) ItemCost(officer, pool string, instance int, item string) (float64, bool)

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

func (p *Proxy) ItemCostWhy(officer, pool string, instance int, item string) (float64, string)

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

func (p *Proxy) ServeMessages(w http.ResponseWriter, r *http.Request, c Caller)

ServeMessages proxies one POST /llm/v1/messages for c.

func (*Proxy) Sync

func (p *Proxy) Sync(officer, pool string, holding map[int][]string, at time.Time)

Sync is a wake-loop pass's view of officer pool's claims, read at at: holding maps an instance number of that pool to the items HQ shows it claiming.

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.

func (Record) Detail

func (r Record) Detail() string

Detail is r as one line of key=value pairs (the audit row's detail and the log line), in a fixed order. upstream_error, quoted, ends the line when the provider answered with an error.

type Store

type Store interface {
	// SpentToday is officer pool's booked USD on day, over every instance of
	// that pool: each pool's budget is its own.
	SpentToday(ctx context.Context, officer, pool string, day time.Time) (float64, error)
	// Book adds u (one request) to its (officer, pool, 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.

type Usage

type Usage struct {
	Officer    string
	Pool       string
	Instance   int
	Day        time.Time // a UTC midnight
	Input      int64
	Output     int64
	CacheRead  int64
	CacheWrite int64
	CostUSD    float64
	Estimated  bool
}

Usage is one request's metered usage, booked to the store.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL