commandcode

package
v0.0.43 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 27 Imported by: 1 module, 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 commandcode serves an Anthropic Messages proxy backed by a Command Code subscription, so clients such as Grok CLI can use Command Code models without the `cmd` binary.

Index

Constants

View Source
const DefaultBaseURL = "https://api.commandcode.ai"

DefaultBaseURL is the production Command Code API endpoint.

View Source
const DefaultPort = 8892

DefaultPort is the loopback port for the proxy (Codex uses 8891).

View Source
const DefaultVersion = "1.53.0"

DefaultVersion is the X-Command-Code-Version sent upstream. The backend rejects requests below a minimum version, so it is overridable by flag.

Variables

View Source
var Catalog = []Model{
	{
		ID:            "deepseek/deepseek-v4-pro",
		Name:          "DeepSeek V4 Pro (latest)",
		Description:   "hybrid-attention long-context reasoning",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "deepseek/deepseek-v4-flash",
		Name:          "DeepSeek V4 Flash (latest)",
		Description:   "fast hybrid-attention reasoning (default)",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "deepseek/deepseek-v4-flash-vision-exp",
		Name:          "DeepSeek V4 Flash Vision (exp)",
		Description:   "fast hybrid-attention reasoning with vision",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "deepseek/deepseek-v4-flash-fast",
		Name:          "DeepSeek V4 Flash Fast",
		Description:   "low-latency V4 Flash deployment",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "deepseek/deepseek-v4.1-flash",
		Name:          "DeepSeek V4.1 Flash",
		Description:   "V4.1 hybrid-attention reasoning with vision",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "moonshotai/kimi-k3",
		Name:          "Kimi K3",
		Description:   "long-horizon coding & knowledge work with 1M context",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "moonshotai/kimi-k2.7-code",
		Name:          "Kimi K2.7 Code",
		Description:   "improved long-horizon coding with vision",
		Group:         "Open Source",
		ContextWindow: 256000,
	},
	{
		ID:            "moonshotai/kimi-k2.7-code-highspeed",
		Name:          "Kimi K2.7 Code HighSpeed",
		Description:   "high-speed long-horizon coding with vision",
		Group:         "Open Source",
		ContextWindow: 262000,
	},
	{
		ID:            "moonshotai/kimi-k2.6",
		Name:          "Kimi K2.6",
		Description:   "long-horizon coding with vision",
		Group:         "Open Source",
		ContextWindow: 256000,
	},
	{
		ID:            "moonshotai/kimi-k2.5",
		Name:          "Kimi K2.5",
		Description:   "multimodal frontend coding",
		Group:         "Open Source",
		ContextWindow: 256000,
	},
	{
		ID:            "z-ai/glm-5.3-flash",
		Name:          "GLM-5.3 Flash",
		Description:   "fast, affordable GLM coding with 1M context",
		Group:         "Open Source",
		ContextWindow: 1048576,
	},
	{
		ID:            "zai-org/glm-5.3",
		Name:          "GLM-5.3",
		Description:   "frontier coding with emergent cyber capabilities",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "zai-org/glm-5.2",
		Name:          "GLM-5.2",
		Description:   "powerful coding with 1M context and long-horizon tasks",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "zai-org/glm-5.2-fast",
		Name:          "GLM-5.2 Fast",
		Description:   "high-throughput GLM-5.2 with 1M context",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "zai-org/glm-5.1",
		Name:          "GLM-5.1",
		Description:   "long-horizon autonomous coding agent",
		Group:         "Open Source",
		ContextWindow: 0,
	},
	{
		ID:            "zai-org/glm-5",
		Name:          "GLM-5",
		Description:   "multi-mode thinking & long-range planning",
		Group:         "Open Source",
		ContextWindow: 200000,
	},
	{
		ID:            "minimaxai/minimax-m3",
		Name:          "MiniMax M3",
		Description:   "frontier coding, agents & native multimodality",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "minimaxai/minimax-m2.7",
		Name:          "MiniMax M2.7",
		Description:   "end-to-end software engineering agent",
		Group:         "Open Source",
		ContextWindow: 0,
	},
	{
		ID:            "minimaxai/minimax-m2.5",
		Name:          "MiniMax M2.5",
		Description:   "cross-platform full-stack agentic dev",
		Group:         "Open Source",
		ContextWindow: 200000,
	},
	{
		ID:            "xiaomi/mimo-v2.5-pro",
		Name:          "MiMo V2.5 Pro",
		Description:   "high-capability long-context agentic coding",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "xiaomi/mimo-v2.5",
		Name:          "MiMo V2.5",
		Description:   "efficient long-context agentic coding",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "qwen/qwen3.8-max-0902",
		Name:          "Qwen 3.8 Max 0902",
		Description:   "upgraded Qwen 3.8 Max: stronger coding & agentic tool use",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "qwen/qwen3.8-max",
		Name:          "Qwen 3.8 Max",
		Description:   "autonomous long-horizon coding & professional work",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "qwen/qwen3.8-27b",
		Name:          "Qwen 3.8 27B",
		Description:   "compact vision-language coding & agentic work",
		Group:         "Open Source",
		ContextWindow: 262144,
	},
	{
		ID:            "qwen/qwen3.8-flash",
		Name:          "Qwen 3.8 Flash",
		Description:   "fast low-cost agentic coding & reasoning",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "qwen/qwen3.7-max",
		Name:          "Qwen 3.7 Max",
		Description:   "frontier coding & long-horizon agent execution",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "qwen/qwen3.7-plus",
		Name:          "Qwen 3.7 Plus",
		Description:   "agentic coding & reasoning at lower cost",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "qwen/qwen3.7-flash",
		Name:          "Qwen 3.7 Flash",
		Description:   "fast low-cost agentic coding & reasoning",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "qwen/qwen3.6-max-preview",
		Name:          "Qwen 3.6 Max Preview",
		Description:   "vibe coding & efficient agent execution",
		Group:         "Open Source",
		ContextWindow: 0,
	},
	{
		ID:            "qwen/qwen3.6-plus",
		Name:          "Qwen 3.6 Plus",
		Description:   "agentic coding & reasoning",
		Group:         "Open Source",
		ContextWindow: 0,
	},
	{
		ID:            "meituan/longcat-2.0:free",
		Name:          "LongCat 2.0",
		Description:   "FREE trillion-parameter agentic coding with 1M context",
		Group:         "Open Source",
		ContextWindow: 0,
	},
	{
		ID:            "stepfun/step-3.7-flash",
		Name:          "Step 3.7 Flash",
		Description:   "multimodal sparse-MoE reasoning",
		Group:         "Open Source",
		ContextWindow: 256000,
	},
	{
		ID:            "stepfun/step-3.5-flash",
		Name:          "Step 3.5 Flash",
		Description:   "fast sparse-MoE agentic reasoning",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "tencent/hy3-paid",
		Name:          "Tencent Hy3",
		Description:   "sparse-MoE reasoning & agentic tool use",
		Group:         "Open Source",
		ContextWindow: 262144,
	},
	{
		ID:            "tencent/hy4-preview",
		Name:          "Tencent Hy4 Preview",
		Description:   "agentic coding & sustained multi-step tool use",
		Group:         "Open Source",
		ContextWindow: 1048576,
	},
	{
		ID:            "nvidia/nemotron-3-ultra-550b-a55b",
		Name:          "Nemotron 3 Ultra",
		Description:   "open reasoning model for long-horizon autonomous agents",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "thinkingmachines/inkling",
		Name:          "Inkling",
		Description:   "multimodal MoE reasoning",
		Group:         "Open Source",
		ContextWindow: 256000,
	},
	{
		ID:            "thinkingmachines/inkling-small",
		Name:          "Inkling Small",
		Description:   "lightweight MoE reasoning at lower cost and latency",
		Group:         "Open Source",
		ContextWindow: 1000000,
	},
	{
		ID:            "poolside/laguna-s-2.1-free",
		Name:          "Laguna S 2.1",
		Description:   "FREE open-weight agentic coding and long-horizon work",
		Group:         "Open Source",
		ContextWindow: 0,
	},
	{
		ID:            "inclusionai/ling-3.0-flash-sante:free",
		Name:          "Ling 3.0 Flash Sante",
		Description:   "FREE health & medicine tuned lightweight-MoE, still strong on code",
		Group:         "Open Source",
		ContextWindow: 0,
	},
	{
		ID:            "claude-sonnet-5",
		Name:          "Claude Sonnet 5",
		Description:   "best combo of speed & intelligence (recommended)",
		Group:         "Anthropic",
		ContextWindow: 1000000,
	},
	{
		ID:            "claude-sonnet-4-6",
		Name:          "Claude Sonnet 4.6",
		Description:   "prev Sonnet, still fast & capable",
		Group:         "Anthropic",
		ContextWindow: 1000000,
	},
	{
		ID:            "claude-fable-5-1",
		Name:          "Claude Fable 5.1",
		Description:   "most capable for demanding reasoning & long-horizon agents",
		Group:         "Anthropic",
		ContextWindow: 1000000,
	},
	{
		ID:            "claude-fable-5",
		Name:          "Claude Fable 5",
		Description:   "prev Fable, still strong for deep reasoning & agents",
		Group:         "Anthropic",
		ContextWindow: 1000000,
	},
	{
		ID:            "claude-opus-5",
		Name:          "Claude Opus 5",
		Description:   "most intelligent Opus for agents and coding",
		Group:         "Anthropic",
		ContextWindow: 1000000,
	},
	{
		ID:            "claude-opus-4-8",
		Name:          "Claude Opus 4.8",
		Description:   "prev flagship, still strong for agents and coding",
		Group:         "Anthropic",
		ContextWindow: 1000000,
	},
	{
		ID:            "claude-opus-4-7",
		Name:          "Claude Opus 4.7",
		Description:   "older Opus, still strong for agents and coding",
		Group:         "Anthropic",
		ContextWindow: 1000000,
	},
	{
		ID:            "claude-haiku-4-5",
		Name:          "claude-haiku-4-5",
		Description:   "fastest & most compact, great for quick tasks",
		Group:         "Anthropic",
		ContextWindow: 0,
	},
	{
		ID:            "gpt-6-astra",
		Name:          "GPT-6 Astra",
		Description:   "most capable OpenAI model for demanding reasoning & agents",
		Group:         "OpenAI",
		ContextWindow: 1050000,
	},
	{
		ID:            "gpt-5.6-sol",
		Name:          "GPT-5.6 Sol",
		Description:   "frontier model for complex professional work",
		Group:         "OpenAI",
		ContextWindow: 1050000,
	},
	{
		ID:            "gpt-5.6-terra",
		Name:          "GPT-5.6 Terra",
		Description:   "balances intelligence and cost",
		Group:         "OpenAI",
		ContextWindow: 1050000,
	},
	{
		ID:            "gpt-5.6-luna",
		Name:          "GPT-5.6 Luna",
		Description:   "optimized for cost-sensitive workloads",
		Group:         "OpenAI",
		ContextWindow: 1050000,
	},
	{
		ID:            "gpt-5.5",
		Name:          "GPT-5.5",
		Description:   "latest frontier model for general complex work",
		Group:         "OpenAI",
		ContextWindow: 400000,
	},
	{
		ID:            "gpt-5.4",
		Name:          "GPT-5.4",
		Description:   "frontier model for general complex work",
		Group:         "OpenAI",
		ContextWindow: 400000,
	},
	{
		ID:            "gpt-5.3-codex",
		Name:          "GPT-5.3 Codex",
		Description:   "frontier coding model",
		Group:         "OpenAI",
		ContextWindow: 400000,
	},
	{
		ID:            "gpt-5.4-mini",
		Name:          "GPT-5.4 Mini",
		Description:   "fast, cost-effective model for everyday tasks",
		Group:         "OpenAI",
		ContextWindow: 400000,
	},
	{
		ID:            "google/gemini-3.8-flash",
		Name:          "Gemini 3.8 Flash",
		Description:   "newest Gemini Flash, improved core reasoning",
		Group:         "Google",
		ContextWindow: 1000000,
	},
	{
		ID:            "google/gemini-3.7-flash",
		Name:          "Gemini 3.7 Flash",
		Description:   "higher-quality coding & agentic workflows, fewer tokens",
		Group:         "Google",
		ContextWindow: 1048576,
	},
	{
		ID:            "google/gemini-3.6-flash",
		Name:          "Gemini 3.6 Flash",
		Description:   "previous Gemini Flash, still fast & capable",
		Group:         "Google",
		ContextWindow: 1000000,
	},
	{
		ID:            "google/gemini-3.5-flash",
		Name:          "Gemini 3.5 Flash",
		Description:   "Pro-level coding proficiency, parallel agentic execution",
		Group:         "Google",
		ContextWindow: 1000000,
	},
	{
		ID:            "google/gemini-3.5-flash-lite",
		Name:          "Gemini 3.5 Flash Lite",
		Description:   "upgraded agentic capabilities, ideal for subagents",
		Group:         "Google",
		ContextWindow: 1000000,
	},
	{
		ID:            "google/gemini-3.1-flash-lite",
		Name:          "Gemini 3.1 Flash Lite",
		Description:   "high-volume workhorse model with implicit caching",
		Group:         "Google",
		ContextWindow: 1000000,
	},
	{
		ID:            "sakana/fugu-ultra",
		Name:          "Fugu Ultra",
		Description:   "multi-agent orchestration across frontier models",
		Group:         "Sakana",
		ContextWindow: 1000000,
	},
	{
		ID:            "meta/muse-spark-1.1",
		Name:          "Muse Spark 1.1",
		Description:   "agentic performance, tool use, and computer use",
		Group:         "Meta",
		ContextWindow: 1048576,
	},
	{
		ID:            "meta/muse-spark-1.2",
		Name:          "Muse Spark 1.2",
		Description:   "coding-optimized for agentic workflows and large codebases",
		Group:         "Meta",
		ContextWindow: 0,
	},
	{
		ID:            "meta/muse-spark-1.2-contributor",
		Name:          "Muse Spark 1.2 Contributor",
		Description:   "Muse Spark 1.2 at ~95% off",
		Group:         "Meta",
		ContextWindow: 0,
	},
	{
		ID:            "meta/muse-spark-1.3",
		Name:          "Muse Spark 1.3",
		Description:   "multimodal reasoning for long-horizon agentic and coding workflows",
		Group:         "Meta",
		ContextWindow: 1048576,
	},
	{
		ID:            "meta/muse-spark-1.3-contributor",
		Name:          "Muse Spark 1.3 Contributor",
		Description:   "Muse Spark 1.3 at up to 95% off",
		Group:         "Meta",
		ContextWindow: 1048576,
	},
	{
		ID:            "xai/grok-4.5",
		Name:          "Grok 4.5",
		Description:   "smartest model for coding, agentic tasks, knowledge work",
		Group:         "xAI",
		ContextWindow: 500000,
	},
	{
		ID:            "xai/grok-4.6",
		Name:          "Grok 4.6",
		Description:   "frontier performance on coding, knowledge work, and STEM",
		Group:         "xAI",
		ContextWindow: 500000,
	},
}

Catalog lists the models Command Code advertises for a subscription. Plan gating still applies server-side, so a listed model may be rejected.

Functions

func AuthPath

func AuthPath(home string) (string, error)

AuthPath resolves the auth.json path inside home.

func ConfigBlocks

func ConfigBlocks(endpoint string) string

ConfigBlocks renders ready-to-paste [model.*] blocks for ~/.grok/config.toml, mirroring `llm-proxy codex-models`.

func DefaultHome

func DefaultHome() string

DefaultHome is the Command Code config directory used when --commandcode-home is not given.

func ModelsV2

func ModelsV2(endpoint string) modelsV2Response

ModelsV2 builds the Grok CLI catalog. Grok requests this on resume from idle to refresh context-window metadata.

func NewHandler added in v0.0.22

func NewHandler(opts Options) (http.Handler, error)

NewHandler validates credentials and returns the Command Code HTTP handler.

func SectionName

func SectionName(id string) string

SectionName is the [model."<section>"] key for a Command Code model id.

func ServeAccounts added in v0.0.38

func ServeAccounts(w http.ResponseWriter, r *http.Request, pools []*AccountPool, liveFor time.Duration)

ServeAccounts writes per-credential quota, in-flight requests, and live sessions. eluc's AI usage page reads it, and so can any local operator. It is the multi-pool entry the config-mode proxy mounts at /v1/accounts, where one provider may own several pools.

func Start

func Start(opts Options) error

Start validates credentials and serves the proxy until the process stops.

Types

type AccountConfig added in v0.0.38

type AccountConfig struct {
	Name string
	Home string
	// Disabled parks the account without removing it. Zero means enabled, so a
	// caller that does not care about parking keeps the account routable.
	Disabled bool
	// MaxInFlight caps concurrent requests; 0 means unlimited.
	MaxInFlight int
	// Selected marks the credential the config's own "selected" flag names.
	// It is the only account used when load balancing is off.
	Selected bool
}

AccountConfig is one credential the pool may route to.

type AccountPool added in v0.0.38

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

AccountPool owns the credentials, their quotas, and their in-flight counts.

func NewAccountPool added in v0.0.38

func NewAccountPool(configs []AccountConfig, opts PoolOptions) (*AccountPool, error)

NewAccountPool builds the pool and, unless disabled, starts the refresher.

func (*AccountPool) Acquire added in v0.0.38

func (p *AccountPool) Acquire(name string) bool

Acquire reserves one in-flight slot on the named account, refusing when its concurrency cap is already reached.

func (*AccountPool) AcquireSlot added in v0.0.40

func (p *AccountPool) AcquireSlot(ctx context.Context, preferred string, exclude map[string]bool) *account

AcquireSlot picks an account and reserves a slot on it, waiting up to the pool's WaitForSlot for a busy pool to drain. A nil account means nothing can serve the request right now (quota, capacity, or every candidate excluded).

func (*AccountPool) Close added in v0.0.38

func (p *AccountPool) Close()

Close stops the refresher.

func (*AccountPool) Configure added in v0.0.40

func (p *AccountPool) Configure(accounts []AccountConfig, settings PoolSettings)

Configure reconciles the pool with the provider's current config. Accounts are matched by name: survivors keep their quota and in-flight counts, new ones start fresh, removed ones stop being routable. The session registry is untouched, so conversations keep their ids across a reload.

func (*AccountPool) Cooldown added in v0.0.38

func (p *AccountPool) Cooldown(name, reason string, d time.Duration)

Cooldown takes an account out of rotation for a while, used after a 429 or a model-permission refusal.

func (*AccountPool) HasCandidate added in v0.0.40

func (p *AccountPool) HasCandidate(preferred string, exclude map[string]bool) bool

HasCandidate reports whether any account could take a request right now.

func (*AccountPool) Len added in v0.0.38

func (p *AccountPool) Len() int

Len reports the number of accounts.

func (*AccountPool) LoadBalance added in v0.0.40

func (p *AccountPool) LoadBalance() bool

LoadBalance reports whether the pool routes across accounts.

func (*AccountPool) Names added in v0.0.38

func (p *AccountPool) Names() []string

Names lists the configured accounts in order.

func (*AccountPool) Refresh added in v0.0.38

func (p *AccountPool) Refresh(ctx context.Context)

Refresh polls every account once. A failure keeps the previous availability (a network blip must not take the pool down) but an auth failure disables the account until it is fixed.

func (*AccountPool) Registry added in v0.0.38

func (p *AccountPool) Registry() *Registry

Registry returns the session registry shared by every route that uses this pool, so one conversation keeps one id across models and the stats view sees every live session.

func (*AccountPool) Release added in v0.0.38

func (p *AccountPool) Release(name string)

Release returns an in-flight slot.

func (*AccountPool) RouteName added in v0.0.40

func (p *AccountPool) RouteName(preferred string, exclude map[string]bool) (string, bool)

RouteName reports which account would serve a request, for diagnostics and tests; the account type itself stays private.

func (*AccountPool) Select added in v0.0.38

func (p *AccountPool) Select(preferred string, exclude map[string]bool) *account

Select returns the account to serve one request: the preferred one when it is still usable, else the least busy usable account, ties broken by remaining weekly quota.

func (*AccountPool) Snapshot added in v0.0.38

func (p *AccountPool) Snapshot() []AccountStat

Snapshot copies the current state for the stats endpoint.

type AccountStat added in v0.0.38

type AccountStat struct {
	Name        string      `json:"name"`
	Home        string      `json:"home,omitempty"`
	Available   bool        `json:"available"`
	Reason      string      `json:"reason,omitempty"`
	InFlight    int         `json:"inFlight"`
	Enabled     bool        `json:"enabled"`
	MaxInFlight int         `json:"maxInFlight"`
	Selected    bool        `json:"selected"`
	Sessions    int         `json:"sessions"`
	FiveHour    WindowUsage `json:"fiveHour"`
	Weekly      WindowUsage `json:"weekly"`
	RefreshedAt time.Time   `json:"refreshedAt,omitempty"`
	LastError   string      `json:"lastError,omitempty"`
}

AccountStat is one row of the pool's public view.

type Auth

type Auth struct {
	APIKey   string
	UserID   string
	UserName string
}

Auth holds the credentials read from a Command Code home directory.

func ReadAuth

func ReadAuth(home string) (*Auth, error)

ReadAuth reads auth.json from home. It is called per request so a rotated apiKey is picked up without restarting the proxy.

type Client

type Client struct {
	BaseURL string
	// Home is the Command Code config directory holding auth.json.
	Home string
	// Version is sent as X-Command-Code-Version; the backend enforces a minimum.
	Version string
	HTTP    *http.Client
}

Client calls the Command Code /alpha/generate endpoint.

func (*Client) Generate

func (c *Client) Generate(ctx context.Context, body *alphaRequest) (*http.Response, error)

Generate posts the translated request to /alpha/generate. Credentials are read per call so a rotated apiKey is picked up without a restart.

type ContentBlock

type ContentBlock struct {
	Type string `json:"type"`

	// type=text
	Text string `json:"text"`

	// type=tool_use
	ID    string          `json:"id"`
	Name  string          `json:"name"`
	Input json.RawMessage `json:"input"`

	// type=tool_result
	ToolUseID string          `json:"tool_use_id"`
	Content   json.RawMessage `json:"content"`

	// type=thinking
	Thinking string `json:"thinking"`

	// type=image (Anthropic nests these under "source").
	Source *ImageSource `json:"source,omitempty"`

	// Prompt caching marker, forwarded verbatim on system text blocks.
	CacheControl json.RawMessage `json:"cache_control,omitempty"`
}

ContentBlock is the flat union of the Anthropic content block fields the proxy translates. Absent fields stay zero and are omitted when encoding.

type CreditSnapshot added in v0.0.38

type CreditSnapshot struct {
	FiveHour WindowUsage
	Weekly   WindowUsage
	Exceeded bool
	Reason   string
}

CreditSnapshot is what one quota refresh learned about an account.

type Digest added in v0.0.38

type Digest [32]byte

Digest is one link of a conversation's fingerprint chain.

func ChainDigests added in v0.0.38

func ChainDigests(model string, system any, messages []alphaMessage) []Digest

ChainDigests derives the conversation's fingerprint chain: one digest per user turn, each folded over the previous one, so an appended turn extends the chain instead of replacing it.

sha0  = H(model ‖ system ‖ body0 ‖ user0)
sha_i = H(sha_{i-1} ‖ body_i ‖ user_i)

A request with no user text at all falls back to a digest of everything, so two different histories can never collapse onto one key.

func (Digest) Short added in v0.0.38

func (d Digest) Short() string

String renders a digest for logs.

func (Digest) String added in v0.0.38

func (d Digest) String() string

type ImageSource

type ImageSource struct {
	Type      string `json:"type"`
	MediaType string `json:"media_type"`
	Data      string `json:"data"`
}

ImageSource is the Anthropic base64 image payload.

type MatchInfo added in v0.0.38

type MatchInfo struct {
	// Created is true when a new session id was allocated.
	Created bool
	// Forked is true when the chain shared a prefix with an existing session
	// but diverged, so it is a branch rather than a continuation.
	Forked bool
	// Parent is the longest-prefix session when Forked.
	Parent *Session
	// Matched is how many retained digests lined up.
	Matched int
}

MatchInfo describes how a chain resolved to a session.

type Message

type Message struct {
	Role    string          `json:"role"`
	Content json.RawMessage `json:"content"`
}

Message is one Anthropic message; Content is a plain string or an array of content blocks.

type MessagesRequest

type MessagesRequest struct {
	Model     string          `json:"model"`
	MaxTokens int             `json:"max_tokens"`
	System    json.RawMessage `json:"system"`
	Messages  []Message       `json:"messages"`
	Tools     []Tool          `json:"tools"`
	Stream    bool            `json:"stream"`
	// Thinking is Grok/Anthropic thinking config. Command Code always reasons
	// for models that support it; the proxy only reads display=summarized so it
	// can coalesce token-level reasoning and text deltas.
	Thinking json.RawMessage `json:"thinking"`
	// OutputConfig carries Grok/Anthropic effort. When --model-capability
	// effort-mapping is set for the request model, Effort is mapped onto
	// params.reasoning_effort.
	OutputConfig outputConfig `json:"output_config"`
}

MessagesRequest is the subset of the Anthropic Messages request the proxy consumes.

type Model

type Model struct {
	// ID is the id sent as params.model (e.g. "deepseek/deepseek-v4-flash").
	ID string
	// Name is a human-readable display name.
	Name string
	// Description is the one-line description shown by `cmd --list-models`.
	Description string
	// Group is the catalog section (e.g. "Open Source", "Anthropic").
	Group string
	// ContextWindow is 0 when the catalog does not advertise one.
	ContextWindow uint64
}

Model describes one Command Code subscription model.

type Options

type Options struct {
	// Home is the Command Code config dir holding auth.json.
	Home string
	// Version is sent as X-Command-Code-Version.
	Version string
	// BaseURL overrides the Command Code API base (default DefaultBaseURL).
	BaseURL string
	// Port is the loopback listen port (default DefaultPort).
	Port int
	// Endpoint is the public catalog base URL. It defaults from Port when empty.
	Endpoint string
	// Verbose logs every proxied request.
	Verbose bool
	// HTTP is the client used for upstream calls.
	HTTP *http.Client
	// Logger receives full request logs when set.
	Logger *logutil.Logger
	// NoCoalesceThinking flushes every Command Code reasoning-delta and
	// text-delta, even when the client sent thinking.display=summarized.
	NoCoalesceThinking bool
	// EffortByModel maps client model id -> (client effort -> Command Code
	// reasoning_effort). Values of "drop" omit the upstream field. A missing
	// model or missing client effort leaves today's behavior (no field).
	EffortByModel map[string]map[string]string
	// AdjustUsageForDSH, keyed by client model id, rewrites Anthropic
	// input_tokens to the uncached miss so DSH cache-hit % is disjoint.
	AdjustUsageForDSH map[string]bool
	// Accounts is the credential pool. When empty, Home becomes a single
	// account so the legacy single-credential flags keep working.
	Accounts []AccountConfig
	// Pool injects an already-built pool, so every model route of one provider
	// shares quotas, in-flight counts, and sessions.
	Pool *AccountPool
	// SessionWindow is how many recent turn digests a session remembers.
	SessionWindow int
	// SessionTTL drops conversations idle longer than this.
	SessionTTL time.Duration
	// LiveSessionFor bounds the sessions the stats endpoint reports.
	LiveSessionFor time.Duration
	// RefreshEvery is the quota refresh interval.
	RefreshEvery time.Duration
}

Options configures the Command Code proxy.

type PoolOptions added in v0.0.38

type PoolOptions struct {
	BaseURL      string
	Version      string
	HTTP         *http.Client
	RefreshEvery time.Duration
	Now          func() time.Time
	Fetch        UsageFetcher
	// DisableRefresh keeps the pool static; tests use it with an explicit Fetch.
	DisableRefresh bool
	// SessionWindow and SessionTTL configure the shared session registry.
	SessionWindow int
	SessionTTL    time.Duration
	// Settings are the provider-level knobs (load balance, refresh interval).
	Settings PoolSettings
	// WaitForSlot bounds how long a request waits for a free concurrency slot.
	WaitForSlot time.Duration
	// LiveSessionFor bounds the sessions reported as live.
	LiveSessionFor time.Duration
}

PoolOptions configures an AccountPool.

type PoolSettings added in v0.0.40

type PoolSettings struct {
	// LoadBalance routes across accounts and allows failover. When false only
	// the selected account serves requests.
	LoadBalance bool
	// Selected names the account used when LoadBalance is off.
	Selected string
	// RefreshEvery overrides the quota poll interval.
	RefreshEvery time.Duration
}

PoolSettings are the provider-level knobs the config file controls.

type Registry added in v0.0.38

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

Registry maps fingerprint chains to sessions. It is the only mutable routing state: one lock covers match, append, and account binding, so two concurrent first requests of the same conversation cannot create two sessions.

func NewRegistry added in v0.0.38

func NewRegistry(options RegistryOptions) *Registry

NewRegistry builds an empty registry.

func (*Registry) AccountOf added in v0.0.38

func (r *Registry) AccountOf(sessionID string) string

AccountOf reports the credential currently bound to a session.

func (*Registry) Acquire added in v0.0.38

func (r *Registry) Acquire(sessionID string)

Acquire marks one in-flight request on the session.

func (*Registry) Len added in v0.0.38

func (r *Registry) Len() int

Len reports the number of tracked sessions.

func (*Registry) MatchOrCreate added in v0.0.38

func (r *Registry) MatchOrCreate(chain []Digest) (*Session, MatchInfo)

MatchOrCreate resolves a chain to a session. The chain is computed outside the lock; everything that mutates state happens inside it.

func (*Registry) Release added in v0.0.38

func (r *Registry) Release(sessionID string)

Release clears one in-flight request.

func (*Registry) SetAccount added in v0.0.38

func (r *Registry) SetAccount(sessionID, account string)

SetAccount binds a session to the credential that serves it.

func (*Registry) Snapshot added in v0.0.38

func (r *Registry) Snapshot(liveFor time.Duration) []SessionStat

Snapshot lists sessions seen within liveFor.

type RegistryOptions added in v0.0.38

type RegistryOptions struct {
	// Window is how many recent digests each session remembers (default 10).
	Window int
	// Max caps the number of sessions (default 2000).
	Max int
	// TTL drops sessions idle longer than this (default 60m).
	TTL time.Duration
	Now func() time.Time
	// NewID allocates a session id; it defaults to a random UUID.
	NewID func() (string, error)
}

RegistryOptions configures a Registry.

type Session added in v0.0.38

type Session struct {
	// ID is the threadId sent upstream. It is allocated, not content-derived.
	ID string
	// Account is the credential currently serving the conversation.
	Account string
	// contains filtered or unexported fields
}

Session is one conversation the proxy has routed.

func (*Session) InFlight added in v0.0.38

func (s *Session) InFlight() int

InFlight reports the requests currently streaming for this session.

func (*Session) LastSeen added in v0.0.38

func (s *Session) LastSeen() time.Time

LastSeen reports when the session last carried a request.

type SessionStat added in v0.0.38

type SessionStat struct {
	ID       string
	Account  string
	InFlight int
	LastSeen time.Time
}

SessionStat is one row of the live session view.

type Tool

type Tool struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	InputSchema json.RawMessage `json:"input_schema"`
}

Tool is an Anthropic tool definition. Command Code accepts the same shape, so input_schema is forwarded verbatim.

type Turn added in v0.0.38

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

Turn is one user turn: the messages that led up to it plus its user text. The chain hashes the previous digest, this body, then the user text.

func SplitTurns added in v0.0.38

func SplitTurns(messages []alphaMessage) []Turn

SplitTurns groups messages into user turns. A turn starts at a user message that carries at least one text block; its body is everything between the previous user text and this one, so tool calls and tool results stay inside the turn they belong to. Messages after the last user text are not part of any turn: they grow while an agent works through tool calls and must not move the fingerprint.

type UsageFetcher added in v0.0.38

type UsageFetcher func(ctx context.Context, home string) (*CreditSnapshot, error)

UsageFetcher reads an account's quota. Tests replace it.

func FetchCredits added in v0.0.38

func FetchCredits(baseURL string) UsageFetcher

FetchCredits is the production fetcher. It reuses agent-pro's Command Code client, so the proxy and eluc read quota through exactly the same code.

type WindowUsage added in v0.0.38

type WindowUsage struct {
	Used     float64
	Cap      float64
	ResetAt  time.Time
	Exceeded bool
}

WindowUsage is one rate-limit window as the usage endpoint reports it.

func (WindowUsage) Remaining added in v0.0.38

func (w WindowUsage) Remaining() float64

Remaining is the unused fraction of the window, used to break ties between equally busy accounts.

Jump to

Keyboard shortcuts

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