diff --git a/README.md b/README.md index 890ec95..2bd228b 100644 --- a/README.md +++ b/README.md @@ -179,7 +179,7 @@ The gateway refreshes Zen/Go `/v1/models` and OpenCode's [capability catalog](ht Allowed protocol values are `chat`, `responses`, and `anthropic`. Models using unsupported native protocols are filtered from discovery unless overridden. -Cost and deprecation metadata come from [models.dev](https://models.dev/api.json), refreshed every 24 hours. Metadata requests use a 30-second timeout per HTTP client. Refresh failures retain existing data. +Cost, deprecation, and model limits come from [models.dev](https://models.dev/api.json), refreshed every 24 hours. OpenCode's capability catalog remains authoritative for context and token limits; models.dev `limit.context`, `limit.input`, and `limit.output` fill fields missing from that catalog. These limits are exposed by `/v1/models` as `context_window`/`context_length`, `max_input`, and `max_output` for discovery clients such as CLIProxyAPI and Pi. Metadata requests use a 30-second timeout per HTTP client. Refresh failures retain existing data. ### Anonymous access and fallback diff --git a/internal/models/catalog.go b/internal/models/catalog.go index bac8874..8f07e79 100644 --- a/internal/models/catalog.go +++ b/internal/models/catalog.go @@ -451,12 +451,34 @@ func (c *Catalog) Supported(model string) bool { // the tier that will actually serve the request. Same-named models can carry // different limits per tier, so callers must pass route.Tier — never a // tier-blind lookup. Anonymous routes always resolve to TierZen, which keeps -// the keyless path on Zen metadata. The zero value is returned for models -// the catalog does not describe (or before the first capability refresh). +// the keyless path on Zen metadata. Limits the catalog omitted are filled from +// models.dev; capability flags always come from the catalog. The zero value is +// returned for models neither source describes (or before the first refresh). func (c *Catalog) MetadataForTier(model string, tier config.Tier) Metadata { c.mu.RLock() - defer c.mu.RUnlock() - return c.modelMeta[tier][model] + md := c.modelMeta[tier][model] + pricing := c.pricing + c.mu.RUnlock() + if pricing == nil { + return md + } + price, ok := pricing.Price(model) + if !ok { + return md + } + // OpenCode's capability catalog is authoritative. Use models.dev limits + // only to fill fields it omitted so discovery clients still get per-model + // context and output limits. + if md.ContextWindow == 0 { + md.ContextWindow = price.ContextWindow + } + if md.MaxInput == 0 { + md.MaxInput = price.MaxInput + } + if md.MaxOutput == 0 { + md.MaxOutput = price.MaxOutput + } + return md } func (c *Catalog) supportedLocked(model string) bool { diff --git a/internal/models/pricing.go b/internal/models/pricing.go index 923e581..31d777d 100644 --- a/internal/models/pricing.go +++ b/internal/models/pricing.go @@ -27,10 +27,13 @@ const ( ) type Price struct { - ID string `json:"id"` - Input *float64 `json:"input_cost,omitempty"` - Output *float64 `json:"output_cost,omitempty"` - Deprecated bool `json:"deprecated"` + ID string `json:"id"` + Input *float64 `json:"input_cost,omitempty"` + Output *float64 `json:"output_cost,omitempty"` + ContextWindow int `json:"context_window,omitempty"` + MaxInput int `json:"max_input,omitempty"` + MaxOutput int `json:"max_output,omitempty"` + Deprecated bool `json:"deprecated"` } type AnonymousDecision struct { @@ -296,6 +299,7 @@ func decodeModelsDev(data []byte) (map[string]Price, error) { } return left < right }) + result := make(map[string]Price) for _, key := range keys { if metadataProviderRank(key) > 1 { continue @@ -310,22 +314,25 @@ func decodeModelsDev(data []byte) (map[string]Price, error) { continue } } - models := jsonutil.MapAt(provider, "models") - if len(models) == 0 { - continue - } - result := make(map[string]Price, len(models)) - for id, raw := range models { + for id, raw := range jsonutil.MapAt(provider, "models") { model, _ := raw.(map[string]any) modelID := jsonutil.FirstString(jsonutil.StringAt(model, "id"), id) + // Providers are sorted with OpenCode first, so keep its metadata + // for duplicate model IDs and use other OpenCode tiers to fill gaps. + if _, exists := result[modelID]; exists { + continue + } cost := jsonutil.MapAt(model, "cost") + limit := jsonutil.MapAt(model, "limit") result[modelID] = Price{ - ID: modelID, Input: numberPointer(cost, "input"), Output: numberPointer(cost, "output"), Deprecated: metadataDeprecated(model), + ID: modelID, Input: numberPointer(cost, "input"), Output: numberPointer(cost, "output"), + ContextWindow: jsonutil.IntAt(limit, "context"), MaxInput: jsonutil.IntAt(limit, "input"), MaxOutput: jsonutil.IntAt(limit, "output"), + Deprecated: metadataDeprecated(model), } } - if len(result) > 0 { - return result, nil - } + } + if len(result) > 0 { + return result, nil } return nil, errors.New("models.dev contains no OpenCode model metadata") } diff --git a/internal/models/pricing_test.go b/internal/models/pricing_test.go new file mode 100644 index 0000000..3284d5c --- /dev/null +++ b/internal/models/pricing_test.go @@ -0,0 +1,94 @@ +package models + +import ( + "testing" + + "opencode2api/internal/config" + wire "opencode2api/internal/protocol" +) + +// models.dev publishes limits per provider. The primary OpenCode provider +// must win for duplicated model IDs, and other OpenCode tiers must still +// contribute the models they alone describe. +func TestDecodeModelsDevKeepsLimitsAndMergesTiers(t *testing.T) { + payload := []byte(`{ + "opencode": {"id":"opencode","models":{ + "shared":{"id":"shared","limit":{"context":1000,"output":100},"cost":{"input":1,"output":2}}, + "zen-only":{"id":"zen-only","limit":{"context":2000,"input":1500,"output":200}} + }}, + "opencode-go": {"id":"opencode-go","models":{ + "shared":{"id":"shared","limit":{"context":9000,"output":900},"cost":{"input":1,"output":2}}, + "go-only":{"id":"go-only","limit":{"context":4000,"output":400},"cost":{"input":0,"output":0}} + }}, + "anthropic":{"id":"anthropic","models":{"claude":{"id":"claude","limit":{"context":7}}}} + }`) + + models, err := decodeModelsDev(payload) + if err != nil { + t.Fatalf("decodeModelsDev: %v", err) + } + if _, exists := models["claude"]; exists { + t.Fatal("non-OpenCode provider leaked into the metadata") + } + + shared := models["shared"] + if shared.ContextWindow != 1000 || shared.MaxOutput != 100 { + t.Errorf("shared = ctx %d/%d, want the primary provider limits 1000/100", shared.ContextWindow, shared.MaxOutput) + } + if shared.Input == nil || *shared.Input != 1 { + t.Errorf("shared input cost = %v, want 1", shared.Input) + } + + zen := models["zen-only"] + if zen.ContextWindow != 2000 || zen.MaxInput != 1500 || zen.MaxOutput != 200 { + t.Errorf("zen-only = ctx %d, input %d, output %d; want 2000/1500/200", zen.ContextWindow, zen.MaxInput, zen.MaxOutput) + } + + goOnly, exists := models["go-only"] + if !exists { + t.Fatal("go-only model missing; tiers must be merged instead of the first provider winning alone") + } + if goOnly.ContextWindow != 4000 || goOnly.MaxOutput != 400 { + t.Errorf("go-only = ctx %d/%d, want 4000/400", goOnly.ContextWindow, goOnly.MaxOutput) + } + if models["go-only"].Output == nil || *models["go-only"].Output != 0 { + t.Errorf("go-only output cost = %v, want zero output cost preserved", models["go-only"].Output) + } +} + +// OpenCode's capability catalog stays authoritative; models.dev only fills the +// limits it omitted so discovery clients still get per-model numbers. +func TestMetadataForTierFillsMissingLimitsFromModelsDev(t *testing.T) { + catalog := NewCatalog(config.TierZen, nil) + catalog.SetPricingStore(&PricingStore{models: map[string]Price{ + "alpha": {ID: "alpha", ContextWindow: 262144, MaxOutput: 32768}, + "beta": {ID: "beta", ContextWindow: 500000, MaxInput: 400000, MaxOutput: 64000}, + }}) + catalog.ReplaceWithCapabilities( + []string{"alpha", "beta"}, + nil, + map[config.Tier]map[string]wire.Protocol{config.TierZen: {}, config.TierGo: {}}, + nil, + map[config.Tier]map[string]Metadata{config.TierZen: { + "alpha": {ContextWindow: 1000000, MaxOutput: 128000}, + "beta": {Reasoning: true}, + }}, + ) + + alpha := catalog.MetadataForTier("alpha", config.TierZen) + if alpha.ContextWindow != 1000000 || alpha.MaxOutput != 128000 { + t.Errorf("alpha = ctx %d/%d, want the catalog values 1000000/128000", alpha.ContextWindow, alpha.MaxOutput) + } + + beta := catalog.MetadataForTier("beta", config.TierZen) + if beta.ContextWindow != 500000 || beta.MaxInput != 400000 || beta.MaxOutput != 64000 { + t.Errorf("beta = ctx %d, input %d, output %d; want 500000/400000/64000", beta.ContextWindow, beta.MaxInput, beta.MaxOutput) + } + if !beta.Reasoning { + t.Error("beta lost its catalog capability flags while limits were filled") + } + + if unknown := catalog.MetadataForTier("gamma", config.TierZen); unknown.ContextWindow != 0 { + t.Errorf("gamma = ctx %d, want zero for a model no source describes", unknown.ContextWindow) + } +}