catalogs

package
v0.16.5 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: AGPL-3.0 Imports: 31 Imported by: 0

README

catalogs

Package catalogs provides a unified catalog abstraction with pluggable storage backends for managing AI model information.

catalogs

import "github.com/agentstation/starmap/pkg/catalogs"

Package catalogs defines Starmap's authored-model and provider-serving construction records plus its immutable canonical read model. Advanced producers use Builder to load or assemble those records, then Build validates and derives definitions, provider offerings, and author membership into a concrete Catalog. Ordinary consumers retain and share that immutable Catalog.

Example usage:

// Advanced producers construct a draft, then publish an immutable catalog.
builder, err := New(WithFS(os.DirFS("./catalog")))
if err != nil {
    log.Fatal(err)
}
catalog, err := builder.Build()
if err != nil {
    log.Fatal(err)
}

// Access canonical model definitions
for _, model := range catalog.Definitions() {
    fmt.Printf("Model: %s\n", model.ID)
}

// Create a file-based draft (development use)
builder, err = New(WithFiles("./catalog"))
if err != nil {
    log.Fatal(err)
}
Example

Example shows advanced catalog construction and publication.

package main

import (
	"fmt"
	"log"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func main() {
	// Create a memory-based draft.
	builder := catalogs.NewEmpty()

	if err := builder.SetAuthor(catalogs.Author{ID: "openai", Name: "OpenAI"}); err != nil {
		log.Fatal(err)
	}
	if err := builder.SetAuthorModel("openai", catalogs.Model{
		ID: "gpt-4", Name: "GPT-4", Description: "Advanced language model",
		Authors: []catalogs.Author{{ID: "openai", Name: "OpenAI"}},
	}); err != nil {
		log.Fatal(err)
	}

	// Add the provider offering and join it to the canonical definition.
	provider := catalogs.Provider{
		ID:   "openai",
		Name: "OpenAI",
		Models: map[string]*catalogs.Model{
			"gpt-4": {
				ID:          "gpt-4",
				ModelRef:    "openai/gpt-4",
				Name:        "GPT-4",
				Description: "Advanced language model",
			},
		},
	}
	if err := builder.SetProvider(provider); err != nil {
		log.Fatal(err)
	}
	catalog, err := builder.Build()
	if err != nil {
		log.Fatal(err)
	}

	// List all models
	models := catalog.Definitions()
	fmt.Printf("Found %d models\n", len(models))
}
Output
Found 1 models

Example (Catalog Copy)

Example_catalogCopy shows creating independent copies.

package main

import (
	"fmt"
	"log"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func main() {
	// Create original catalog
	original := catalogs.NewEmpty()
	provider := catalogs.Provider{
		ID:   "test",
		Name: "Test Provider",
		Models: map[string]*catalogs.Model{
			"model-1": {
				ID:   "model-1",
				Name: "Original Model",
			},
		},
	}
	_ = original.SetProvider(provider)

	// Create a copy
	copy, err := original.Copy()
	if err != nil {
		log.Fatal(err)
	}

	// Modify the copy by updating the provider
	copiedProvider, _ := copy.Provider("test")
	if copiedProvider.Models == nil {
		copiedProvider.Models = make(map[string]*catalogs.Model)
	}
	copiedProvider.Models["model-2"] = &catalogs.Model{
		ID:   "model-2",
		Name: "Copy Model",
	}
	_ = copy.SetProvider(copiedProvider)

	originalModels, _ := original.ProviderModels("test")
	copyModels, _ := copy.ProviderModels("test")
	fmt.Printf("Original has %d models\n", len(originalModels.List()))
	fmt.Printf("Copy has %d models\n", len(copyModels.List()))
}
Output
Original has 1 models
Copy has 2 models

Example (Concurrent Access)

Example_concurrentAccess shows thread-safe concurrent usage.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/agentstation/starmap/pkg/catalogs"
	"github.com/agentstation/starmap/pkg/catalogs/internal/resourcepolicy"
)

func main() {
	catalog := catalogs.NewEmpty()
	ctx, cancel := context.WithTimeout(context.Background(), resourcepolicy.DefaultHTTPTimeout)
	defer cancel()

	// Safe for concurrent reads and writes
	done := make(chan bool, 2)

	// Writer goroutine
	go func() {
		provider := catalogs.Provider{
			ID:     "test-provider",
			Name:   "Test Provider",
			Models: make(map[string]*catalogs.Model),
		}
		for i := range 100 {
			provider.Models[fmt.Sprintf("model-%d", i)] = &catalogs.Model{
				ID:   fmt.Sprintf("model-%d", i),
				Name: fmt.Sprintf("Model %d", i),
			}
		}
		_ = catalog.SetProvider(provider)
		done <- true
	}()

	// Reader goroutine
	go func() {
		for {
			select {
			case <-ctx.Done():
				done <- true
				return
			default:
				models, _ := catalog.ProviderModels("test-provider")
				if models != nil {
					_ = models.List()
				}
				time.Sleep(10 * time.Millisecond)
			}
		}
	}()

	// Wait for both
	<-done
	<-done

	models, _ := catalog.ProviderModels("test-provider")
	fmt.Printf("Created %d models concurrently\n", len(models.List()))
}

Example (Embedded Catalog)

Example_embeddedCatalog shows using the embedded catalog.

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func embeddedBuilder() (*catalogs.Builder, error) {
	return catalogs.New(catalogs.WithFS(os.DirFS("../../internal/embedded/catalog")))
}

func main() {
	// Load embedded data into a builder, then publish it.
	builder, err := embeddedBuilder()
	if err != nil {
		log.Fatal(err)
	}
	catalog, err := builder.Build()
	if err != nil {
		log.Fatal(err)
	}

	// Access pre-loaded models
	models := catalog.Definitions()
	fmt.Printf("Embedded catalog has %d+ models\n", len(models))

	// Find a specific model
	model, err := catalog.FindModel("gpt-4o")
	if err == nil {
		fmt.Printf("Found model: %s\n", model.Name)
	}
}

Example (File Based Catalog)

Example_fileBasedCatalog shows file-based persistence.

package main

import (
	"fmt"
	"log"
	"path/filepath"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func main() {
	// Create a file-based builder.
	catalogPath := filepath.Join(".", "my-catalog")
	builder, err := catalogs.New(
		catalogs.WithPath(catalogPath),
		catalogs.WithWritePath(catalogPath),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Add and save data
	provider := catalogs.Provider{
		ID:   "custom",
		Name: "Custom Provider",
		Models: map[string]*catalogs.Model{
			"custom-model": {
				ID:   "custom-model",
				Name: "My Custom Model",
			},
		},
	}
	if err := builder.SetProvider(provider); err != nil {
		log.Fatal(err)
	}

	fmt.Println("Catalog saved to disk")
}

Example (Merge Catalogs)

Example_mergeCatalogs shows merging two catalogs.

package main

import (
	"fmt"
	"log"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func main() {
	// Create base catalog
	base := catalogs.NewEmpty()
	baseProvider := catalogs.Provider{
		ID:   "test",
		Name: "Test Provider",
		Models: map[string]*catalogs.Model{
			"model-1": {
				ID:          "model-1",
				Name:        "Model One",
				Description: "Original description",
			},
		},
	}
	_ = base.SetProvider(baseProvider)

	// Create updates catalog
	updates := catalogs.NewEmpty()
	updateProvider := catalogs.Provider{
		ID:   "test",
		Name: "Test Provider",
		Models: map[string]*catalogs.Model{
			"model-1": {
				ID:          "model-1",
				Name:        "Model One Enhanced",
				Description: "Updated description",
				Pricing: &catalogs.ModelPricing{
					Tokens: &catalogs.ModelTokenPricing{
						Input: &catalogs.ModelTokenCost{
							Per1M: 2.0, // $2 per 1M tokens
						},
						Output: &catalogs.ModelTokenCost{
							Per1M: 4.0, // $4 per 1M tokens
						},
					},
					Currency: "USD",
				},
			},
		},
	}
	_ = updates.SetProvider(updateProvider)

	// Merge with EnrichEmpty strategy (default)
	if err := base.MergeWith(updates); err != nil {
		log.Fatal(err)
	}

	model, _ := base.ProviderModel("test", "model-1")
	fmt.Printf("Model name: %s\n", model.Name)
}
Output
Model name: Model One Enhanced

Example (Merge Strategies)

Example_mergeStrategies shows different merge strategies.

package main

import (
	"fmt"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func main() {
	base := catalogs.NewEmpty()
	baseProvider := catalogs.Provider{
		ID:   "test",
		Name: "Test",
		Models: map[string]*catalogs.Model{
			"m1": {ID: "m1", Name: "Original"},
		},
	}
	_ = base.SetProvider(baseProvider)

	updates := catalogs.NewEmpty()
	updateProvider := catalogs.Provider{
		ID:   "test",
		Name: "Test",
		Models: map[string]*catalogs.Model{
			"m1": {ID: "m1", Name: "Updated"},
			"m2": {ID: "m2", Name: "New"},
		},
	}
	_ = updates.SetProvider(updateProvider)

	// Example 1: Append only (keeps existing, adds new)
	cat1, _ := base.Copy()
	cat1.MergeWith(updates, catalogs.WithStrategy(catalogs.MergeAppendOnly))

	m1, _ := cat1.ProviderModel("test", "m1")
	fmt.Printf("AppendOnly - m1: %s\n", m1.Name) // Original

	// Example 2: Replace all
	cat2, _ := base.Copy()
	cat2.MergeWith(updates, catalogs.WithStrategy(catalogs.MergeReplaceAll))

	m1, _ = cat2.ProviderModel("test", "m1")
	fmt.Printf("ReplaceAll - m1: %s\n", m1.Name) // Updated

	// Example 3: Enrich empty (smart merge)
	cat3, _ := base.Copy()
	cat3.MergeWith(updates, catalogs.WithStrategy(catalogs.MergeEnrichEmpty))

	m1, _ = cat3.ProviderModel("test", "m1")
	fmt.Printf("EnrichEmpty - m1: %s\n", m1.Name) // Updated
}

Example (Model Filtering)

Example_modelFiltering shows filtering models.

package main

import (
	"fmt"
	"os"
	"slices"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func embeddedBuilder() (*catalogs.Builder, error) {
	return catalogs.New(catalogs.WithFS(os.DirFS("../../internal/embedded/catalog")))
}

func main() {
	builder, _ := embeddedBuilder()
	catalog, _ := builder.Build()

	// Filter immutable provider-independent definitions.
	var gptModels []catalogs.ModelDefinition
	for _, model := range catalog.Definitions() {
		if len(model.ID) > 3 && model.ID[:3] == "gpt" {
			gptModels = append(gptModels, model)
		}
	}
	fmt.Printf("Found %d GPT models\n", len(gptModels))

	// Filter by features
	var visionModels []catalogs.ModelDefinition
	for _, model := range catalog.Definitions() {
		if model.Capabilities.Features != nil &&
			slices.Contains(model.Capabilities.Features.Modalities.Input, "image") {
			visionModels = append(visionModels, model)
		}
	}
	fmt.Printf("Found %d models with vision\n", len(visionModels))
}

Example (Provider Capabilities)

Example_providerCapabilities shows working with provider features.

package main

import (
	"fmt"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func main() {
	catalog := catalogs.NewEmpty()

	// Add provider with capabilities
	provider := catalogs.Provider{
		ID:   "openai",
		Name: "OpenAI",
		Credentials: &catalogs.ProviderCredentials{
			Fields: []catalogs.ProviderCredentialField{{
				ID: "api-key", Kind: catalogs.ProviderCredentialFieldSecret, Required: true,
				Environment: []string{"OPENAI_API_KEY"},
			}},
			Profiles: []catalogs.ProviderCredentialProfile{{
				ID: "api-key", Primitive: catalogs.ProviderAuthenticationAPIKey,
				Fields: []catalogs.ProviderCredentialFieldID{"api-key"},
			}},
			CatalogAcquisition: catalogs.ProviderCredentialPlane{
				Required: true, Alternatives: []catalogs.ProviderCredentialProfileID{"api-key"},
			},
		},
		Catalog: &catalogs.ProviderCatalog{
			Endpoint: catalogs.ProviderEndpoint{
				Type: catalogs.EndpointTypeOpenAI,
				URL:  "https://api.openai.com/v1/models",
				ProtocolOptions: catalogs.ProviderCatalogProtocolOptions{OpenAI: &catalogs.ProviderOpenAICatalogProtocolOptions{
					TokenPriceUnit: catalogs.ProviderTokenPriceUnitPerMillion,
				}},
			},
		},
	}
	_ = catalog.SetProvider(provider)

	// Check capabilities
	p, _ := catalog.Provider("openai")
	if p.IsCatalogAuthRequired() {
		fmt.Println("Provider requires catalog credentials")
	}
}

Index

Constants

const (
    // CurrentGenerationManifestVersion is the manifest envelope version emitted
    // by this release. It is intentionally independent of the Starmap binary
    // version and the catalog payload schema version.
    CurrentGenerationManifestVersion uint64 = 2

    // CurrentCatalogSchemaVersion identifies the canonical catalog payload
    // schema emitted by this release.
    CurrentCatalogSchemaVersion uint64 = 6

    // CatalogPayloadMediaType identifies the canonical JSON catalog payload.
    CatalogPayloadMediaType = "application/vnd.agentstation.starmap.catalog+json"
)

CurrentBootstrapManifestVersion is the embedded-bootstrap metadata format.

const CurrentBootstrapManifestVersion uint64 = 2

func CatalogSemanticChecksum

func CatalogSemanticChecksum(reader Reader) (string, error)

CatalogSemanticChecksum returns the stable SHA-256 identity of catalog facts. It excludes provenance and observation evidence. EncodeCatalogPayload remains the exact integrity representation for storage, transport, and audit.

func DeepCopyProviderModels

func DeepCopyProviderModels(models map[string]*Model) map[string]*Model

DeepCopyProviderModels creates a deep copy of a provider's Models map. Returns nil if the input map is nil.

func DerivedCredentialEnvironmentName

func DerivedCredentialEnvironmentName(product string, providerID ProviderID, fieldID ProviderCredentialFieldID) (string, error)

DerivedCredentialEnvironmentName derives a product-specific ambient name. It validates all components before it replaces ID separators with underscores.

func EncodeCatalogPayload

func EncodeCatalogPayload(reader Reader) ([]byte, error)

EncodeCatalogPayload deterministically encodes a readable catalog.

func IsMediaOperation

func IsMediaOperation(operation ProviderOperation) bool

IsMediaOperation reports whether an operation names a dedicated media path.

func NormalizeExtensionFields

func NormalizeExtensionFields(fields map[string]any) map[string]any

NormalizeExtensionFields returns a copy with maps, slices, and numbers normalized to stable dynamic types after JSON/YAML round trips.

func ShallowCopyProviderModels

func ShallowCopyProviderModels(models map[string]*Model) map[string]*Model

ShallowCopyProviderModels copies a provider's Models map while sharing its Model pointers. It returns nil for a nil input map.

func ValidateReviewCandidates

func ValidateReviewCandidates(candidates []evidence.ReviewCandidate, observations []SourceObservationLink) error

ValidateReviewCandidates verifies durable review candidates against the exact source observations that supplied their evidence.

type ArchitectureType

ArchitectureType represents the type of model architecture.

type ArchitectureType string

Architecture types.

const (
    ArchitectureTypeTransformer ArchitectureType = "transformer"
    ArchitectureTypeMoE         ArchitectureType = "moe"
    ArchitectureTypeCNN         ArchitectureType = "cnn"
    ArchitectureTypeRNN         ArchitectureType = "rnn"
    ArchitectureTypeLSTM        ArchitectureType = "lstm"
    ArchitectureTypeGRU         ArchitectureType = "gru"
    ArchitectureTypeVAE         ArchitectureType = "vae"
    ArchitectureTypeGAN         ArchitectureType = "gan"
    ArchitectureTypeDiffusion   ArchitectureType = "diffusion"
)

func (ArchitectureType) String
func (at ArchitectureType) String() string

String returns text for ArchitectureType.

type Author

Author represents a known model author or organization.

type Author struct {
    ID          AuthorID   `json:"id" yaml:"id"`
    Aliases     []AuthorID `json:"aliases,omitempty" yaml:"aliases,omitempty"`
    Name        string     `json:"name" yaml:"name"` // Display name of the author
    Description *string    `json:"description,omitempty" yaml:"description,omitempty"`

    // Company/organization info
    Headquarters *string `json:"headquarters,omitempty" yaml:"headquarters,omitempty"` // Company headquarters location
    IconURL      *string `json:"icon_url,omitempty" yaml:"icon_url,omitempty"`         // Author icon/logo URL

    // Logo holds the author's SVG brand mark. The bytes travel in the JSON
    // catalog payload but stay out of authors.yaml. On a filesystem catalog
    // they live in the authors/<id>/logo.svg sidecar file.
    Logo []byte `json:"logo_svg,omitempty" yaml:"-"`

    // Website, social links, and other relevant URLs
    Website     *string `json:"website,omitempty" yaml:"website,omitempty"`         // Official website URL
    HuggingFace *string `json:"huggingface,omitempty" yaml:"huggingface,omitempty"` // Hugging Face profile/organization URL
    GitHub      *string `json:"github,omitempty" yaml:"github,omitempty"`           // GitHub profile/organization URL
    Twitter     *string `json:"twitter,omitempty" yaml:"twitter,omitempty"`         // X (formerly Twitter) profile URL

    // Catalog contains attribution rules used to derive author membership from
    // canonical provider model records.
    Catalog *AuthorCatalog `json:"catalog,omitempty" yaml:"catalog,omitempty"`

    // Timestamps for record keeping and auditing
    CreatedAt utc.Time `json:"created_at" yaml:"created_at"` // Created date (YYYY-MM or YYYY-MM-DD format)
    UpdatedAt utc.Time `json:"updated_at" yaml:"updated_at"` // Last updated date (YYYY-MM or YYYY-MM-DD format)
}

func DeepCopyAuthor
func DeepCopyAuthor(author Author) Author

DeepCopyAuthor creates a deep copy of an Author.

func DeepCopyAuthors
func DeepCopyAuthors(authors []Author) []Author

DeepCopyAuthors creates a deep copy of an Author slice.

type AuthorAttribution

AuthorAttribution defines how to identify an author's models across providers. Uses standard Go glob pattern syntax for case-insensitive model ID matching.

Supports three modes:

  1. Provider-only: provider_id set, no patterns - all models from that provider belong to this author
  2. Provider + patterns: provider_id + patterns - only matching models from that provider, then cross-provider attribution
  3. Global patterns: patterns only - direct case-insensitive pattern matching across all providers

Glob pattern syntax is case-insensitive:

  • "*" matches any character sequence except path separators.
  • "?" matches one character.
  • "[abc]" matches one listed character.
  • "[a-z]" matches one character in the range.

Examples:

"llama*" matches llama-3, Llama3.1-8b, LLAMA-BIG
"*-llama-*" matches deepseek-r1-distill-llama-70b, DeepSeek-R1-Distill-LLAMA-70B
"gpt-*" matches gpt-4, GPT-3.5-turbo, Gpt-4o
type AuthorAttribution struct {
    ProviderID ProviderID `json:"provider_id,omitempty" yaml:"provider_id,omitempty"` // Optional provider to source models from
    Patterns   []string   `json:"patterns,omitempty" yaml:"patterns,omitempty"`       // Glob patterns to match model IDs
}

type AuthorCatalog

AuthorCatalog represents the relationship between an author and their authoritative provider catalog. This contains the attribution configuration for identifying the author's models across providers.

type AuthorCatalog struct {
    Description *string            `json:"description,omitempty" yaml:"description,omitempty"`
    Attribution *AuthorAttribution `json:"attribution,omitempty" yaml:"attribution,omitempty"` // Model attribution configuration for multi-provider inference
}

type AuthorID

AuthorID is a unique identifier for an author.

type AuthorID string

Author ID constants for compile-time safety and consistency.

const (
    // Major AI Companies.
    AuthorIDOpenAI    AuthorID = "openai"
    AuthorIDAnthropic AuthorID = "anthropic"
    AuthorIDGoogle    AuthorID = "google"
    AuthorIDDeepMind  AuthorID = "deepmind"
    AuthorIDMeta      AuthorID = "meta"
    AuthorIDMicrosoft AuthorID = "microsoft"
    AuthorIDMistralAI AuthorID = "mistral"
    AuthorIDCohere    AuthorID = "cohere"
    // AuthorIDCerebras removed - Cerebras is an inference provider, not a model creator.
    AuthorIDGroq AuthorID = "groq"
    AuthorIDQwen AuthorID = "qwen"
    AuthorIDXAI  AuthorID = "xai"

    // Research Institutions.
    AuthorIDStanford    AuthorID = "stanford"
    AuthorIDMIT         AuthorID = "mit"
    AuthorIDCMU         AuthorID = "cmu"
    AuthorIDUCBerkeley  AuthorID = "uc-berkeley"
    AuthorIDCornell     AuthorID = "cornell"
    AuthorIDPrinceton   AuthorID = "princeton"
    AuthorIDHarvard     AuthorID = "harvard"
    AuthorIDOxford      AuthorID = "oxford"
    AuthorIDCambridge   AuthorID = "cambridge"
    AuthorIDETHZurich   AuthorID = "eth-zurich"
    AuthorIDUWashington AuthorID = "uw"
    AuthorIDUChicago    AuthorID = "uchicago"
    AuthorIDYale        AuthorID = "yale"
    AuthorIDDuke        AuthorID = "duke"
    AuthorIDCaltech     AuthorID = "caltech"

    // Open Source Communities & Platforms.
    AuthorIDHuggingFace AuthorID = "huggingface"
    AuthorIDEleutherAI  AuthorID = "eleutherai"
    AuthorIDTogether    AuthorID = "together"
    AuthorIDMosaicML    AuthorID = "mosaicml"
    AuthorIDStabilityAI AuthorID = "stability"
    AuthorIDRunwayML    AuthorID = "runway"
    AuthorIDMidjourney  AuthorID = "midjourney"
    AuthorIDLAION       AuthorID = "laion"
    AuthorIDBigScience  AuthorID = "bigscience"
    AuthorIDAlignmentRC AuthorID = "alignment-research"
    AuthorIDH2OAI       AuthorID = "h2o.ai"
    AuthorIDMoxin       AuthorID = "moxin"

    // Chinese Organizations.
    AuthorIDBaidu      AuthorID = "baidu"
    AuthorIDTencent    AuthorID = "tencent"
    AuthorIDByteDance  AuthorID = "bytedance"
    AuthorIDDeepSeek   AuthorID = "deepseek"
    AuthorIDBAAI       AuthorID = "baai"
    AuthorID01AI       AuthorID = "01.ai"
    AuthorIDBaichuan   AuthorID = "baichuan"
    AuthorIDMiniMax    AuthorID = "minimax"
    AuthorIDMoonshot   AuthorID = "moonshot-ai"
    AuthorIDShanghaiAI AuthorID = "shanghai-ai-lab"
    AuthorIDZhipuAI    AuthorID = "zhipu-ai"
    AuthorIDSenseTime  AuthorID = "sensetime"
    AuthorIDHuawei     AuthorID = "huawei"
    AuthorIDTsinghua   AuthorID = "tsinghua"
    AuthorIDPeking     AuthorID = "peking"

    // Other Notable Organizations.
    AuthorIDNVIDIA     AuthorID = "nvidia"
    AuthorIDSalesforce AuthorID = "salesforce"
    AuthorIDIBM        AuthorID = "ibm"
    AuthorIDApple      AuthorID = "apple"
    AuthorIDAmazon     AuthorID = "amazon"
    AuthorIDAdept      AuthorID = "adept"
    AuthorIDAI21       AuthorID = "ai21"
    AuthorIDInflection AuthorID = "inflection"
    AuthorIDCharacter  AuthorID = "character"
    AuthorIDPerplexity AuthorID = "perplexity"
    AuthorIDAnysphere  AuthorID = "anysphere"
    AuthorIDCursor     AuthorID = "cursor"

    // Notable Fine-Tuned Model Creators & Publishers.
    AuthorIDCognitiveComputations AuthorID = "cognitivecomputations"
    AuthorIDEricHartford          AuthorID = "ehartford"
    AuthorIDNousResearch          AuthorID = "nousresearch"
    AuthorIDTeknium               AuthorID = "teknium"
    AuthorIDJonDurbin             AuthorID = "jondurbin"
    AuthorIDLMSYS                 AuthorID = "lmsys"
    AuthorIDVicuna                AuthorID = "vicuna-team"
    AuthorIDAlpacaTeam            AuthorID = "stanford-alpaca"
    AuthorIDWizardLM              AuthorID = "wizardlm"
    AuthorIDOpenOrca              AuthorID = "open-orca"
    AuthorIDPhind                 AuthorID = "phind"
    AuthorIDCodeFuse              AuthorID = "codefuse"
    AuthorIDTHUDM                 AuthorID = "thudm"
    AuthorIDGeorgiaTechRI         AuthorID = "gatech"
    AuthorIDFastChat              AuthorID = "fastchat"

    // Special constant for unknown authors.
    AuthorIDUnknown AuthorID = "unknown"
)

func ParseAuthorID
func ParseAuthorID(s string) AuthorID

ParseAuthorID normalizes stable author aliases without consulting catalog state. Use Authors.Resolve when alias resolution needs a specific catalog.

func ParseModelDefinitionID
func ParseModelDefinitionID(id ModelDefinitionID) (AuthorID, string, error)

ParseModelDefinitionID validates and splits one canonical author/slug ID.

func (AuthorID) String
func (id AuthorID) String() string

String returns text for AuthorID.

type AuthorMapping

AuthorMapping defines how to extract and normalize authors.

type AuthorMapping struct {
    Field      string              `yaml:"field" json:"field"`           // Field to extract from (e.g., "owned_by")
    Normalized map[string]AuthorID `yaml:"normalized" json:"normalized"` // Normalization map (e.g., "Meta" -> "meta")
}

func (AuthorMapping) Resolve
func (m AuthorMapping) Resolve(value string) (AuthorID, bool)

Resolve returns the configured author for one exact provider field value. Exact and case-insensitive matches precede the most-specific glob pattern.

func (AuthorMapping) Validate
func (m AuthorMapping) Validate() error

Validate checks the transport-independent author-normalization contract. Transport adapters separately validate which source fields they support.

type AuthoredModel

AuthoredModel is one provider-independent construction record stored at authors/<author>/models/<slug>.yaml. Model contains intrinsic facts only.

type AuthoredModel struct {
    AuthorID AuthorID
    Model    Model
}

func (AuthoredModel) ID
func (m AuthoredModel) ID() ModelDefinitionID

ID returns the canonical author/slug identity.

type Authors

Authors is a concurrent safe map of authors.

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

func NewAuthors
func NewAuthors(opts ...AuthorsOption) *Authors

NewAuthors creates a new Authors map with optional configuration.

func (*Authors) Add
func (a *Authors) Add(author *Author) error

Add adds an author, returning an error if it already exists.

func (*Authors) AddBatch
func (a *Authors) AddBatch(authors []*Author) map[AuthorID]error

AddBatch adds multiple authors in a single operation. Only adds authors that do not already exist - fails if an author ID already exists. Returns a map of author IDs to errors for any failed additions.

func (*Authors) Clear
func (a *Authors) Clear()

Clear removes all authors.

func (*Authors) Delete
func (a *Authors) Delete(id AuthorID) error

Delete removes an author by id. Returns an error if the author does not exist.

func (*Authors) DeleteBatch
func (a *Authors) DeleteBatch(ids []AuthorID) map[AuthorID]error

DeleteBatch removes multiple authors by ID. The returned map identifies IDs that DeleteBatch did not find.

func (*Authors) EncodeYAML
func (a *Authors) EncodeYAML() (string, error)

EncodeYAML returns formatted author YAML. It returns a typed parse error for values that YAML cannot represent safely.

func (*Authors) Exists
func (a *Authors) Exists(id AuthorID) bool

Exists checks if an author exists without returning it.

func (*Authors) ForEach
func (a *Authors) ForEach(fn func(id AuthorID, author *Author) bool)

ForEach applies a function to each author. The function should not modify the author. If the function returns false, iteration stops early.

func (*Authors) FormatYAML
func (a *Authors) FormatYAML() string

FormatYAML returns the authors as formatted YAML sorted alphabetically by ID.

func (*Authors) Get
func (a *Authors) Get(id AuthorID) (*Author, bool)

Get returns an author by id and whether it exists.

func (*Authors) Len
func (a *Authors) Len() int

Len returns the number of authors.

func (*Authors) List
func (a *Authors) List() []Author

List returns a slice of all authors as values (copies).

func (*Authors) Map
func (a *Authors) Map() map[AuthorID]*Author

Map returns a copy of all authors.

func (*Authors) Resolve
func (a *Authors) Resolve(id AuthorID) (*Author, bool)

Resolve returns an author by ID or alias. It first tries an exact ID match, then searches all author aliases. This allows commands to accept both canonical IDs and common aliases silently.

func (*Authors) Set
func (a *Authors) Set(id AuthorID, author *Author) error

Set sets an author by id. Returns an error if author is nil.

func (*Authors) SetBatch
func (a *Authors) SetBatch(authors map[AuthorID]*Author) error

SetBatch sets multiple authors in a single operation. Overwrites existing authors or adds new ones (upsert behavior). Returns an error if any author is nil.

type AuthorsOption

AuthorsOption defines a function that configures an Authors instance.

type AuthorsOption func(*Authors)

func WithAuthorsCapacity
func WithAuthorsCapacity(capacity int) AuthorsOption

WithAuthorsCapacity sets the initial capacity of the authors map.

func WithAuthorsMap
func WithAuthorsMap(authors map[AuthorID]*Author) AuthorsOption

WithAuthorsMap initializes the map with existing authors.

type AuthorsReader

AuthorsReader exposes author collection reads without mutation methods.

type AuthorsReader interface {
    Get(AuthorID) (*Author, bool)
    Resolve(AuthorID) (*Author, bool)
    Exists(AuthorID) bool
    Len() int
    List() []Author
    Map() map[AuthorID]*Author
    ForEach(func(AuthorID, *Author) bool)
    FormatYAML() string
}

type BootstrapManifest

BootstrapManifest binds the offline embedded catalog to exact canonical catalog bytes and a generation time.

type BootstrapManifest struct {
    ManifestVersion  uint64            `json:"manifest_version" yaml:"manifest_version"`
    GenerationID     string            `json:"generation_id" yaml:"generation_id"`
    GeneratedAt      time.Time         `json:"generated_at" yaml:"generated_at"`
    SchemaVersion    uint64            `json:"schema_version" yaml:"schema_version"`
    SemanticChecksum string            `json:"semantic_checksum" yaml:"semantic_checksum"`
    Payload          PayloadDescriptor `json:"payload" yaml:"payload"`
}

func ParseBootstrapManifestEnvelopeJSON
func ParseBootstrapManifestEnvelopeJSON(data []byte) (BootstrapManifest, error)

ParseBootstrapManifestEnvelopeJSON strictly parses bootstrap metadata without requiring the current catalog schema. Catalog refresh tooling uses it to replace a valid manifest from the previous schema.

func ParseBootstrapManifestJSON
func ParseBootstrapManifestJSON(data []byte) (BootstrapManifest, error)

ParseBootstrapManifestJSON strictly parses embedded-bootstrap metadata.

func (BootstrapManifest) Validate
func (m BootstrapManifest) Validate() error

Validate checks the embedded-bootstrap metadata contract and requires the current catalog schema.

func (BootstrapManifest) ValidateEnvelope
func (m BootstrapManifest) ValidateEnvelope() error

ValidateEnvelope checks schema-independent embedded-bootstrap metadata.

type Builder

Builder is the advanced mutable catalog construction type. Use it for custom update callbacks, source or plugin authors, and persistence pipelines. Ordinary consumers should use the immutable *Catalog from *starmap.Client.Catalog. It can work as: - Memory catalog (readFS == nil) - Embedded catalog (readFS is embed.FS) - Files catalog (readFS is os.DirFS) - Custom catalog (readFS is any fs.FS implementation).

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

func New
func New(opt Option, opts ...Option) (*Builder, error)

New creates a new builder with the given options. WithFS(fsys) and WithPath(path) load the configured files automatically.

func NewBuilderFrom
func NewBuilderFrom(source Reader) (*Builder, error)

NewBuilderFrom copies source into a new independent builder.

func NewEmpty
func NewEmpty() *Builder

NewEmpty creates an in-memory empty catalog. This is useful for testing or temporary catalogs that do not need persistence.

Example:

catalog := NewEmpty()
provider := Provider{ID: "openai", Models: map[string]Model{}}
catalog.SetProvider(provider)

func NewFromFS
func NewFromFS(fsys fs.FS, root string) (*Builder, error)

NewFromFS creates a catalog from a custom filesystem implementation. This allows for advanced use cases like virtual filesystems or custom storage backends.

Example:

var myFS embed.FS
catalog, err := NewFromFS(myFS, "catalog")

func NewFromPath
func NewFromPath(path string) (*Builder, error)

NewFromPath creates a catalog backed by files on disk. This is useful for development when you want to edit catalog files without recompiling the binary.

Example:

catalog, err := NewFromPath("./internal/embedded/catalog")
if err != nil {
    log.Fatal(err)
}

func (*Builder) Author
func (cat *Builder) Author(id AuthorID) (Author, error)

Author returns an author by ID or alias. Silently resolves aliases to canonical author IDs.

func (*Builder) AuthoredModels
func (cat *Builder) AuthoredModels() []AuthoredModel

AuthoredModels returns caller-owned provider-independent construction records in canonical author/slug order.

func (*Builder) Authors
func (cat *Builder) Authors() AuthorsReader

Authors returns the authors collection.

func (*Builder) Build
func (cat *Builder) Build() (*Catalog, error)

Build publishes an immutable deep copy of the builder's current state.

func (*Builder) ClearProvenance
func (cat *Builder) ClearProvenance()

ClearProvenance removes catalog provenance.

func (*Builder) Copy
func (cat *Builder) Copy() (*Builder, error)

Copy creates a deep copy of the catalog.

func (*Builder) DeleteAuthor
func (cat *Builder) DeleteAuthor(id AuthorID) error

DeleteAuthor deletes an author.

func (*Builder) DeleteAuthorModel
func (cat *Builder) DeleteAuthorModel(authorID AuthorID, slug string) error

DeleteAuthorModel deletes one provider-independent model from an author.

func (*Builder) DeleteProvider
func (cat *Builder) DeleteProvider(id ProviderID) error

DeleteProvider deletes a provider.

func (*Builder) DeleteProviderModel
func (cat *Builder) DeleteProviderModel(providerID ProviderID, modelID string) error

DeleteProviderModel deletes a model from a provider atomically.

func (*Builder) Load
func (cat *Builder) Load() error

Load loads the catalog from the configured filesystem.

func (*Builder) LoadReport
func (cat *Builder) LoadReport() LoadReport

LoadReport returns a caller-owned copy of the builder's load diagnostics.

func (*Builder) MergeProvenance
func (cat *Builder) MergeProvenance(value provenance.Map)

MergeProvenance appends catalog provenance.

func (*Builder) MergeStrategy
func (cat *Builder) MergeStrategy() MergeStrategy

MergeStrategy returns the default merge strategy.

func (*Builder) MergeWith
func (cat *Builder) MergeWith(source Reader, opts ...MergeOption) error

MergeWith merges another catalog into this one.

func (*Builder) Provenance
func (cat *Builder) Provenance() ProvenanceReader

Provenance returns the provenance collection.

func (*Builder) Provider
func (cat *Builder) Provider(id ProviderID) (Provider, error)

Provider returns a provider by ID or alias. Silently resolves aliases to canonical provider IDs.

func (*Builder) ProviderModel
func (cat *Builder) ProviderModel(providerID ProviderID, modelID string) (Model, error)

ProviderModel returns one provider-specific model offering without flattening equal model IDs from other providers.

func (*Builder) ProviderModels
func (cat *Builder) ProviderModels(id ProviderID) (ModelsReader, error)

ProviderModels returns the models served by a provider or one of its aliases.

func (*Builder) Providers
func (cat *Builder) Providers() ProvidersReader

Providers returns the providers collection.

func (*Builder) ReplaceWith
func (cat *Builder) ReplaceWith(source Reader) error

ReplaceWith replaces this catalog's contents with another.

func (*Builder) Save
func (cat *Builder) Save() error

Save serializes a mutable builder to its configured construction path. It is not a publication primitive. The Starmap client materializes committed catalogs atomically.

func (*Builder) SaveTo
func (cat *Builder) SaveTo(path string) error

SaveTo serializes a mutable builder to path.

func (*Builder) SetAuthor
func (cat *Builder) SetAuthor(author Author) error

SetAuthor sets an author (upsert).

func (*Builder) SetAuthorModel
func (cat *Builder) SetAuthorModel(authorID AuthorID, model Model) error

SetAuthorModel sets one provider-independent model on its owning author.

func (*Builder) SetMergeStrategy
func (cat *Builder) SetMergeStrategy(strategy MergeStrategy)

SetMergeStrategy sets the default merge strategy.

func (*Builder) SetProvenance
func (cat *Builder) SetProvenance(value provenance.Map)

SetProvenance replaces catalog provenance.

func (*Builder) SetProvider
func (cat *Builder) SetProvider(provider Provider) error

SetProvider sets a provider (upsert).

func (*Builder) SetProviderModel
func (cat *Builder) SetProviderModel(providerID ProviderID, model Model) error

SetProviderModel sets a model on a provider atomically.

type CapabilityMapping

CapabilityMapping maps one typed provider predicate to each canonical fact that the cited provider contract entails.

type CapabilityMapping struct {
    From     string                        `yaml:"from" json:"from"`
    To       []ModelFeature                `yaml:"to" json:"to"`
    Combine  ProviderCapabilityCombination `yaml:"combine,omitempty" json:"combine,omitempty"`
    Evidence string                        `yaml:"evidence" json:"evidence"`
}

type Catalog

Catalog is Starmap's immutable canonical catalog. Read methods provide the only access to its private state. Callers can retain it across goroutines.

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

func DecodeCatalogPayload
func DecodeCatalogPayload(data []byte) (*Catalog, error)

DecodeCatalogPayload decodes the current catalog payload. A non-nil catalog with *sourcepayload.QuarantineError is only a partial diagnostic result. Callers must not activate it as the manifest-bound generation.

func DecodeSourceObservationPayload
func DecodeSourceObservationPayload(data []byte) (*Catalog, error)

DecodeSourceObservationPayload decodes a source candidate without requiring resolved canonical authorship for every provider record. The returned catalog is suitable only for reconciliation. Durable generation activation must use DecodeCatalogPayload.

func NewCatalog
func NewCatalog(source Reader) (*Catalog, error)

NewCatalog copies source into an immutable canonical catalog.

func NewObservationCatalog
func NewObservationCatalog(source Reader) (*Catalog, error)

NewObservationCatalog copies source records into an immutable source observation without deriving consumer definitions or offerings. It exists for acquisition boundaries that must preserve provider records before reconciliation resolves every ModelRef. Final publication must use NewCatalog or Builder.Build, which fail closed on unresolved references.

func (*Catalog) Author
func (r *Catalog) Author(id AuthorID) (Author, error)

Author returns a caller-owned copy of an author.

func (*Catalog) AuthorModel
func (r *Catalog) AuthorModel(authorID AuthorID, slug string) (ModelDefinition, error)

AuthorModel resolves an author ID or alias plus a model slug.

func (*Catalog) AuthorModels
func (r *Catalog) AuthorModels(authorID AuthorID) ([]ModelDefinition, error)

AuthorModels returns caller-owned canonical model definitions attributed to an author or one of its aliases, ordered by definition ID.

func (*Catalog) AuthoredModels
func (r *Catalog) AuthoredModels() []AuthoredModel

AuthoredModels returns caller-owned provider-independent construction records. Ordinary consumers normally use Definitions and AuthorModels.

func (*Catalog) Authors
func (r *Catalog) Authors() AuthorsReader

Authors returns the immutable catalog's author collection reader.

func (*Catalog) Definition
func (r *Catalog) Definition(id ModelDefinitionID) (ModelDefinition, error)

Definition returns one caller-owned canonical model definition.

func (*Catalog) DefinitionOfferings
func (r *Catalog) DefinitionOfferings(id ModelDefinitionID) ([]ProviderOffering, error)

DefinitionOfferings returns caller-owned offerings for one canonical model, ordered by provider and exact provider model ID.

func (*Catalog) Definitions
func (r *Catalog) Definitions() []ModelDefinition

Definitions returns caller-owned canonical definitions in ID order.

func (*Catalog) FindModel
func (r *Catalog) FindModel(id string) (ModelDefinition, error)

FindModel returns the canonical provider-independent model definition. Use Offering for provider price, limits, availability, and request behavior.

func (*Catalog) MaterializeRouteAlias
func (r *Catalog) MaterializeRouteAlias(alias RouteAlias) (RouteAliasResolution, error)

MaterializeRouteAlias resolves current eligibility without storing routing policy in source ingestion or the canonical catalog.

func (*Catalog) Offering
func (r *Catalog) Offering(providerID ProviderID, providerModelID ProviderModelID) (ProviderOffering, error)

Offering returns one caller-owned provider-scoped model offering. Provider aliases resolve to their canonical provider before key lookup.

func (*Catalog) Provenance
func (r *Catalog) Provenance() ProvenanceReader

Provenance returns the immutable catalog's provenance reader.

func (*Catalog) Provider
func (r *Catalog) Provider(id ProviderID) (Provider, error)

Provider returns a caller-owned copy of a provider.

func (*Catalog) ProviderOfferings
func (r *Catalog) ProviderOfferings(providerID ProviderID) ([]ProviderOffering, error)

ProviderOfferings returns caller-owned offerings in provider-model-ID order.

func (*Catalog) Providers
func (r *Catalog) Providers() ProvidersReader

Providers returns the immutable catalog's provider collection reader.

type CatalogPayload

CatalogPayload is the canonical construction-record JSON representation. Author models own provider-independent facts. Provider models own serving facts and link to author models through Model.ModelRef.

type CatalogPayload struct {
    SchemaVersion  uint64             `json:"schema_version"`
    Providers      []Provider         `json:"providers"`
    Authors        []Author           `json:"authors"`
    ProviderModels map[string][]Model `json:"provider_models"`
    AuthorModels   map[string][]Model `json:"author_models"`
    Provenance     provenance.Map     `json:"provenance"`
}

type ConsumerCompatibility

ConsumerCompatibility declares the catalog schema versions that can consume this generation. It never refers to a Starmap or Starport binary version.

type ConsumerCompatibility struct {
    MinSchemaVersion uint64 `json:"min_schema_version" yaml:"min_schema_version"`
    MaxSchemaVersion uint64 `json:"max_schema_version" yaml:"max_schema_version"`
}

func (ConsumerCompatibility) SupportsSchema
func (c ConsumerCompatibility) SupportsSchema(schemaVersion uint64) bool

SupportsSchema reports whether a consumer catalog schema is compatible.

type EndpointType

EndpointType specifies the API style for model listing.

type EndpointType string

const (
    // EndpointTypeOpenAI represents OpenAI-compatible API.
    EndpointTypeOpenAI EndpointType = "openai"
    // EndpointTypeAnthropic represents Anthropic API format.
    EndpointTypeAnthropic EndpointType = "anthropic"
    // EndpointTypeGoogle represents Google AI Studio.
    EndpointTypeGoogle EndpointType = "google"
    // EndpointTypeGoogleCloud represents Google Vertex AI.
    EndpointTypeGoogleCloud EndpointType = "google-cloud"
    // EndpointTypeOllama represents the native Ollama API.
    EndpointTypeOllama EndpointType = "ollama"
    // EndpointTypeCohere represents the Cohere API. Reranking has no OpenAI
    // standard, so Cohere's request shape is the one other services copied.
    EndpointTypeCohere EndpointType = "cohere"
    // EndpointTypeVoyage represents the Voyage AI API. Its reranker names the
    // result count and the response envelope differently from Cohere's, so it
    // cannot share that style.
    EndpointTypeVoyage EndpointType = "voyage"
)

type FieldMapping

FieldMapping defines how to map API response fields to model fields. Type conversion is automatic based on the destination field type.

type FieldMapping struct {
    From string `yaml:"from" json:"from"` // Source field path in API response (e.g., "max_model_len")
    To   string `yaml:"to" json:"to"`     // Target field path in Model (e.g., "limits.context_window")
}

type FloatRange

FloatRange represents a range of float values.

type FloatRange struct {
    Min     float64 `json:"min" yaml:"min"`         // Minimum value
    Max     float64 `json:"max" yaml:"max"`         // Maximum value
    Default float64 `json:"default" yaml:"default"` // Default value
}

type Generation

Generation is an immutable manifest and its exact catalog payload bytes.

type Generation struct {
    Manifest GenerationManifest
    Payload  []byte
}

func (Generation) Copy
func (g Generation) Copy() Generation

Copy returns a generation that does not share mutable slices with g.

func (Generation) SemanticChecksum
func (g Generation) SemanticChecksum() (string, error)

SemanticChecksum returns the facts-only identity of the catalog the payload carries. It excludes provenance, so a regenerated payload with the same facts keeps the same value. The publisher keys the immutable release tag and the channel catalog digest by this value. The exact payload checksum stays in the manifest.

func (Generation) Validate
func (g Generation) Validate() error

Validate verifies the manifest and its binding to the payload.

type GenerationCompleteness

GenerationCompleteness describes whether a generation contains every record expected from the observations used to build it.

type GenerationCompleteness string

const (
    // GenerationCompletenessComplete means the generation contains every expected record.
    GenerationCompletenessComplete GenerationCompleteness = "complete"
    // GenerationCompletenessPartial means at least one expected input or record is
    // absent. The generation must also have a degraded status.
    GenerationCompletenessPartial GenerationCompleteness = "partial"
)

type GenerationManifest

GenerationManifest describes one immutable, validated catalog generation. Local stores and distribution transports share it. Transport-specific URLs, release tags, and binary versions do not belong in this domain record.

type GenerationManifest struct {
    ManifestVersion       uint64                     `json:"manifest_version" yaml:"manifest_version"`
    SchemaVersion         uint64                     `json:"schema_version" yaml:"schema_version"`
    GenerationID          string                     `json:"generation_id" yaml:"generation_id"`
    GeneratedAt           time.Time                  `json:"generated_at" yaml:"generated_at"`
    Payload               PayloadDescriptor          `json:"payload" yaml:"payload"`
    Validation            GenerationValidationReport `json:"validation" yaml:"validation"`
    SyncRunID             string                     `json:"sync_run_id" yaml:"sync_run_id"`
    SourceObservations    []SourceObservationLink    `json:"source_observations" yaml:"source_observations"`
    ReviewCandidates      []evidence.ReviewCandidate `json:"review_candidates" yaml:"review_candidates"`
    Completeness          GenerationCompleteness     `json:"completeness" yaml:"completeness"`
    Degraded              bool                       `json:"degraded" yaml:"degraded"`
    DegradationReasons    []string                   `json:"degradation_reasons,omitempty" yaml:"degradation_reasons,omitempty"`
    ConsumerCompatibility ConsumerCompatibility      `json:"consumer_compatibility" yaml:"consumer_compatibility"`
}

func ParseGenerationManifestJSON
func ParseGenerationManifestJSON(data []byte) (GenerationManifest, error)

ParseGenerationManifestJSON strictly parses and validates a JSON manifest. It returns typed validation errors for unknown or missing members, including false or zero values. It also rejects malformed JSON and trailing documents.

func (GenerationManifest) Copy
func (m GenerationManifest) Copy() GenerationManifest

Copy returns a value whose slices do not alias the original manifest.

func (GenerationManifest) Validate
func (m GenerationManifest) Validate() error

Validate verifies that a manifest is complete and eligible for publication.

type GenerationValidationCheck

GenerationValidationCheck records one deterministic validation decision.

type GenerationValidationCheck struct {
    Name    string                          `json:"name" yaml:"name"`
    Status  GenerationValidationCheckStatus `json:"status" yaml:"status"`
    Message string                          `json:"message,omitempty" yaml:"message,omitempty"`
}

type GenerationValidationCheckStatus

GenerationValidationCheckStatus is the result of one validation check.

type GenerationValidationCheckStatus string

const (
    // GenerationValidationCheckPassed records a successful check.
    GenerationValidationCheckPassed GenerationValidationCheckStatus = "passed"
    // GenerationValidationCheckWarning records a non-fatal validation warning.
    GenerationValidationCheckWarning GenerationValidationCheckStatus = "warning"
    // GenerationValidationCheckFailed records a failed required check.
    GenerationValidationCheckFailed GenerationValidationCheckStatus = "failed"
)

type GenerationValidationReport

GenerationValidationReport records the validator identity and exact outcome that made a candidate eligible (or ineligible) for publication.

type GenerationValidationReport struct {
    ValidatorVersion string                      `json:"validator_version" yaml:"validator_version"`
    ValidatedAt      time.Time                   `json:"validated_at" yaml:"validated_at"`
    Status           GenerationValidationStatus  `json:"status" yaml:"status"`
    ErrorCount       int                         `json:"error_count" yaml:"error_count"`
    WarningCount     int                         `json:"warning_count" yaml:"warning_count"`
    Checks           []GenerationValidationCheck `json:"checks" yaml:"checks"`
}

type GenerationValidationStatus

GenerationValidationStatus is the overall result of generation validation.

type GenerationValidationStatus string

const (
    // GenerationValidationPassed means every required validation check passed.
    GenerationValidationPassed GenerationValidationStatus = "passed"
    // GenerationValidationFailed means at least one required check failed. A
    // failed generation is evidence, but is not eligible for publication.
    GenerationValidationFailed GenerationValidationStatus = "failed"
)

type HealthAPIKind

HealthAPIKind names the wire convention a provider's health API speaks. An empty kind means HealthAPIKindStatuspage, the convention every entry used before the kind existed.

type HealthAPIKind string

const (
    // HealthAPIKindStatuspage is the Atlassian Statuspage JSON API
    // (/api/v2/summary.json and /api/v2/components.json).
    HealthAPIKindStatuspage HealthAPIKind = "statuspage"
    // HealthAPIKindHyperping is the Hyperping status JSON document
    // (schemaVersion 1 with overallStatus and per-service statuses).
    HealthAPIKindHyperping HealthAPIKind = "hyperping"
    // HealthAPIKindRSS is an incident feed (RSS or Atom) with one item
    // per incident and no structured component status.
    HealthAPIKindRSS HealthAPIKind = "rss"
    // HealthAPIKindGoogleCloud is the Google Cloud service health JSON
    // (incidents.json filtered by the product names in HealthComponents).
    HealthAPIKindGoogleCloud HealthAPIKind = "google-cloud"
)

type IntRange

IntRange represents a range of integer values.

type IntRange struct {
    Min     int `json:"min" yaml:"min"`         // Minimum value
    Max     int `json:"max" yaml:"max"`         // Maximum value
    Default int `json:"default" yaml:"default"` // Default value
}

type LoadIssue

LoadIssue describes one malformed model file quarantined during a catalog load.

type LoadIssue struct {
    // Path identifies the model file relative to the catalog root.
    Path string
    // Err is the typed parse or validation failure.
    Err error
    // Limit reports that the collection budget, rather than record syntax,
    // caused the quarantine.
    Limit bool
}

type LoadReport

LoadReport describes bounded model-file loading. Structural catalog files remain fail-closed and are not represented here.

type LoadReport struct {
    // Accepted is the number of model files loaded successfully.
    Accepted int
    // Rejected includes malformed and excess model files.
    Rejected int
    // Issues contains bounded typed diagnostics.
    Issues []LoadIssue
    // Truncated reports that excess model files were not read.
    Truncated bool
}

func (LoadReport) Err
func (r LoadReport) Err() error

Err joins quarantined record failures for callers that require a fully valid catalog, such as embedded bootstrap and atomic projection validation.

type MediaOperationFacts

MediaOperationFacts states the exact model facts that a dedicated media operation requires. Consumers request such an operation by name instead of discovering it in a chat answer. A chat model that returns a picture therefore does not qualify.

Naming it is not the same as reaching a separate path. A provider that reads a document serves the read through its chat path, and the endpoint table says so. What makes the operation its own is that a consumer asks for it and pays for it in the operation's own unit.

The derivation reads this table, and the fact-consistency rule enforces it. One statement therefore decides both what Starmap publishes and what Starmap refuses, and neither reads a price to do it.

type MediaOperationFacts struct {
    // Operation is the published operation name.
    Operation ProviderOperation
    // Tags name the operation on a model. Any one of them is enough.
    Tags []ModelTag
    // TagRequired means the modalities alone cannot identify the operation, so
    // a model has to carry one of the tags. Transcription reads audio and
    // writes text, which is also the shape of a chat model that hears.
    TagRequired bool
    // Input lists the input modalities the model must declare. It may declare
    // more.
    Input []ModelModality
    // Output is the exact output modality set. A model that also writes text
    // answers through chat completions rather than through a media path.
    Output []ModelModality
}

func MediaOperationDefinition
func MediaOperationDefinition(operation ProviderOperation) (MediaOperationFacts, bool)

MediaOperationDefinition returns the canonical facts for one operation.

func MediaOperationDefinitions
func MediaOperationDefinitions() []MediaOperationFacts

MediaOperationDefinitions returns the canonical facts for every dedicated media operation, in published order.

func (MediaOperationFacts) Matches
func (f MediaOperationFacts) Matches(model Model) bool

Matches reports whether a model declares the facts this operation requires.

type MergeOption

MergeOption configures catalog merging.

type MergeOption func(*MergeOptions)

func WithStrategy
func WithStrategy(s MergeStrategy) MergeOption

WithStrategy overrides the merge strategy.

type MergeOptions

MergeOptions holds merge configuration.

type MergeOptions struct {
    Strategy MergeStrategy // nil means use source catalog's suggestion
}

func ParseMergeOptions
func ParseMergeOptions(opts ...MergeOption) *MergeOptions

ParseMergeOptions processes merge options and returns the configuration.

type MergeStrategy

MergeStrategy defines how to merge catalogs.

type MergeStrategy int

const (
    // MergeEnrichEmpty intelligently merges, preserving existing non-empty values.
    MergeEnrichEmpty MergeStrategy = iota
    // MergeReplaceAll completely replaces the target catalog with the source.
    MergeReplaceAll
    // MergeAppendOnly only adds new items, skips existing ones.
    MergeAppendOnly
)

type Model

Model represents a model configuration.

type Model struct {
    // Core identity
    ID  string `json:"id" yaml:"id"` // Exact provider model ID or authored-model slug
    // ModelRef links a provider serving record to its canonical author/slug
    // model. It is empty on authored-model records.
    ModelRef    ModelDefinitionID `json:"model,omitempty" yaml:"model,omitempty"`
    Name        string            `json:"name" yaml:"name"`
    Authors     []Author          `json:"authors,omitempty" yaml:"authors,omitempty"` // Authors/organizations of the model (if known)
    Description string            `json:"description,omitempty" yaml:"description,omitempty"`
    Status      ModelStatus       `json:"status,omitempty" yaml:"status,omitempty"` // Lifecycle status such as active, beta, preview, or deprecated

    // Provider-announced lifecycle dates for this serving record. A nil value
    // means the provider has not announced the date.
    DeprecatedAt *utc.Time `json:"deprecated_at,omitempty" yaml:"deprecated_at,omitempty"` // When the provider deprecated this model
    RetiresAt    *utc.Time `json:"retires_at,omitempty" yaml:"retires_at,omitempty"`       // When the provider retires this model and stops serving requests

    // Metadata - version and timing information
    Metadata *ModelMetadata `json:"metadata,omitempty" yaml:"metadata,omitempty"` // Metadata for the model

    // Lineage - model family and derivation information
    Lineage *ModelLineage `json:"lineage,omitempty" yaml:"lineage,omitempty"`

    // Features - what this model can do
    Features *ModelFeatures `json:"features,omitempty" yaml:"features,omitempty"`

    // Attachments - attachment support details
    Attachments *ModelAttachments `json:"attachments,omitempty" yaml:"attachments,omitempty"`

    // Generation - core chat completions generation controls
    Generation *ModelGeneration `json:"generation,omitempty" yaml:"generation,omitempty"`

    // Reasoning - reasoning effort levels
    Reasoning *ModelControlLevels `json:"reasoning,omitempty" yaml:"reasoning,omitempty"`

    // ReasoningTokens - specific token allocation for reasoning processes
    ReasoningTokens *IntRange `json:"reasoning_tokens,omitempty" yaml:"reasoning_tokens,omitempty"`

    // Verbosity - response verbosity levels
    Verbosity *ModelControlLevels `json:"verbosity,omitempty" yaml:"verbosity,omitempty"`

    // Tools - external tool and capability integrations
    Tools *ModelTools `json:"tools,omitempty" yaml:"tools,omitempty"`

    // Delivery - technical response delivery capabilities (formats, protocols, streaming)
    Delivery *ModelDelivery `json:"response,omitempty" yaml:"response,omitempty"`

    // Modes - alternate service modes such as fast/priority variants
    Modes map[string]ModelMode `json:"modes,omitempty" yaml:"modes,omitempty"`

    // Operational characteristics
    Pricing *ModelPricing `json:"pricing,omitempty" yaml:"pricing,omitempty"` // Optional pricing information
    Limits  *ModelLimits  `json:"limits,omitempty" yaml:"limits,omitempty"`   // Model limits

    // Extensions - controlled source-specific fields that are not canonical schema
    Extensions SourceExtensions `json:"extensions,omitempty" yaml:"extensions,omitempty"`

    CreatedAt utc.Time `json:"created_at" yaml:"created_at"`
    UpdatedAt utc.Time `json:"updated_at" yaml:"updated_at"`
    // contains filtered or unexported fields
}

func DeepCopyModel
func DeepCopyModel(model Model) Model

DeepCopyModel creates a deep copy of a Model.

func MergeModels
func MergeModels(existing, updated Model) Model

MergeModels combines two models and retains existing values when updated has an empty or nil value.

func (*Model) DescriptionValue
func (m *Model) DescriptionValue() (string, ValuePresence)

DescriptionValue returns the description and its presence state.

func (*Model) EncodeYAML
func (m *Model) EncodeYAML() (string, error)

EncodeYAML returns formatted YAML. It returns a typed parse error for values that YAML cannot represent safely.

func (Model) Equal
func (m Model) Equal(other Model) bool

Equal reports whether two models have the same serialized facts and presence semantics.

func (*Model) FormatYAML
func (m *Model) FormatYAML() string

FormatYAML returns a well-formatted YAML representation with comments and proper structure.

func (*Model) FormatYAMLHeaderComment
func (m *Model) FormatYAMLHeaderComment() string

FormatYAMLHeaderComment returns a descriptive string for the model header comment.

func (Model) MarshalJSON
func (m Model) MarshalJSON() ([]byte, error)

MarshalJSON preserves description presence in immutable catalog payloads.

func (Model) MarshalYAML
func (m Model) MarshalYAML() (any, error)

MarshalYAML preserves an explicit empty or unknown description.

func (*Model) SetDescription
func (m *Model) SetDescription(description string)

SetDescription records an explicit model description, including an empty description.

func (*Model) SetDescriptionUnknown
func (m *Model) SetDescriptionUnknown()

SetDescriptionUnknown records that the description is explicitly unknown.

func (*Model) UnmarshalJSON
func (m *Model) UnmarshalJSON(data []byte) error

UnmarshalJSON restores description presence from immutable catalog payloads.

func (*Model) UnmarshalYAML
func (m *Model) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML restores description presence from the human YAML record.

func (*Model) UnsetDescription
func (m *Model) UnsetDescription()

UnsetDescription removes the model's description claim.

type ModelArchitecture

ModelArchitecture represents the technical architecture details of a model.

type ModelArchitecture struct {
    ParameterCount string           `json:"parameter_count,omitempty" yaml:"parameter_count,omitempty"`
    Type           ArchitectureType `json:"type,omitempty" yaml:"type,omitempty"`                 // Type of architecture
    Tokenizer      Tokenizer        `json:"tokenizer,omitempty" yaml:"tokenizer,omitempty"`       // Tokenizer type used by the model
    Quantization   Quantization     `json:"quantization,omitempty" yaml:"quantization,omitempty"` // Quantization level used by the model
    Quantized      bool             `json:"quantized" yaml:"quantized"`
    FineTuned      bool             `json:"fine_tuned" yaml:"fine_tuned"`                     // Whether this is a fine-tuned variant
    BaseModel      *string          `json:"base_model,omitempty" yaml:"base_model,omitempty"` // Base model ID if fine-tuned
}

type ModelAttachments

ModelAttachments represents the attachment capabilities of a model.

type ModelAttachments struct {
    MimeTypes   []string `json:"mime_types,omitempty" yaml:"mime_types,omitempty"`       // Supported MIME types
    MaxFileSize *int64   `json:"max_file_size,omitempty" yaml:"max_file_size,omitempty"` // Maximum file size in bytes
    MaxFiles    *int     `json:"max_files,omitempty" yaml:"max_files,omitempty"`         // Maximum number of files per request
}

type ModelControlLevel

ModelControlLevel represents an effort/intensity level for model controls.

type ModelControlLevel string

Supported model control levels.

const (
    ModelControlLevelMinimum ModelControlLevel = "minimum"
    ModelControlLevelLow     ModelControlLevel = "low"
    ModelControlLevelMedium  ModelControlLevel = "medium"
    ModelControlLevelHigh    ModelControlLevel = "high"
    ModelControlLevelMaximum ModelControlLevel = "maximum"
)

func (ModelControlLevel) String
func (mcl ModelControlLevel) String() string

String returns text for ModelControlLevel.

type ModelControlLevels

ModelControlLevels represents a set of effort/intensity levels for model controls.

type ModelControlLevels struct {
    Levels  []ModelControlLevel `json:"levels" yaml:"levels"`   // Which levels this model supports
    Default *ModelControlLevel  `json:"default" yaml:"default"` // Default level
}

type ModelDefinition

ModelDefinition describes a canonical, provider-independent model. Provider service facts belong to ProviderOffering, never this record.

type ModelDefinition struct {
    ID           ModelDefinitionID           `json:"id" yaml:"id"`
    Name         string                      `json:"name" yaml:"name"`
    AuthorIDs    []AuthorID                  `json:"author_ids" yaml:"author_ids"`
    Description  string                      `json:"description,omitempty" yaml:"description,omitempty"`
    Metadata     ModelDefinitionMetadata     `json:"metadata" yaml:"metadata"`
    Lineage      ModelDefinitionLineage      `json:"lineage" yaml:"lineage"`
    Weights      ModelDefinitionWeights      `json:"weights" yaml:"weights"`
    Capabilities ModelDefinitionCapabilities `json:"capabilities" yaml:"capabilities"`
    // CreatedAt and UpdatedAt bound the earliest and latest known lifecycle
    // evidence for this definition. Zero means unknown.
    CreatedAt utc.Time `json:"created_at" yaml:"created_at"`
    UpdatedAt utc.Time `json:"updated_at" yaml:"updated_at"`
}

func (ModelDefinition) Validate
func (d ModelDefinition) Validate() error

Validate verifies canonical identity and authorship invariants.

type ModelDefinitionCapabilities

ModelDefinitionCapabilities groups intrinsic model behavior independently of any provider's service limits, price, endpoint, or availability.

type ModelDefinitionCapabilities struct {
    Features        *ModelFeatures      `json:"features,omitempty" yaml:"features,omitempty"`
    Attachments     *ModelAttachments   `json:"attachments,omitempty" yaml:"attachments,omitempty"`
    Generation      *ModelGeneration    `json:"generation,omitempty" yaml:"generation,omitempty"`
    Reasoning       *ModelControlLevels `json:"reasoning,omitempty" yaml:"reasoning,omitempty"`
    ReasoningTokens *IntRange           `json:"reasoning_tokens,omitempty" yaml:"reasoning_tokens,omitempty"`
    Verbosity       *ModelControlLevels `json:"verbosity,omitempty" yaml:"verbosity,omitempty"`
    Tools           *ModelTools         `json:"tools,omitempty" yaml:"tools,omitempty"`
    Delivery        *ModelDelivery      `json:"delivery,omitempty" yaml:"delivery,omitempty"`
}

type ModelDefinitionID

ModelDefinitionID identifies one provider-independent model definition.

type ModelDefinitionID string

func AuthoredModelID
func AuthoredModelID(authorID AuthorID, slug string) ModelDefinitionID

AuthoredModelID returns the canonical author/slug identity for one authored model record.

type ModelDefinitionLineage

ModelDefinitionLineage describes canonical model-family relationships.

type ModelDefinitionLineage struct {
    Family string             `json:"family,omitempty" yaml:"family,omitempty"`
    Root   *ModelDefinitionID `json:"root,omitempty" yaml:"root,omitempty"`
    Parent *ModelDefinitionID `json:"parent,omitempty" yaml:"parent,omitempty"`
}

type ModelDefinitionMetadata

ModelDefinitionMetadata contains provider-independent release and discovery metadata.

type ModelDefinitionMetadata struct {
    // ReleaseDate is the first known public release of this identity. A rolling
    // alias may later route to revisions with a newer KnowledgeCutoff. Zero
    // means unknown. Do not invent missing day precision.
    ReleaseDate     utc.Time   `json:"release_date" yaml:"release_date"`
    KnowledgeCutoff *utc.Time  `json:"knowledge_cutoff,omitempty" yaml:"knowledge_cutoff,omitempty"`
    Tags            []ModelTag `json:"tags,omitempty" yaml:"tags,omitempty"`
}

type ModelDefinitionWeights

ModelDefinitionWeights describes provider-independent model weights and architecture.

type ModelDefinitionWeights struct {
    Open         *bool              `json:"open,omitempty" yaml:"open,omitempty"`
    Architecture *ModelArchitecture `json:"architecture,omitempty" yaml:"architecture,omitempty"`
}

type ModelDelivery

ModelDelivery represents technical response delivery capabilities.

type ModelDelivery struct {
    // Response delivery mechanisms
    Protocols []ModelResponseProtocol `json:"protocols,omitempty" yaml:"protocols,omitempty"` // Supported delivery protocols (HTTP, gRPC, etc.)
    Streaming []ModelStreaming        `json:"streaming,omitempty" yaml:"streaming,omitempty"` // Supported streaming modes (sse, websocket, chunked)
    Formats   []ModelResponseFormat   `json:"formats,omitempty" yaml:"formats,omitempty"`     // Available response formats (if format_response feature enabled)
}

type ModelFeature

ModelFeature identifies one boolean model capability.

type ModelFeature string

Model feature identifiers.

const (
    ModelFeatureToolCalls                     ModelFeature = "tool_calls"
    ModelFeatureTools                         ModelFeature = "tools"
    ModelFeatureToolChoice                    ModelFeature = "tool_choice"
    ModelFeatureWebSearch                     ModelFeature = "web_search"
    ModelFeatureAttachments                   ModelFeature = "attachments"
    ModelFeatureReasoning                     ModelFeature = "reasoning"
    ModelFeatureReasoningEffort               ModelFeature = "reasoning_effort"
    ModelFeatureReasoningTokens               ModelFeature = "reasoning_tokens"
    ModelFeatureIncludeReasoning              ModelFeature = "include_reasoning"
    ModelFeatureVerbosity                     ModelFeature = "verbosity"
    ModelFeatureTemperature                   ModelFeature = "temperature"
    ModelFeatureTopP                          ModelFeature = "top_p"
    ModelFeatureTopK                          ModelFeature = "top_k"
    ModelFeatureTopA                          ModelFeature = "top_a"
    ModelFeatureMinP                          ModelFeature = "min_p"
    ModelFeatureTypicalP                      ModelFeature = "typical_p"
    ModelFeatureTFS                           ModelFeature = "tfs"
    ModelFeatureMaxTokens                     ModelFeature = "max_tokens"
    ModelFeatureMaxOutputTokens               ModelFeature = "max_output_tokens"
    ModelFeatureStop                          ModelFeature = "stop"
    ModelFeatureStopTokenIDs                  ModelFeature = "stop_token_ids"
    ModelFeatureFrequencyPenalty              ModelFeature = "frequency_penalty"
    ModelFeaturePresencePenalty               ModelFeature = "presence_penalty"
    ModelFeatureRepetitionPenalty             ModelFeature = "repetition_penalty"
    ModelFeatureNoRepeatNgramSize             ModelFeature = "no_repeat_ngram_size"
    ModelFeatureLengthPenalty                 ModelFeature = "length_penalty"
    ModelFeatureLogitBias                     ModelFeature = "logit_bias"
    ModelFeatureBadWords                      ModelFeature = "bad_words"
    ModelFeatureAllowedTokens                 ModelFeature = "allowed_tokens"
    ModelFeatureSeed                          ModelFeature = "seed"
    ModelFeatureLogprobs                      ModelFeature = "logprobs"
    ModelFeatureTopLogprobs                   ModelFeature = "top_logprobs"
    ModelFeatureEcho                          ModelFeature = "echo"
    ModelFeatureN                             ModelFeature = "n"
    ModelFeatureBestOf                        ModelFeature = "best_of"
    ModelFeatureMirostat                      ModelFeature = "mirostat"
    ModelFeatureMirostatTau                   ModelFeature = "mirostat_tau"
    ModelFeatureMirostatEta                   ModelFeature = "mirostat_eta"
    ModelFeatureContrastiveSearchPenaltyAlpha ModelFeature = "contrastive_search_penalty_alpha"
    ModelFeatureNumBeams                      ModelFeature = "num_beams"
    ModelFeatureEarlyStopping                 ModelFeature = "early_stopping"
    ModelFeatureDiversityPenalty              ModelFeature = "diversity_penalty"
    ModelFeatureFormatResponse                ModelFeature = "format_response"
    ModelFeatureStructuredOutputs             ModelFeature = "structured_outputs"
    ModelFeatureStreaming                     ModelFeature = "streaming"
)

type ModelFeatures

ModelFeatures represents a set of feature flags that describe what a model can do.

type ModelFeatures struct {
    // Input/Output modalities
    Modalities ModelModalities `json:"modalities" yaml:"modalities"` // Supported input/output modalities

    ToolCalls   bool `json:"tool_calls" yaml:"tool_calls"`
    Tools       bool `json:"tools" yaml:"tools"`             // Accepts tool definitions in requests (accepts tools parameter)
    ToolChoice  bool `json:"tool_choice" yaml:"tool_choice"` // Supports tool choice strategies (auto/none/required control)
    WebSearch   bool `json:"web_search" yaml:"web_search"`   // Supports web search capabilities
    Attachments bool `json:"attachments" yaml:"attachments"` // Attachment support details

    // Reasoning & Verbosity
    Reasoning        bool `json:"reasoning" yaml:"reasoning"`                 // Supports basic reasoning
    ReasoningEffort  bool `json:"reasoning_effort" yaml:"reasoning_effort"`   // Supports configurable reasoning intensity
    ReasoningTokens  bool `json:"reasoning_tokens" yaml:"reasoning_tokens"`   // Supports specific reasoning token allocation
    IncludeReasoning bool `json:"include_reasoning" yaml:"include_reasoning"` // Supports including reasoning traces in response
    Verbosity        bool `json:"verbosity" yaml:"verbosity"`                 // Supports verbosity control (GPT-5+)

    Temperature bool `json:"temperature" yaml:"temperature"`
    TopP        bool `json:"top_p" yaml:"top_p"`         // Supports nucleus sampling through top_p.
    TopK        bool `json:"top_k" yaml:"top_k"`         // [Advanced] Supports top_k parameter
    TopA        bool `json:"top_a" yaml:"top_a"`         // [Advanced] Supports top_a parameter (top-a sampling)
    MinP        bool `json:"min_p" yaml:"min_p"`         // [Advanced] Supports min_p parameter (minimum probability threshold)
    TypicalP    bool `json:"typical_p" yaml:"typical_p"` // [Advanced] Supports typical_p parameter (typical sampling)
    TFS         bool `json:"tfs" yaml:"tfs"`             // [Advanced] Supports tail free sampling

    // Generation control - Length and termination
    MaxTokens       bool `json:"max_tokens" yaml:"max_tokens"`               // [Core] Supports max_tokens parameter
    MaxOutputTokens bool `json:"max_output_tokens" yaml:"max_output_tokens"` // [Core] Supports max_output_tokens parameter (some providers distinguish from max_tokens)
    Stop            bool `json:"stop" yaml:"stop"`                           // [Core] Supports stop sequences/words
    StopTokenIDs    bool `json:"stop_token_ids" yaml:"stop_token_ids"`       // [Advanced] Supports stop token IDs (numeric)

    FrequencyPenalty  bool `json:"frequency_penalty" yaml:"frequency_penalty"`       // [Core] Supports frequency penalty
    PresencePenalty   bool `json:"presence_penalty" yaml:"presence_penalty"`         // [Core] Supports presence penalty
    RepetitionPenalty bool `json:"repetition_penalty" yaml:"repetition_penalty"`     // [Advanced] Supports repetition penalty
    NoRepeatNgramSize bool `json:"no_repeat_ngram_size" yaml:"no_repeat_ngram_size"` // [Niche] Supports n-gram repetition blocking
    LengthPenalty     bool `json:"length_penalty" yaml:"length_penalty"`             // [Niche] Supports length penalty (seq2seq style)

    // Generation control - Token biasing
    LogitBias     bool `json:"logit_bias" yaml:"logit_bias"`         // [Core] Supports token-level bias adjustment
    BadWords      bool `json:"bad_words" yaml:"bad_words"`           // [Advanced] Supports bad words/disallowed tokens
    AllowedTokens bool `json:"allowed_tokens" yaml:"allowed_tokens"` // [Niche] Supports token whitelist

    // Generation control - Determinism
    Seed bool `json:"seed" yaml:"seed"` // [Advanced] Supports deterministic seeding

    // Generation control - Observability
    Logprobs    bool `json:"logprobs" yaml:"logprobs"`         // [Core] Supports returning log probabilities
    TopLogprobs bool `json:"top_logprobs" yaml:"top_logprobs"` // [Core] Supports returning top N log probabilities
    Echo        bool `json:"echo" yaml:"echo"`                 // [Advanced] Supports echoing prompt with completion

    // Generation control - Multiplicity and reranking
    N      bool `json:"n" yaml:"n"`             // [Advanced] Supports generating multiple candidates
    BestOf bool `json:"best_of" yaml:"best_of"` // [Advanced] Supports server-side sampling with best selection

    // Generation control - Alternative sampling strategies (niche)
    Mirostat                      bool `json:"mirostat" yaml:"mirostat"`                                                 // [Niche] Supports Mirostat sampling
    MirostatTau                   bool `json:"mirostat_tau" yaml:"mirostat_tau"`                                         // [Niche] Supports Mirostat tau parameter
    MirostatEta                   bool `json:"mirostat_eta" yaml:"mirostat_eta"`                                         // [Niche] Supports Mirostat eta parameter
    ContrastiveSearchPenaltyAlpha bool `json:"contrastive_search_penalty_alpha" yaml:"contrastive_search_penalty_alpha"` // [Niche] Supports contrastive decoding

    // Generation control - Beam search (niche)
    NumBeams         bool `json:"num_beams" yaml:"num_beams"`                 // [Niche] Supports beam search
    EarlyStopping    bool `json:"early_stopping" yaml:"early_stopping"`       // [Niche] Supports early stopping in beam search
    DiversityPenalty bool `json:"diversity_penalty" yaml:"diversity_penalty"` // [Niche] Supports diversity penalty in beam search

    // Response delivery
    FormatResponse    bool `json:"format_response" yaml:"format_response"`       // Supports alternative response formats (beyond text)
    StructuredOutputs bool `json:"structured_outputs" yaml:"structured_outputs"` // Supports structured outputs (JSON schema validation)
    Streaming         bool `json:"streaming" yaml:"streaming"`                   // Supports response streaming
    // contains filtered or unexported fields
}

func (ModelFeatures) MarshalJSON
func (f ModelFeatures) MarshalJSON() ([]byte, error)

MarshalJSON preserves feature presence in immutable catalog payloads.

func (ModelFeatures) MarshalYAML
func (f ModelFeatures) MarshalYAML() (any, error)

MarshalYAML renders the complete Boolean capability surface for the human-editable YAML workspace. Capabilities without an observed claim use the conservative false default, while explicitly unknown claims remain null. Immutable JSON generations retain the precise missing/unknown/known distinction.

func (*ModelFeatures) SetSupport
func (f *ModelFeatures) SetSupport(feature ModelFeature, supported bool) bool

SetSupport records an explicit supported or unsupported capability.

func (*ModelFeatures) SetSupportUnknown
func (f *ModelFeatures) SetSupportUnknown(feature ModelFeature) bool

SetSupportUnknown records that a capability was explicitly reported as unknown.

func (*ModelFeatures) Support
func (f *ModelFeatures) Support(feature ModelFeature) (bool, ValuePresence)

Support returns the capability value and its presence state.

func (*ModelFeatures) UnmarshalJSON
func (f *ModelFeatures) UnmarshalJSON(data []byte) error

UnmarshalJSON restores feature presence from immutable catalog payloads.

func (*ModelFeatures) UnmarshalYAML
func (f *ModelFeatures) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML restores per-capability presence from the human YAML record.

func (*ModelFeatures) UnsetSupport
func (f *ModelFeatures) UnsetSupport(feature ModelFeature) bool

UnsetSupport removes a capability claim.

type ModelGeneration

ModelGeneration - core chat completions generation controls.

type ModelGeneration struct {
    // Core sampling and decoding
    Temperature *FloatRange `json:"temperature,omitempty" yaml:"temperature,omitempty"`
    TopP        *FloatRange `json:"top_p,omitempty" yaml:"top_p,omitempty"`
    TopK        *IntRange   `json:"top_k,omitempty" yaml:"top_k,omitempty"`
    TopA        *FloatRange `json:"top_a,omitempty" yaml:"top_a,omitempty"`
    MinP        *FloatRange `json:"min_p,omitempty" yaml:"min_p,omitempty"`
    TypicalP    *FloatRange `json:"typical_p,omitempty" yaml:"typical_p,omitempty"`
    TFS         *FloatRange `json:"tfs,omitempty" yaml:"tfs,omitempty"`

    // Length and termination
    MaxTokens       *int `json:"max_tokens,omitempty" yaml:"max_tokens,omitempty"`
    MaxOutputTokens *int `json:"max_output_tokens,omitempty" yaml:"max_output_tokens,omitempty"`

    // Repetition control
    FrequencyPenalty  *FloatRange `json:"frequency_penalty,omitempty" yaml:"frequency_penalty,omitempty"`
    PresencePenalty   *FloatRange `json:"presence_penalty,omitempty" yaml:"presence_penalty,omitempty"`
    RepetitionPenalty *FloatRange `json:"repetition_penalty,omitempty" yaml:"repetition_penalty,omitempty"`
    NoRepeatNgramSize *IntRange   `json:"no_repeat_ngram_size,omitempty" yaml:"no_repeat_ngram_size,omitempty"`
    LengthPenalty     *FloatRange `json:"length_penalty,omitempty" yaml:"length_penalty,omitempty"`

    // Observability
    TopLogprobs *int `json:"top_logprobs,omitempty" yaml:"top_logprobs,omitempty"` // Number of top log probabilities to return

    // Multiplicity and reranking
    N      *IntRange `json:"n,omitempty" yaml:"n,omitempty"`             // Number of candidates to generate
    BestOf *IntRange `json:"best_of,omitempty" yaml:"best_of,omitempty"` // Server-side sampling with best selection

    // Alternative sampling strategies (niche)
    MirostatTau                   *FloatRange `json:"mirostat_tau,omitempty" yaml:"mirostat_tau,omitempty"`
    MirostatEta                   *FloatRange `json:"mirostat_eta,omitempty" yaml:"mirostat_eta,omitempty"`
    ContrastiveSearchPenaltyAlpha *FloatRange `json:"contrastive_search_penalty_alpha,omitempty" yaml:"contrastive_search_penalty_alpha,omitempty"`

    // Beam search (niche)
    NumBeams         *IntRange   `json:"num_beams,omitempty" yaml:"num_beams,omitempty"`
    DiversityPenalty *FloatRange `json:"diversity_penalty,omitempty" yaml:"diversity_penalty,omitempty"`
}

type ModelLimit

ModelLimit identifies one model token limit.

type ModelLimit string

Model limit identifiers.

const (
    ModelLimitContextWindow  ModelLimit = "context_window"
    ModelLimitInputTokens    ModelLimit = "input_tokens"
    ModelLimitOutputTokens   ModelLimit = "output_tokens"
    ModelLimitDocumentPages  ModelLimit = "document_pages"
    ModelLimitMaxDocuments   ModelLimit = "max_documents"
    ModelLimitDocumentTokens ModelLimit = "document_tokens"
)

func PublishedModelLimits
func PublishedModelLimits() []ModelLimit

PublishedModelLimits returns every model limit in published order. External consumers use this list so they report the same limits.

type ModelLimits

ModelLimits represents the limits for a model.

type ModelLimits struct {
    ContextWindow int64 `json:"context_window" yaml:"context_window"` // Context window size in tokens
    InputTokens   int64 `json:"input_tokens" yaml:"input_tokens"`     // Maximum input tokens
    OutputTokens  int64 `json:"output_tokens" yaml:"output_tokens"`   // Maximum output tokens
    // DocumentPages is the largest document the provider reads in one call,
    // counted in pages. A provider states this bound in pages rather than in
    // tokens, because it refuses the document before it reads a token of it.
    DocumentPages int64 `json:"document_pages,omitempty" yaml:"document_pages,omitempty"`
    // MaxDocuments is the longest document list the provider ranks in one
    // call. A reranker refuses a longer list rather than truncating it, and a
    // caller that does not read this bound sends a request that cannot succeed.
    MaxDocuments   int64 `json:"max_documents,omitempty" yaml:"max_documents,omitempty"`
    DocumentTokens int64 `json:"document_tokens,omitempty" yaml:"document_tokens,omitempty"`
    // contains filtered or unexported fields
}

func (ModelLimits) MarshalJSON
func (l ModelLimits) MarshalJSON() ([]byte, error)

MarshalJSON preserves limit presence in immutable catalog payloads.

func (ModelLimits) MarshalYAML
func (l ModelLimits) MarshalYAML() (any, error)

MarshalYAML preserves explicit zero and unknown limits while omitting unobserved limits.

func (*ModelLimits) Set
func (l *ModelLimits) Set(limit ModelLimit, value int64) bool

Set records an explicit model limit, including zero.

func (*ModelLimits) SetUnknown
func (l *ModelLimits) SetUnknown(limit ModelLimit) bool

SetUnknown records that a model limit was explicitly reported as unknown.

func (*ModelLimits) UnmarshalJSON
func (l *ModelLimits) UnmarshalJSON(data []byte) error

UnmarshalJSON restores limit presence from immutable catalog payloads.

func (*ModelLimits) UnmarshalYAML
func (l *ModelLimits) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML restores per-limit presence from the human YAML record.

func (*ModelLimits) Unset
func (l *ModelLimits) Unset(limit ModelLimit) bool

Unset removes a model limit claim.

func (*ModelLimits) Value
func (l *ModelLimits) Value(limit ModelLimit) (int64, ValuePresence)

Value returns a model limit and its presence state.

type ModelLineage

ModelLineage represents model family and derivation metadata.

type ModelLineage struct {
    Family string  `json:"family,omitempty" yaml:"family,omitempty"` // Model family or series, such as gpt-5 or claude
    Root   *string `json:"root,omitempty" yaml:"root,omitempty"`     // Root/base model ID reported by a provider
    Parent *string `json:"parent,omitempty" yaml:"parent,omitempty"` // Parent model ID for derived/fine-tuned models
}

type ModelMetadata

ModelMetadata represents the metadata for a model.

type ModelMetadata struct {
    // ReleaseDate is the first known public release of this model identity. For
    // a rolling alias, its KnowledgeCutoff may advance beyond that initial date.
    // A zero value means unknown. Starmap does not invent missing day precision.
    ReleaseDate     utc.Time           `json:"release_date" yaml:"release_date"`
    OpenWeights     bool               `json:"open_weights" yaml:"open_weights"`                             // Whether model weights are open
    KnowledgeCutoff *utc.Time          `json:"knowledge_cutoff,omitempty" yaml:"knowledge_cutoff,omitempty"` // Knowledge cutoff date (YYYY-MM or YYYY-MM-DD format)
    Tags            []ModelTag         `json:"tags,omitempty" yaml:"tags,omitempty"`                         // Use case tags for categorizing the model
    Architecture    *ModelArchitecture `json:"architecture,omitempty" yaml:"architecture,omitempty"`         // Technical architecture details
    // contains filtered or unexported fields
}

func (ModelMetadata) MarshalJSON
func (m ModelMetadata) MarshalJSON() ([]byte, error)

MarshalJSON preserves open-weights presence in immutable catalog payloads.

func (ModelMetadata) MarshalYAML
func (m ModelMetadata) MarshalYAML() (any, error)

MarshalYAML preserves explicit false and unknown open-weights claims.

func (*ModelMetadata) OpenWeightsValue
func (m *ModelMetadata) OpenWeightsValue() (bool, ValuePresence)

OpenWeightsValue returns open-weights support and its presence state.

func (*ModelMetadata) SetOpenWeights
func (m *ModelMetadata) SetOpenWeights(open bool)

SetOpenWeights records an explicit open-weights value.

func (*ModelMetadata) SetOpenWeightsUnknown
func (m *ModelMetadata) SetOpenWeightsUnknown()

SetOpenWeightsUnknown records that open-weights status is explicitly unknown.

func (*ModelMetadata) UnmarshalJSON
func (m *ModelMetadata) UnmarshalJSON(data []byte) error

UnmarshalJSON restores open-weights presence from immutable catalog payloads.

func (*ModelMetadata) UnmarshalYAML
func (m *ModelMetadata) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML restores open-weights presence from the human YAML record.

func (*ModelMetadata) UnsetOpenWeights
func (m *ModelMetadata) UnsetOpenWeights()

UnsetOpenWeights removes the open-weights claim.

type ModelModalities

ModelModalities represents the input/output modalities supported by a model.

type ModelModalities struct {
    Input  []ModelModality `json:"input" yaml:"input"`   // Supported input modalities
    Output []ModelModality `json:"output" yaml:"output"` // Supported output modalities
}

type ModelModality

ModelModality represents a supported input or output modality for AI models.

type ModelModality string

Supported model modalities.

const (
    ModelModalityText      ModelModality = "text"
    ModelModalityAudio     ModelModality = "audio"
    ModelModalityImage     ModelModality = "image"
    ModelModalityVideo     ModelModality = "video"
    ModelModalityPDF       ModelModality = "pdf"
    ModelModalityEmbedding ModelModality = "embedding" // Vector embeddings
)

func (ModelModality) String
func (m ModelModality) String() string

String returns text for ModelModality.

type ModelMode

ModelMode represents an alternate provider service mode for a model.

type ModelMode struct {
    Pricing  *ModelPricing      `json:"pricing,omitempty" yaml:"pricing,omitempty"`   // Mode-specific pricing
    Provider *ModelProviderMode `json:"provider,omitempty" yaml:"provider,omitempty"` // Mode-specific provider request overrides
}

type ModelOperationPricing

ModelOperationPricing represents fixed costs for operations.

type ModelOperationPricing struct {
    // Core operations
    Request *float64 `json:"request,omitempty" yaml:"request,omitempty"` // Cost per API request

    // Media operations
    ImageInput *float64 `json:"image_input,omitempty" yaml:"image_input,omitempty"` // Cost per image processed
    PageInput  *float64 `json:"page_input,omitempty" yaml:"page_input,omitempty"`
    AudioInput *float64 `json:"audio_input,omitempty" yaml:"audio_input,omitempty"` // Cost per audio input
    VideoInput *float64 `json:"video_input,omitempty" yaml:"video_input,omitempty"` // Cost per video input

    // Generation operations
    ImageGen *float64 `json:"image_gen,omitempty" yaml:"image_gen,omitempty"` // Cost per image generated
    AudioGen *float64 `json:"audio_gen,omitempty" yaml:"audio_gen,omitempty"` // Cost per audio generated
    VideoGen *float64 `json:"video_gen,omitempty" yaml:"video_gen,omitempty"` // Cost per video generated

    // Service operations
    WebSearch    *float64 `json:"web_search,omitempty" yaml:"web_search,omitempty"`       // Cost per web search
    FunctionCall *float64 `json:"function_call,omitempty" yaml:"function_call,omitempty"` // Cost per function call
    ToolUse      *float64 `json:"tool_use,omitempty" yaml:"tool_use,omitempty"`           // Cost per tool usage

    SearchUnit *float64 `json:"search_unit,omitempty" yaml:"search_unit,omitempty"`
    // RerankBasis names which recorded price a rerank turn draws from.
    // Providers disagree: some bill a search unit and some bill the tokens they
    // read. A consumer reads this field rather than guessing from which price
    // happens to be present.
    RerankBasis ModelRerankBasis `json:"rerank_basis,omitempty" yaml:"rerank_basis,omitempty"`
}

type ModelPricing

ModelPricing represents the pricing structure for a model.

type ModelPricing struct {
    // Token-based costs
    Tokens *ModelTokenPricing `json:"tokens,omitempty" yaml:"tokens,omitempty"`

    // Fixed costs per operation
    Operations *ModelOperationPricing `json:"operations,omitempty" yaml:"operations,omitempty"`

    // Conditional/tiered pricing
    Tiers []ModelPricingTier `json:"tiers,omitempty" yaml:"tiers,omitempty"`

    // Metadata
    Currency ModelPricingCurrency `json:"currency" yaml:"currency"` // "USD", "EUR", etc.

    // Optional half-open validity interval [effective_from, effective_until).
    EffectiveFrom  *utc.Time `json:"effective_from,omitempty" yaml:"effective_from,omitempty"`
    EffectiveUntil *utc.Time `json:"effective_until,omitempty" yaml:"effective_until,omitempty"`
}

func (*ModelPricing) IsEffectiveAt
func (p *ModelPricing) IsEffectiveAt(at time.Time) bool

IsEffectiveAt reports whether pricing applies at the supplied instant.

func (*ModelPricing) Validate
func (p *ModelPricing) Validate() error

Validate verifies that pricing is structurally complete and financially safe to use as an authoritative provider-offering observation.

type ModelPricingCurrency

ModelPricingCurrency represents a currency code for model pricing.

type ModelPricingCurrency string

Model pricing currencies.

const (
    ModelPricingCurrencyUSD ModelPricingCurrency = "USD"
    ModelPricingCurrencyEUR ModelPricingCurrency = "EUR"
    ModelPricingCurrencyJPY ModelPricingCurrency = "JPY"
    ModelPricingCurrencyGBP ModelPricingCurrency = "GBP"
    ModelPricingCurrencyAUD ModelPricingCurrency = "AUD"
    ModelPricingCurrencyCAD ModelPricingCurrency = "CAD"
    ModelPricingCurrencyCNY ModelPricingCurrency = "CNY"
    ModelPricingCurrencyNZD ModelPricingCurrency = "NZD"
)

func (ModelPricingCurrency) String
func (m ModelPricingCurrency) String() string

String returns text for ModelPricingCurrency.

func (ModelPricingCurrency) Symbol
func (m ModelPricingCurrency) Symbol() string

Symbol returns the symbol for a given currency.

type ModelPricingTier

ModelPricingTier represents conditional pricing for a model.

type ModelPricingTier struct {
    Name       string                 `json:"name,omitempty" yaml:"name,omitempty"`             // Optional source/name, such as context_over_200k
    Type       ModelPricingTierType   `json:"type" yaml:"type"`                                 // Tier dimension, such as context
    Size       int64                  `json:"size,omitempty" yaml:"size,omitempty"`             // Threshold size for the tier dimension
    Tokens     *ModelTokenPricing     `json:"tokens,omitempty" yaml:"tokens,omitempty"`         // Token prices in this tier
    Operations *ModelOperationPricing `json:"operations,omitempty" yaml:"operations,omitempty"` // Operation prices in this tier
}

type ModelPricingTierType

ModelPricingTierType represents the dimension that activates a pricing tier.

type ModelPricingTierType string

const (
    // ModelPricingTierTypeContext means the tier applies above a context-size threshold.
    ModelPricingTierTypeContext ModelPricingTierType = "context"
)

func (ModelPricingTierType) String
func (m ModelPricingTierType) String() string

String returns text for ModelPricingTierType.

type ModelProviderMode

ModelProviderMode represents provider request overrides for a model mode.

type ModelProviderMode struct {
    Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"` // HTTP headers required by this mode
    Body    map[string]any    `json:"body,omitempty" yaml:"body,omitempty"`       // JSON request body fields required by this mode
}

func (ModelProviderMode) MarshalYAML
func (m ModelProviderMode) MarshalYAML() (any, error)

MarshalYAML preserves request-body values as native YAML scalars, sequences, mappings, and nulls. The body is a JSON request fragment, so SetExtension rejects values that JSON cannot represent.

func (*ModelProviderMode) UnmarshalYAML
func (m *ModelProviderMode) UnmarshalYAML(data []byte) error

UnmarshalYAML restores request-body values through JSON so YAML library implementation types such as []byte cannot leak into the provider request contract.

type ModelRerankBasis

ModelRerankBasis names the unit a provider bills one rerank call in.

type ModelRerankBasis string

const (
    // ModelRerankBasisSearchUnit bills one query against a bounded document
    // count. Cohere and OpenRouter bill this way.
    ModelRerankBasisSearchUnit ModelRerankBasis = "search-unit"
    // ModelRerankBasisToken bills the tokens the provider reads across the
    // query and the documents. Jina and Voyage bill this way.
    ModelRerankBasisToken ModelRerankBasis = "token"
)

func (ModelRerankBasis) String
func (m ModelRerankBasis) String() string

String returns text for ModelRerankBasis.

type ModelResponseFormat

ModelResponseFormat represents a supported response format.

type ModelResponseFormat string

Model response formats.

const (
    // Basic formats.
    ModelResponseFormatText ModelResponseFormat = "text" // Plain text responses (default)

    // JSON formats.
    ModelResponseFormatJSON       ModelResponseFormat = "json"        // JSON encouraged via prompting
    ModelResponseFormatJSONMode   ModelResponseFormat = "json_mode"   // Forced valid JSON (OpenAI style)
    ModelResponseFormatJSONObject ModelResponseFormat = "json_object" // Same as json_mode (OpenAI API name)

    // Structured formats.
    ModelResponseFormatJSONSchema       ModelResponseFormat = "json_schema"       // Schema-validated JSON (OpenAI structured output)
    ModelResponseFormatStructuredOutput ModelResponseFormat = "structured_output" // General structured output support

    // Function calling (alternative to JSON schema).
    ModelResponseFormatFunctionCall ModelResponseFormat = "function_call" // Tool/function calling for structured data
)

func (ModelResponseFormat) String
func (mrf ModelResponseFormat) String() string

String returns text for ModelResponseFormat.

type ModelResponseProtocol

ModelResponseProtocol represents a supported delivery protocol.

type ModelResponseProtocol string

Model delivery protocols.

const (
    ModelResponseProtocolHTTP      ModelResponseProtocol = "http"      // HTTP/HTTPS REST API
    ModelResponseProtocolGRPC      ModelResponseProtocol = "grpc"      // gRPC protocol
    ModelResponseProtocolWebSocket ModelResponseProtocol = "websocket" // WebSocket protocol
)

type ModelStatus

ModelStatus represents a model lifecycle or availability state.

type ModelStatus string

Model lifecycle states.

const (
    ModelStatusActive     ModelStatus = "active"
    ModelStatusBeta       ModelStatus = "beta"
    ModelStatusPreview    ModelStatus = "preview"
    ModelStatusDeprecated ModelStatus = "deprecated"
    ModelStatusUnknown    ModelStatus = "unknown"
)

func (ModelStatus) String
func (ms ModelStatus) String() string

String returns text for ModelStatus.

type ModelStreaming

ModelStreaming describes the available response delivery modes.

type ModelStreaming string

Model streaming modes.

const (
    ModelStreamingSSE       ModelStreaming = "sse"       // Server-Sent Events streaming
    ModelStreamingWebSocket ModelStreaming = "websocket" // WebSocket streaming
    ModelStreamingChunked   ModelStreaming = "chunked"   // HTTP chunked transfer encoding
)

func (ModelStreaming) String
func (ms ModelStreaming) String() string

String returns text for ModelStreaming.

type ModelTag

ModelTag represents a use case or category tag for models.

type ModelTag string

Model tags for categorizing models by use case and capabilities.

const (
    // Core Use Cases.
    ModelTagCoding    ModelTag = "coding"
    ModelTagWriting   ModelTag = "writing"
    ModelTagReasoning ModelTag = "reasoning"
    ModelTagMath      ModelTag = "math"
    ModelTagChat      ModelTag = "chat"
    ModelTagInstruct  ModelTag = "instruct"
    ModelTagResearch  ModelTag = "research"
    ModelTagCreative  ModelTag = "creative"
    ModelTagRoleplay  ModelTag = "roleplay"

    // Technical Capabilities.
    ModelTagFunctionCalling ModelTag = "function_calling"   // Tool/function calling
    ModelTagEmbedding       ModelTag = "embedding"          // Text embeddings
    ModelTagRerank          ModelTag = "rerank"             // Relevance ranking of documents
    ModelTagModeration      ModelTag = "moderation"         // Harm-category classification
    ModelTagSummarization   ModelTag = "summarization"      // Text summarization
    ModelTagTranslation     ModelTag = "translation"        // Language translation
    ModelTagQA              ModelTag = "question_answering" // Question answering

    // Modality-Specific.
    ModelTagVision       ModelTag = "vision"         // Computer vision
    ModelTagMultimodal   ModelTag = "multimodal"     // Multiple input modalities
    ModelTagAudio        ModelTag = "audio"          // Audio processing
    ModelTagTextToImage  ModelTag = "text_to_image"  // Text-to-image generation
    ModelTagTextToVideo  ModelTag = "text_to_video"  // Text-to-video generation
    ModelTagTextToSpeech ModelTag = "text_to_speech" // Text-to-speech synthesis
    ModelTagSpeechToText ModelTag = "speech_to_text" // Speech recognition
    ModelTagImageToText  ModelTag = "image_to_text"  // Image captioning/OCR

    // Domain-Specific.
    ModelTagMedical   ModelTag = "medical"   // Medical and healthcare
    ModelTagLegal     ModelTag = "legal"     // Legal document processing
    ModelTagFinance   ModelTag = "finance"   // Financial analysis
    ModelTagScience   ModelTag = "science"   // Scientific applications
    ModelTagEducation ModelTag = "education" // Educational content
)

func (ModelTag) String
func (tag ModelTag) String() string

String returns text for ModelTag.

type ModelTokenCost

ModelTokenCost represents cost per token with flexible units.

type ModelTokenCost struct {
    PerToken float64 `json:"per_token" yaml:"per_token"`  // Cost per individual token
    Per1M    float64 `json:"per_1m_tokens" yaml:"per_1m"` // Cost per 1M tokens
}

func (*ModelTokenCost) MarshalYAML
func (t *ModelTokenCost) MarshalYAML() (any, error)

MarshalYAML implements custom YAML marshaling for TokenCost to format decimals consistently.

type ModelTokenPricing

ModelTokenPricing represents all token-based costs.

type ModelTokenPricing struct {
    // Core tokens
    Input  *ModelTokenCost `json:"input,omitempty" yaml:"input,omitempty"`   // Input/prompt tokens
    Output *ModelTokenCost `json:"output,omitempty" yaml:"output,omitempty"` // Standard output tokens

    // Advanced token types
    Reasoning  *ModelTokenCost `json:"reasoning,omitempty" yaml:"reasoning,omitempty"`     // Internal reasoning tokens
    CacheRead  *ModelTokenCost `json:"cache_read,omitempty" yaml:"cache_read,omitempty"`   // Cache read costs (flat structure)
    CacheWrite *ModelTokenCost `json:"cache_write,omitempty" yaml:"cache_write,omitempty"` // Cache write costs (flat structure)

    AudioInput  *ModelTokenCost `json:"audio_input,omitempty" yaml:"audio_input,omitempty"`   // Audio input tokens
    AudioOutput *ModelTokenCost `json:"audio_output,omitempty" yaml:"audio_output,omitempty"` // Audio output tokens
}

func (*ModelTokenPricing) MarshalYAML
func (t *ModelTokenPricing) MarshalYAML() (any, error)

MarshalYAML implements custom YAML marshaling for token pricing.

type ModelTools

ModelTools represents external tool and capability integrations.

type ModelTools struct {
    // Tool calling configuration
    // Specifies which tool choice strategies this model supports.
    // Requires both Tools=true and ToolChoice=true in ModelFeatures.
    // Common values: ["auto"], ["auto", "none"], ["auto", "none", "required"]
    ToolChoices []ToolChoice `json:"tool_choices,omitempty" yaml:"tool_choices,omitempty"` // Supported tool choice strategies

    // Web search configuration
    // Only applicable if WebSearch=true in ModelFeatures
    WebSearch *ModelWebSearch `json:"web_search,omitempty" yaml:"web_search,omitempty"`
}

type ModelWebSearch

ModelWebSearch represents web search configuration for search-enabled models.

type ModelWebSearch struct {
    // Plugin-based web search options (for models using OpenRouter's web plugin)
    MaxResults   *int    `json:"max_results,omitempty" yaml:"max_results,omitempty"`     // Maximum number of search results (defaults to 5)
    SearchPrompt *string `json:"search_prompt,omitempty" yaml:"search_prompt,omitempty"` // Custom prompt for search results

    // Built-in web search options (for models with native web search like GPT-4.1, Perplexity)
    SearchContextSizes []ModelControlLevel `json:"search_context_sizes,omitempty" yaml:"search_context_sizes,omitempty"` // Supported context sizes (low, medium, high)
    DefaultContextSize *ModelControlLevel  `json:"default_context_size,omitempty" yaml:"default_context_size,omitempty"` // Default search context size
}

type Models

Models is a concurrent safe map of models.

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

func NewModels
func NewModels() *Models

NewModels creates a new Models instance.

func (*Models) Add
func (m *Models) Add(model *Model) error

Add adds a model, returning an error if it already exists.

func (*Models) AddBatch
func (m *Models) AddBatch(models []*Model) map[string]error

AddBatch adds multiple models in a single operation. Only adds models that do not already exist - fails if a model ID already exists. Returns a map of model IDs to errors for any failed additions.

func (*Models) Clear
func (m *Models) Clear()

Clear removes all models.

func (*Models) Delete
func (m *Models) Delete(id string) error

Delete removes a model by id. Returns an error if the model does not exist.

func (*Models) DeleteBatch
func (m *Models) DeleteBatch(ids []string) map[string]error

DeleteBatch removes multiple models by ID. The returned map identifies IDs that DeleteBatch did not find.

func (*Models) Exists
func (m *Models) Exists(id string) bool

Exists checks if a model exists without returning it.

func (*Models) ForEach
func (m *Models) ForEach(fn func(id string, model *Model) bool)

ForEach applies a function to each model. The function should not modify the model. If the function returns false, iteration stops early.

func (*Models) Get
func (m *Models) Get(id string) (*Model, bool)

Get returns a model by id and whether it exists.

func (*Models) Len
func (m *Models) Len() int

Len returns the number of models.

func (*Models) List
func (m *Models) List() []Model

List returns a slice of all models as values (copies).

func (*Models) Map
func (m *Models) Map() map[string]*Model

Map returns a copy of all models.

func (*Models) Set
func (m *Models) Set(id string, model *Model) error

Set sets a model by id. Returns an error if model is nil.

func (*Models) SetBatch
func (m *Models) SetBatch(models map[string]*Model) error

SetBatch sets multiple models in a single operation. Overwrites existing models or adds new ones (upsert behavior). Returns an error if any model is nil.

type ModelsReader

ModelsReader exposes model collection reads without mutation methods.

type ModelsReader interface {
    Get(string) (*Model, bool)
    Exists(string) bool
    Len() int
    List() []Model
    Map() map[string]*Model
    ForEach(func(string, *Model) bool)
}

type OfferingAvailability

OfferingAvailability describes an offering's current availability.

type OfferingAvailability string

const (
    // OfferingAvailabilityUnknown means no source supplied current availability.
    OfferingAvailabilityUnknown OfferingAvailability = "unknown"
    // OfferingAvailabilityAvailable means the offering is generally available.
    OfferingAvailabilityAvailable OfferingAvailability = "available"
    // OfferingAvailabilityRestricted means access depends on region, account, or allowlisting.
    OfferingAvailabilityRestricted OfferingAvailability = "restricted"
    // OfferingAvailabilityUnavailable means the provider does not currently serve the offering.
    OfferingAvailabilityUnavailable OfferingAvailability = "unavailable"
)

type OfferingKey

OfferingKey is the globally unique identity of a provider model offering.

type OfferingKey struct {
    ProviderID      ProviderID      `json:"provider_id" yaml:"provider_id"`
    ProviderModelID ProviderModelID `json:"provider_model_id" yaml:"provider_model_id"`
}

type OfferingLifecycle

OfferingLifecycle describes the provider-specific lifecycle of an offering.

type OfferingLifecycle string

const (
    // OfferingLifecycleUnknown means no source supplied a lifecycle state.
    OfferingLifecycleUnknown OfferingLifecycle = "unknown"
    // OfferingLifecycleActive means the provider supports new requests.
    OfferingLifecycleActive OfferingLifecycle = "active"
    // OfferingLifecyclePreview means the offering is preview or beta quality.
    OfferingLifecyclePreview OfferingLifecycle = "preview"
    // OfferingLifecycleDeprecated means callers should migrate away from the offering.
    OfferingLifecycleDeprecated OfferingLifecycle = "deprecated"
    // OfferingLifecycleRetired means the provider no longer accepts new requests.
    OfferingLifecycleRetired OfferingLifecycle = "retired"
)

type OfferingRequestBody

OfferingRequestBody is a typed set of exact JSON request-body values. RawMessage preserves booleans, numbers, strings, arrays, objects, and null without routing values through map[string]any.

type OfferingRequestBody map[string]json.RawMessage

func (OfferingRequestBody) MarshalYAML
func (b OfferingRequestBody) MarshalYAML() (any, error)

MarshalYAML converts each exact JSON value to a native YAML scalar, sequence, mapping, or null. This prevents RawMessage bytes from becoming integers.

func (*OfferingRequestBody) UnmarshalYAML
func (b *OfferingRequestBody) UnmarshalYAML(data []byte) error

UnmarshalYAML restores native YAML values as exact JSON values.

type OfferingRequestHeaders

OfferingRequestHeaders is a typed set of provider request header overrides.

type OfferingRequestHeaders map[string]string

type Option

Option configures a catalog.

type Option func(*options)

func WithFS
func WithFS(fsys fs.FS) Option

WithFS configures the catalog to use a custom fs.FS for reading.

func WithMergeStrategy
func WithMergeStrategy(strategy MergeStrategy) Option

WithMergeStrategy sets the default merge strategy.

func WithPath
func WithPath(path string) Option

WithPath configures the catalog to use a directory path for reading This creates an os.DirFS under the hood.

func WithWritePath
func WithWritePath(path string) Option

WithWritePath sets a specific path for writing catalog files.

type PayloadDescriptor

PayloadDescriptor binds a generation manifest to exact immutable bytes.

type PayloadDescriptor struct {
    Checksum  string `json:"checksum" yaml:"checksum"`
    SizeBytes int64  `json:"size_bytes" yaml:"size_bytes"`
    MediaType string `json:"media_type" yaml:"media_type"`
}

func DescribeCatalogPayload
func DescribeCatalogPayload(payload []byte) PayloadDescriptor

DescribeCatalogPayload returns the descriptor for canonical catalog bytes.

func (PayloadDescriptor) Verify
func (d PayloadDescriptor) Verify(payload []byte) error

Verify checks that payload exactly matches the descriptor.

type Provenance

Provenance is a concurrent-safe container for provenance data. It follows the same pattern as Authors, Models, and Providers containers, using RWMutex for thread safety and returning deep copies to prevent external modification.

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

func NewProvenance
func NewProvenance(opts ...ProvenanceOption) *Provenance

NewProvenance creates a new Provenance container with optional configuration.

func (*Provenance) Clear
func (p *Provenance) Clear()

Clear removes all provenance data.

func (*Provenance) EncodeYAML
func (p *Provenance) EncodeYAML() (string, error)

EncodeYAML returns provenance YAML. It returns a typed parse error for evidence values that YAML cannot represent safely.

func (*Provenance) FindByField
func (p *Provenance) FindByField(resourceType evidence.ResourceType, resourceID string, field string) []provenance.Entry

FindByField retrieves provenance for a specific resource field. It returns nil when no entry matches.

func (*Provenance) FindByResource
func (p *Provenance) FindByResource(resourceType evidence.ResourceType, resourceID string) map[string][]provenance.Entry

FindByResource retrieves all provenance for a resource. Returns a map of field names to their provenance entries.

func (*Provenance) FindModel
func (p *Provenance) FindModel(providerID ProviderID, modelID string) map[string][]provenance.Entry

FindModel retrieves all provenance for one provider model.

func (*Provenance) FindModelField
func (p *Provenance) FindModelField(providerID ProviderID, modelID, field string) []provenance.Entry

FindModelField retrieves provenance for one field of one provider model.

func (*Provenance) FormatYAML
func (p *Provenance) FormatYAML() string

FormatYAML returns the provenance data formatted as YAML. This follows the same pattern as Authors and Providers containers.

func (*Provenance) Len
func (p *Provenance) Len() int

Len returns the number of provenance entries.

func (*Provenance) Map
func (p *Provenance) Map() provenance.Map

Map returns a deep copy of the provenance map. The copy prevents callers from modifying internal state across goroutines.

func (*Provenance) Merge
func (p *Provenance) Merge(m provenance.Map)

Merge adds new provenance entries to existing data. This appends to existing keys rather than replacing them.

func (*Provenance) Set
func (p *Provenance) Set(m provenance.Map)

Set replaces the entire provenance map with new data. The input map is deep copied to prevent external modification.

type ProvenanceOption

ProvenanceOption defines a function that configures a Provenance instance.

type ProvenanceOption func(*Provenance)

type ProvenanceReader

ProvenanceReader exposes provenance reads without mutation methods.

type ProvenanceReader interface {
    Map() provenance.Map
    Len() int
    FindByField(evidence.ResourceType, string, string) []provenance.Entry
    FindByResource(evidence.ResourceType, string) map[string][]provenance.Entry
    FindModelField(ProviderID, string, string) []provenance.Entry
    FindModel(ProviderID, string) map[string][]provenance.Entry
    FormatYAML() string
}

type Provider

Provider represents a provider configuration.

type Provider struct {
    ID           ProviderID   `json:"id" yaml:"id"`
    Aliases      []ProviderID `json:"aliases,omitempty" yaml:"aliases,omitempty"`
    Name         string       `json:"name" yaml:"name"` // Display name (must not be empty)
    Description  *string      `json:"description,omitempty" yaml:"description,omitempty"`
    Website      *string      `json:"website,omitempty" yaml:"website,omitempty"`           // Official website URL
    DocsURL      *string      `json:"docs_url,omitempty" yaml:"docs_url,omitempty"`         // Link to the provider's API documentation
    Headquarters *string      `json:"headquarters,omitempty" yaml:"headquarters,omitempty"` // Company headquarters location
    IconURL      *string      `json:"icon_url,omitempty" yaml:"icon_url,omitempty"`         // Provider icon/logo URL

    // Logo holds the provider's SVG brand mark. The bytes travel in the JSON
    // catalog payload but stay out of providers.yaml. On a filesystem catalog
    // they live in the providers/<id>/logo.svg sidecar file.
    Logo []byte `json:"logo_svg,omitempty" yaml:"-"`

    // Secret-free credential metadata for catalog acquisition and inference.
    Credentials *ProviderCredentials `json:"credentials,omitempty" yaml:"credentials,omitempty"`

    // Models
    Catalog *ProviderCatalog  `json:"catalog,omitempty" yaml:"catalog,omitempty"` // Models catalog configuration
    Models  map[string]*Model `json:"-" yaml:"-"`                                 // Available models indexed by model ID - not serialized to YAML

    // Status & Health
    StatusPageURL *string            `json:"status_page_url,omitempty" yaml:"status_page_url,omitempty"` // Link to service status page
    Inference     *ProviderInference `json:"inference,omitempty" yaml:"inference,omitempty"`             // Provider inference service contract

    // Privacy, Retention, and Governance Policies
    PrivacyPolicy    *ProviderPrivacyPolicy    `json:"privacy_policy,omitempty" yaml:"privacy_policy,omitempty"`       // Data collection and usage practices
    RetentionPolicy  *ProviderRetentionPolicy  `json:"retention_policy,omitempty" yaml:"retention_policy,omitempty"`   // Data retention and deletion practices
    GovernancePolicy *ProviderGovernancePolicy `json:"governance_policy,omitempty" yaml:"governance_policy,omitempty"` // Oversight and moderation practices

    // Extensions - controlled source-specific fields that are not canonical schema
    Extensions SourceExtensions `json:"extensions,omitempty" yaml:"extensions,omitempty"`
}

func DeepCopyProvider
func DeepCopyProvider(provider Provider) Provider

DeepCopyProvider creates a deep copy of a Provider including its Models map.

func (*Provider) BindCatalogEndpoint
func (p *Provider) BindCatalogEndpoint(bindings map[string]string) (string, error)

BindCatalogEndpoint resolves catalog-declared endpoint variables.

func (*Provider) CatalogEndpointURL
func (p *Provider) CatalogEndpointURL() string

CatalogEndpointURL returns the resolved model catalog endpoint URL.

func (*Provider) IsCatalogAuthRequired
func (p *Provider) IsCatalogAuthRequired() bool

IsCatalogAuthRequired reports whether catalog acquisition requires credentials.

func (*Provider) Model
func (p *Provider) Model(modelID string) (*Model, error)

Model retrieves a specific model from the provider.

func (Provider) ValidateContract
func (p Provider) ValidateContract() error

ValidateContract validates serializable catalog-acquisition and inference metadata. It does not inspect runtime credential values.

type ProviderAWSDefaultProtocolOptions

ProviderAWSDefaultProtocolOptions configures AWS request signing.

type ProviderAWSDefaultProtocolOptions struct {
    RegionField ProviderCredentialFieldID `json:"region_field" yaml:"region_field"`
    Service     string                    `json:"service" yaml:"service"`
}

type ProviderAnthropicCatalogProtocolOptions

ProviderAnthropicCatalogProtocolOptions defines Anthropic wire-version facts.

type ProviderAnthropicCatalogProtocolOptions struct {
    Version string `json:"version" yaml:"version"`
}

type ProviderAuthenticationPrimitive

ProviderAuthenticationPrimitive identifies compiled authentication behavior. It never identifies a provider.

type ProviderAuthenticationPrimitive string

const (
    // ProviderAuthenticationNone sends no authentication material.
    ProviderAuthenticationNone ProviderAuthenticationPrimitive = "none"
    // ProviderAuthenticationAPIKey places a static API key on a request.
    ProviderAuthenticationAPIKey ProviderAuthenticationPrimitive = "api-key"
    // ProviderAuthenticationBearerToken places a resolved bearer token.
    ProviderAuthenticationBearerToken ProviderAuthenticationPrimitive = "bearer-token"
    // ProviderAuthenticationGoogleDefault uses Google's default credential chain.
    ProviderAuthenticationGoogleDefault ProviderAuthenticationPrimitive = "google-default"
    // ProviderAuthenticationAzureDefault uses Azure's default credential chain.
    ProviderAuthenticationAzureDefault ProviderAuthenticationPrimitive = "azure-default"
    // ProviderAuthenticationAWSDefault uses AWS's default credential chain.
    ProviderAuthenticationAWSDefault ProviderAuthenticationPrimitive = "aws-default"
)

type ProviderAuthenticationProtocolOptions

ProviderAuthenticationProtocolOptions is a typed union of primitive-owned protocol settings. Provider membership does not belong in this union.

type ProviderAuthenticationProtocolOptions struct {
    GoogleDefault *ProviderGoogleDefaultProtocolOptions `json:"google_default,omitempty" yaml:"google_default,omitempty"`
    AWSDefault    *ProviderAWSDefaultProtocolOptions    `json:"aws_default,omitempty" yaml:"aws_default,omitempty"`
}

type ProviderCapabilityCombination

ProviderCapabilityCombination defines how multiple source predicates prove one canonical capability.

type ProviderCapabilityCombination string

const (
    // ProviderCapabilityConflict accepts equal known values and rejects contradictions.
    ProviderCapabilityConflict ProviderCapabilityCombination = "conflict"
    // ProviderCapabilityFirstKnown selects the first present source in YAML order.
    ProviderCapabilityFirstKnown ProviderCapabilityCombination = "first-known"
    // ProviderCapabilityAny requires any known true, or all known false.
    ProviderCapabilityAny ProviderCapabilityCombination = "any"
    // ProviderCapabilityAll requires any known false, or all known true.
    ProviderCapabilityAll ProviderCapabilityCombination = "all"
)

type ProviderCatalog

ProviderCatalog represents information about a provider's models.

type ProviderCatalog struct {
    Docs     *string          `yaml:"docs" json:"docs"`         // Documentation URL
    Endpoint ProviderEndpoint `yaml:"endpoint" json:"endpoint"` // API endpoint configuration
}

type ProviderCatalogProtocolOptions

ProviderCatalogProtocolOptions is a typed union of catalog-transport facts.

type ProviderCatalogProtocolOptions struct {
    OpenAI    *ProviderOpenAICatalogProtocolOptions    `json:"openai,omitempty" yaml:"openai,omitempty"`
    Anthropic *ProviderAnthropicCatalogProtocolOptions `json:"anthropic,omitempty" yaml:"anthropic,omitempty"`
}

type ProviderCredentialEndpointBinding

ProviderCredentialEndpointBinding binds one non-secret field to a named URL template variable.

type ProviderCredentialEndpointBinding struct {
    Field    ProviderCredentialFieldID               `json:"field" yaml:"field"`
    Variable string                                  `json:"variable" yaml:"variable"`
    Format   ProviderCredentialEndpointBindingFormat `json:"format" yaml:"format"`
}

type ProviderCredentialEndpointBindingFormat

ProviderCredentialEndpointBindingFormat identifies how to encode a value before it replaces an endpoint template variable.

type ProviderCredentialEndpointBindingFormat string

const (
    // ProviderCredentialEndpointBindingURL permits one absolute HTTP(S) base URL.
    ProviderCredentialEndpointBindingURL ProviderCredentialEndpointBindingFormat = "url"
    // ProviderCredentialEndpointBindingPathSegment percent-encodes one URL path segment.
    ProviderCredentialEndpointBindingPathSegment ProviderCredentialEndpointBindingFormat = "path-segment"
)

type ProviderCredentialField

ProviderCredentialField defines one named material field and its conventional ambient environment names. Its ID determines product-specific names.

type ProviderCredentialField struct {
    ID          ProviderCredentialFieldID   `json:"id" yaml:"id"`
    Kind        ProviderCredentialFieldKind `json:"kind" yaml:"kind"`
    Required    bool                        `json:"required" yaml:"required"`
    Environment []string                    `json:"environment,omitempty" yaml:"environment,omitempty"`
    Default     string                      `json:"default,omitempty" yaml:"default,omitempty"`
    Pattern     string                      `json:"pattern,omitempty" yaml:"pattern,omitempty"`
    Description string                      `json:"description,omitempty" yaml:"description,omitempty"`
}

type ProviderCredentialFieldID

ProviderCredentialFieldID identifies one secret or non-secret credential field. Values are runtime state and are not part of the catalog.

type ProviderCredentialFieldID string

const (
    // ProviderAWSCredentialAccessKeyID is the primitive-owned AWS access-key field.
    ProviderAWSCredentialAccessKeyID ProviderCredentialFieldID = "access-key-id"
    // ProviderAWSCredentialSecretAccessKey is the primitive-owned AWS secret-key field.
    ProviderAWSCredentialSecretAccessKey ProviderCredentialFieldID = "secret-access-key"
    // ProviderAWSCredentialSessionToken is the primitive-owned AWS session-token field.
    ProviderAWSCredentialSessionToken ProviderCredentialFieldID = "session-token"
)

type ProviderCredentialFieldKind

ProviderCredentialFieldKind distinguishes secret material from non-secret endpoint and protocol parameters.

type ProviderCredentialFieldKind string

const (
    // ProviderCredentialFieldSecret is sensitive authentication material.
    ProviderCredentialFieldSecret ProviderCredentialFieldKind = "secret"
    // ProviderCredentialFieldParameter is non-secret runtime configuration.
    ProviderCredentialFieldParameter ProviderCredentialFieldKind = "parameter"
)

type ProviderCredentialPlacement

ProviderCredentialPlacement binds one resolved field to a request location. Query placement requires an HTTPS provider-evidence URL.

type ProviderCredentialPlacement struct {
    Field       ProviderCredentialFieldID       `json:"field" yaml:"field"`
    Kind        ProviderCredentialPlacementKind `json:"kind" yaml:"kind"`
    Name        string                          `json:"name" yaml:"name"`
    Scheme      ProviderCredentialScheme        `json:"scheme" yaml:"scheme"`
    EvidenceURL string                          `json:"evidence_url,omitempty" yaml:"evidence_url,omitempty"`
}

type ProviderCredentialPlacementKind

ProviderCredentialPlacementKind identifies the request location for one credential field.

type ProviderCredentialPlacementKind string

const (
    // ProviderCredentialPlacementHeader applies material to an HTTP header.
    ProviderCredentialPlacementHeader ProviderCredentialPlacementKind = "header"
    // ProviderCredentialPlacementQuery applies material to a URL query value.
    ProviderCredentialPlacementQuery ProviderCredentialPlacementKind = "query"
)

type ProviderCredentialPlane

ProviderCredentialPlane defines the ordered authentication profiles that one credential plane permits. Selecting a profile is terminal. The catalog does not define automatic fallback between profiles.

type ProviderCredentialPlane struct {
    Required     bool                          `json:"required" yaml:"required"`
    Alternatives []ProviderCredentialProfileID `json:"alternatives" yaml:"alternatives"`
}

type ProviderCredentialProfile

ProviderCredentialProfile defines one complete authentication alternative. Field references share provider-level definitions across alternatives.

type ProviderCredentialProfile struct {
    ID               ProviderCredentialProfileID           `json:"id" yaml:"id"`
    Primitive        ProviderAuthenticationPrimitive       `json:"primitive" yaml:"primitive"`
    Fields           []ProviderCredentialFieldID           `json:"fields,omitempty" yaml:"fields,omitempty"`
    Placements       []ProviderCredentialPlacement         `json:"placements,omitempty" yaml:"placements,omitempty"`
    Scopes           []string                              `json:"scopes,omitempty" yaml:"scopes,omitempty"`
    EndpointBindings []ProviderCredentialEndpointBinding   `json:"endpoint_bindings,omitempty" yaml:"endpoint_bindings,omitempty"`
    ProtocolOptions  ProviderAuthenticationProtocolOptions `json:"protocol_options,omitempty" yaml:"protocol_options,omitempty"`
}

type ProviderCredentialProfileID

ProviderCredentialProfileID identifies one authentication profile.

type ProviderCredentialProfileID string

type ProviderCredentialScheme

ProviderCredentialScheme identifies the transformation to apply before placing a credential field on a request.

type ProviderCredentialScheme string

const (
    // ProviderCredentialSchemeDirect places bytes without a prefix.
    ProviderCredentialSchemeDirect ProviderCredentialScheme = "direct"
    // ProviderCredentialSchemeBearer adds the Bearer authentication prefix.
    ProviderCredentialSchemeBearer ProviderCredentialScheme = "bearer"
    // ProviderCredentialSchemeBasic adds the Basic authentication prefix.
    ProviderCredentialSchemeBasic ProviderCredentialScheme = "basic"
)

type ProviderCredentials

ProviderCredentials defines credential fields once and composes them into named profiles. Each plane lists its permitted profiles in selection order.

type ProviderCredentials struct {
    Fields             []ProviderCredentialField   `json:"fields" yaml:"fields"`
    Profiles           []ProviderCredentialProfile `json:"profiles" yaml:"profiles"`
    CatalogAcquisition ProviderCredentialPlane     `json:"catalog_acquisition" yaml:"catalog_acquisition"`
    Inference          ProviderCredentialPlane     `json:"inference" yaml:"inference"`
}

type ProviderEndpoint

ProviderEndpoint configures how to access the provider's model catalog.

type ProviderEndpoint struct {
    Type               EndpointType                   `yaml:"type" json:"type"`                                                   // Required: API style
    URL                string                         `yaml:"url" json:"url"`                                                     // Required: API endpoint
    ProtocolOptions    ProviderCatalogProtocolOptions `yaml:"protocol_options,omitempty" json:"protocol_options,omitempty"`       // Typed wire-protocol facts
    FieldMappings      []FieldMapping                 `yaml:"field_mappings,omitempty" json:"field_mappings,omitempty"`           // Field mappings
    CapabilityMappings []CapabilityMapping            `yaml:"capability_mappings,omitempty" json:"capability_mappings,omitempty"` // Typed capability predicates
    AuthorMapping      *AuthorMapping                 `yaml:"author_mapping,omitempty" json:"author_mapping,omitempty"`           // Author extraction
}

type ProviderGoogleDefaultProtocolOptions

ProviderGoogleDefaultProtocolOptions configures Google token application.

type ProviderGoogleDefaultProtocolOptions struct {
    ProjectField      ProviderCredentialFieldID `json:"project_field,omitempty" yaml:"project_field,omitempty"`
    QuotaProjectField ProviderCredentialFieldID `json:"quota_project_field,omitempty" yaml:"quota_project_field,omitempty"`
}

type ProviderGovernancePolicy

ProviderGovernancePolicy represents oversight and moderation practices.

type ProviderGovernancePolicy struct {
    ModerationRequired *bool   `json:"moderation_required,omitempty" yaml:"moderation_required,omitempty"` // Whether the provider requires moderation
    Moderated          *bool   `json:"moderated,omitempty" yaml:"moderated,omitempty"`
    Moderator          *string `json:"moderator,omitempty" yaml:"moderator,omitempty"` // Who moderates the provider
}

type ProviderHealthComponent

ProviderHealthComponent represents a specific component to monitor in a provider's health API. The ID is the identifier the health API uses for the component: a Statuspage component id, a Hyperping service publicId, or a Google Cloud product id.

type ProviderHealthComponent struct {
    ID   string `json:"id" yaml:"id"`                         // Component ID from the health API
    Name string `json:"name,omitempty" yaml:"name,omitempty"` // Human-readable component name
}

type ProviderID

ProviderID represents a provider identifier type for compile-time safety.

type ProviderID string

Provider ID constants for compile-time safety and consistency.

const (
    ProviderIDAlibabaQwen    ProviderID = "alibaba"
    ProviderIDAlibabaCloud   ProviderID = "alibaba"
    ProviderIDAnthropic      ProviderID = "anthropic"
    ProviderIDAnyscale       ProviderID = "anyscale"
    ProviderIDCerebras       ProviderID = "cerebras"
    ProviderIDCheckstep      ProviderID = "checkstep"
    ProviderIDCohere         ProviderID = "cohere"
    ProviderIDConectys       ProviderID = "conectys"
    ProviderIDCove           ProviderID = "cove"
    ProviderIDDeepMind       ProviderID = "deepmind"
    ProviderIDDeepInfra      ProviderID = "deepinfra"
    ProviderIDDeepSeek       ProviderID = "deepseek"
    ProviderIDFireworksAI    ProviderID = "fireworks-ai"
    ProviderIDGoogleAIStudio ProviderID = "google-ai-studio"
    ProviderIDGoogleVertex   ProviderID = "google-vertex"
    ProviderIDGroq           ProviderID = "groq"
    ProviderIDHetzner        ProviderID = "hetzner"
    ProviderIDHuggingFace    ProviderID = "huggingface"
    ProviderIDMeta           ProviderID = "meta"
    ProviderIDMicrosoft      ProviderID = "microsoft"
    ProviderIDMistralAI      ProviderID = "mistral"
    ProviderIDAzureOpenAI    ProviderID = "azure-openai"
    ProviderIDOllama         ProviderID = "ollama"
    ProviderIDMoonshotAI     ProviderID = "moonshot-ai"
    ProviderIDOpenAI         ProviderID = "openai"
    ProviderIDOpenRouter     ProviderID = "openrouter"
    ProviderIDPerplexity     ProviderID = "perplexity"
    ProviderIDReplicate      ProviderID = "replicate"
    ProviderIDSafetyKit      ProviderID = "safetykit"
    ProviderIDTogetherAI     ProviderID = "together"
    ProviderIDVirtuousAI     ProviderID = "virtuousai"
    ProviderIDVoyageAI       ProviderID = "voyage"
    ProviderIDWebPurify      ProviderID = "webpurify"
    ProviderIDXAI            ProviderID = "xai"
)

func (ProviderID) String
func (pid ProviderID) String() string

String returns text for ProviderID.

type ProviderInference

ProviderInference defines stable provider-level inference service facts. Gateway consumers supply runtime endpoint overrides and inference credentials.

type ProviderInference struct {
    BaseURL          string                      `json:"base_url,omitempty" yaml:"base_url,omitempty"`
    Endpoints        []ProviderInferenceEndpoint `json:"endpoints" yaml:"endpoints"`
    HealthAPIURL     *string                     `json:"health_api_url,omitempty" yaml:"health_api_url,omitempty"`
    HealthAPIKind    HealthAPIKind               `json:"health_api_kind,omitempty" yaml:"health_api_kind,omitempty"`
    HealthComponents []ProviderHealthComponent   `json:"health_components,omitempty" yaml:"health_components,omitempty"`
}

func (*ProviderInference) BindOfferingEndpoint
func (i *ProviderInference) BindOfferingEndpoint(endpoint ProviderOfferingEndpoint, baseURLOverride string, bindings map[string]string) (ProviderOfferingEndpoint, error)

BindOfferingEndpoint applies runtime endpoint bindings to one immutable offering endpoint. Catalog data owns URL templates. Consumers supply only tenant-specific values and an optional base URL override.

func (*ProviderInference) Endpoint
func (i *ProviderInference) Endpoint(operation ProviderOperation) (ProviderInferenceEndpoint, bool)

Endpoint returns the endpoint for an exact inference operation.

func (*ProviderInference) EndpointURL
func (i *ProviderInference) EndpointURL(endpoint ProviderInferenceEndpoint, baseURLOverride string) string

EndpointURL resolves an endpoint against a runtime base URL override.

type ProviderInferenceEndpoint

ProviderInferenceEndpoint defines one operation path and wire protocol.

type ProviderInferenceEndpoint struct {
    Operation           ProviderOperation         `json:"operation" yaml:"operation"`
    Type                EndpointType              `json:"type" yaml:"type"`
    Path                string                    `json:"path" yaml:"path"`
    StreamPath          string                    `json:"stream_path,omitempty" yaml:"stream_path,omitempty"`
    ProtocolsByAuthor   map[AuthorID]EndpointType `json:"protocols_by_author,omitempty" yaml:"protocols_by_author,omitempty"`
    PathsByAuthor       map[AuthorID]string       `json:"paths_by_author,omitempty" yaml:"paths_by_author,omitempty"`
    StreamPathsByAuthor map[AuthorID]string       `json:"stream_paths_by_author,omitempty" yaml:"stream_paths_by_author,omitempty"`
}

type ProviderModelID

ProviderModelID is the exact opaque model identifier accepted by a provider.

type ProviderModelID string

type ProviderModerator

ProviderModerator represents a moderator for a provider.

type ProviderModerator string

ProviderModerators.

const (
    // AI Platform Aggregators/Moderators.
    ProviderModeratorAnyscale    ProviderModerator = "anyscale"
    ProviderModeratorHuggingFace ProviderModerator = "huggingface"
    ProviderModeratorOpenRouter  ProviderModerator = "openrouter"
    ProviderModeratorReplicate   ProviderModerator = "replicate"
    ProviderModeratorTogetherAI  ProviderModerator = "together"

    // Specialized AI Safety/Moderation Companies.
    ProviderModeratorCheckstep  ProviderModerator = "checkstep"
    ProviderModeratorConectys   ProviderModerator = "conectys"
    ProviderModeratorCove       ProviderModerator = "cove"
    ProviderModeratorSafetyKit  ProviderModerator = "safetykit"
    ProviderModeratorVirtuousAI ProviderModerator = "virtuousai"
    ProviderModeratorWebPurify  ProviderModerator = "webpurify"

    // Self-Moderated (Major AI Companies).
    ProviderModeratorAnthropic      ProviderModerator = "anthropic"
    ProviderModeratorGoogleAIStudio ProviderModerator = "google-ai-studio"
    ProviderModeratorGoogleVertex   ProviderModerator = "google-vertex"
    ProviderModeratorGroq           ProviderModerator = "groq"
    ProviderModeratorMicrosoft      ProviderModerator = "microsoft"
    ProviderModeratorOpenAI         ProviderModerator = "openai"

    // Unknown/Unspecified.
    ProviderModeratorUnknown ProviderModerator = "unknown"
)

func (ProviderModerator) String
func (pm ProviderModerator) String() string

String returns text for ProviderModerator.

type ProviderOffering

ProviderOffering is one provider's service contract for a model definition. Provider-specific price, limits, availability, regions, lifecycle, endpoint, modes, and request overrides live here rather than on the definition.

type ProviderOffering struct {
    ProviderID      ProviderID                          `json:"provider_id" yaml:"provider_id"`
    ProviderModelID ProviderModelID                     `json:"provider_model_id" yaml:"provider_model_id"`
    DefinitionID    ModelDefinitionID                   `json:"definition_id" yaml:"definition_id"`
    Pricing         *ModelPricing                       `json:"pricing,omitempty" yaml:"pricing,omitempty"`
    Limits          *ModelLimits                        `json:"limits,omitempty" yaml:"limits,omitempty"`
    Availability    OfferingAvailability                `json:"availability" yaml:"availability"`
    Regions         []string                            `json:"regions,omitempty" yaml:"regions,omitempty"`
    Endpoints       []ProviderOfferingEndpoint          `json:"endpoints,omitempty" yaml:"endpoints,omitempty"`
    Lifecycle       OfferingLifecycle                   `json:"lifecycle" yaml:"lifecycle"`
    DeprecatedAt    *utc.Time                           `json:"deprecated_at,omitempty" yaml:"deprecated_at,omitempty"`
    RetiresAt       *utc.Time                           `json:"retires_at,omitempty" yaml:"retires_at,omitempty"`
    Service         ProviderOfferingServiceCapabilities `json:"service" yaml:"service"`
    Modes           map[string]ProviderOfferingMode     `json:"modes,omitempty" yaml:"modes,omitempty"`
}

func (ProviderOffering) Endpoint
func (o ProviderOffering) Endpoint(operation ProviderOperation) (ProviderOfferingEndpoint, bool)

Endpoint returns the endpoint for an exact supported operation.

func (ProviderOffering) Key
func (o ProviderOffering) Key() OfferingKey

Key returns the provider-scoped immutable offering identity.

func (ProviderOffering) Supports
func (o ProviderOffering) Supports(operation ProviderOperation) bool

Supports reports whether this exact offering supports an operation.

func (ProviderOffering) Validate
func (o ProviderOffering) Validate() error

Validate verifies required identity and provider-specific fields.

type ProviderOfferingEndpoint

ProviderOfferingEndpoint describes provider-specific inference endpoint behavior.

type ProviderOfferingEndpoint struct {
    Operation ProviderOperation `json:"operation" yaml:"operation"`
    Type      EndpointType      `json:"type,omitempty" yaml:"type,omitempty"`
    URL       string            `json:"url,omitempty" yaml:"url,omitempty"`
    StreamURL string            `json:"stream_url,omitempty" yaml:"stream_url,omitempty"`
}

type ProviderOfferingMode

ProviderOfferingMode describes one named service mode for an offering.

type ProviderOfferingMode struct {
    Pricing *ModelPricing            `json:"pricing,omitempty" yaml:"pricing,omitempty"`
    Request ProviderRequestOverrides `json:"request" yaml:"request,omitempty"`
}

type ProviderOfferingServiceCapabilities

ProviderOfferingServiceCapabilities defines exact service behavior for one provider model offering. A nil PromptCache value means unknown.

type ProviderOfferingServiceCapabilities struct {
    Operations  []ProviderOperation `json:"operations,omitempty" yaml:"operations,omitempty"`
    PromptCache *bool               `json:"prompt_cache,omitempty" yaml:"prompt_cache,omitempty"`
}

type ProviderOpenAICatalogProtocolOptions

ProviderOpenAICatalogProtocolOptions defines OpenAI-compatible payload facts.

type ProviderOpenAICatalogProtocolOptions struct {
    TokenPriceUnit ProviderTokenPriceUnit `json:"token_price_unit" yaml:"token_price_unit"`
}

type ProviderOperation

ProviderOperation identifies one provider inference operation.

type ProviderOperation string

const (
    // ProviderOperationChatCompletions generates chat completions.
    ProviderOperationChatCompletions ProviderOperation = "chat-completions"
    // ProviderOperationEmbeddings generates vector embeddings.
    ProviderOperationEmbeddings ProviderOperation = "embeddings"
    // ProviderOperationImagesGenerations generates an image from a prompt.
    ProviderOperationImagesGenerations ProviderOperation = "images-generations"
    // ProviderOperationImagesEdits generates an image from a prompt and an image.
    ProviderOperationImagesEdits ProviderOperation = "images-edits"
    // ProviderOperationAudioSpeech generates speech from text.
    ProviderOperationAudioSpeech ProviderOperation = "audio-speech"
    // ProviderOperationAudioTranscriptions transcribes speech in its own language.
    ProviderOperationAudioTranscriptions ProviderOperation = "audio-transcriptions"
    // ProviderOperationAudioTranslations transcribes speech into English.
    ProviderOperationAudioTranslations ProviderOperation = "audio-translations"
    // ProviderOperationVideosGenerations generates a video from a prompt. The
    // provider answers with a job rather than a video, so a consumer submits,
    // polls, and collects.
    ProviderOperationVideosGenerations ProviderOperation = "videos-generations"
    // ProviderOperationDocumentsRecognition reads the text off a document that
    // carries none. A document with a text layer needs no model at all, so this
    // operation names the case a reader cannot answer on its own.
    ProviderOperationDocumentsRecognition ProviderOperation = "documents-recognition"
    // ProviderOperationRerank orders a document list by its relevance to one
    // query. The provider answers with a score for each document rather than
    // with generated text, and it bills the call in its own unit.
    ProviderOperationRerank ProviderOperation = "rerank"
    // ProviderOperationModerations classifies text against a fixed set of
    // harm categories and answers with a score for each one. A moderation
    // model reads text and writes scores rather than prose, so the tag is
    // what separates it from a chat model.
    ProviderOperationModerations ProviderOperation = "moderations"
)

type ProviderPrivacyPolicy

ProviderPrivacyPolicy represents data collection and usage practices.

type ProviderPrivacyPolicy struct {
    PrivacyPolicyURL  *string `json:"privacy_policy_url,omitempty" yaml:"privacy_policy_url,omitempty"`     // Link to privacy policy
    TermsOfServiceURL *string `json:"terms_of_service_url,omitempty" yaml:"terms_of_service_url,omitempty"` // Link to terms of service
    RetainsData       *bool   `json:"retains_data,omitempty" yaml:"retains_data,omitempty"`                 // Whether provider stores/retains user data
    TrainsOnData      *bool   `json:"trains_on_data,omitempty" yaml:"trains_on_data,omitempty"`             // Whether provider trains models on user data
}

type ProviderRequestOverrides

ProviderRequestOverrides contains provider-specific inference request changes.

type ProviderRequestOverrides struct {
    Headers OfferingRequestHeaders `json:"headers,omitempty" yaml:"headers,omitempty"`
    Body    OfferingRequestBody    `json:"body,omitempty" yaml:"body,omitempty"`
}

type ProviderRetentionPolicy

ProviderRetentionPolicy describes data retention duration and deletion practices.

type ProviderRetentionPolicy struct {
    Type     ProviderRetentionType `json:"type" yaml:"type"`                                                   // Type of retention policy
    Duration *time.Duration        `json:"duration,omitempty" yaml:"duration,omitempty" swaggertype:"integer"` // nil = forever, 0 = immediate deletion
    Details  *string               `json:"details,omitempty" yaml:"details,omitempty"`                         // Human-readable description
}

type ProviderRetentionType

ProviderRetentionType represents different types of data retention policies.

type ProviderRetentionType string

ProviderRetention types.

const (
    ProviderRetentionTypeFixed       ProviderRetentionType = "fixed"       // Specific duration (use Duration field)
    ProviderRetentionTypeNone        ProviderRetentionType = "none"        // No retention (immediate deletion)
    ProviderRetentionTypeIndefinite  ProviderRetentionType = "indefinite"  // Forever (duration = nil)
    ProviderRetentionTypeConditional ProviderRetentionType = "conditional" // Based on conditions (e.g., "until account deletion")
)

func (ProviderRetentionType) String
func (prt ProviderRetentionType) String() string

String returns text for ProviderRetentionType.

type ProviderTokenPriceUnit

ProviderTokenPriceUnit identifies the unit used by one provider payload.

type ProviderTokenPriceUnit string

const (
    // ProviderTokenPriceUnitPerToken means USD per token.
    // #nosec G101 -- This value identifies a price unit, not authentication material.
    ProviderTokenPriceUnitPerToken ProviderTokenPriceUnit = "usd-per-token"
    // ProviderTokenPriceUnitPerMillion means USD per one million tokens.
    // #nosec G101 -- This value identifies a price unit, not authentication material.
    ProviderTokenPriceUnitPerMillion ProviderTokenPriceUnit = "usd-per-million-tokens"
)

type Providers

Providers is a concurrent safe map of providers.

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

func NewProviders
func NewProviders(opts ...ProvidersOption) *Providers

NewProviders creates a new Providers map with optional configuration.

func (*Providers) Add
func (p *Providers) Add(provider *Provider) error

Add adds a provider, returning an error if it already exists.

func (*Providers) AddBatch
func (p *Providers) AddBatch(providers []*Provider) map[ProviderID]error

AddBatch adds multiple providers in a single operation. Only adds providers that do not already exist - fails if a provider ID already exists. Returns a map of provider IDs to errors for any failed additions.

func (*Providers) Clear
func (p *Providers) Clear()

Clear removes all providers.

func (*Providers) Delete
func (p *Providers) Delete(id ProviderID) error

Delete removes a provider by id. Returns an error if the provider does not exist.

func (*Providers) DeleteBatch
func (p *Providers) DeleteBatch(ids []ProviderID) map[ProviderID]error

DeleteBatch removes multiple providers by ID. The returned map identifies IDs that DeleteBatch did not find.

func (*Providers) DeleteModel
func (p *Providers) DeleteModel(providerID ProviderID, modelID string) error

DeleteModel removes a model from a provider.

func (*Providers) EncodeYAML
func (p *Providers) EncodeYAML() (string, error)

EncodeYAML returns formatted provider YAML. It returns a typed parse error for values that YAML cannot represent safely.

func (*Providers) Exists
func (p *Providers) Exists(id ProviderID) bool

Exists checks if a provider exists without returning it.

func (*Providers) ForEach
func (p *Providers) ForEach(fn func(id ProviderID, provider *Provider) bool)

ForEach applies a function to each provider. The function should not modify the provider. If the function returns false, iteration stops early.

func (*Providers) FormatYAML
func (p *Providers) FormatYAML() string

FormatYAML returns the providers as formatted YAML with enhanced formatting, comments, and structure.

func (*Providers) Get
func (p *Providers) Get(id ProviderID) (*Provider, bool)

Get returns a provider by id and whether it exists.

func (*Providers) Len
func (p *Providers) Len() int

Len returns the number of providers.

func (*Providers) List
func (p *Providers) List() []Provider

List returns a slice of all providers as values (copies).

func (*Providers) Map
func (p *Providers) Map() map[ProviderID]*Provider

Map returns a copy of all providers.

func (*Providers) Resolve
func (p *Providers) Resolve(id ProviderID) (*Provider, bool)

Resolve returns a provider by ID or alias. It first tries an exact ID match, then searches all provider aliases. This allows commands to accept both canonical IDs and common aliases silently.

func (*Providers) Set
func (p *Providers) Set(id ProviderID, provider *Provider) error

Set sets a provider by id. Returns an error if provider is nil.

func (*Providers) SetBatch
func (p *Providers) SetBatch(providers map[ProviderID]*Provider) error

SetBatch sets multiple providers in a single operation. Overwrites existing providers or adds new ones (upsert behavior). Returns an error if any provider is nil.

func (*Providers) SetModel
func (p *Providers) SetModel(providerID ProviderID, model Model) error

SetModel adds or updates a model in a provider.

type ProvidersOption

ProvidersOption defines a function that configures a Providers instance.

type ProvidersOption func(*Providers)

func WithProvidersCapacity
func WithProvidersCapacity(capacity int) ProvidersOption

WithProvidersCapacity sets the initial capacity of the providers map.

func WithProvidersMap
func WithProvidersMap(providers map[ProviderID]*Provider) ProvidersOption

WithProvidersMap initializes the map with existing providers.

type ProvidersReader

ProvidersReader exposes provider collection reads without mutation methods.

type ProvidersReader interface {
    Get(ProviderID) (*Provider, bool)
    Resolve(ProviderID) (*Provider, bool)
    Exists(ProviderID) bool
    Len() int
    List() []Provider
    Map() map[ProviderID]*Provider
    ForEach(func(ProviderID, *Provider) bool)
    FormatYAML() string
}

type Quantization

Quantization represents the quantization level used by a model. Quantization reduces model size and computational requirements while aiming to preserve performance.

type Quantization string

Quantization levels.

const (
    QuantizationINT4    Quantization = "int4"
    QuantizationINT8    Quantization = "int8"
    QuantizationFP4     Quantization = "fp4"
    QuantizationFP6     Quantization = "fp6"
    QuantizationFP8     Quantization = "fp8"
    QuantizationFP16    Quantization = "fp16"
    QuantizationBF16    Quantization = "bf16"
    QuantizationFP32    Quantization = "fp32"
    QuantizationUnknown Quantization = "unknown"
)

func (Quantization) String
func (q Quantization) String() string

String returns text for Quantization.

type Reader

Reader provides read-only access to catalog data.

type Reader interface {
    // Lists providers, authors, authored models, and provenance.
    Providers() ProvidersReader
    Authors() AuthorsReader
    AuthoredModels() []AuthoredModel
    Provenance() ProvenanceReader

    // Gets a provider or author by ID.
    Provider(id ProviderID) (Provider, error)
    Author(id AuthorID) (Author, error)
}

type RouteAlias

RouteAlias names a set of candidate offering identities. It intentionally contains no weights, fallback order, tenancy, or routing strategy.

type RouteAlias struct {
    ID      RouteAliasID  `json:"id" yaml:"id"`
    Targets []OfferingKey `json:"targets" yaml:"targets"`
}

func (RouteAlias) Validate
func (a RouteAlias) Validate() error

Validate verifies route identity and exact target uniqueness.

type RouteAliasID

RouteAliasID is a Starport-facing routing identity independent of provider IDs.

type RouteAliasID string

type RouteAliasRejection

RouteAliasRejection records one ineligible target without hiding it.

type RouteAliasRejection struct {
    Key    OfferingKey               `json:"key" yaml:"key"`
    Reason RouteAliasRejectionReason `json:"reason" yaml:"reason"`
}

type RouteAliasRejectionReason

RouteAliasRejectionReason classifies why a target is not currently eligible.

type RouteAliasRejectionReason string

const (
    // RouteAliasRejectedMissing means the offering key is absent from the catalog.
    RouteAliasRejectedMissing RouteAliasRejectionReason = "missing"
    // RouteAliasRejectedUnavailable means the provider marks the offering unavailable.
    RouteAliasRejectedUnavailable RouteAliasRejectionReason = "unavailable"
    // RouteAliasRejectedRetired means the provider retired the offering.
    RouteAliasRejectedRetired RouteAliasRejectionReason = "retired"
)

type RouteAliasResolution

RouteAliasResolution is a point-in-time materialization against one catalog generation.

type RouteAliasResolution struct {
    AliasID  RouteAliasID          `json:"alias_id" yaml:"alias_id"`
    Eligible []ProviderOffering    `json:"eligible" yaml:"eligible"`
    Rejected []RouteAliasRejection `json:"rejected,omitempty" yaml:"rejected,omitempty"`
}

type SourceExtension

SourceExtension stores controlled non-canonical fields reported by one source.

type SourceExtension struct {
    Fields map[string]any `json:"fields,omitempty" yaml:"fields,omitempty"` // Preserved source-specific fields
}

func (SourceExtension) Copy
func (se SourceExtension) Copy() SourceExtension

Copy returns a deep copy of the source extension.

func (SourceExtension) MarshalJSON
func (se SourceExtension) MarshalJSON() ([]byte, error)

MarshalJSON canonicalizes source-defined dynamic values. This keeps immutable catalog bytes independent of the evidence representation. The evidence can use concrete provider structs or generic maps from a prior decode.

func (*SourceExtension) UnmarshalJSON
func (se *SourceExtension) UnmarshalJSON(data []byte) error

UnmarshalJSON normalizes dynamic extension field types after JSON decoding.

func (*SourceExtension) UnmarshalYAML
func (se *SourceExtension) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML normalizes dynamic extension field types after YAML decoding.

type SourceExtensions

SourceExtensions stores source-specific attributes that Starmap preserves without treating as canonical schema fields.

type SourceExtensions map[string]SourceExtension

func NormalizeSourceExtensions
func NormalizeSourceExtensions(extensions SourceExtensions) SourceExtensions

NormalizeSourceExtensions returns a copy with JSON/YAML-stable dynamic value types for equality checks and sync idempotency.

func (SourceExtensions) Copy
func (se SourceExtensions) Copy() SourceExtensions

Copy returns a deep copy of the source extension map.

SourceObservationLink binds a generation to one immutable source observation. The source pipeline defines the observation schema and retention policy. This link is deliberately small and replay-oriented.

type SourceObservationLink struct {
    Source           evidence.SourceID                `json:"source" yaml:"source"`
    ObservationID    string                           `json:"observation_id" yaml:"observation_id"`
    ObservedAt       time.Time                        `json:"observed_at" yaml:"observed_at"`
    Revision         evidence.ObservationRevision     `json:"revision" yaml:"revision"`
    Completeness     evidence.ObservationCompleteness `json:"completeness" yaml:"completeness"`
    Status           evidence.ObservationStatus       `json:"status" yaml:"status"`
    EvidenceChecksum string                           `json:"evidence_checksum" yaml:"evidence_checksum"`
}

func (o SourceObservationLink) Validate() error

Validate verifies one complete source-observation link.

type Tokenizer

Tokenizer represents the tokenizer type used by a model.

type Tokenizer string

Tokenizer types.

const (
    TokenizerClaude   Tokenizer = "claude"
    TokenizerCohere   Tokenizer = "cohere"
    TokenizerDeepSeek Tokenizer = "deepseek"
    TokenizerGPT      Tokenizer = "gpt"
    TokenizerGemini   Tokenizer = "gemini"
    TokenizerGrok     Tokenizer = "grok"
    TokenizerLlama2   Tokenizer = "llama2"
    TokenizerLlama3   Tokenizer = "llama3"
    TokenizerLlama4   Tokenizer = "llama4"
    TokenizerMistral  Tokenizer = "mistral"
    TokenizerNova     Tokenizer = "nova"
    TokenizerQwen     Tokenizer = "qwen"
    TokenizerQwen3    Tokenizer = "qwen3"
    TokenizerRouter   Tokenizer = "router"
    TokenizerYi       Tokenizer = "yi"
    TokenizerUnknown  Tokenizer = "unknown"
)

func (Tokenizer) String
func (t Tokenizer) String() string

String returns text for Tokenizer.

type ToolChoice

ToolChoice represents the strategy for selecting tools. Used in API requests as the "tool_choice" parameter value.

type ToolChoice string

Tool choice strategies for controlling tool usage behavior.

const (
    ToolChoiceAuto     ToolChoice = "auto"
    ToolChoiceNone     ToolChoice = "none"
    ToolChoiceRequired ToolChoice = "required" // Model must call at least one tool before responding
)

func (ToolChoice) String
func (tc ToolChoice) String() string

String returns text for ToolChoice.

type ValuePresence

ValuePresence describes whether a source supplied a field value.

Missing means the source omitted the field and makes no claim. Unknown means the source explicitly reported that it does not know the value. Known means the source supplied a value, including false, zero, or an empty string.

type ValuePresence uint8

const (
    // ValueMissing means the source omitted a field and made no claim.
    ValueMissing ValuePresence = iota
    // ValueUnknown means a field was explicitly reported as unknown.
    ValueUnknown
    // ValueKnown means a field has a supplied value, including its zero value.
    ValueKnown
)

Generated by gomarkdoc

Documentation

Overview

Package catalogs defines Starmap's authored-model and provider-serving construction records plus its immutable canonical read model. Advanced producers use Builder to load or assemble those records, then Build validates and derives definitions, provider offerings, and author membership into a concrete Catalog. Ordinary consumers retain and share that immutable Catalog.

Example usage:

// Advanced producers construct a draft, then publish an immutable catalog.
builder, err := New(WithFS(os.DirFS("./catalog")))
if err != nil {
    log.Fatal(err)
}
catalog, err := builder.Build()
if err != nil {
    log.Fatal(err)
}

// Access canonical model definitions
for _, model := range catalog.Definitions() {
    fmt.Printf("Model: %s\n", model.ID)
}

// Create a file-based draft (development use)
builder, err = New(WithFiles("./catalog"))
if err != nil {
    log.Fatal(err)
}
Example

Example shows advanced catalog construction and publication.

package main

import (
	"fmt"
	"log"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func main() {
	// Create a memory-based draft.
	builder := catalogs.NewEmpty()

	if err := builder.SetAuthor(catalogs.Author{ID: "openai", Name: "OpenAI"}); err != nil {
		log.Fatal(err)
	}
	if err := builder.SetAuthorModel("openai", catalogs.Model{
		ID: "gpt-4", Name: "GPT-4", Description: "Advanced language model",
		Authors: []catalogs.Author{{ID: "openai", Name: "OpenAI"}},
	}); err != nil {
		log.Fatal(err)
	}

	// Add the provider offering and join it to the canonical definition.
	provider := catalogs.Provider{
		ID:   "openai",
		Name: "OpenAI",
		Models: map[string]*catalogs.Model{
			"gpt-4": {
				ID:          "gpt-4",
				ModelRef:    "openai/gpt-4",
				Name:        "GPT-4",
				Description: "Advanced language model",
			},
		},
	}
	if err := builder.SetProvider(provider); err != nil {
		log.Fatal(err)
	}
	catalog, err := builder.Build()
	if err != nil {
		log.Fatal(err)
	}

	// List all models
	models := catalog.Definitions()
	fmt.Printf("Found %d models\n", len(models))
}
Output:
Found 1 models
Example (CatalogCopy)

Example_catalogCopy shows creating independent copies.

package main

import (
	"fmt"
	"log"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func main() {
	// Create original catalog
	original := catalogs.NewEmpty()
	provider := catalogs.Provider{
		ID:   "test",
		Name: "Test Provider",
		Models: map[string]*catalogs.Model{
			"model-1": {
				ID:   "model-1",
				Name: "Original Model",
			},
		},
	}
	_ = original.SetProvider(provider)

	// Create a copy
	copy, err := original.Copy()
	if err != nil {
		log.Fatal(err)
	}

	// Modify the copy by updating the provider
	copiedProvider, _ := copy.Provider("test")
	if copiedProvider.Models == nil {
		copiedProvider.Models = make(map[string]*catalogs.Model)
	}
	copiedProvider.Models["model-2"] = &catalogs.Model{
		ID:   "model-2",
		Name: "Copy Model",
	}
	_ = copy.SetProvider(copiedProvider)

	originalModels, _ := original.ProviderModels("test")
	copyModels, _ := copy.ProviderModels("test")
	fmt.Printf("Original has %d models\n", len(originalModels.List()))
	fmt.Printf("Copy has %d models\n", len(copyModels.List()))
}
Output:
Original has 1 models
Copy has 2 models
Example (ConcurrentAccess)

Example_concurrentAccess shows thread-safe concurrent usage.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/agentstation/starmap/pkg/catalogs"
	"github.com/agentstation/starmap/pkg/catalogs/internal/resourcepolicy"
)

func main() {
	catalog := catalogs.NewEmpty()
	ctx, cancel := context.WithTimeout(context.Background(), resourcepolicy.DefaultHTTPTimeout)
	defer cancel()

	// Safe for concurrent reads and writes
	done := make(chan bool, 2)

	// Writer goroutine
	go func() {
		provider := catalogs.Provider{
			ID:     "test-provider",
			Name:   "Test Provider",
			Models: make(map[string]*catalogs.Model),
		}
		for i := range 100 {
			provider.Models[fmt.Sprintf("model-%d", i)] = &catalogs.Model{
				ID:   fmt.Sprintf("model-%d", i),
				Name: fmt.Sprintf("Model %d", i),
			}
		}
		_ = catalog.SetProvider(provider)
		done <- true
	}()

	// Reader goroutine
	go func() {
		for {
			select {
			case <-ctx.Done():
				done <- true
				return
			default:
				models, _ := catalog.ProviderModels("test-provider")
				if models != nil {
					_ = models.List()
				}
				time.Sleep(10 * time.Millisecond)
			}
		}
	}()

	// Wait for both
	<-done
	<-done

	models, _ := catalog.ProviderModels("test-provider")
	fmt.Printf("Created %d models concurrently\n", len(models.List()))
}
Example (EmbeddedCatalog)

Example_embeddedCatalog shows using the embedded catalog.

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func embeddedBuilder() (*catalogs.Builder, error) {
	return catalogs.New(catalogs.WithFS(os.DirFS("../../internal/embedded/catalog")))
}

func main() {
	// Load embedded data into a builder, then publish it.
	builder, err := embeddedBuilder()
	if err != nil {
		log.Fatal(err)
	}
	catalog, err := builder.Build()
	if err != nil {
		log.Fatal(err)
	}

	// Access pre-loaded models
	models := catalog.Definitions()
	fmt.Printf("Embedded catalog has %d+ models\n", len(models))

	// Find a specific model
	model, err := catalog.FindModel("gpt-4o")
	if err == nil {
		fmt.Printf("Found model: %s\n", model.Name)
	}
}
Example (FileBasedCatalog)

Example_fileBasedCatalog shows file-based persistence.

package main

import (
	"fmt"
	"log"
	"path/filepath"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func main() {
	// Create a file-based builder.
	catalogPath := filepath.Join(".", "my-catalog")
	builder, err := catalogs.New(
		catalogs.WithPath(catalogPath),
		catalogs.WithWritePath(catalogPath),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Add and save data
	provider := catalogs.Provider{
		ID:   "custom",
		Name: "Custom Provider",
		Models: map[string]*catalogs.Model{
			"custom-model": {
				ID:   "custom-model",
				Name: "My Custom Model",
			},
		},
	}
	if err := builder.SetProvider(provider); err != nil {
		log.Fatal(err)
	}

	fmt.Println("Catalog saved to disk")
}
Example (MergeCatalogs)

Example_mergeCatalogs shows merging two catalogs.

package main

import (
	"fmt"
	"log"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func main() {
	// Create base catalog
	base := catalogs.NewEmpty()
	baseProvider := catalogs.Provider{
		ID:   "test",
		Name: "Test Provider",
		Models: map[string]*catalogs.Model{
			"model-1": {
				ID:          "model-1",
				Name:        "Model One",
				Description: "Original description",
			},
		},
	}
	_ = base.SetProvider(baseProvider)

	// Create updates catalog
	updates := catalogs.NewEmpty()
	updateProvider := catalogs.Provider{
		ID:   "test",
		Name: "Test Provider",
		Models: map[string]*catalogs.Model{
			"model-1": {
				ID:          "model-1",
				Name:        "Model One Enhanced",
				Description: "Updated description",
				Pricing: &catalogs.ModelPricing{
					Tokens: &catalogs.ModelTokenPricing{
						Input: &catalogs.ModelTokenCost{
							Per1M: 2.0, // $2 per 1M tokens
						},
						Output: &catalogs.ModelTokenCost{
							Per1M: 4.0, // $4 per 1M tokens
						},
					},
					Currency: "USD",
				},
			},
		},
	}
	_ = updates.SetProvider(updateProvider)

	// Merge with EnrichEmpty strategy (default)
	if err := base.MergeWith(updates); err != nil {
		log.Fatal(err)
	}

	model, _ := base.ProviderModel("test", "model-1")
	fmt.Printf("Model name: %s\n", model.Name)
}
Output:
Model name: Model One Enhanced
Example (MergeStrategies)

Example_mergeStrategies shows different merge strategies.

package main

import (
	"fmt"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func main() {
	base := catalogs.NewEmpty()
	baseProvider := catalogs.Provider{
		ID:   "test",
		Name: "Test",
		Models: map[string]*catalogs.Model{
			"m1": {ID: "m1", Name: "Original"},
		},
	}
	_ = base.SetProvider(baseProvider)

	updates := catalogs.NewEmpty()
	updateProvider := catalogs.Provider{
		ID:   "test",
		Name: "Test",
		Models: map[string]*catalogs.Model{
			"m1": {ID: "m1", Name: "Updated"},
			"m2": {ID: "m2", Name: "New"},
		},
	}
	_ = updates.SetProvider(updateProvider)

	// Example 1: Append only (keeps existing, adds new)
	cat1, _ := base.Copy()
	cat1.MergeWith(updates, catalogs.WithStrategy(catalogs.MergeAppendOnly))

	m1, _ := cat1.ProviderModel("test", "m1")
	fmt.Printf("AppendOnly - m1: %s\n", m1.Name) // Original

	// Example 2: Replace all
	cat2, _ := base.Copy()
	cat2.MergeWith(updates, catalogs.WithStrategy(catalogs.MergeReplaceAll))

	m1, _ = cat2.ProviderModel("test", "m1")
	fmt.Printf("ReplaceAll - m1: %s\n", m1.Name) // Updated

	// Example 3: Enrich empty (smart merge)
	cat3, _ := base.Copy()
	cat3.MergeWith(updates, catalogs.WithStrategy(catalogs.MergeEnrichEmpty))

	m1, _ = cat3.ProviderModel("test", "m1")
	fmt.Printf("EnrichEmpty - m1: %s\n", m1.Name) // Updated
}
Example (ModelFiltering)

Example_modelFiltering shows filtering models.

package main

import (
	"fmt"
	"os"
	"slices"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func embeddedBuilder() (*catalogs.Builder, error) {
	return catalogs.New(catalogs.WithFS(os.DirFS("../../internal/embedded/catalog")))
}

func main() {
	builder, _ := embeddedBuilder()
	catalog, _ := builder.Build()

	// Filter immutable provider-independent definitions.
	var gptModels []catalogs.ModelDefinition
	for _, model := range catalog.Definitions() {
		if len(model.ID) > 3 && model.ID[:3] == "gpt" {
			gptModels = append(gptModels, model)
		}
	}
	fmt.Printf("Found %d GPT models\n", len(gptModels))

	// Filter by features
	var visionModels []catalogs.ModelDefinition
	for _, model := range catalog.Definitions() {
		if model.Capabilities.Features != nil &&
			slices.Contains(model.Capabilities.Features.Modalities.Input, "image") {
			visionModels = append(visionModels, model)
		}
	}
	fmt.Printf("Found %d models with vision\n", len(visionModels))
}
Example (ProviderCapabilities)

Example_providerCapabilities shows working with provider features.

package main

import (
	"fmt"

	"github.com/agentstation/starmap/pkg/catalogs"
)

func main() {
	catalog := catalogs.NewEmpty()

	// Add provider with capabilities
	provider := catalogs.Provider{
		ID:   "openai",
		Name: "OpenAI",
		Credentials: &catalogs.ProviderCredentials{
			Fields: []catalogs.ProviderCredentialField{{
				ID: "api-key", Kind: catalogs.ProviderCredentialFieldSecret, Required: true,
				Environment: []string{"OPENAI_API_KEY"},
			}},
			Profiles: []catalogs.ProviderCredentialProfile{{
				ID: "api-key", Primitive: catalogs.ProviderAuthenticationAPIKey,
				Fields: []catalogs.ProviderCredentialFieldID{"api-key"},
			}},
			CatalogAcquisition: catalogs.ProviderCredentialPlane{
				Required: true, Alternatives: []catalogs.ProviderCredentialProfileID{"api-key"},
			},
		},
		Catalog: &catalogs.ProviderCatalog{
			Endpoint: catalogs.ProviderEndpoint{
				Type: catalogs.EndpointTypeOpenAI,
				URL:  "https://api.openai.com/v1/models",
				ProtocolOptions: catalogs.ProviderCatalogProtocolOptions{OpenAI: &catalogs.ProviderOpenAICatalogProtocolOptions{
					TokenPriceUnit: catalogs.ProviderTokenPriceUnitPerMillion,
				}},
			},
		},
	}
	_ = catalog.SetProvider(provider)

	// Check capabilities
	p, _ := catalog.Provider("openai")
	if p.IsCatalogAuthRequired() {
		fmt.Println("Provider requires catalog credentials")
	}
}

Index

Examples

Constants

View Source
const (
	// CurrentGenerationManifestVersion is the manifest envelope version emitted
	// by this release. It is intentionally independent of the Starmap binary
	// version and the catalog payload schema version.
	CurrentGenerationManifestVersion uint64 = 2

	// CurrentCatalogSchemaVersion identifies the canonical catalog payload
	// schema emitted by this release.
	CurrentCatalogSchemaVersion uint64 = 6

	// CatalogPayloadMediaType identifies the canonical JSON catalog payload.
	CatalogPayloadMediaType = "application/vnd.agentstation.starmap.catalog+json"
)
View Source
const CurrentBootstrapManifestVersion uint64 = 2

CurrentBootstrapManifestVersion is the embedded-bootstrap metadata format.

Variables

This section is empty.

Functions

func CatalogSemanticChecksum added in v0.2.0

func CatalogSemanticChecksum(reader Reader) (string, error)

CatalogSemanticChecksum returns the stable SHA-256 identity of catalog facts. It excludes provenance and observation evidence. EncodeCatalogPayload remains the exact integrity representation for storage, transport, and audit.

func DeepCopyProviderModels added in v0.0.15

func DeepCopyProviderModels(models map[string]*Model) map[string]*Model

DeepCopyProviderModels creates a deep copy of a provider's Models map. Returns nil if the input map is nil.

func DerivedCredentialEnvironmentName added in v0.4.0

func DerivedCredentialEnvironmentName(
	product string,
	providerID ProviderID,
	fieldID ProviderCredentialFieldID,
) (string, error)

DerivedCredentialEnvironmentName derives a product-specific ambient name. It validates all components before it replaces ID separators with underscores.

func EncodeCatalogPayload added in v0.1.0

func EncodeCatalogPayload(reader Reader) ([]byte, error)

EncodeCatalogPayload deterministically encodes a readable catalog.

func IsMediaOperation added in v0.10.0

func IsMediaOperation(operation ProviderOperation) bool

IsMediaOperation reports whether an operation names a dedicated media path.

func NormalizeExtensionFields added in v0.1.0

func NormalizeExtensionFields(fields map[string]any) map[string]any

NormalizeExtensionFields returns a copy with maps, slices, and numbers normalized to stable dynamic types after JSON/YAML round trips.

func ShallowCopyProviderModels added in v0.0.15

func ShallowCopyProviderModels(models map[string]*Model) map[string]*Model

ShallowCopyProviderModels copies a provider's Models map while sharing its Model pointers. It returns nil for a nil input map.

func ValidateReviewCandidates added in v0.4.0

func ValidateReviewCandidates(
	candidates []evidence.ReviewCandidate,
	observations []SourceObservationLink,
) error

ValidateReviewCandidates verifies durable review candidates against the exact source observations that supplied their evidence.

Types

type ArchitectureType

type ArchitectureType string

ArchitectureType represents the type of model architecture.

const (
	ArchitectureTypeTransformer ArchitectureType = "transformer"
	ArchitectureTypeMoE         ArchitectureType = "moe"
	ArchitectureTypeCNN         ArchitectureType = "cnn"
	ArchitectureTypeRNN         ArchitectureType = "rnn"
	ArchitectureTypeLSTM        ArchitectureType = "lstm"
	ArchitectureTypeGRU         ArchitectureType = "gru"
	ArchitectureTypeVAE         ArchitectureType = "vae"
	ArchitectureTypeGAN         ArchitectureType = "gan"
	ArchitectureTypeDiffusion   ArchitectureType = "diffusion"
)

Architecture types.

func (ArchitectureType) String

func (at ArchitectureType) String() string

String returns text for ArchitectureType.

type Author

type Author struct {
	ID          AuthorID   `json:"id" yaml:"id"`
	Aliases     []AuthorID `json:"aliases,omitempty" yaml:"aliases,omitempty"`
	Name        string     `json:"name" yaml:"name"` // Display name of the author
	Description *string    `json:"description,omitempty" yaml:"description,omitempty"`

	// Company/organization info
	Headquarters *string `json:"headquarters,omitempty" yaml:"headquarters,omitempty"` // Company headquarters location
	IconURL      *string `json:"icon_url,omitempty" yaml:"icon_url,omitempty"`         // Author icon/logo URL

	// catalog payload but stay out of authors.yaml. On a filesystem catalog
	// they live in the authors/<id>/logo.svg sidecar file.
	Logo []byte `json:"logo_svg,omitempty" yaml:"-"`

	// Website, social links, and other relevant URLs
	Website     *string `json:"website,omitempty" yaml:"website,omitempty"`         // Official website URL
	HuggingFace *string `json:"huggingface,omitempty" yaml:"huggingface,omitempty"` // Hugging Face profile/organization URL
	GitHub      *string `json:"github,omitempty" yaml:"github,omitempty"`           // GitHub profile/organization URL
	Twitter     *string `json:"twitter,omitempty" yaml:"twitter,omitempty"`         // X (formerly Twitter) profile URL

	// Catalog contains attribution rules used to derive author membership from
	// canonical provider model records.
	Catalog *AuthorCatalog `json:"catalog,omitempty" yaml:"catalog,omitempty"`

	// Timestamps for record keeping and auditing
	CreatedAt utc.Time `json:"created_at" yaml:"created_at"` // Created date (YYYY-MM or YYYY-MM-DD format)
	UpdatedAt utc.Time `json:"updated_at" yaml:"updated_at"` // Last updated date (YYYY-MM or YYYY-MM-DD format)
}

Author represents a known model author or organization.

func DeepCopyAuthor added in v0.0.15

func DeepCopyAuthor(author Author) Author

DeepCopyAuthor creates a deep copy of an Author.

func DeepCopyAuthors added in v0.1.0

func DeepCopyAuthors(authors []Author) []Author

DeepCopyAuthors creates a deep copy of an Author slice.

type AuthorAttribution added in v0.0.15

type AuthorAttribution struct {
	ProviderID ProviderID `json:"provider_id,omitempty" yaml:"provider_id,omitempty"` // Optional provider to source models from
	Patterns   []string   `json:"patterns,omitempty" yaml:"patterns,omitempty"`       // Glob patterns to match model IDs
}

AuthorAttribution defines how to identify an author's models across providers. Uses standard Go glob pattern syntax for case-insensitive model ID matching.

Supports three modes:

  1. Provider-only: provider_id set, no patterns - all models from that provider belong to this author
  2. Provider + patterns: provider_id + patterns - only matching models from that provider, then cross-provider attribution
  3. Global patterns: patterns only - direct case-insensitive pattern matching across all providers

Glob pattern syntax is case-insensitive:

  • "*" matches any character sequence except path separators.
  • "?" matches one character.
  • "[abc]" matches one listed character.
  • "[a-z]" matches one character in the range.

Examples:

"llama*" matches llama-3, Llama3.1-8b, LLAMA-BIG
"*-llama-*" matches deepseek-r1-distill-llama-70b, DeepSeek-R1-Distill-LLAMA-70B
"gpt-*" matches gpt-4, GPT-3.5-turbo, Gpt-4o

type AuthorCatalog

type AuthorCatalog struct {
	Description *string            `json:"description,omitempty" yaml:"description,omitempty"`
	Attribution *AuthorAttribution `json:"attribution,omitempty" yaml:"attribution,omitempty"` // Model attribution configuration for multi-provider inference
}

AuthorCatalog represents the relationship between an author and their authoritative provider catalog. This contains the attribution configuration for identifying the author's models across providers.

type AuthorID

type AuthorID string

AuthorID is a unique identifier for an author.

const (
	// Major AI Companies.
	AuthorIDOpenAI    AuthorID = "openai"
	AuthorIDAnthropic AuthorID = "anthropic"
	AuthorIDGoogle    AuthorID = "google"
	AuthorIDDeepMind  AuthorID = "deepmind"
	AuthorIDMeta      AuthorID = "meta"
	AuthorIDMicrosoft AuthorID = "microsoft"
	AuthorIDMistralAI AuthorID = "mistral"
	AuthorIDCohere    AuthorID = "cohere"
	// AuthorIDCerebras removed - Cerebras is an inference provider, not a model creator.
	AuthorIDGroq AuthorID = "groq"
	AuthorIDQwen AuthorID = "qwen"
	AuthorIDXAI  AuthorID = "xai"

	// Research Institutions.
	AuthorIDStanford    AuthorID = "stanford"
	AuthorIDMIT         AuthorID = "mit"
	AuthorIDCMU         AuthorID = "cmu"
	AuthorIDUCBerkeley  AuthorID = "uc-berkeley"
	AuthorIDCornell     AuthorID = "cornell"
	AuthorIDPrinceton   AuthorID = "princeton"
	AuthorIDHarvard     AuthorID = "harvard"
	AuthorIDOxford      AuthorID = "oxford"
	AuthorIDCambridge   AuthorID = "cambridge"
	AuthorIDETHZurich   AuthorID = "eth-zurich"
	AuthorIDUWashington AuthorID = "uw"
	AuthorIDUChicago    AuthorID = "uchicago"
	AuthorIDYale        AuthorID = "yale"
	AuthorIDDuke        AuthorID = "duke"
	AuthorIDCaltech     AuthorID = "caltech"

	// Open Source Communities & Platforms.
	AuthorIDHuggingFace AuthorID = "huggingface"
	AuthorIDEleutherAI  AuthorID = "eleutherai"
	AuthorIDTogether    AuthorID = "together"
	AuthorIDMosaicML    AuthorID = "mosaicml"
	AuthorIDStabilityAI AuthorID = "stability"
	AuthorIDRunwayML    AuthorID = "runway"
	AuthorIDMidjourney  AuthorID = "midjourney"
	AuthorIDLAION       AuthorID = "laion"
	AuthorIDBigScience  AuthorID = "bigscience"
	AuthorIDAlignmentRC AuthorID = "alignment-research"
	AuthorIDH2OAI       AuthorID = "h2o.ai"
	AuthorIDMoxin       AuthorID = "moxin"

	// Chinese Organizations.
	AuthorIDBaidu      AuthorID = "baidu"
	AuthorIDTencent    AuthorID = "tencent"
	AuthorIDByteDance  AuthorID = "bytedance"
	AuthorIDDeepSeek   AuthorID = "deepseek"
	AuthorIDBAAI       AuthorID = "baai"
	AuthorID01AI       AuthorID = "01.ai"
	AuthorIDBaichuan   AuthorID = "baichuan"
	AuthorIDMiniMax    AuthorID = "minimax"
	AuthorIDMoonshot   AuthorID = "moonshot-ai"
	AuthorIDShanghaiAI AuthorID = "shanghai-ai-lab"
	AuthorIDZhipuAI    AuthorID = "zhipu-ai"
	AuthorIDSenseTime  AuthorID = "sensetime"
	AuthorIDHuawei     AuthorID = "huawei"
	AuthorIDTsinghua   AuthorID = "tsinghua"
	AuthorIDPeking     AuthorID = "peking"

	// Other Notable Organizations.
	AuthorIDNVIDIA     AuthorID = "nvidia"
	AuthorIDSalesforce AuthorID = "salesforce"
	AuthorIDIBM        AuthorID = "ibm"
	AuthorIDApple      AuthorID = "apple"
	AuthorIDAmazon     AuthorID = "amazon"
	AuthorIDAdept      AuthorID = "adept"
	AuthorIDAI21       AuthorID = "ai21"
	AuthorIDInflection AuthorID = "inflection"
	AuthorIDCharacter  AuthorID = "character"
	AuthorIDPerplexity AuthorID = "perplexity"
	AuthorIDAnysphere  AuthorID = "anysphere"
	AuthorIDCursor     AuthorID = "cursor"

	// Notable Fine-Tuned Model Creators & Publishers.
	AuthorIDCognitiveComputations AuthorID = "cognitivecomputations"
	AuthorIDEricHartford          AuthorID = "ehartford"
	AuthorIDNousResearch          AuthorID = "nousresearch"
	AuthorIDTeknium               AuthorID = "teknium"
	AuthorIDJonDurbin             AuthorID = "jondurbin"
	AuthorIDLMSYS                 AuthorID = "lmsys"
	AuthorIDVicuna                AuthorID = "vicuna-team"
	AuthorIDAlpacaTeam            AuthorID = "stanford-alpaca"
	AuthorIDWizardLM              AuthorID = "wizardlm"
	AuthorIDOpenOrca              AuthorID = "open-orca"
	AuthorIDPhind                 AuthorID = "phind"
	AuthorIDCodeFuse              AuthorID = "codefuse"
	AuthorIDTHUDM                 AuthorID = "thudm"
	AuthorIDGeorgiaTechRI         AuthorID = "gatech"
	AuthorIDFastChat              AuthorID = "fastchat"

	// Special constant for unknown authors.
	AuthorIDUnknown AuthorID = "unknown"
)

Author ID constants for compile-time safety and consistency.

func ParseAuthorID added in v0.0.15

func ParseAuthorID(s string) AuthorID

ParseAuthorID normalizes stable author aliases without consulting catalog state. Use Authors.Resolve when alias resolution needs a specific catalog.

func ParseModelDefinitionID added in v0.2.0

func ParseModelDefinitionID(id ModelDefinitionID) (AuthorID, string, error)

ParseModelDefinitionID validates and splits one canonical author/slug ID.

func (AuthorID) String

func (id AuthorID) String() string

String returns text for AuthorID.

type AuthorMapping added in v0.0.15

type AuthorMapping struct {
	Field      string              `yaml:"field" json:"field"`           // Field to extract from (e.g., "owned_by")
	Normalized map[string]AuthorID `yaml:"normalized" json:"normalized"` // Normalization map (e.g., "Meta" -> "meta")
}

AuthorMapping defines how to extract and normalize authors.

func (AuthorMapping) Resolve added in v0.4.0

func (m AuthorMapping) Resolve(value string) (AuthorID, bool)

Resolve returns the configured author for one exact provider field value. Exact and case-insensitive matches precede the most-specific glob pattern.

func (AuthorMapping) Validate added in v0.4.0

func (m AuthorMapping) Validate() error

Validate checks the transport-independent author-normalization contract. Transport adapters separately validate which source fields they support.

type AuthoredModel added in v0.2.0

type AuthoredModel struct {
	AuthorID AuthorID
	Model    Model
}

AuthoredModel is one provider-independent construction record stored at authors/<author>/models/<slug>.yaml. Model contains intrinsic facts only.

func (AuthoredModel) ID added in v0.2.0

ID returns the canonical author/slug identity.

type Authors

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

Authors is a concurrent safe map of authors.

func NewAuthors

func NewAuthors(opts ...AuthorsOption) *Authors

NewAuthors creates a new Authors map with optional configuration.

func (*Authors) Add

func (a *Authors) Add(author *Author) error

Add adds an author, returning an error if it already exists.

func (*Authors) AddBatch

func (a *Authors) AddBatch(authors []*Author) map[AuthorID]error

AddBatch adds multiple authors in a single operation. Only adds authors that do not already exist - fails if an author ID already exists. Returns a map of author IDs to errors for any failed additions.

func (*Authors) Clear

func (a *Authors) Clear()

Clear removes all authors.

func (*Authors) Delete

func (a *Authors) Delete(id AuthorID) error

Delete removes an author by id. Returns an error if the author does not exist.

func (*Authors) DeleteBatch

func (a *Authors) DeleteBatch(ids []AuthorID) map[AuthorID]error

DeleteBatch removes multiple authors by ID. The returned map identifies IDs that DeleteBatch did not find.

func (*Authors) EncodeYAML added in v0.1.0

func (a *Authors) EncodeYAML() (string, error)

EncodeYAML returns formatted author YAML. It returns a typed parse error for values that YAML cannot represent safely.

func (*Authors) Exists

func (a *Authors) Exists(id AuthorID) bool

Exists checks if an author exists without returning it.

func (*Authors) ForEach

func (a *Authors) ForEach(fn func(id AuthorID, author *Author) bool)

ForEach applies a function to each author. The function should not modify the author. If the function returns false, iteration stops early.

func (*Authors) FormatYAML added in v0.0.13

func (a *Authors) FormatYAML() string

FormatYAML returns the authors as formatted YAML sorted alphabetically by ID.

func (*Authors) Get

func (a *Authors) Get(id AuthorID) (*Author, bool)

Get returns an author by id and whether it exists.

func (*Authors) Len

func (a *Authors) Len() int

Len returns the number of authors.

func (*Authors) List

func (a *Authors) List() []Author

List returns a slice of all authors as values (copies).

func (*Authors) Map

func (a *Authors) Map() map[AuthorID]*Author

Map returns a copy of all authors.

func (*Authors) Resolve added in v0.0.21

func (a *Authors) Resolve(id AuthorID) (*Author, bool)

Resolve returns an author by ID or alias. It first tries an exact ID match, then searches all author aliases. This allows commands to accept both canonical IDs and common aliases silently.

func (*Authors) Set

func (a *Authors) Set(id AuthorID, author *Author) error

Set sets an author by id. Returns an error if author is nil.

func (*Authors) SetBatch

func (a *Authors) SetBatch(authors map[AuthorID]*Author) error

SetBatch sets multiple authors in a single operation. Overwrites existing authors or adds new ones (upsert behavior). Returns an error if any author is nil.

type AuthorsOption

type AuthorsOption func(*Authors)

AuthorsOption defines a function that configures an Authors instance.

func WithAuthorsCapacity

func WithAuthorsCapacity(capacity int) AuthorsOption

WithAuthorsCapacity sets the initial capacity of the authors map.

func WithAuthorsMap

func WithAuthorsMap(authors map[AuthorID]*Author) AuthorsOption

WithAuthorsMap initializes the map with existing authors.

type AuthorsReader added in v0.1.0

type AuthorsReader interface {
	Get(AuthorID) (*Author, bool)
	Resolve(AuthorID) (*Author, bool)
	Exists(AuthorID) bool
	Len() int
	List() []Author
	Map() map[AuthorID]*Author
	ForEach(func(AuthorID, *Author) bool)
	FormatYAML() string
}

AuthorsReader exposes author collection reads without mutation methods.

type BootstrapManifest added in v0.1.0

type BootstrapManifest struct {
	ManifestVersion  uint64            `json:"manifest_version" yaml:"manifest_version"`
	GenerationID     string            `json:"generation_id" yaml:"generation_id"`
	GeneratedAt      time.Time         `json:"generated_at" yaml:"generated_at"`
	SchemaVersion    uint64            `json:"schema_version" yaml:"schema_version"`
	SemanticChecksum string            `json:"semantic_checksum" yaml:"semantic_checksum"`
	Payload          PayloadDescriptor `json:"payload" yaml:"payload"`
}

BootstrapManifest binds the offline embedded catalog to exact canonical catalog bytes and a generation time.

func ParseBootstrapManifestEnvelopeJSON added in v0.4.0

func ParseBootstrapManifestEnvelopeJSON(data []byte) (BootstrapManifest, error)

ParseBootstrapManifestEnvelopeJSON strictly parses bootstrap metadata without requiring the current catalog schema. Catalog refresh tooling uses it to replace a valid manifest from the previous schema.

func ParseBootstrapManifestJSON added in v0.1.0

func ParseBootstrapManifestJSON(data []byte) (BootstrapManifest, error)

ParseBootstrapManifestJSON strictly parses embedded-bootstrap metadata.

func (BootstrapManifest) Validate added in v0.1.0

func (m BootstrapManifest) Validate() error

Validate checks the embedded-bootstrap metadata contract and requires the current catalog schema.

func (BootstrapManifest) ValidateEnvelope added in v0.4.0

func (m BootstrapManifest) ValidateEnvelope() error

ValidateEnvelope checks schema-independent embedded-bootstrap metadata.

type Builder added in v0.1.0

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

Builder is the advanced mutable catalog construction type. Use it for custom update callbacks, source or plugin authors, and persistence pipelines. Ordinary consumers should use the immutable *Catalog from *starmap.Client.Catalog. It can work as: - Memory catalog (readFS == nil) - Embedded catalog (readFS is embed.FS) - Files catalog (readFS is os.DirFS) - Custom catalog (readFS is any fs.FS implementation).

func New

func New(opt Option, opts ...Option) (*Builder, error)

New creates a new builder with the given options. WithFS(fsys) and WithPath(path) load the configured files automatically.

func NewBuilderFrom added in v0.1.0

func NewBuilderFrom(source Reader) (*Builder, error)

NewBuilderFrom copies source into a new independent builder.

func NewEmpty added in v0.0.16

func NewEmpty() *Builder

NewEmpty creates an in-memory empty catalog. This is useful for testing or temporary catalogs that do not need persistence.

Example:

catalog := NewEmpty()
provider := Provider{ID: "openai", Models: map[string]Model{}}
catalog.SetProvider(provider)

func NewFromFS

func NewFromFS(fsys fs.FS, root string) (*Builder, error)

NewFromFS creates a catalog from a custom filesystem implementation. This allows for advanced use cases like virtual filesystems or custom storage backends.

Example:

var myFS embed.FS
catalog, err := NewFromFS(myFS, "catalog")

func NewFromPath added in v0.0.16

func NewFromPath(path string) (*Builder, error)

NewFromPath creates a catalog backed by files on disk. This is useful for development when you want to edit catalog files without recompiling the binary.

Example:

catalog, err := NewFromPath("./internal/embedded/catalog")
if err != nil {
    log.Fatal(err)
}

func (*Builder) Author added in v0.1.0

func (cat *Builder) Author(id AuthorID) (Author, error)

Author returns an author by ID or alias. Silently resolves aliases to canonical author IDs.

func (*Builder) AuthoredModels added in v0.2.0

func (cat *Builder) AuthoredModels() []AuthoredModel

AuthoredModels returns caller-owned provider-independent construction records in canonical author/slug order.

func (*Builder) Authors added in v0.1.0

func (cat *Builder) Authors() AuthorsReader

Authors returns the authors collection.

func (*Builder) Build added in v0.1.0

func (cat *Builder) Build() (*Catalog, error)

Build publishes an immutable deep copy of the builder's current state.

func (*Builder) ClearProvenance added in v0.1.0

func (cat *Builder) ClearProvenance()

ClearProvenance removes catalog provenance.

func (*Builder) Copy added in v0.1.0

func (cat *Builder) Copy() (*Builder, error)

Copy creates a deep copy of the catalog.

func (*Builder) DeleteAuthor added in v0.1.0

func (cat *Builder) DeleteAuthor(id AuthorID) error

DeleteAuthor deletes an author.

func (*Builder) DeleteAuthorModel added in v0.2.0

func (cat *Builder) DeleteAuthorModel(authorID AuthorID, slug string) error

DeleteAuthorModel deletes one provider-independent model from an author.

func (*Builder) DeleteProvider added in v0.1.0

func (cat *Builder) DeleteProvider(id ProviderID) error

DeleteProvider deletes a provider.

func (*Builder) DeleteProviderModel added in v0.1.0

func (cat *Builder) DeleteProviderModel(providerID ProviderID, modelID string) error

DeleteProviderModel deletes a model from a provider atomically.

func (*Builder) Load added in v0.1.0

func (cat *Builder) Load() error

Load loads the catalog from the configured filesystem.

func (*Builder) LoadReport added in v0.2.0

func (cat *Builder) LoadReport() LoadReport

LoadReport returns a caller-owned copy of the builder's load diagnostics.

func (*Builder) MergeProvenance added in v0.1.0

func (cat *Builder) MergeProvenance(value provenance.Map)

MergeProvenance appends catalog provenance.

func (*Builder) MergeStrategy added in v0.1.0

func (cat *Builder) MergeStrategy() MergeStrategy

MergeStrategy returns the default merge strategy.

func (*Builder) MergeWith added in v0.1.0

func (cat *Builder) MergeWith(source Reader, opts ...MergeOption) error

MergeWith merges another catalog into this one.

func (*Builder) Provenance added in v0.1.0

func (cat *Builder) Provenance() ProvenanceReader

Provenance returns the provenance collection.

func (*Builder) Provider added in v0.1.0

func (cat *Builder) Provider(id ProviderID) (Provider, error)

Provider returns a provider by ID or alias. Silently resolves aliases to canonical provider IDs.

func (*Builder) ProviderModel added in v0.1.0

func (cat *Builder) ProviderModel(providerID ProviderID, modelID string) (Model, error)

ProviderModel returns one provider-specific model offering without flattening equal model IDs from other providers.

func (*Builder) ProviderModels added in v0.1.0

func (cat *Builder) ProviderModels(id ProviderID) (ModelsReader, error)

ProviderModels returns the models served by a provider or one of its aliases.

func (*Builder) Providers added in v0.1.0

func (cat *Builder) Providers() ProvidersReader

Providers returns the providers collection.

func (*Builder) ReplaceWith added in v0.1.0

func (cat *Builder) ReplaceWith(source Reader) error

ReplaceWith replaces this catalog's contents with another.

func (*Builder) Save added in v0.1.0

func (cat *Builder) Save() error

Save serializes a mutable builder to its configured construction path. It is not a publication primitive. The Starmap client materializes committed catalogs atomically.

func (*Builder) SaveTo added in v0.2.0

func (cat *Builder) SaveTo(path string) error

SaveTo serializes a mutable builder to path.

func (*Builder) SetAuthor added in v0.1.0

func (cat *Builder) SetAuthor(author Author) error

SetAuthor sets an author (upsert).

func (*Builder) SetAuthorModel added in v0.2.0

func (cat *Builder) SetAuthorModel(authorID AuthorID, model Model) error

SetAuthorModel sets one provider-independent model on its owning author.

func (*Builder) SetMergeStrategy added in v0.1.0

func (cat *Builder) SetMergeStrategy(strategy MergeStrategy)

SetMergeStrategy sets the default merge strategy.

func (*Builder) SetProvenance added in v0.1.0

func (cat *Builder) SetProvenance(value provenance.Map)

SetProvenance replaces catalog provenance.

func (*Builder) SetProvider added in v0.1.0

func (cat *Builder) SetProvider(provider Provider) error

SetProvider sets a provider (upsert).

func (*Builder) SetProviderModel added in v0.1.0

func (cat *Builder) SetProviderModel(providerID ProviderID, model Model) error

SetProviderModel sets a model on a provider atomically.

type CapabilityMapping added in v0.4.0

type CapabilityMapping struct {
	From     string                        `yaml:"from" json:"from"`
	To       []ModelFeature                `yaml:"to" json:"to"`
	Combine  ProviderCapabilityCombination `yaml:"combine,omitempty" json:"combine,omitempty"`
	Evidence string                        `yaml:"evidence" json:"evidence"`
}

CapabilityMapping maps one typed provider predicate to each canonical fact that the cited provider contract entails.

type Catalog

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

Catalog is Starmap's immutable canonical catalog. Read methods provide the only access to its private state. Callers can retain it across goroutines.

func DecodeCatalogPayload added in v0.5.0

func DecodeCatalogPayload(data []byte) (*Catalog, error)

DecodeCatalogPayload decodes the current catalog payload. A non-nil catalog with *sourcepayload.QuarantineError is only a partial diagnostic result. Callers must not activate it as the manifest-bound generation.

func DecodeSourceObservationPayload added in v0.5.0

func DecodeSourceObservationPayload(data []byte) (*Catalog, error)

DecodeSourceObservationPayload decodes a source candidate without requiring resolved canonical authorship for every provider record. The returned catalog is suitable only for reconciliation. Durable generation activation must use DecodeCatalogPayload.

func NewCatalog added in v0.1.0

func NewCatalog(source Reader) (*Catalog, error)

NewCatalog copies source into an immutable canonical catalog.

func NewObservationCatalog added in v0.2.0

func NewObservationCatalog(source Reader) (*Catalog, error)

NewObservationCatalog copies source records into an immutable source observation without deriving consumer definitions or offerings. It exists for acquisition boundaries that must preserve provider records before reconciliation resolves every ModelRef. Final publication must use NewCatalog or Builder.Build, which fail closed on unresolved references.

func (*Catalog) Author added in v0.1.0

func (r *Catalog) Author(id AuthorID) (Author, error)

Author returns a caller-owned copy of an author.

func (*Catalog) AuthorModel added in v0.2.0

func (r *Catalog) AuthorModel(authorID AuthorID, slug string) (ModelDefinition, error)

AuthorModel resolves an author ID or alias plus a model slug.

func (*Catalog) AuthorModels added in v0.2.0

func (r *Catalog) AuthorModels(authorID AuthorID) ([]ModelDefinition, error)

AuthorModels returns caller-owned canonical model definitions attributed to an author or one of its aliases, ordered by definition ID.

func (*Catalog) AuthoredModels added in v0.2.0

func (r *Catalog) AuthoredModels() []AuthoredModel

AuthoredModels returns caller-owned provider-independent construction records. Ordinary consumers normally use Definitions and AuthorModels.

func (*Catalog) Authors added in v0.1.0

func (r *Catalog) Authors() AuthorsReader

Authors returns the immutable catalog's author collection reader.

func (*Catalog) Definition added in v0.1.0

func (r *Catalog) Definition(id ModelDefinitionID) (ModelDefinition, error)

Definition returns one caller-owned canonical model definition.

func (*Catalog) DefinitionOfferings added in v0.2.0

func (r *Catalog) DefinitionOfferings(id ModelDefinitionID) ([]ProviderOffering, error)

DefinitionOfferings returns caller-owned offerings for one canonical model, ordered by provider and exact provider model ID.

func (*Catalog) Definitions added in v0.1.0

func (r *Catalog) Definitions() []ModelDefinition

Definitions returns caller-owned canonical definitions in ID order.

func (*Catalog) FindModel added in v0.1.0

func (r *Catalog) FindModel(id string) (ModelDefinition, error)

FindModel returns the canonical provider-independent model definition. Use Offering for provider price, limits, availability, and request behavior.

func (*Catalog) MaterializeRouteAlias added in v0.1.0

func (r *Catalog) MaterializeRouteAlias(alias RouteAlias) (RouteAliasResolution, error)

MaterializeRouteAlias resolves current eligibility without storing routing policy in source ingestion or the canonical catalog.

func (*Catalog) Offering added in v0.1.0

func (r *Catalog) Offering(providerID ProviderID, providerModelID ProviderModelID) (ProviderOffering, error)

Offering returns one caller-owned provider-scoped model offering. Provider aliases resolve to their canonical provider before key lookup.

func (*Catalog) Provenance added in v0.1.0

func (r *Catalog) Provenance() ProvenanceReader

Provenance returns the immutable catalog's provenance reader.

func (*Catalog) Provider added in v0.1.0

func (r *Catalog) Provider(id ProviderID) (Provider, error)

Provider returns a caller-owned copy of a provider.

func (*Catalog) ProviderOfferings added in v0.1.0

func (r *Catalog) ProviderOfferings(providerID ProviderID) ([]ProviderOffering, error)

ProviderOfferings returns caller-owned offerings in provider-model-ID order.

func (*Catalog) Providers added in v0.1.0

func (r *Catalog) Providers() ProvidersReader

Providers returns the immutable catalog's provider collection reader.

type CatalogPayload added in v0.1.0

type CatalogPayload struct {
	SchemaVersion  uint64             `json:"schema_version"`
	Providers      []Provider         `json:"providers"`
	Authors        []Author           `json:"authors"`
	ProviderModels map[string][]Model `json:"provider_models"`
	AuthorModels   map[string][]Model `json:"author_models"`
	Provenance     provenance.Map     `json:"provenance"`
}

CatalogPayload is the canonical construction-record JSON representation. Author models own provider-independent facts. Provider models own serving facts and link to author models through Model.ModelRef.

type ConsumerCompatibility added in v0.1.0

type ConsumerCompatibility struct {
	MinSchemaVersion uint64 `json:"min_schema_version" yaml:"min_schema_version"`
	MaxSchemaVersion uint64 `json:"max_schema_version" yaml:"max_schema_version"`
}

ConsumerCompatibility declares the catalog schema versions that can consume this generation. It never refers to a Starmap or Starport binary version.

func (ConsumerCompatibility) SupportsSchema added in v0.1.0

func (c ConsumerCompatibility) SupportsSchema(schemaVersion uint64) bool

SupportsSchema reports whether a consumer catalog schema is compatible.

type EndpointType added in v0.0.15

type EndpointType string

EndpointType specifies the API style for model listing.

const (
	// EndpointTypeOpenAI represents OpenAI-compatible API.
	EndpointTypeOpenAI EndpointType = "openai"
	// EndpointTypeAnthropic represents Anthropic API format.
	EndpointTypeAnthropic EndpointType = "anthropic"
	// EndpointTypeGoogle represents Google AI Studio.
	EndpointTypeGoogle EndpointType = "google"
	// EndpointTypeGoogleCloud represents Google Vertex AI.
	EndpointTypeGoogleCloud EndpointType = "google-cloud"
	// EndpointTypeOllama represents the native Ollama API.
	EndpointTypeOllama EndpointType = "ollama"
	// EndpointTypeCohere represents the Cohere API. Reranking has no OpenAI
	// standard, so Cohere's request shape is the one other services copied.
	EndpointTypeCohere EndpointType = "cohere"
	// EndpointTypeVoyage represents the Voyage AI API. Its reranker names the
	// result count and the response envelope differently from Cohere's, so it
	// cannot share that style.
	EndpointTypeVoyage EndpointType = "voyage"
)

type FieldMapping added in v0.0.15

type FieldMapping struct {
	From string `yaml:"from" json:"from"` // Source field path in API response (e.g., "max_model_len")
	To   string `yaml:"to" json:"to"`     // Target field path in Model (e.g., "limits.context_window")
}

FieldMapping defines how to map API response fields to model fields. Type conversion is automatic based on the destination field type.

type FloatRange

type FloatRange struct {
	Min     float64 `json:"min" yaml:"min"`         // Minimum value
	Max     float64 `json:"max" yaml:"max"`         // Maximum value
	Default float64 `json:"default" yaml:"default"` // Default value
}

FloatRange represents a range of float values.

type Generation added in v0.5.0

type Generation struct {
	Manifest GenerationManifest
	Payload  []byte
}

Generation is an immutable manifest and its exact catalog payload bytes.

func (Generation) Copy added in v0.5.0

func (g Generation) Copy() Generation

Copy returns a generation that does not share mutable slices with g.

func (Generation) SemanticChecksum added in v0.16.3

func (g Generation) SemanticChecksum() (string, error)

SemanticChecksum returns the facts-only identity of the catalog the payload carries. It excludes provenance, so a regenerated payload with the same facts keeps the same value. The publisher keys the immutable release tag and the channel catalog digest by this value. The exact payload checksum stays in the manifest.

func (Generation) Validate added in v0.5.0

func (g Generation) Validate() error

Validate verifies the manifest and its binding to the payload.

type GenerationCompleteness added in v0.1.0

type GenerationCompleteness string

GenerationCompleteness describes whether a generation contains every record expected from the observations used to build it.

const (
	// GenerationCompletenessComplete means the generation contains every expected record.
	GenerationCompletenessComplete GenerationCompleteness = "complete"
	// GenerationCompletenessPartial means at least one expected input or record is
	// absent. The generation must also have a degraded status.
	GenerationCompletenessPartial GenerationCompleteness = "partial"
)

type GenerationManifest added in v0.1.0

type GenerationManifest struct {
	ManifestVersion       uint64                     `json:"manifest_version" yaml:"manifest_version"`
	SchemaVersion         uint64                     `json:"schema_version" yaml:"schema_version"`
	GenerationID          string                     `json:"generation_id" yaml:"generation_id"`
	GeneratedAt           time.Time                  `json:"generated_at" yaml:"generated_at"`
	Payload               PayloadDescriptor          `json:"payload" yaml:"payload"`
	Validation            GenerationValidationReport `json:"validation" yaml:"validation"`
	SyncRunID             string                     `json:"sync_run_id" yaml:"sync_run_id"`
	SourceObservations    []SourceObservationLink    `json:"source_observations" yaml:"source_observations"`
	ReviewCandidates      []evidence.ReviewCandidate `json:"review_candidates" yaml:"review_candidates"`
	Completeness          GenerationCompleteness     `json:"completeness" yaml:"completeness"`
	Degraded              bool                       `json:"degraded" yaml:"degraded"`
	DegradationReasons    []string                   `json:"degradation_reasons,omitempty" yaml:"degradation_reasons,omitempty"`
	ConsumerCompatibility ConsumerCompatibility      `json:"consumer_compatibility" yaml:"consumer_compatibility"`
}

GenerationManifest describes one immutable, validated catalog generation. Local stores and distribution transports share it. Transport-specific URLs, release tags, and binary versions do not belong in this domain record.

func ParseGenerationManifestJSON added in v0.1.0

func ParseGenerationManifestJSON(data []byte) (GenerationManifest, error)

ParseGenerationManifestJSON strictly parses and validates a JSON manifest. It returns typed validation errors for unknown or missing members, including false or zero values. It also rejects malformed JSON and trailing documents.

func (GenerationManifest) Copy added in v0.1.0

Copy returns a value whose slices do not alias the original manifest.

func (GenerationManifest) Validate added in v0.1.0

func (m GenerationManifest) Validate() error

Validate verifies that a manifest is complete and eligible for publication.

type GenerationValidationCheck added in v0.1.0

type GenerationValidationCheck struct {
	Name    string                          `json:"name" yaml:"name"`
	Status  GenerationValidationCheckStatus `json:"status" yaml:"status"`
	Message string                          `json:"message,omitempty" yaml:"message,omitempty"`
}

GenerationValidationCheck records one deterministic validation decision.

type GenerationValidationCheckStatus added in v0.1.0

type GenerationValidationCheckStatus string

GenerationValidationCheckStatus is the result of one validation check.

const (
	// GenerationValidationCheckPassed records a successful check.
	GenerationValidationCheckPassed GenerationValidationCheckStatus = "passed"
	// GenerationValidationCheckWarning records a non-fatal validation warning.
	GenerationValidationCheckWarning GenerationValidationCheckStatus = "warning"
	// GenerationValidationCheckFailed records a failed required check.
	GenerationValidationCheckFailed GenerationValidationCheckStatus = "failed"
)

type GenerationValidationReport added in v0.1.0

type GenerationValidationReport struct {
	ValidatorVersion string                      `json:"validator_version" yaml:"validator_version"`
	ValidatedAt      time.Time                   `json:"validated_at" yaml:"validated_at"`
	Status           GenerationValidationStatus  `json:"status" yaml:"status"`
	ErrorCount       int                         `json:"error_count" yaml:"error_count"`
	WarningCount     int                         `json:"warning_count" yaml:"warning_count"`
	Checks           []GenerationValidationCheck `json:"checks" yaml:"checks"`
}

GenerationValidationReport records the validator identity and exact outcome that made a candidate eligible (or ineligible) for publication.

type GenerationValidationStatus added in v0.1.0

type GenerationValidationStatus string

GenerationValidationStatus is the overall result of generation validation.

const (
	// GenerationValidationPassed means every required validation check passed.
	GenerationValidationPassed GenerationValidationStatus = "passed"
	// GenerationValidationFailed means at least one required check failed. A
	// failed generation is evidence, but is not eligible for publication.
	GenerationValidationFailed GenerationValidationStatus = "failed"
)

type HealthAPIKind added in v0.14.0

type HealthAPIKind string

HealthAPIKind names the wire convention a provider's health API speaks. An empty kind means HealthAPIKindStatuspage, the convention every entry used before the kind existed.

const (
	// HealthAPIKindStatuspage is the Atlassian Statuspage JSON API
	// (/api/v2/summary.json and /api/v2/components.json).
	HealthAPIKindStatuspage HealthAPIKind = "statuspage"
	// HealthAPIKindHyperping is the Hyperping status JSON document
	// (schemaVersion 1 with overallStatus and per-service statuses).
	HealthAPIKindHyperping HealthAPIKind = "hyperping"
	// HealthAPIKindRSS is an incident feed (RSS or Atom) with one item
	// per incident and no structured component status.
	HealthAPIKindRSS HealthAPIKind = "rss"
	// HealthAPIKindGoogleCloud is the Google Cloud service health JSON
	// (incidents.json filtered by the product names in HealthComponents).
	HealthAPIKindGoogleCloud HealthAPIKind = "google-cloud"
)

type IntRange

type IntRange struct {
	Min     int `json:"min" yaml:"min"`         // Minimum value
	Max     int `json:"max" yaml:"max"`         // Maximum value
	Default int `json:"default" yaml:"default"` // Default value
}

IntRange represents a range of integer values.

type LoadIssue added in v0.2.0

type LoadIssue struct {
	// Path identifies the model file relative to the catalog root.
	Path string
	// Err is the typed parse or validation failure.
	Err error
	// Limit reports that the collection budget, rather than record syntax,
	// caused the quarantine.
	Limit bool
}

LoadIssue describes one malformed model file quarantined during a catalog load.

type LoadReport added in v0.2.0

type LoadReport struct {
	// Accepted is the number of model files loaded successfully.
	Accepted int
	// Rejected includes malformed and excess model files.
	Rejected int
	// Issues contains bounded typed diagnostics.
	Issues []LoadIssue
	// Truncated reports that excess model files were not read.
	Truncated bool
}

LoadReport describes bounded model-file loading. Structural catalog files remain fail-closed and are not represented here.

func (LoadReport) Err added in v0.2.0

func (r LoadReport) Err() error

Err joins quarantined record failures for callers that require a fully valid catalog, such as embedded bootstrap and atomic projection validation.

type MediaOperationFacts added in v0.10.0

type MediaOperationFacts struct {
	// Operation is the published operation name.
	Operation ProviderOperation
	// Tags name the operation on a model. Any one of them is enough.
	Tags []ModelTag
	// TagRequired means the modalities alone cannot identify the operation, so
	// a model has to carry one of the tags. Transcription reads audio and
	// writes text, which is also the shape of a chat model that hears.
	TagRequired bool
	// Input lists the input modalities the model must declare. It may declare
	// more.
	Input []ModelModality
	// Output is the exact output modality set. A model that also writes text
	// answers through chat completions rather than through a media path.
	Output []ModelModality
}

MediaOperationFacts states the exact model facts that a dedicated media operation requires. Consumers request such an operation by name instead of discovering it in a chat answer. A chat model that returns a picture therefore does not qualify.

Naming it is not the same as reaching a separate path. A provider that reads a document serves the read through its chat path, and the endpoint table says so. What makes the operation its own is that a consumer asks for it and pays for it in the operation's own unit.

The derivation reads this table, and the fact-consistency rule enforces it. One statement therefore decides both what Starmap publishes and what Starmap refuses, and neither reads a price to do it.

func MediaOperationDefinition added in v0.10.0

func MediaOperationDefinition(operation ProviderOperation) (MediaOperationFacts, bool)

MediaOperationDefinition returns the canonical facts for one operation.

func MediaOperationDefinitions added in v0.10.0

func MediaOperationDefinitions() []MediaOperationFacts

MediaOperationDefinitions returns the canonical facts for every dedicated media operation, in published order.

func (MediaOperationFacts) Matches added in v0.10.0

func (f MediaOperationFacts) Matches(model Model) bool

Matches reports whether a model declares the facts this operation requires.

type MergeOption

type MergeOption func(*MergeOptions)

MergeOption configures catalog merging.

func WithStrategy

func WithStrategy(s MergeStrategy) MergeOption

WithStrategy overrides the merge strategy.

type MergeOptions

type MergeOptions struct {
	Strategy MergeStrategy // nil means use source catalog's suggestion
}

MergeOptions holds merge configuration.

func ParseMergeOptions

func ParseMergeOptions(opts ...MergeOption) *MergeOptions

ParseMergeOptions processes merge options and returns the configuration.

type MergeStrategy

type MergeStrategy int

MergeStrategy defines how to merge catalogs.

const (
	// MergeEnrichEmpty intelligently merges, preserving existing non-empty values.
	MergeEnrichEmpty MergeStrategy = iota
	// MergeReplaceAll completely replaces the target catalog with the source.
	MergeReplaceAll
	// MergeAppendOnly only adds new items, skips existing ones.
	MergeAppendOnly
)

type Model

type Model struct {
	// Core identity
	ID string `json:"id" yaml:"id"` // Exact provider model ID or authored-model slug
	// ModelRef links a provider serving record to its canonical author/slug
	// model. It is empty on authored-model records.
	ModelRef    ModelDefinitionID `json:"model,omitempty" yaml:"model,omitempty"`
	Name        string            `json:"name" yaml:"name"`
	Authors     []Author          `json:"authors,omitempty" yaml:"authors,omitempty"` // Authors/organizations of the model (if known)
	Description string            `json:"description,omitempty" yaml:"description,omitempty"`
	Status      ModelStatus       `json:"status,omitempty" yaml:"status,omitempty"` // Lifecycle status such as active, beta, preview, or deprecated

	// Provider-announced lifecycle dates for this serving record. A nil value
	// means the provider has not announced the date.
	DeprecatedAt *utc.Time `json:"deprecated_at,omitempty" yaml:"deprecated_at,omitempty"` // When the provider deprecated this model
	RetiresAt    *utc.Time `json:"retires_at,omitempty" yaml:"retires_at,omitempty"`       // When the provider retires this model and stops serving requests

	// Metadata - version and timing information
	Metadata *ModelMetadata `json:"metadata,omitempty" yaml:"metadata,omitempty"` // Metadata for the model

	// Lineage - model family and derivation information
	Lineage *ModelLineage `json:"lineage,omitempty" yaml:"lineage,omitempty"`

	// Features - what this model can do
	Features *ModelFeatures `json:"features,omitempty" yaml:"features,omitempty"`

	// Attachments - attachment support details
	Attachments *ModelAttachments `json:"attachments,omitempty" yaml:"attachments,omitempty"`

	// Generation - core chat completions generation controls
	Generation *ModelGeneration `json:"generation,omitempty" yaml:"generation,omitempty"`

	// Reasoning - reasoning effort levels
	Reasoning *ModelControlLevels `json:"reasoning,omitempty" yaml:"reasoning,omitempty"`

	// ReasoningTokens - specific token allocation for reasoning processes
	ReasoningTokens *IntRange `json:"reasoning_tokens,omitempty" yaml:"reasoning_tokens,omitempty"`

	// Verbosity - response verbosity levels
	Verbosity *ModelControlLevels `json:"verbosity,omitempty" yaml:"verbosity,omitempty"`

	// Tools - external tool and capability integrations
	Tools *ModelTools `json:"tools,omitempty" yaml:"tools,omitempty"`

	// Delivery - technical response delivery capabilities (formats, protocols, streaming)
	Delivery *ModelDelivery `json:"response,omitempty" yaml:"response,omitempty"`

	// Modes - alternate service modes such as fast/priority variants
	Modes map[string]ModelMode `json:"modes,omitempty" yaml:"modes,omitempty"`

	// Operational characteristics
	Pricing *ModelPricing `json:"pricing,omitempty" yaml:"pricing,omitempty"` // Optional pricing information
	Limits  *ModelLimits  `json:"limits,omitempty" yaml:"limits,omitempty"`   // Model limits

	// Extensions - controlled source-specific fields that are not canonical schema
	Extensions SourceExtensions `json:"extensions,omitempty" yaml:"extensions,omitempty"`

	CreatedAt utc.Time `json:"created_at" yaml:"created_at"`
	UpdatedAt utc.Time `json:"updated_at" yaml:"updated_at"`
	// contains filtered or unexported fields
}

Model represents a model configuration.

func DeepCopyModel added in v0.1.0

func DeepCopyModel(model Model) Model

DeepCopyModel creates a deep copy of a Model.

func MergeModels

func MergeModels(existing, updated Model) Model

MergeModels combines two models and retains existing values when updated has an empty or nil value.

func (*Model) DescriptionValue added in v0.2.0

func (m *Model) DescriptionValue() (string, ValuePresence)

DescriptionValue returns the description and its presence state.

func (*Model) EncodeYAML added in v0.1.0

func (m *Model) EncodeYAML() (string, error)

EncodeYAML returns formatted YAML. It returns a typed parse error for values that YAML cannot represent safely.

func (Model) Equal added in v0.2.0

func (m Model) Equal(other Model) bool

Equal reports whether two models have the same serialized facts and presence semantics.

func (*Model) FormatYAML

func (m *Model) FormatYAML() string

FormatYAML returns a well-formatted YAML representation with comments and proper structure.

func (*Model) FormatYAMLHeaderComment

func (m *Model) FormatYAMLHeaderComment() string

FormatYAMLHeaderComment returns a descriptive string for the model header comment.

func (Model) MarshalJSON added in v0.2.0

func (m Model) MarshalJSON() ([]byte, error)

MarshalJSON preserves description presence in immutable catalog payloads.

func (Model) MarshalYAML added in v0.2.0

func (m Model) MarshalYAML() (any, error)

MarshalYAML preserves an explicit empty or unknown description.

func (*Model) SetDescription added in v0.2.0

func (m *Model) SetDescription(description string)

SetDescription records an explicit model description, including an empty description.

func (*Model) SetDescriptionUnknown added in v0.2.0

func (m *Model) SetDescriptionUnknown()

SetDescriptionUnknown records that the description is explicitly unknown.

func (*Model) UnmarshalJSON added in v0.2.0

func (m *Model) UnmarshalJSON(data []byte) error

UnmarshalJSON restores description presence from immutable catalog payloads.

func (*Model) UnmarshalYAML added in v0.2.0

func (m *Model) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML restores description presence from the human YAML record.

func (*Model) UnsetDescription added in v0.2.0

func (m *Model) UnsetDescription()

UnsetDescription removes the model's description claim.

type ModelArchitecture

type ModelArchitecture struct {
	ParameterCount string           `json:"parameter_count,omitempty" yaml:"parameter_count,omitempty"`
	Type           ArchitectureType `json:"type,omitempty" yaml:"type,omitempty"`                 // Type of architecture
	Tokenizer      Tokenizer        `json:"tokenizer,omitempty" yaml:"tokenizer,omitempty"`       // Tokenizer type used by the model
	Quantization   Quantization     `json:"quantization,omitempty" yaml:"quantization,omitempty"` // Quantization level used by the model
	Quantized      bool             `json:"quantized" yaml:"quantized"`
	FineTuned      bool             `json:"fine_tuned" yaml:"fine_tuned"`                     // Whether this is a fine-tuned variant
	BaseModel      *string          `json:"base_model,omitempty" yaml:"base_model,omitempty"` // Base model ID if fine-tuned
}

ModelArchitecture represents the technical architecture details of a model.

type ModelAttachments

type ModelAttachments struct {
	MimeTypes   []string `json:"mime_types,omitempty" yaml:"mime_types,omitempty"`       // Supported MIME types
	MaxFileSize *int64   `json:"max_file_size,omitempty" yaml:"max_file_size,omitempty"` // Maximum file size in bytes
	MaxFiles    *int     `json:"max_files,omitempty" yaml:"max_files,omitempty"`         // Maximum number of files per request
}

ModelAttachments represents the attachment capabilities of a model.

type ModelControlLevel

type ModelControlLevel string

ModelControlLevel represents an effort/intensity level for model controls.

const (
	ModelControlLevelMinimum ModelControlLevel = "minimum"
	ModelControlLevelLow     ModelControlLevel = "low"
	ModelControlLevelMedium  ModelControlLevel = "medium"
	ModelControlLevelHigh    ModelControlLevel = "high"
	ModelControlLevelMaximum ModelControlLevel = "maximum"
)

Supported model control levels.

func (ModelControlLevel) String

func (mcl ModelControlLevel) String() string

String returns text for ModelControlLevel.

type ModelControlLevels

type ModelControlLevels struct {
	Levels  []ModelControlLevel `json:"levels" yaml:"levels"`   // Which levels this model supports
	Default *ModelControlLevel  `json:"default" yaml:"default"` // Default level
}

ModelControlLevels represents a set of effort/intensity levels for model controls.

type ModelDefinition added in v0.1.0

type ModelDefinition struct {
	ID           ModelDefinitionID           `json:"id" yaml:"id"`
	Name         string                      `json:"name" yaml:"name"`
	AuthorIDs    []AuthorID                  `json:"author_ids" yaml:"author_ids"`
	Description  string                      `json:"description,omitempty" yaml:"description,omitempty"`
	Metadata     ModelDefinitionMetadata     `json:"metadata" yaml:"metadata"`
	Lineage      ModelDefinitionLineage      `json:"lineage" yaml:"lineage"`
	Weights      ModelDefinitionWeights      `json:"weights" yaml:"weights"`
	Capabilities ModelDefinitionCapabilities `json:"capabilities" yaml:"capabilities"`
	// CreatedAt and UpdatedAt bound the earliest and latest known lifecycle
	// evidence for this definition. Zero means unknown.
	CreatedAt utc.Time `json:"created_at" yaml:"created_at"`
	UpdatedAt utc.Time `json:"updated_at" yaml:"updated_at"`
}

ModelDefinition describes a canonical, provider-independent model. Provider service facts belong to ProviderOffering, never this record.

func (ModelDefinition) Validate added in v0.1.0

func (d ModelDefinition) Validate() error

Validate verifies canonical identity and authorship invariants.

type ModelDefinitionCapabilities added in v0.1.0

type ModelDefinitionCapabilities struct {
	Features        *ModelFeatures      `json:"features,omitempty" yaml:"features,omitempty"`
	Attachments     *ModelAttachments   `json:"attachments,omitempty" yaml:"attachments,omitempty"`
	Generation      *ModelGeneration    `json:"generation,omitempty" yaml:"generation,omitempty"`
	Reasoning       *ModelControlLevels `json:"reasoning,omitempty" yaml:"reasoning,omitempty"`
	ReasoningTokens *IntRange           `json:"reasoning_tokens,omitempty" yaml:"reasoning_tokens,omitempty"`
	Verbosity       *ModelControlLevels `json:"verbosity,omitempty" yaml:"verbosity,omitempty"`
	Tools           *ModelTools         `json:"tools,omitempty" yaml:"tools,omitempty"`
	Delivery        *ModelDelivery      `json:"delivery,omitempty" yaml:"delivery,omitempty"`
}

ModelDefinitionCapabilities groups intrinsic model behavior independently of any provider's service limits, price, endpoint, or availability.

type ModelDefinitionID added in v0.1.0

type ModelDefinitionID string

ModelDefinitionID identifies one provider-independent model definition.

func AuthoredModelID added in v0.2.0

func AuthoredModelID(authorID AuthorID, slug string) ModelDefinitionID

AuthoredModelID returns the canonical author/slug identity for one authored model record.

type ModelDefinitionLineage added in v0.1.0

type ModelDefinitionLineage struct {
	Family string             `json:"family,omitempty" yaml:"family,omitempty"`
	Root   *ModelDefinitionID `json:"root,omitempty" yaml:"root,omitempty"`
	Parent *ModelDefinitionID `json:"parent,omitempty" yaml:"parent,omitempty"`
}

ModelDefinitionLineage describes canonical model-family relationships.

type ModelDefinitionMetadata added in v0.1.0

type ModelDefinitionMetadata struct {
	// ReleaseDate is the first known public release of this identity. A rolling
	// alias may later route to revisions with a newer KnowledgeCutoff. Zero
	// means unknown. Do not invent missing day precision.
	ReleaseDate     utc.Time   `json:"release_date" yaml:"release_date"`
	KnowledgeCutoff *utc.Time  `json:"knowledge_cutoff,omitempty" yaml:"knowledge_cutoff,omitempty"`
	Tags            []ModelTag `json:"tags,omitempty" yaml:"tags,omitempty"`
}

ModelDefinitionMetadata contains provider-independent release and discovery metadata.

type ModelDefinitionWeights added in v0.1.0

type ModelDefinitionWeights struct {
	Open         *bool              `json:"open,omitempty" yaml:"open,omitempty"`
	Architecture *ModelArchitecture `json:"architecture,omitempty" yaml:"architecture,omitempty"`
}

ModelDefinitionWeights describes provider-independent model weights and architecture.

type ModelDelivery

type ModelDelivery struct {
	// Response delivery mechanisms
	Protocols []ModelResponseProtocol `json:"protocols,omitempty" yaml:"protocols,omitempty"` // Supported delivery protocols (HTTP, gRPC, etc.)
	Streaming []ModelStreaming        `json:"streaming,omitempty" yaml:"streaming,omitempty"` // Supported streaming modes (sse, websocket, chunked)
	Formats   []ModelResponseFormat   `json:"formats,omitempty" yaml:"formats,omitempty"`     // Available response formats (if format_response feature enabled)
}

ModelDelivery represents technical response delivery capabilities.

type ModelFeature added in v0.2.0

type ModelFeature string

ModelFeature identifies one boolean model capability.

const (
	ModelFeatureToolCalls                     ModelFeature = "tool_calls"
	ModelFeatureTools                         ModelFeature = "tools"
	ModelFeatureToolChoice                    ModelFeature = "tool_choice"
	ModelFeatureWebSearch                     ModelFeature = "web_search"
	ModelFeatureAttachments                   ModelFeature = "attachments"
	ModelFeatureReasoning                     ModelFeature = "reasoning"
	ModelFeatureReasoningEffort               ModelFeature = "reasoning_effort"
	ModelFeatureReasoningTokens               ModelFeature = "reasoning_tokens"
	ModelFeatureIncludeReasoning              ModelFeature = "include_reasoning"
	ModelFeatureVerbosity                     ModelFeature = "verbosity"
	ModelFeatureTemperature                   ModelFeature = "temperature"
	ModelFeatureTopP                          ModelFeature = "top_p"
	ModelFeatureTopK                          ModelFeature = "top_k"
	ModelFeatureTopA                          ModelFeature = "top_a"
	ModelFeatureMinP                          ModelFeature = "min_p"
	ModelFeatureTypicalP                      ModelFeature = "typical_p"
	ModelFeatureTFS                           ModelFeature = "tfs"
	ModelFeatureMaxTokens                     ModelFeature = "max_tokens"
	ModelFeatureMaxOutputTokens               ModelFeature = "max_output_tokens"
	ModelFeatureStop                          ModelFeature = "stop"
	ModelFeatureStopTokenIDs                  ModelFeature = "stop_token_ids"
	ModelFeatureFrequencyPenalty              ModelFeature = "frequency_penalty"
	ModelFeaturePresencePenalty               ModelFeature = "presence_penalty"
	ModelFeatureRepetitionPenalty             ModelFeature = "repetition_penalty"
	ModelFeatureNoRepeatNgramSize             ModelFeature = "no_repeat_ngram_size"
	ModelFeatureLengthPenalty                 ModelFeature = "length_penalty"
	ModelFeatureLogitBias                     ModelFeature = "logit_bias"
	ModelFeatureBadWords                      ModelFeature = "bad_words"
	ModelFeatureAllowedTokens                 ModelFeature = "allowed_tokens"
	ModelFeatureSeed                          ModelFeature = "seed"
	ModelFeatureLogprobs                      ModelFeature = "logprobs"
	ModelFeatureTopLogprobs                   ModelFeature = "top_logprobs"
	ModelFeatureEcho                          ModelFeature = "echo"
	ModelFeatureN                             ModelFeature = "n"
	ModelFeatureBestOf                        ModelFeature = "best_of"
	ModelFeatureMirostat                      ModelFeature = "mirostat"
	ModelFeatureMirostatTau                   ModelFeature = "mirostat_tau"
	ModelFeatureMirostatEta                   ModelFeature = "mirostat_eta"
	ModelFeatureContrastiveSearchPenaltyAlpha ModelFeature = "contrastive_search_penalty_alpha"
	ModelFeatureNumBeams                      ModelFeature = "num_beams"
	ModelFeatureEarlyStopping                 ModelFeature = "early_stopping"
	ModelFeatureDiversityPenalty              ModelFeature = "diversity_penalty"
	ModelFeatureFormatResponse                ModelFeature = "format_response"
	ModelFeatureStructuredOutputs             ModelFeature = "structured_outputs"
	ModelFeatureStreaming                     ModelFeature = "streaming"
)

Model feature identifiers.

type ModelFeatures

type ModelFeatures struct {
	// Input/Output modalities
	Modalities ModelModalities `json:"modalities" yaml:"modalities"` // Supported input/output modalities

	ToolCalls   bool `json:"tool_calls" yaml:"tool_calls"`
	Tools       bool `json:"tools" yaml:"tools"`             // Accepts tool definitions in requests (accepts tools parameter)
	ToolChoice  bool `json:"tool_choice" yaml:"tool_choice"` // Supports tool choice strategies (auto/none/required control)
	WebSearch   bool `json:"web_search" yaml:"web_search"`   // Supports web search capabilities
	Attachments bool `json:"attachments" yaml:"attachments"` // Attachment support details

	// Reasoning & Verbosity
	Reasoning        bool `json:"reasoning" yaml:"reasoning"`                 // Supports basic reasoning
	ReasoningEffort  bool `json:"reasoning_effort" yaml:"reasoning_effort"`   // Supports configurable reasoning intensity
	ReasoningTokens  bool `json:"reasoning_tokens" yaml:"reasoning_tokens"`   // Supports specific reasoning token allocation
	IncludeReasoning bool `json:"include_reasoning" yaml:"include_reasoning"` // Supports including reasoning traces in response
	Verbosity        bool `json:"verbosity" yaml:"verbosity"`                 // Supports verbosity control (GPT-5+)

	Temperature bool `json:"temperature" yaml:"temperature"`
	TopP        bool `json:"top_p" yaml:"top_p"`         // Supports nucleus sampling through top_p.
	TopK        bool `json:"top_k" yaml:"top_k"`         // [Advanced] Supports top_k parameter
	TopA        bool `json:"top_a" yaml:"top_a"`         // [Advanced] Supports top_a parameter (top-a sampling)
	MinP        bool `json:"min_p" yaml:"min_p"`         // [Advanced] Supports min_p parameter (minimum probability threshold)
	TypicalP    bool `json:"typical_p" yaml:"typical_p"` // [Advanced] Supports typical_p parameter (typical sampling)
	TFS         bool `json:"tfs" yaml:"tfs"`             // [Advanced] Supports tail free sampling

	// Generation control - Length and termination
	MaxTokens       bool `json:"max_tokens" yaml:"max_tokens"`               // [Core] Supports max_tokens parameter
	MaxOutputTokens bool `json:"max_output_tokens" yaml:"max_output_tokens"` // [Core] Supports max_output_tokens parameter (some providers distinguish from max_tokens)
	Stop            bool `json:"stop" yaml:"stop"`                           // [Core] Supports stop sequences/words
	StopTokenIDs    bool `json:"stop_token_ids" yaml:"stop_token_ids"`       // [Advanced] Supports stop token IDs (numeric)

	FrequencyPenalty  bool `json:"frequency_penalty" yaml:"frequency_penalty"`       // [Core] Supports frequency penalty
	PresencePenalty   bool `json:"presence_penalty" yaml:"presence_penalty"`         // [Core] Supports presence penalty
	RepetitionPenalty bool `json:"repetition_penalty" yaml:"repetition_penalty"`     // [Advanced] Supports repetition penalty
	NoRepeatNgramSize bool `json:"no_repeat_ngram_size" yaml:"no_repeat_ngram_size"` // [Niche] Supports n-gram repetition blocking
	LengthPenalty     bool `json:"length_penalty" yaml:"length_penalty"`             // [Niche] Supports length penalty (seq2seq style)

	// Generation control - Token biasing
	LogitBias     bool `json:"logit_bias" yaml:"logit_bias"`         // [Core] Supports token-level bias adjustment
	BadWords      bool `json:"bad_words" yaml:"bad_words"`           // [Advanced] Supports bad words/disallowed tokens
	AllowedTokens bool `json:"allowed_tokens" yaml:"allowed_tokens"` // [Niche] Supports token whitelist

	// Generation control - Determinism
	Seed bool `json:"seed" yaml:"seed"` // [Advanced] Supports deterministic seeding

	// Generation control - Observability
	Logprobs    bool `json:"logprobs" yaml:"logprobs"`         // [Core] Supports returning log probabilities
	TopLogprobs bool `json:"top_logprobs" yaml:"top_logprobs"` // [Core] Supports returning top N log probabilities
	Echo        bool `json:"echo" yaml:"echo"`                 // [Advanced] Supports echoing prompt with completion

	// Generation control - Multiplicity and reranking
	N      bool `json:"n" yaml:"n"`             // [Advanced] Supports generating multiple candidates
	BestOf bool `json:"best_of" yaml:"best_of"` // [Advanced] Supports server-side sampling with best selection

	// Generation control - Alternative sampling strategies (niche)
	Mirostat                      bool `json:"mirostat" yaml:"mirostat"`                                                 // [Niche] Supports Mirostat sampling
	MirostatTau                   bool `json:"mirostat_tau" yaml:"mirostat_tau"`                                         // [Niche] Supports Mirostat tau parameter
	MirostatEta                   bool `json:"mirostat_eta" yaml:"mirostat_eta"`                                         // [Niche] Supports Mirostat eta parameter
	ContrastiveSearchPenaltyAlpha bool `json:"contrastive_search_penalty_alpha" yaml:"contrastive_search_penalty_alpha"` // [Niche] Supports contrastive decoding

	// Generation control - Beam search (niche)
	NumBeams         bool `json:"num_beams" yaml:"num_beams"`                 // [Niche] Supports beam search
	EarlyStopping    bool `json:"early_stopping" yaml:"early_stopping"`       // [Niche] Supports early stopping in beam search
	DiversityPenalty bool `json:"diversity_penalty" yaml:"diversity_penalty"` // [Niche] Supports diversity penalty in beam search

	// Response delivery
	FormatResponse    bool `json:"format_response" yaml:"format_response"`       // Supports alternative response formats (beyond text)
	StructuredOutputs bool `json:"structured_outputs" yaml:"structured_outputs"` // Supports structured outputs (JSON schema validation)
	Streaming         bool `json:"streaming" yaml:"streaming"`                   // Supports response streaming
	// contains filtered or unexported fields
}

ModelFeatures represents a set of feature flags that describe what a model can do.

func (ModelFeatures) MarshalJSON added in v0.2.0

func (f ModelFeatures) MarshalJSON() ([]byte, error)

MarshalJSON preserves feature presence in immutable catalog payloads.

func (ModelFeatures) MarshalYAML added in v0.2.0

func (f ModelFeatures) MarshalYAML() (any, error)

MarshalYAML renders the complete Boolean capability surface for the human-editable YAML workspace. Capabilities without an observed claim use the conservative false default, while explicitly unknown claims remain null. Immutable JSON generations retain the precise missing/unknown/known distinction.

func (*ModelFeatures) SetSupport added in v0.2.0

func (f *ModelFeatures) SetSupport(feature ModelFeature, supported bool) bool

SetSupport records an explicit supported or unsupported capability.

func (*ModelFeatures) SetSupportUnknown added in v0.2.0

func (f *ModelFeatures) SetSupportUnknown(feature ModelFeature) bool

SetSupportUnknown records that a capability was explicitly reported as unknown.

func (*ModelFeatures) Support added in v0.2.0

func (f *ModelFeatures) Support(feature ModelFeature) (bool, ValuePresence)

Support returns the capability value and its presence state.

func (*ModelFeatures) UnmarshalJSON added in v0.2.0

func (f *ModelFeatures) UnmarshalJSON(data []byte) error

UnmarshalJSON restores feature presence from immutable catalog payloads.

func (*ModelFeatures) UnmarshalYAML added in v0.2.0

func (f *ModelFeatures) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML restores per-capability presence from the human YAML record.

func (*ModelFeatures) UnsetSupport added in v0.2.0

func (f *ModelFeatures) UnsetSupport(feature ModelFeature) bool

UnsetSupport removes a capability claim.

type ModelGeneration

type ModelGeneration struct {
	// Core sampling and decoding
	Temperature *FloatRange `json:"temperature,omitempty" yaml:"temperature,omitempty"`
	TopP        *FloatRange `json:"top_p,omitempty" yaml:"top_p,omitempty"`
	TopK        *IntRange   `json:"top_k,omitempty" yaml:"top_k,omitempty"`
	TopA        *FloatRange `json:"top_a,omitempty" yaml:"top_a,omitempty"`
	MinP        *FloatRange `json:"min_p,omitempty" yaml:"min_p,omitempty"`
	TypicalP    *FloatRange `json:"typical_p,omitempty" yaml:"typical_p,omitempty"`
	TFS         *FloatRange `json:"tfs,omitempty" yaml:"tfs,omitempty"`

	// Length and termination
	MaxTokens       *int `json:"max_tokens,omitempty" yaml:"max_tokens,omitempty"`
	MaxOutputTokens *int `json:"max_output_tokens,omitempty" yaml:"max_output_tokens,omitempty"`

	// Repetition control
	FrequencyPenalty  *FloatRange `json:"frequency_penalty,omitempty" yaml:"frequency_penalty,omitempty"`
	PresencePenalty   *FloatRange `json:"presence_penalty,omitempty" yaml:"presence_penalty,omitempty"`
	RepetitionPenalty *FloatRange `json:"repetition_penalty,omitempty" yaml:"repetition_penalty,omitempty"`
	NoRepeatNgramSize *IntRange   `json:"no_repeat_ngram_size,omitempty" yaml:"no_repeat_ngram_size,omitempty"`
	LengthPenalty     *FloatRange `json:"length_penalty,omitempty" yaml:"length_penalty,omitempty"`

	// Observability
	TopLogprobs *int `json:"top_logprobs,omitempty" yaml:"top_logprobs,omitempty"` // Number of top log probabilities to return

	// Multiplicity and reranking
	N      *IntRange `json:"n,omitempty" yaml:"n,omitempty"`             // Number of candidates to generate
	BestOf *IntRange `json:"best_of,omitempty" yaml:"best_of,omitempty"` // Server-side sampling with best selection

	// Alternative sampling strategies (niche)
	MirostatTau                   *FloatRange `json:"mirostat_tau,omitempty" yaml:"mirostat_tau,omitempty"`
	MirostatEta                   *FloatRange `json:"mirostat_eta,omitempty" yaml:"mirostat_eta,omitempty"`
	ContrastiveSearchPenaltyAlpha *FloatRange `json:"contrastive_search_penalty_alpha,omitempty" yaml:"contrastive_search_penalty_alpha,omitempty"`

	// Beam search (niche)
	NumBeams         *IntRange   `json:"num_beams,omitempty" yaml:"num_beams,omitempty"`
	DiversityPenalty *FloatRange `json:"diversity_penalty,omitempty" yaml:"diversity_penalty,omitempty"`
}

ModelGeneration - core chat completions generation controls.

type ModelLimit added in v0.2.0

type ModelLimit string

ModelLimit identifies one model token limit.

const (
	ModelLimitContextWindow  ModelLimit = "context_window"
	ModelLimitInputTokens    ModelLimit = "input_tokens"
	ModelLimitOutputTokens   ModelLimit = "output_tokens"
	ModelLimitDocumentPages  ModelLimit = "document_pages"
	ModelLimitMaxDocuments   ModelLimit = "max_documents"
	ModelLimitDocumentTokens ModelLimit = "document_tokens"
)

Model limit identifiers.

func PublishedModelLimits added in v0.13.0

func PublishedModelLimits() []ModelLimit

PublishedModelLimits returns every model limit in published order. External consumers use this list so they report the same limits.

type ModelLimits

type ModelLimits struct {
	ContextWindow int64 `json:"context_window" yaml:"context_window"` // Context window size in tokens
	InputTokens   int64 `json:"input_tokens" yaml:"input_tokens"`     // Maximum input tokens
	OutputTokens  int64 `json:"output_tokens" yaml:"output_tokens"`   // Maximum output tokens
	// DocumentPages is the largest document the provider reads in one call,
	// counted in pages. A provider states this bound in pages rather than in
	// tokens, because it refuses the document before it reads a token of it.
	DocumentPages int64 `json:"document_pages,omitempty" yaml:"document_pages,omitempty"`
	// MaxDocuments is the longest document list the provider ranks in one
	// call. A reranker refuses a longer list rather than truncating it, and a
	// caller that does not read this bound sends a request that cannot succeed.
	MaxDocuments   int64 `json:"max_documents,omitempty" yaml:"max_documents,omitempty"`
	DocumentTokens int64 `json:"document_tokens,omitempty" yaml:"document_tokens,omitempty"`
	// contains filtered or unexported fields
}

ModelLimits represents the limits for a model.

func (ModelLimits) MarshalJSON added in v0.2.0

func (l ModelLimits) MarshalJSON() ([]byte, error)

MarshalJSON preserves limit presence in immutable catalog payloads.

func (ModelLimits) MarshalYAML added in v0.2.0

func (l ModelLimits) MarshalYAML() (any, error)

MarshalYAML preserves explicit zero and unknown limits while omitting unobserved limits.

func (*ModelLimits) Set added in v0.2.0

func (l *ModelLimits) Set(limit ModelLimit, value int64) bool

Set records an explicit model limit, including zero.

func (*ModelLimits) SetUnknown added in v0.2.0

func (l *ModelLimits) SetUnknown(limit ModelLimit) bool

SetUnknown records that a model limit was explicitly reported as unknown.

func (*ModelLimits) UnmarshalJSON added in v0.2.0

func (l *ModelLimits) UnmarshalJSON(data []byte) error

UnmarshalJSON restores limit presence from immutable catalog payloads.

func (*ModelLimits) UnmarshalYAML added in v0.2.0

func (l *ModelLimits) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML restores per-limit presence from the human YAML record.

func (*ModelLimits) Unset added in v0.2.0

func (l *ModelLimits) Unset(limit ModelLimit) bool

Unset removes a model limit claim.

func (*ModelLimits) Value added in v0.2.0

func (l *ModelLimits) Value(limit ModelLimit) (int64, ValuePresence)

Value returns a model limit and its presence state.

type ModelLineage added in v0.1.0

type ModelLineage struct {
	Family string  `json:"family,omitempty" yaml:"family,omitempty"` // Model family or series, such as gpt-5 or claude
	Root   *string `json:"root,omitempty" yaml:"root,omitempty"`     // Root/base model ID reported by a provider
	Parent *string `json:"parent,omitempty" yaml:"parent,omitempty"` // Parent model ID for derived/fine-tuned models
}

ModelLineage represents model family and derivation metadata.

type ModelMetadata

type ModelMetadata struct {
	// ReleaseDate is the first known public release of this model identity. For
	// a rolling alias, its KnowledgeCutoff may advance beyond that initial date.
	// A zero value means unknown. Starmap does not invent missing day precision.
	ReleaseDate     utc.Time           `json:"release_date" yaml:"release_date"`
	OpenWeights     bool               `json:"open_weights" yaml:"open_weights"`                             // Whether model weights are open
	KnowledgeCutoff *utc.Time          `json:"knowledge_cutoff,omitempty" yaml:"knowledge_cutoff,omitempty"` // Knowledge cutoff date (YYYY-MM or YYYY-MM-DD format)
	Tags            []ModelTag         `json:"tags,omitempty" yaml:"tags,omitempty"`                         // Use case tags for categorizing the model
	Architecture    *ModelArchitecture `json:"architecture,omitempty" yaml:"architecture,omitempty"`         // Technical architecture details
	// contains filtered or unexported fields
}

ModelMetadata represents the metadata for a model.

func (ModelMetadata) MarshalJSON added in v0.2.0

func (m ModelMetadata) MarshalJSON() ([]byte, error)

MarshalJSON preserves open-weights presence in immutable catalog payloads.

func (ModelMetadata) MarshalYAML added in v0.2.0

func (m ModelMetadata) MarshalYAML() (any, error)

MarshalYAML preserves explicit false and unknown open-weights claims.

func (*ModelMetadata) OpenWeightsValue added in v0.2.0

func (m *ModelMetadata) OpenWeightsValue() (bool, ValuePresence)

OpenWeightsValue returns open-weights support and its presence state.

func (*ModelMetadata) SetOpenWeights added in v0.2.0

func (m *ModelMetadata) SetOpenWeights(open bool)

SetOpenWeights records an explicit open-weights value.

func (*ModelMetadata) SetOpenWeightsUnknown added in v0.2.0

func (m *ModelMetadata) SetOpenWeightsUnknown()

SetOpenWeightsUnknown records that open-weights status is explicitly unknown.

func (*ModelMetadata) UnmarshalJSON added in v0.2.0

func (m *ModelMetadata) UnmarshalJSON(data []byte) error

UnmarshalJSON restores open-weights presence from immutable catalog payloads.

func (*ModelMetadata) UnmarshalYAML added in v0.2.0

func (m *ModelMetadata) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML restores open-weights presence from the human YAML record.

func (*ModelMetadata) UnsetOpenWeights added in v0.2.0

func (m *ModelMetadata) UnsetOpenWeights()

UnsetOpenWeights removes the open-weights claim.

type ModelModalities

type ModelModalities struct {
	Input  []ModelModality `json:"input" yaml:"input"`   // Supported input modalities
	Output []ModelModality `json:"output" yaml:"output"` // Supported output modalities
}

ModelModalities represents the input/output modalities supported by a model.

type ModelModality

type ModelModality string

ModelModality represents a supported input or output modality for AI models.

const (
	ModelModalityText      ModelModality = "text"
	ModelModalityAudio     ModelModality = "audio"
	ModelModalityImage     ModelModality = "image"
	ModelModalityVideo     ModelModality = "video"
	ModelModalityPDF       ModelModality = "pdf"
	ModelModalityEmbedding ModelModality = "embedding" // Vector embeddings
)

Supported model modalities.

func (ModelModality) String

func (m ModelModality) String() string

String returns text for ModelModality.

type ModelMode added in v0.1.0

type ModelMode struct {
	Pricing  *ModelPricing      `json:"pricing,omitempty" yaml:"pricing,omitempty"`   // Mode-specific pricing
	Provider *ModelProviderMode `json:"provider,omitempty" yaml:"provider,omitempty"` // Mode-specific provider request overrides
}

ModelMode represents an alternate provider service mode for a model.

type ModelOperationPricing

type ModelOperationPricing struct {
	// Core operations
	Request *float64 `json:"request,omitempty" yaml:"request,omitempty"` // Cost per API request

	// Media operations
	ImageInput *float64 `json:"image_input,omitempty" yaml:"image_input,omitempty"` // Cost per image processed
	PageInput  *float64 `json:"page_input,omitempty" yaml:"page_input,omitempty"`
	AudioInput *float64 `json:"audio_input,omitempty" yaml:"audio_input,omitempty"` // Cost per audio input
	VideoInput *float64 `json:"video_input,omitempty" yaml:"video_input,omitempty"` // Cost per video input

	// Generation operations
	ImageGen *float64 `json:"image_gen,omitempty" yaml:"image_gen,omitempty"` // Cost per image generated
	AudioGen *float64 `json:"audio_gen,omitempty" yaml:"audio_gen,omitempty"` // Cost per audio generated
	VideoGen *float64 `json:"video_gen,omitempty" yaml:"video_gen,omitempty"` // Cost per video generated

	// Service operations
	WebSearch    *float64 `json:"web_search,omitempty" yaml:"web_search,omitempty"`       // Cost per web search
	FunctionCall *float64 `json:"function_call,omitempty" yaml:"function_call,omitempty"` // Cost per function call
	ToolUse      *float64 `json:"tool_use,omitempty" yaml:"tool_use,omitempty"`           // Cost per tool usage

	SearchUnit *float64 `json:"search_unit,omitempty" yaml:"search_unit,omitempty"`
	// RerankBasis names which recorded price a rerank turn draws from.
	// Providers disagree: some bill a search unit and some bill the tokens they
	// read. A consumer reads this field rather than guessing from which price
	// happens to be present.
	RerankBasis ModelRerankBasis `json:"rerank_basis,omitempty" yaml:"rerank_basis,omitempty"`
}

ModelOperationPricing represents fixed costs for operations.

type ModelPricing

type ModelPricing struct {
	// Token-based costs
	Tokens *ModelTokenPricing `json:"tokens,omitempty" yaml:"tokens,omitempty"`

	// Fixed costs per operation
	Operations *ModelOperationPricing `json:"operations,omitempty" yaml:"operations,omitempty"`

	// Conditional/tiered pricing
	Tiers []ModelPricingTier `json:"tiers,omitempty" yaml:"tiers,omitempty"`

	// Metadata
	Currency ModelPricingCurrency `json:"currency" yaml:"currency"` // "USD", "EUR", etc.

	// Optional half-open validity interval [effective_from, effective_until).
	EffectiveFrom  *utc.Time `json:"effective_from,omitempty" yaml:"effective_from,omitempty"`
	EffectiveUntil *utc.Time `json:"effective_until,omitempty" yaml:"effective_until,omitempty"`
}

ModelPricing represents the pricing structure for a model.

func (*ModelPricing) IsEffectiveAt added in v0.1.0

func (p *ModelPricing) IsEffectiveAt(at time.Time) bool

IsEffectiveAt reports whether pricing applies at the supplied instant.

func (*ModelPricing) Validate added in v0.1.0

func (p *ModelPricing) Validate() error

Validate verifies that pricing is structurally complete and financially safe to use as an authoritative provider-offering observation.

type ModelPricingCurrency

type ModelPricingCurrency string

ModelPricingCurrency represents a currency code for model pricing.

const (
	ModelPricingCurrencyUSD ModelPricingCurrency = "USD"
	ModelPricingCurrencyEUR ModelPricingCurrency = "EUR"
	ModelPricingCurrencyJPY ModelPricingCurrency = "JPY"
	ModelPricingCurrencyGBP ModelPricingCurrency = "GBP"
	ModelPricingCurrencyAUD ModelPricingCurrency = "AUD"
	ModelPricingCurrencyCAD ModelPricingCurrency = "CAD"
	ModelPricingCurrencyCNY ModelPricingCurrency = "CNY"
	ModelPricingCurrencyNZD ModelPricingCurrency = "NZD"
)

Model pricing currencies.

func (ModelPricingCurrency) String

func (m ModelPricingCurrency) String() string

String returns text for ModelPricingCurrency.

func (ModelPricingCurrency) Symbol

func (m ModelPricingCurrency) Symbol() string

Symbol returns the symbol for a given currency.

type ModelPricingTier added in v0.1.0

type ModelPricingTier struct {
	Name       string                 `json:"name,omitempty" yaml:"name,omitempty"`             // Optional source/name, such as context_over_200k
	Type       ModelPricingTierType   `json:"type" yaml:"type"`                                 // Tier dimension, such as context
	Size       int64                  `json:"size,omitempty" yaml:"size,omitempty"`             // Threshold size for the tier dimension
	Tokens     *ModelTokenPricing     `json:"tokens,omitempty" yaml:"tokens,omitempty"`         // Token prices in this tier
	Operations *ModelOperationPricing `json:"operations,omitempty" yaml:"operations,omitempty"` // Operation prices in this tier
}

ModelPricingTier represents conditional pricing for a model.

type ModelPricingTierType added in v0.1.0

type ModelPricingTierType string

ModelPricingTierType represents the dimension that activates a pricing tier.

const (
	// ModelPricingTierTypeContext means the tier applies above a context-size threshold.
	ModelPricingTierTypeContext ModelPricingTierType = "context"
)

func (ModelPricingTierType) String added in v0.1.0

func (m ModelPricingTierType) String() string

String returns text for ModelPricingTierType.

type ModelProviderMode added in v0.1.0

type ModelProviderMode struct {
	Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"` // HTTP headers required by this mode
	Body    map[string]any    `json:"body,omitempty" yaml:"body,omitempty"`       // JSON request body fields required by this mode
}

ModelProviderMode represents provider request overrides for a model mode.

func (ModelProviderMode) MarshalYAML added in v0.2.0

func (m ModelProviderMode) MarshalYAML() (any, error)

MarshalYAML preserves request-body values as native YAML scalars, sequences, mappings, and nulls. The body is a JSON request fragment, so SetExtension rejects values that JSON cannot represent.

func (*ModelProviderMode) UnmarshalYAML added in v0.2.0

func (m *ModelProviderMode) UnmarshalYAML(data []byte) error

UnmarshalYAML restores request-body values through JSON so YAML library implementation types such as []byte cannot leak into the provider request contract.

type ModelRerankBasis added in v0.13.0

type ModelRerankBasis string

ModelRerankBasis names the unit a provider bills one rerank call in.

const (
	// ModelRerankBasisSearchUnit bills one query against a bounded document
	// count. Cohere and OpenRouter bill this way.
	ModelRerankBasisSearchUnit ModelRerankBasis = "search-unit"
	// ModelRerankBasisToken bills the tokens the provider reads across the
	// query and the documents. Jina and Voyage bill this way.
	ModelRerankBasisToken ModelRerankBasis = "token"
)

func (ModelRerankBasis) String added in v0.13.0

func (m ModelRerankBasis) String() string

String returns text for ModelRerankBasis.

type ModelResponseFormat

type ModelResponseFormat string

ModelResponseFormat represents a supported response format.

const (
	// Basic formats.
	ModelResponseFormatText ModelResponseFormat = "text" // Plain text responses (default)

	// JSON formats.
	ModelResponseFormatJSON       ModelResponseFormat = "json"        // JSON encouraged via prompting
	ModelResponseFormatJSONMode   ModelResponseFormat = "json_mode"   // Forced valid JSON (OpenAI style)
	ModelResponseFormatJSONObject ModelResponseFormat = "json_object" // Same as json_mode (OpenAI API name)

	// Structured formats.
	ModelResponseFormatJSONSchema       ModelResponseFormat = "json_schema"       // Schema-validated JSON (OpenAI structured output)
	ModelResponseFormatStructuredOutput ModelResponseFormat = "structured_output" // General structured output support

	// Function calling (alternative to JSON schema).
	ModelResponseFormatFunctionCall ModelResponseFormat = "function_call" // Tool/function calling for structured data
)

Model response formats.

func (ModelResponseFormat) String

func (mrf ModelResponseFormat) String() string

String returns text for ModelResponseFormat.

type ModelResponseProtocol

type ModelResponseProtocol string

ModelResponseProtocol represents a supported delivery protocol.

const (
	ModelResponseProtocolHTTP      ModelResponseProtocol = "http"      // HTTP/HTTPS REST API
	ModelResponseProtocolGRPC      ModelResponseProtocol = "grpc"      // gRPC protocol
	ModelResponseProtocolWebSocket ModelResponseProtocol = "websocket" // WebSocket protocol
)

Model delivery protocols.

type ModelStatus added in v0.1.0

type ModelStatus string

ModelStatus represents a model lifecycle or availability state.

const (
	ModelStatusActive     ModelStatus = "active"
	ModelStatusBeta       ModelStatus = "beta"
	ModelStatusPreview    ModelStatus = "preview"
	ModelStatusDeprecated ModelStatus = "deprecated"
	ModelStatusUnknown    ModelStatus = "unknown"
)

Model lifecycle states.

func (ModelStatus) String added in v0.1.0

func (ms ModelStatus) String() string

String returns text for ModelStatus.

type ModelStreaming

type ModelStreaming string

ModelStreaming describes the available response delivery modes.

const (
	ModelStreamingSSE       ModelStreaming = "sse"       // Server-Sent Events streaming
	ModelStreamingWebSocket ModelStreaming = "websocket" // WebSocket streaming
	ModelStreamingChunked   ModelStreaming = "chunked"   // HTTP chunked transfer encoding
)

Model streaming modes.

func (ModelStreaming) String

func (ms ModelStreaming) String() string

String returns text for ModelStreaming.

type ModelTag

type ModelTag string

ModelTag represents a use case or category tag for models.

const (
	// Core Use Cases.
	ModelTagCoding    ModelTag = "coding"
	ModelTagWriting   ModelTag = "writing"
	ModelTagReasoning ModelTag = "reasoning"
	ModelTagMath      ModelTag = "math"
	ModelTagChat      ModelTag = "chat"
	ModelTagInstruct  ModelTag = "instruct"
	ModelTagResearch  ModelTag = "research"
	ModelTagCreative  ModelTag = "creative"
	ModelTagRoleplay  ModelTag = "roleplay"

	// Technical Capabilities.
	ModelTagFunctionCalling ModelTag = "function_calling"   // Tool/function calling
	ModelTagEmbedding       ModelTag = "embedding"          // Text embeddings
	ModelTagRerank          ModelTag = "rerank"             // Relevance ranking of documents
	ModelTagModeration      ModelTag = "moderation"         // Harm-category classification
	ModelTagSummarization   ModelTag = "summarization"      // Text summarization
	ModelTagTranslation     ModelTag = "translation"        // Language translation
	ModelTagQA              ModelTag = "question_answering" // Question answering

	// Modality-Specific.
	ModelTagVision       ModelTag = "vision"         // Computer vision
	ModelTagMultimodal   ModelTag = "multimodal"     // Multiple input modalities
	ModelTagAudio        ModelTag = "audio"          // Audio processing
	ModelTagTextToImage  ModelTag = "text_to_image"  // Text-to-image generation
	ModelTagTextToVideo  ModelTag = "text_to_video"  // Text-to-video generation
	ModelTagTextToSpeech ModelTag = "text_to_speech" // Text-to-speech synthesis
	ModelTagSpeechToText ModelTag = "speech_to_text" // Speech recognition
	ModelTagImageToText  ModelTag = "image_to_text"  // Image captioning/OCR

	// Domain-Specific.
	ModelTagMedical   ModelTag = "medical"   // Medical and healthcare
	ModelTagLegal     ModelTag = "legal"     // Legal document processing
	ModelTagFinance   ModelTag = "finance"   // Financial analysis
	ModelTagScience   ModelTag = "science"   // Scientific applications
	ModelTagEducation ModelTag = "education" // Educational content
)

Model tags for categorizing models by use case and capabilities.

func (ModelTag) String

func (tag ModelTag) String() string

String returns text for ModelTag.

type ModelTokenCost

type ModelTokenCost struct {
	PerToken float64 `json:"per_token" yaml:"per_token"`  // Cost per individual token
	Per1M    float64 `json:"per_1m_tokens" yaml:"per_1m"` // Cost per 1M tokens
}

ModelTokenCost represents cost per token with flexible units.

func (*ModelTokenCost) MarshalYAML

func (t *ModelTokenCost) MarshalYAML() (any, error)

MarshalYAML implements custom YAML marshaling for TokenCost to format decimals consistently.

type ModelTokenPricing

type ModelTokenPricing struct {
	// Core tokens
	Input  *ModelTokenCost `json:"input,omitempty" yaml:"input,omitempty"`   // Input/prompt tokens
	Output *ModelTokenCost `json:"output,omitempty" yaml:"output,omitempty"` // Standard output tokens

	// Advanced token types
	Reasoning  *ModelTokenCost `json:"reasoning,omitempty" yaml:"reasoning,omitempty"`     // Internal reasoning tokens
	CacheRead  *ModelTokenCost `json:"cache_read,omitempty" yaml:"cache_read,omitempty"`   // Cache read costs (flat structure)
	CacheWrite *ModelTokenCost `json:"cache_write,omitempty" yaml:"cache_write,omitempty"` // Cache write costs (flat structure)

	AudioInput  *ModelTokenCost `json:"audio_input,omitempty" yaml:"audio_input,omitempty"`   // Audio input tokens
	AudioOutput *ModelTokenCost `json:"audio_output,omitempty" yaml:"audio_output,omitempty"` // Audio output tokens
}

ModelTokenPricing represents all token-based costs.

func (*ModelTokenPricing) MarshalYAML

func (t *ModelTokenPricing) MarshalYAML() (any, error)

MarshalYAML implements custom YAML marshaling for token pricing.

type ModelTools

type ModelTools struct {
	// Tool calling configuration
	// Specifies which tool choice strategies this model supports.
	// Requires both Tools=true and ToolChoice=true in ModelFeatures.
	// Common values: ["auto"], ["auto", "none"], ["auto", "none", "required"]
	ToolChoices []ToolChoice `json:"tool_choices,omitempty" yaml:"tool_choices,omitempty"` // Supported tool choice strategies

	// Web search configuration
	// Only applicable if WebSearch=true in ModelFeatures
	WebSearch *ModelWebSearch `json:"web_search,omitempty" yaml:"web_search,omitempty"`
}

ModelTools represents external tool and capability integrations.

type ModelWebSearch

type ModelWebSearch struct {
	// Plugin-based web search options (for models using OpenRouter's web plugin)
	MaxResults   *int    `json:"max_results,omitempty" yaml:"max_results,omitempty"`     // Maximum number of search results (defaults to 5)
	SearchPrompt *string `json:"search_prompt,omitempty" yaml:"search_prompt,omitempty"` // Custom prompt for search results

	// Built-in web search options (for models with native web search like GPT-4.1, Perplexity)
	SearchContextSizes []ModelControlLevel `json:"search_context_sizes,omitempty" yaml:"search_context_sizes,omitempty"` // Supported context sizes (low, medium, high)
	DefaultContextSize *ModelControlLevel  `json:"default_context_size,omitempty" yaml:"default_context_size,omitempty"` // Default search context size
}

ModelWebSearch represents web search configuration for search-enabled models.

type Models

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

Models is a concurrent safe map of models.

func NewModels added in v0.0.15

func NewModels() *Models

NewModels creates a new Models instance.

func (*Models) Add

func (m *Models) Add(model *Model) error

Add adds a model, returning an error if it already exists.

func (*Models) AddBatch

func (m *Models) AddBatch(models []*Model) map[string]error

AddBatch adds multiple models in a single operation. Only adds models that do not already exist - fails if a model ID already exists. Returns a map of model IDs to errors for any failed additions.

func (*Models) Clear

func (m *Models) Clear()

Clear removes all models.

func (*Models) Delete

func (m *Models) Delete(id string) error

Delete removes a model by id. Returns an error if the model does not exist.

func (*Models) DeleteBatch

func (m *Models) DeleteBatch(ids []string) map[string]error

DeleteBatch removes multiple models by ID. The returned map identifies IDs that DeleteBatch did not find.

func (*Models) Exists

func (m *Models) Exists(id string) bool

Exists checks if a model exists without returning it.

func (*Models) ForEach

func (m *Models) ForEach(fn func(id string, model *Model) bool)

ForEach applies a function to each model. The function should not modify the model. If the function returns false, iteration stops early.

func (*Models) Get

func (m *Models) Get(id string) (*Model, bool)

Get returns a model by id and whether it exists.

func (*Models) Len

func (m *Models) Len() int

Len returns the number of models.

func (*Models) List

func (m *Models) List() []Model

List returns a slice of all models as values (copies).

func (*Models) Map

func (m *Models) Map() map[string]*Model

Map returns a copy of all models.

func (*Models) Set

func (m *Models) Set(id string, model *Model) error

Set sets a model by id. Returns an error if model is nil.

func (*Models) SetBatch

func (m *Models) SetBatch(models map[string]*Model) error

SetBatch sets multiple models in a single operation. Overwrites existing models or adds new ones (upsert behavior). Returns an error if any model is nil.

type ModelsReader added in v0.1.0

type ModelsReader interface {
	Get(string) (*Model, bool)
	Exists(string) bool
	Len() int
	List() []Model
	Map() map[string]*Model
	ForEach(func(string, *Model) bool)
}

ModelsReader exposes model collection reads without mutation methods.

type OfferingAvailability added in v0.1.0

type OfferingAvailability string

OfferingAvailability describes an offering's current availability.

const (
	// OfferingAvailabilityUnknown means no source supplied current availability.
	OfferingAvailabilityUnknown OfferingAvailability = "unknown"
	// OfferingAvailabilityAvailable means the offering is generally available.
	OfferingAvailabilityAvailable OfferingAvailability = "available"
	// OfferingAvailabilityRestricted means access depends on region, account, or allowlisting.
	OfferingAvailabilityRestricted OfferingAvailability = "restricted"
	// OfferingAvailabilityUnavailable means the provider does not currently serve the offering.
	OfferingAvailabilityUnavailable OfferingAvailability = "unavailable"
)

type OfferingKey added in v0.1.0

type OfferingKey struct {
	ProviderID      ProviderID      `json:"provider_id" yaml:"provider_id"`
	ProviderModelID ProviderModelID `json:"provider_model_id" yaml:"provider_model_id"`
}

OfferingKey is the globally unique identity of a provider model offering.

type OfferingLifecycle added in v0.1.0

type OfferingLifecycle string

OfferingLifecycle describes the provider-specific lifecycle of an offering.

const (
	// OfferingLifecycleUnknown means no source supplied a lifecycle state.
	OfferingLifecycleUnknown OfferingLifecycle = "unknown"
	// OfferingLifecycleActive means the provider supports new requests.
	OfferingLifecycleActive OfferingLifecycle = "active"
	// OfferingLifecyclePreview means the offering is preview or beta quality.
	OfferingLifecyclePreview OfferingLifecycle = "preview"
	// OfferingLifecycleDeprecated means callers should migrate away from the offering.
	OfferingLifecycleDeprecated OfferingLifecycle = "deprecated"
	// OfferingLifecycleRetired means the provider no longer accepts new requests.
	OfferingLifecycleRetired OfferingLifecycle = "retired"
)

type OfferingRequestBody added in v0.1.0

type OfferingRequestBody map[string]json.RawMessage

OfferingRequestBody is a typed set of exact JSON request-body values. RawMessage preserves booleans, numbers, strings, arrays, objects, and null without routing values through map[string]any.

func (OfferingRequestBody) MarshalYAML added in v0.2.0

func (b OfferingRequestBody) MarshalYAML() (any, error)

MarshalYAML converts each exact JSON value to a native YAML scalar, sequence, mapping, or null. This prevents RawMessage bytes from becoming integers.

func (*OfferingRequestBody) UnmarshalYAML added in v0.2.0

func (b *OfferingRequestBody) UnmarshalYAML(data []byte) error

UnmarshalYAML restores native YAML values as exact JSON values.

type OfferingRequestHeaders added in v0.1.0

type OfferingRequestHeaders map[string]string

OfferingRequestHeaders is a typed set of provider request header overrides.

type Option

type Option func(*options)

Option configures a catalog.

func WithFS

func WithFS(fsys fs.FS) Option

WithFS configures the catalog to use a custom fs.FS for reading.

func WithMergeStrategy

func WithMergeStrategy(strategy MergeStrategy) Option

WithMergeStrategy sets the default merge strategy.

func WithPath

func WithPath(path string) Option

WithPath configures the catalog to use a directory path for reading This creates an os.DirFS under the hood.

func WithWritePath

func WithWritePath(path string) Option

WithWritePath sets a specific path for writing catalog files.

type PayloadDescriptor added in v0.1.0

type PayloadDescriptor struct {
	Checksum  string `json:"checksum" yaml:"checksum"`
	SizeBytes int64  `json:"size_bytes" yaml:"size_bytes"`
	MediaType string `json:"media_type" yaml:"media_type"`
}

PayloadDescriptor binds a generation manifest to exact immutable bytes.

func DescribeCatalogPayload added in v0.1.0

func DescribeCatalogPayload(payload []byte) PayloadDescriptor

DescribeCatalogPayload returns the descriptor for canonical catalog bytes.

func (PayloadDescriptor) Verify added in v0.1.0

func (d PayloadDescriptor) Verify(payload []byte) error

Verify checks that payload exactly matches the descriptor.

type Provenance added in v0.0.23

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

Provenance is a concurrent-safe container for provenance data. It follows the same pattern as Authors, Models, and Providers containers, using RWMutex for thread safety and returning deep copies to prevent external modification.

func NewProvenance added in v0.0.23

func NewProvenance(opts ...ProvenanceOption) *Provenance

NewProvenance creates a new Provenance container with optional configuration.

func (*Provenance) Clear added in v0.0.23

func (p *Provenance) Clear()

Clear removes all provenance data.

func (*Provenance) EncodeYAML added in v0.1.0

func (p *Provenance) EncodeYAML() (string, error)

EncodeYAML returns provenance YAML. It returns a typed parse error for evidence values that YAML cannot represent safely.

func (*Provenance) FindByField added in v0.0.23

func (p *Provenance) FindByField(resourceType evidence.ResourceType, resourceID string, field string) []provenance.Entry

FindByField retrieves provenance for a specific resource field. It returns nil when no entry matches.

func (*Provenance) FindByResource added in v0.0.23

func (p *Provenance) FindByResource(resourceType evidence.ResourceType, resourceID string) map[string][]provenance.Entry

FindByResource retrieves all provenance for a resource. Returns a map of field names to their provenance entries.

func (*Provenance) FindModel added in v0.2.0

func (p *Provenance) FindModel(providerID ProviderID, modelID string) map[string][]provenance.Entry

FindModel retrieves all provenance for one provider model.

func (*Provenance) FindModelField added in v0.2.0

func (p *Provenance) FindModelField(providerID ProviderID, modelID, field string) []provenance.Entry

FindModelField retrieves provenance for one field of one provider model.

func (*Provenance) FormatYAML added in v0.0.23

func (p *Provenance) FormatYAML() string

FormatYAML returns the provenance data formatted as YAML. This follows the same pattern as Authors and Providers containers.

func (*Provenance) Len added in v0.0.23

func (p *Provenance) Len() int

Len returns the number of provenance entries.

func (*Provenance) Map added in v0.0.23

func (p *Provenance) Map() provenance.Map

Map returns a deep copy of the provenance map. The copy prevents callers from modifying internal state across goroutines.

func (*Provenance) Merge added in v0.0.23

func (p *Provenance) Merge(m provenance.Map)

Merge adds new provenance entries to existing data. This appends to existing keys rather than replacing them.

func (*Provenance) Set added in v0.0.23

func (p *Provenance) Set(m provenance.Map)

Set replaces the entire provenance map with new data. The input map is deep copied to prevent external modification.

type ProvenanceOption added in v0.0.23

type ProvenanceOption func(*Provenance)

ProvenanceOption defines a function that configures a Provenance instance.

type ProvenanceReader added in v0.1.0

type ProvenanceReader interface {
	Map() provenance.Map
	Len() int
	FindByField(evidence.ResourceType, string, string) []provenance.Entry
	FindByResource(evidence.ResourceType, string) map[string][]provenance.Entry
	FindModelField(ProviderID, string, string) []provenance.Entry
	FindModel(ProviderID, string) map[string][]provenance.Entry
	FormatYAML() string
}

ProvenanceReader exposes provenance reads without mutation methods.

type Provider

type Provider struct {
	ID           ProviderID   `json:"id" yaml:"id"`
	Aliases      []ProviderID `json:"aliases,omitempty" yaml:"aliases,omitempty"`
	Name         string       `json:"name" yaml:"name"` // Display name (must not be empty)
	Description  *string      `json:"description,omitempty" yaml:"description,omitempty"`
	Website      *string      `json:"website,omitempty" yaml:"website,omitempty"`           // Official website URL
	DocsURL      *string      `json:"docs_url,omitempty" yaml:"docs_url,omitempty"`         // Link to the provider's API documentation
	Headquarters *string      `json:"headquarters,omitempty" yaml:"headquarters,omitempty"` // Company headquarters location
	IconURL      *string      `json:"icon_url,omitempty" yaml:"icon_url,omitempty"`         // Provider icon/logo URL

	// catalog payload but stay out of providers.yaml. On a filesystem catalog
	// they live in the providers/<id>/logo.svg sidecar file.
	Logo []byte `json:"logo_svg,omitempty" yaml:"-"`

	// Secret-free credential metadata for catalog acquisition and inference.
	Credentials *ProviderCredentials `json:"credentials,omitempty" yaml:"credentials,omitempty"`

	// Models
	Catalog *ProviderCatalog  `json:"catalog,omitempty" yaml:"catalog,omitempty"` // Models catalog configuration
	Models  map[string]*Model `json:"-" yaml:"-"`                                 // Available models indexed by model ID - not serialized to YAML

	// Status & Health
	StatusPageURL *string            `json:"status_page_url,omitempty" yaml:"status_page_url,omitempty"` // Link to service status page
	Inference     *ProviderInference `json:"inference,omitempty" yaml:"inference,omitempty"`             // Provider inference service contract

	// Privacy, Retention, and Governance Policies
	PrivacyPolicy    *ProviderPrivacyPolicy    `json:"privacy_policy,omitempty" yaml:"privacy_policy,omitempty"`       // Data collection and usage practices
	RetentionPolicy  *ProviderRetentionPolicy  `json:"retention_policy,omitempty" yaml:"retention_policy,omitempty"`   // Data retention and deletion practices
	GovernancePolicy *ProviderGovernancePolicy `json:"governance_policy,omitempty" yaml:"governance_policy,omitempty"` // Oversight and moderation practices

	// Extensions - controlled source-specific fields that are not canonical schema
	Extensions SourceExtensions `json:"extensions,omitempty" yaml:"extensions,omitempty"`
}

Provider represents a provider configuration.

func DeepCopyProvider added in v0.0.15

func DeepCopyProvider(provider Provider) Provider

DeepCopyProvider creates a deep copy of a Provider including its Models map.

func (*Provider) BindCatalogEndpoint added in v0.4.0

func (p *Provider) BindCatalogEndpoint(bindings map[string]string) (string, error)

BindCatalogEndpoint resolves catalog-declared endpoint variables.

func (*Provider) CatalogEndpointURL added in v0.1.0

func (p *Provider) CatalogEndpointURL() string

CatalogEndpointURL returns the resolved model catalog endpoint URL.

func (*Provider) IsCatalogAuthRequired added in v0.3.0

func (p *Provider) IsCatalogAuthRequired() bool

IsCatalogAuthRequired reports whether catalog acquisition requires credentials.

func (*Provider) Model

func (p *Provider) Model(modelID string) (*Model, error)

Model retrieves a specific model from the provider.

func (Provider) ValidateContract added in v0.3.0

func (p Provider) ValidateContract() error

ValidateContract validates serializable catalog-acquisition and inference metadata. It does not inspect runtime credential values.

type ProviderAWSDefaultProtocolOptions added in v0.4.0

type ProviderAWSDefaultProtocolOptions struct {
	RegionField ProviderCredentialFieldID `json:"region_field" yaml:"region_field"`
	Service     string                    `json:"service" yaml:"service"`
}

ProviderAWSDefaultProtocolOptions configures AWS request signing.

type ProviderAnthropicCatalogProtocolOptions added in v0.4.0

type ProviderAnthropicCatalogProtocolOptions struct {
	Version string `json:"version" yaml:"version"`
}

ProviderAnthropicCatalogProtocolOptions defines Anthropic wire-version facts.

type ProviderAuthenticationPrimitive added in v0.4.0

type ProviderAuthenticationPrimitive string

ProviderAuthenticationPrimitive identifies compiled authentication behavior. It never identifies a provider.

const (
	// ProviderAuthenticationNone sends no authentication material.
	ProviderAuthenticationNone ProviderAuthenticationPrimitive = "none"
	// ProviderAuthenticationAPIKey places a static API key on a request.
	ProviderAuthenticationAPIKey ProviderAuthenticationPrimitive = "api-key"
	// ProviderAuthenticationBearerToken places a resolved bearer token.
	ProviderAuthenticationBearerToken ProviderAuthenticationPrimitive = "bearer-token"
	// ProviderAuthenticationGoogleDefault uses Google's default credential chain.
	ProviderAuthenticationGoogleDefault ProviderAuthenticationPrimitive = "google-default"
	// ProviderAuthenticationAzureDefault uses Azure's default credential chain.
	ProviderAuthenticationAzureDefault ProviderAuthenticationPrimitive = "azure-default"
	// ProviderAuthenticationAWSDefault uses AWS's default credential chain.
	ProviderAuthenticationAWSDefault ProviderAuthenticationPrimitive = "aws-default"
)

type ProviderAuthenticationProtocolOptions added in v0.4.0

type ProviderAuthenticationProtocolOptions struct {
	GoogleDefault *ProviderGoogleDefaultProtocolOptions `json:"google_default,omitempty" yaml:"google_default,omitempty"`
	AWSDefault    *ProviderAWSDefaultProtocolOptions    `json:"aws_default,omitempty" yaml:"aws_default,omitempty"`
}

ProviderAuthenticationProtocolOptions is a typed union of primitive-owned protocol settings. Provider membership does not belong in this union.

type ProviderCapabilityCombination added in v0.4.0

type ProviderCapabilityCombination string

ProviderCapabilityCombination defines how multiple source predicates prove one canonical capability.

const (
	// ProviderCapabilityConflict accepts equal known values and rejects contradictions.
	ProviderCapabilityConflict ProviderCapabilityCombination = "conflict"
	// ProviderCapabilityFirstKnown selects the first present source in YAML order.
	ProviderCapabilityFirstKnown ProviderCapabilityCombination = "first-known"
	// ProviderCapabilityAny requires any known true, or all known false.
	ProviderCapabilityAny ProviderCapabilityCombination = "any"
	// ProviderCapabilityAll requires any known false, or all known true.
	ProviderCapabilityAll ProviderCapabilityCombination = "all"
)

type ProviderCatalog

type ProviderCatalog struct {
	Docs     *string          `yaml:"docs" json:"docs"`         // Documentation URL
	Endpoint ProviderEndpoint `yaml:"endpoint" json:"endpoint"` // API endpoint configuration
}

ProviderCatalog represents information about a provider's models.

type ProviderCatalogProtocolOptions added in v0.4.0

type ProviderCatalogProtocolOptions struct {
	OpenAI    *ProviderOpenAICatalogProtocolOptions    `json:"openai,omitempty" yaml:"openai,omitempty"`
	Anthropic *ProviderAnthropicCatalogProtocolOptions `json:"anthropic,omitempty" yaml:"anthropic,omitempty"`
}

ProviderCatalogProtocolOptions is a typed union of catalog-transport facts.

type ProviderCredentialEndpointBinding added in v0.4.0

type ProviderCredentialEndpointBinding struct {
	Field    ProviderCredentialFieldID               `json:"field" yaml:"field"`
	Variable string                                  `json:"variable" yaml:"variable"`
	Format   ProviderCredentialEndpointBindingFormat `json:"format" yaml:"format"`
}

ProviderCredentialEndpointBinding binds one non-secret field to a named URL template variable.

type ProviderCredentialEndpointBindingFormat added in v0.4.0

type ProviderCredentialEndpointBindingFormat string

ProviderCredentialEndpointBindingFormat identifies how to encode a value before it replaces an endpoint template variable.

const (
	// ProviderCredentialEndpointBindingURL permits one absolute HTTP(S) base URL.
	ProviderCredentialEndpointBindingURL ProviderCredentialEndpointBindingFormat = "url"
	// ProviderCredentialEndpointBindingPathSegment percent-encodes one URL path segment.
	ProviderCredentialEndpointBindingPathSegment ProviderCredentialEndpointBindingFormat = "path-segment"
)

type ProviderCredentialField added in v0.4.0

type ProviderCredentialField struct {
	ID          ProviderCredentialFieldID   `json:"id" yaml:"id"`
	Kind        ProviderCredentialFieldKind `json:"kind" yaml:"kind"`
	Required    bool                        `json:"required" yaml:"required"`
	Environment []string                    `json:"environment,omitempty" yaml:"environment,omitempty"`
	Default     string                      `json:"default,omitempty" yaml:"default,omitempty"`
	Pattern     string                      `json:"pattern,omitempty" yaml:"pattern,omitempty"`
	Description string                      `json:"description,omitempty" yaml:"description,omitempty"`
}

ProviderCredentialField defines one named material field and its conventional ambient environment names. Its ID determines product-specific names.

type ProviderCredentialFieldID added in v0.4.0

type ProviderCredentialFieldID string

ProviderCredentialFieldID identifies one secret or non-secret credential field. Values are runtime state and are not part of the catalog.

const (
	// ProviderAWSCredentialAccessKeyID is the primitive-owned AWS access-key field.
	ProviderAWSCredentialAccessKeyID ProviderCredentialFieldID = "access-key-id"
	// ProviderAWSCredentialSecretAccessKey is the primitive-owned AWS secret-key field.
	ProviderAWSCredentialSecretAccessKey ProviderCredentialFieldID = "secret-access-key"
	// ProviderAWSCredentialSessionToken is the primitive-owned AWS session-token field.
	ProviderAWSCredentialSessionToken ProviderCredentialFieldID = "session-token"
)

type ProviderCredentialFieldKind added in v0.4.0

type ProviderCredentialFieldKind string

ProviderCredentialFieldKind distinguishes secret material from non-secret endpoint and protocol parameters.

const (
	// ProviderCredentialFieldSecret is sensitive authentication material.
	ProviderCredentialFieldSecret ProviderCredentialFieldKind = "secret"
	// ProviderCredentialFieldParameter is non-secret runtime configuration.
	ProviderCredentialFieldParameter ProviderCredentialFieldKind = "parameter"
)

type ProviderCredentialPlacement added in v0.4.0

type ProviderCredentialPlacement struct {
	Field       ProviderCredentialFieldID       `json:"field" yaml:"field"`
	Kind        ProviderCredentialPlacementKind `json:"kind" yaml:"kind"`
	Name        string                          `json:"name" yaml:"name"`
	Scheme      ProviderCredentialScheme        `json:"scheme" yaml:"scheme"`
	EvidenceURL string                          `json:"evidence_url,omitempty" yaml:"evidence_url,omitempty"`
}

ProviderCredentialPlacement binds one resolved field to a request location. Query placement requires an HTTPS provider-evidence URL.

type ProviderCredentialPlacementKind added in v0.4.0

type ProviderCredentialPlacementKind string

ProviderCredentialPlacementKind identifies the request location for one credential field.

const (
	// ProviderCredentialPlacementHeader applies material to an HTTP header.
	ProviderCredentialPlacementHeader ProviderCredentialPlacementKind = "header"
	// ProviderCredentialPlacementQuery applies material to a URL query value.
	ProviderCredentialPlacementQuery ProviderCredentialPlacementKind = "query"
)

type ProviderCredentialPlane added in v0.4.0

type ProviderCredentialPlane struct {
	Required     bool                          `json:"required" yaml:"required"`
	Alternatives []ProviderCredentialProfileID `json:"alternatives" yaml:"alternatives"`
}

ProviderCredentialPlane defines the ordered authentication profiles that one credential plane permits. Selecting a profile is terminal. The catalog does not define automatic fallback between profiles.

type ProviderCredentialProfile added in v0.4.0

type ProviderCredentialProfile struct {
	ID               ProviderCredentialProfileID           `json:"id" yaml:"id"`
	Primitive        ProviderAuthenticationPrimitive       `json:"primitive" yaml:"primitive"`
	Fields           []ProviderCredentialFieldID           `json:"fields,omitempty" yaml:"fields,omitempty"`
	Placements       []ProviderCredentialPlacement         `json:"placements,omitempty" yaml:"placements,omitempty"`
	Scopes           []string                              `json:"scopes,omitempty" yaml:"scopes,omitempty"`
	EndpointBindings []ProviderCredentialEndpointBinding   `json:"endpoint_bindings,omitempty" yaml:"endpoint_bindings,omitempty"`
	ProtocolOptions  ProviderAuthenticationProtocolOptions `json:"protocol_options,omitempty" yaml:"protocol_options,omitempty"`
}

ProviderCredentialProfile defines one complete authentication alternative. Field references share provider-level definitions across alternatives.

type ProviderCredentialProfileID added in v0.4.0

type ProviderCredentialProfileID string

ProviderCredentialProfileID identifies one authentication profile.

type ProviderCredentialScheme added in v0.4.0

type ProviderCredentialScheme string

ProviderCredentialScheme identifies the transformation to apply before placing a credential field on a request.

const (
	// ProviderCredentialSchemeDirect places bytes without a prefix.
	ProviderCredentialSchemeDirect ProviderCredentialScheme = "direct"
	// ProviderCredentialSchemeBearer adds the Bearer authentication prefix.
	ProviderCredentialSchemeBearer ProviderCredentialScheme = "bearer"
	// ProviderCredentialSchemeBasic adds the Basic authentication prefix.
	ProviderCredentialSchemeBasic ProviderCredentialScheme = "basic"
)

type ProviderCredentials added in v0.4.0

type ProviderCredentials struct {
	Fields             []ProviderCredentialField   `json:"fields" yaml:"fields"`
	Profiles           []ProviderCredentialProfile `json:"profiles" yaml:"profiles"`
	CatalogAcquisition ProviderCredentialPlane     `json:"catalog_acquisition" yaml:"catalog_acquisition"`
	Inference          ProviderCredentialPlane     `json:"inference" yaml:"inference"`
}

ProviderCredentials defines credential fields once and composes them into named profiles. Each plane lists its permitted profiles in selection order.

type ProviderEndpoint added in v0.0.15

type ProviderEndpoint struct {
	Type               EndpointType                   `yaml:"type" json:"type"`                                                   // Required: API style
	URL                string                         `yaml:"url" json:"url"`                                                     // Required: API endpoint
	ProtocolOptions    ProviderCatalogProtocolOptions `yaml:"protocol_options,omitempty" json:"protocol_options,omitempty"`       // Typed wire-protocol facts
	FieldMappings      []FieldMapping                 `yaml:"field_mappings,omitempty" json:"field_mappings,omitempty"`           // Field mappings
	CapabilityMappings []CapabilityMapping            `yaml:"capability_mappings,omitempty" json:"capability_mappings,omitempty"` // Typed capability predicates
	AuthorMapping      *AuthorMapping                 `yaml:"author_mapping,omitempty" json:"author_mapping,omitempty"`           // Author extraction
}

ProviderEndpoint configures how to access the provider's model catalog.

type ProviderGoogleDefaultProtocolOptions added in v0.4.0

type ProviderGoogleDefaultProtocolOptions struct {
	ProjectField      ProviderCredentialFieldID `json:"project_field,omitempty" yaml:"project_field,omitempty"`
	QuotaProjectField ProviderCredentialFieldID `json:"quota_project_field,omitempty" yaml:"quota_project_field,omitempty"`
}

ProviderGoogleDefaultProtocolOptions configures Google token application.

type ProviderGovernancePolicy

type ProviderGovernancePolicy struct {
	ModerationRequired *bool   `json:"moderation_required,omitempty" yaml:"moderation_required,omitempty"` // Whether the provider requires moderation
	Moderated          *bool   `json:"moderated,omitempty" yaml:"moderated,omitempty"`
	Moderator          *string `json:"moderator,omitempty" yaml:"moderator,omitempty"` // Who moderates the provider
}

ProviderGovernancePolicy represents oversight and moderation practices.

type ProviderHealthComponent

type ProviderHealthComponent struct {
	ID   string `json:"id" yaml:"id"`                         // Component ID from the health API
	Name string `json:"name,omitempty" yaml:"name,omitempty"` // Human-readable component name
}

ProviderHealthComponent represents a specific component to monitor in a provider's health API. The ID is the identifier the health API uses for the component: a Statuspage component id, a Hyperping service publicId, or a Google Cloud product id.

type ProviderID

type ProviderID string

ProviderID represents a provider identifier type for compile-time safety.

const (
	ProviderIDAlibabaQwen    ProviderID = "alibaba"
	ProviderIDAlibabaCloud   ProviderID = "alibaba"
	ProviderIDAnthropic      ProviderID = "anthropic"
	ProviderIDAnyscale       ProviderID = "anyscale"
	ProviderIDCerebras       ProviderID = "cerebras"
	ProviderIDCheckstep      ProviderID = "checkstep"
	ProviderIDCohere         ProviderID = "cohere"
	ProviderIDConectys       ProviderID = "conectys"
	ProviderIDCove           ProviderID = "cove"
	ProviderIDDeepMind       ProviderID = "deepmind"
	ProviderIDDeepInfra      ProviderID = "deepinfra"
	ProviderIDDeepSeek       ProviderID = "deepseek"
	ProviderIDFireworksAI    ProviderID = "fireworks-ai"
	ProviderIDGoogleAIStudio ProviderID = "google-ai-studio"
	ProviderIDGoogleVertex   ProviderID = "google-vertex"
	ProviderIDGroq           ProviderID = "groq"
	ProviderIDHetzner        ProviderID = "hetzner"
	ProviderIDHuggingFace    ProviderID = "huggingface"
	ProviderIDMeta           ProviderID = "meta"
	ProviderIDMicrosoft      ProviderID = "microsoft"
	ProviderIDMistralAI      ProviderID = "mistral"
	ProviderIDAzureOpenAI    ProviderID = "azure-openai"
	ProviderIDOllama         ProviderID = "ollama"
	ProviderIDMoonshotAI     ProviderID = "moonshot-ai"
	ProviderIDOpenAI         ProviderID = "openai"
	ProviderIDOpenRouter     ProviderID = "openrouter"
	ProviderIDPerplexity     ProviderID = "perplexity"
	ProviderIDReplicate      ProviderID = "replicate"
	ProviderIDSafetyKit      ProviderID = "safetykit"
	ProviderIDTogetherAI     ProviderID = "together"
	ProviderIDVirtuousAI     ProviderID = "virtuousai"
	ProviderIDVoyageAI       ProviderID = "voyage"
	ProviderIDWebPurify      ProviderID = "webpurify"
	ProviderIDXAI            ProviderID = "xai"
)

Provider ID constants for compile-time safety and consistency.

func (ProviderID) String

func (pid ProviderID) String() string

String returns text for ProviderID.

type ProviderInference added in v0.3.0

type ProviderInference struct {
	BaseURL          string                      `json:"base_url,omitempty" yaml:"base_url,omitempty"`
	Endpoints        []ProviderInferenceEndpoint `json:"endpoints" yaml:"endpoints"`
	HealthAPIURL     *string                     `json:"health_api_url,omitempty" yaml:"health_api_url,omitempty"`
	HealthAPIKind    HealthAPIKind               `json:"health_api_kind,omitempty" yaml:"health_api_kind,omitempty"`
	HealthComponents []ProviderHealthComponent   `json:"health_components,omitempty" yaml:"health_components,omitempty"`
}

ProviderInference defines stable provider-level inference service facts. Gateway consumers supply runtime endpoint overrides and inference credentials.

func (*ProviderInference) BindOfferingEndpoint added in v0.3.0

func (i *ProviderInference) BindOfferingEndpoint(
	endpoint ProviderOfferingEndpoint,
	baseURLOverride string,
	bindings map[string]string,
) (ProviderOfferingEndpoint, error)

BindOfferingEndpoint applies runtime endpoint bindings to one immutable offering endpoint. Catalog data owns URL templates. Consumers supply only tenant-specific values and an optional base URL override.

func (*ProviderInference) Endpoint added in v0.3.0

Endpoint returns the endpoint for an exact inference operation.

func (*ProviderInference) EndpointURL added in v0.3.0

func (i *ProviderInference) EndpointURL(endpoint ProviderInferenceEndpoint, baseURLOverride string) string

EndpointURL resolves an endpoint against a runtime base URL override.

type ProviderInferenceEndpoint added in v0.3.0

type ProviderInferenceEndpoint struct {
	Operation           ProviderOperation         `json:"operation" yaml:"operation"`
	Type                EndpointType              `json:"type" yaml:"type"`
	Path                string                    `json:"path" yaml:"path"`
	StreamPath          string                    `json:"stream_path,omitempty" yaml:"stream_path,omitempty"`
	ProtocolsByAuthor   map[AuthorID]EndpointType `json:"protocols_by_author,omitempty" yaml:"protocols_by_author,omitempty"`
	PathsByAuthor       map[AuthorID]string       `json:"paths_by_author,omitempty" yaml:"paths_by_author,omitempty"`
	StreamPathsByAuthor map[AuthorID]string       `json:"stream_paths_by_author,omitempty" yaml:"stream_paths_by_author,omitempty"`
}

ProviderInferenceEndpoint defines one operation path and wire protocol.

type ProviderModelID added in v0.1.0

type ProviderModelID string

ProviderModelID is the exact opaque model identifier accepted by a provider.

type ProviderModerator

type ProviderModerator string

ProviderModerator represents a moderator for a provider.

const (
	// AI Platform Aggregators/Moderators.
	ProviderModeratorAnyscale    ProviderModerator = "anyscale"
	ProviderModeratorHuggingFace ProviderModerator = "huggingface"
	ProviderModeratorOpenRouter  ProviderModerator = "openrouter"
	ProviderModeratorReplicate   ProviderModerator = "replicate"
	ProviderModeratorTogetherAI  ProviderModerator = "together"

	// Specialized AI Safety/Moderation Companies.
	ProviderModeratorCheckstep  ProviderModerator = "checkstep"
	ProviderModeratorConectys   ProviderModerator = "conectys"
	ProviderModeratorCove       ProviderModerator = "cove"
	ProviderModeratorSafetyKit  ProviderModerator = "safetykit"
	ProviderModeratorVirtuousAI ProviderModerator = "virtuousai"
	ProviderModeratorWebPurify  ProviderModerator = "webpurify"

	// Self-Moderated (Major AI Companies).
	ProviderModeratorAnthropic      ProviderModerator = "anthropic"
	ProviderModeratorGoogleAIStudio ProviderModerator = "google-ai-studio"
	ProviderModeratorGoogleVertex   ProviderModerator = "google-vertex"
	ProviderModeratorGroq           ProviderModerator = "groq"
	ProviderModeratorMicrosoft      ProviderModerator = "microsoft"
	ProviderModeratorOpenAI         ProviderModerator = "openai"

	// Unknown/Unspecified.
	ProviderModeratorUnknown ProviderModerator = "unknown"
)

ProviderModerators.

func (ProviderModerator) String

func (pm ProviderModerator) String() string

String returns text for ProviderModerator.

type ProviderOffering added in v0.1.0

type ProviderOffering struct {
	ProviderID      ProviderID                          `json:"provider_id" yaml:"provider_id"`
	ProviderModelID ProviderModelID                     `json:"provider_model_id" yaml:"provider_model_id"`
	DefinitionID    ModelDefinitionID                   `json:"definition_id" yaml:"definition_id"`
	Pricing         *ModelPricing                       `json:"pricing,omitempty" yaml:"pricing,omitempty"`
	Limits          *ModelLimits                        `json:"limits,omitempty" yaml:"limits,omitempty"`
	Availability    OfferingAvailability                `json:"availability" yaml:"availability"`
	Regions         []string                            `json:"regions,omitempty" yaml:"regions,omitempty"`
	Endpoints       []ProviderOfferingEndpoint          `json:"endpoints,omitempty" yaml:"endpoints,omitempty"`
	Lifecycle       OfferingLifecycle                   `json:"lifecycle" yaml:"lifecycle"`
	DeprecatedAt    *utc.Time                           `json:"deprecated_at,omitempty" yaml:"deprecated_at,omitempty"`
	RetiresAt       *utc.Time                           `json:"retires_at,omitempty" yaml:"retires_at,omitempty"`
	Service         ProviderOfferingServiceCapabilities `json:"service" yaml:"service"`
	Modes           map[string]ProviderOfferingMode     `json:"modes,omitempty" yaml:"modes,omitempty"`
}

ProviderOffering is one provider's service contract for a model definition. Provider-specific price, limits, availability, regions, lifecycle, endpoint, modes, and request overrides live here rather than on the definition.

func (ProviderOffering) Endpoint added in v0.1.0

Endpoint returns the endpoint for an exact supported operation.

func (ProviderOffering) Key added in v0.1.0

func (o ProviderOffering) Key() OfferingKey

Key returns the provider-scoped immutable offering identity.

func (ProviderOffering) Supports added in v0.3.0

func (o ProviderOffering) Supports(operation ProviderOperation) bool

Supports reports whether this exact offering supports an operation.

func (ProviderOffering) Validate added in v0.1.0

func (o ProviderOffering) Validate() error

Validate verifies required identity and provider-specific fields.

type ProviderOfferingEndpoint added in v0.1.0

type ProviderOfferingEndpoint struct {
	Operation ProviderOperation `json:"operation" yaml:"operation"`
	Type      EndpointType      `json:"type,omitempty" yaml:"type,omitempty"`
	URL       string            `json:"url,omitempty" yaml:"url,omitempty"`
	StreamURL string            `json:"stream_url,omitempty" yaml:"stream_url,omitempty"`
}

ProviderOfferingEndpoint describes provider-specific inference endpoint behavior.

type ProviderOfferingMode added in v0.1.0

type ProviderOfferingMode struct {
	Pricing *ModelPricing            `json:"pricing,omitempty" yaml:"pricing,omitempty"`
	Request ProviderRequestOverrides `json:"request" yaml:"request,omitempty"`
}

ProviderOfferingMode describes one named service mode for an offering.

type ProviderOfferingServiceCapabilities added in v0.3.0

type ProviderOfferingServiceCapabilities struct {
	Operations  []ProviderOperation `json:"operations,omitempty" yaml:"operations,omitempty"`
	PromptCache *bool               `json:"prompt_cache,omitempty" yaml:"prompt_cache,omitempty"`
}

ProviderOfferingServiceCapabilities defines exact service behavior for one provider model offering. A nil PromptCache value means unknown.

type ProviderOpenAICatalogProtocolOptions added in v0.4.0

type ProviderOpenAICatalogProtocolOptions struct {
	TokenPriceUnit ProviderTokenPriceUnit `json:"token_price_unit" yaml:"token_price_unit"`
}

ProviderOpenAICatalogProtocolOptions defines OpenAI-compatible payload facts.

type ProviderOperation added in v0.3.0

type ProviderOperation string

ProviderOperation identifies one provider inference operation.

const (
	// ProviderOperationChatCompletions generates chat completions.
	ProviderOperationChatCompletions ProviderOperation = "chat-completions"
	// ProviderOperationEmbeddings generates vector embeddings.
	ProviderOperationEmbeddings ProviderOperation = "embeddings"
	// ProviderOperationImagesGenerations generates an image from a prompt.
	ProviderOperationImagesGenerations ProviderOperation = "images-generations"
	// ProviderOperationImagesEdits generates an image from a prompt and an image.
	ProviderOperationImagesEdits ProviderOperation = "images-edits"
	// ProviderOperationAudioSpeech generates speech from text.
	ProviderOperationAudioSpeech ProviderOperation = "audio-speech"
	// ProviderOperationAudioTranscriptions transcribes speech in its own language.
	ProviderOperationAudioTranscriptions ProviderOperation = "audio-transcriptions"
	// ProviderOperationAudioTranslations transcribes speech into English.
	ProviderOperationAudioTranslations ProviderOperation = "audio-translations"
	// ProviderOperationVideosGenerations generates a video from a prompt. The
	// provider answers with a job rather than a video, so a consumer submits,
	// polls, and collects.
	ProviderOperationVideosGenerations ProviderOperation = "videos-generations"
	// ProviderOperationDocumentsRecognition reads the text off a document that
	// carries none. A document with a text layer needs no model at all, so this
	// operation names the case a reader cannot answer on its own.
	ProviderOperationDocumentsRecognition ProviderOperation = "documents-recognition"
	// ProviderOperationRerank orders a document list by its relevance to one
	// query. The provider answers with a score for each document rather than
	// with generated text, and it bills the call in its own unit.
	ProviderOperationRerank ProviderOperation = "rerank"
	// ProviderOperationModerations classifies text against a fixed set of
	// harm categories and answers with a score for each one. A moderation
	// model reads text and writes scores rather than prose, so the tag is
	// what separates it from a chat model.
	ProviderOperationModerations ProviderOperation = "moderations"
)

type ProviderPrivacyPolicy

type ProviderPrivacyPolicy struct {
	PrivacyPolicyURL  *string `json:"privacy_policy_url,omitempty" yaml:"privacy_policy_url,omitempty"`     // Link to privacy policy
	TermsOfServiceURL *string `json:"terms_of_service_url,omitempty" yaml:"terms_of_service_url,omitempty"` // Link to terms of service
	RetainsData       *bool   `json:"retains_data,omitempty" yaml:"retains_data,omitempty"`                 // Whether provider stores/retains user data
	TrainsOnData      *bool   `json:"trains_on_data,omitempty" yaml:"trains_on_data,omitempty"`             // Whether provider trains models on user data
}

ProviderPrivacyPolicy represents data collection and usage practices.

type ProviderRequestOverrides added in v0.1.0

type ProviderRequestOverrides struct {
	Headers OfferingRequestHeaders `json:"headers,omitempty" yaml:"headers,omitempty"`
	Body    OfferingRequestBody    `json:"body,omitempty" yaml:"body,omitempty"`
}

ProviderRequestOverrides contains provider-specific inference request changes.

type ProviderRetentionPolicy

type ProviderRetentionPolicy struct {
	Type     ProviderRetentionType `json:"type" yaml:"type"`                                                   // Type of retention policy
	Duration *time.Duration        `json:"duration,omitempty" yaml:"duration,omitempty" swaggertype:"integer"` // nil = forever, 0 = immediate deletion
	Details  *string               `json:"details,omitempty" yaml:"details,omitempty"`                         // Human-readable description
}

ProviderRetentionPolicy describes data retention duration and deletion practices.

type ProviderRetentionType

type ProviderRetentionType string

ProviderRetentionType represents different types of data retention policies.

const (
	ProviderRetentionTypeFixed       ProviderRetentionType = "fixed"       // Specific duration (use Duration field)
	ProviderRetentionTypeNone        ProviderRetentionType = "none"        // No retention (immediate deletion)
	ProviderRetentionTypeIndefinite  ProviderRetentionType = "indefinite"  // Forever (duration = nil)
	ProviderRetentionTypeConditional ProviderRetentionType = "conditional" // Based on conditions (e.g., "until account deletion")
)

ProviderRetention types.

func (ProviderRetentionType) String

func (prt ProviderRetentionType) String() string

String returns text for ProviderRetentionType.

type ProviderTokenPriceUnit added in v0.4.0

type ProviderTokenPriceUnit string

ProviderTokenPriceUnit identifies the unit used by one provider payload.

const (
	// ProviderTokenPriceUnitPerToken means USD per token.
	// #nosec G101 -- This value identifies a price unit, not authentication material.
	ProviderTokenPriceUnitPerToken ProviderTokenPriceUnit = "usd-per-token"
	// ProviderTokenPriceUnitPerMillion means USD per one million tokens.
	// #nosec G101 -- This value identifies a price unit, not authentication material.
	ProviderTokenPriceUnitPerMillion ProviderTokenPriceUnit = "usd-per-million-tokens"
)

type Providers

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

Providers is a concurrent safe map of providers.

func NewProviders

func NewProviders(opts ...ProvidersOption) *Providers

NewProviders creates a new Providers map with optional configuration.

func (*Providers) Add

func (p *Providers) Add(provider *Provider) error

Add adds a provider, returning an error if it already exists.

func (*Providers) AddBatch

func (p *Providers) AddBatch(providers []*Provider) map[ProviderID]error

AddBatch adds multiple providers in a single operation. Only adds providers that do not already exist - fails if a provider ID already exists. Returns a map of provider IDs to errors for any failed additions.

func (*Providers) Clear

func (p *Providers) Clear()

Clear removes all providers.

func (*Providers) Delete

func (p *Providers) Delete(id ProviderID) error

Delete removes a provider by id. Returns an error if the provider does not exist.

func (*Providers) DeleteBatch

func (p *Providers) DeleteBatch(ids []ProviderID) map[ProviderID]error

DeleteBatch removes multiple providers by ID. The returned map identifies IDs that DeleteBatch did not find.

func (*Providers) DeleteModel

func (p *Providers) DeleteModel(providerID ProviderID, modelID string) error

DeleteModel removes a model from a provider.

func (*Providers) EncodeYAML added in v0.1.0

func (p *Providers) EncodeYAML() (string, error)

EncodeYAML returns formatted provider YAML. It returns a typed parse error for values that YAML cannot represent safely.

func (*Providers) Exists

func (p *Providers) Exists(id ProviderID) bool

Exists checks if a provider exists without returning it.

func (*Providers) ForEach

func (p *Providers) ForEach(fn func(id ProviderID, provider *Provider) bool)

ForEach applies a function to each provider. The function should not modify the provider. If the function returns false, iteration stops early.

func (*Providers) FormatYAML

func (p *Providers) FormatYAML() string

FormatYAML returns the providers as formatted YAML with enhanced formatting, comments, and structure.

func (*Providers) Get

func (p *Providers) Get(id ProviderID) (*Provider, bool)

Get returns a provider by id and whether it exists.

func (*Providers) Len

func (p *Providers) Len() int

Len returns the number of providers.

func (*Providers) List

func (p *Providers) List() []Provider

List returns a slice of all providers as values (copies).

func (*Providers) Map

func (p *Providers) Map() map[ProviderID]*Provider

Map returns a copy of all providers.

func (*Providers) Resolve added in v0.0.21

func (p *Providers) Resolve(id ProviderID) (*Provider, bool)

Resolve returns a provider by ID or alias. It first tries an exact ID match, then searches all provider aliases. This allows commands to accept both canonical IDs and common aliases silently.

func (*Providers) Set

func (p *Providers) Set(id ProviderID, provider *Provider) error

Set sets a provider by id. Returns an error if provider is nil.

func (*Providers) SetBatch

func (p *Providers) SetBatch(providers map[ProviderID]*Provider) error

SetBatch sets multiple providers in a single operation. Overwrites existing providers or adds new ones (upsert behavior). Returns an error if any provider is nil.

func (*Providers) SetModel

func (p *Providers) SetModel(providerID ProviderID, model Model) error

SetModel adds or updates a model in a provider.

type ProvidersOption

type ProvidersOption func(*Providers)

ProvidersOption defines a function that configures a Providers instance.

func WithProvidersCapacity

func WithProvidersCapacity(capacity int) ProvidersOption

WithProvidersCapacity sets the initial capacity of the providers map.

func WithProvidersMap

func WithProvidersMap(providers map[ProviderID]*Provider) ProvidersOption

WithProvidersMap initializes the map with existing providers.

type ProvidersReader added in v0.1.0

type ProvidersReader interface {
	Get(ProviderID) (*Provider, bool)
	Resolve(ProviderID) (*Provider, bool)
	Exists(ProviderID) bool
	Len() int
	List() []Provider
	Map() map[ProviderID]*Provider
	ForEach(func(ProviderID, *Provider) bool)
	FormatYAML() string
}

ProvidersReader exposes provider collection reads without mutation methods.

type Quantization

type Quantization string

Quantization represents the quantization level used by a model. Quantization reduces model size and computational requirements while aiming to preserve performance.

const (
	QuantizationINT4    Quantization = "int4"
	QuantizationINT8    Quantization = "int8"
	QuantizationFP4     Quantization = "fp4"
	QuantizationFP6     Quantization = "fp6"
	QuantizationFP8     Quantization = "fp8"
	QuantizationFP16    Quantization = "fp16"
	QuantizationBF16    Quantization = "bf16"
	QuantizationFP32    Quantization = "fp32"
	QuantizationUnknown Quantization = "unknown"
)

Quantization levels.

func (Quantization) String

func (q Quantization) String() string

String returns text for Quantization.

type Reader

type Reader interface {
	// Lists providers, authors, authored models, and provenance.
	Providers() ProvidersReader
	Authors() AuthorsReader
	AuthoredModels() []AuthoredModel
	Provenance() ProvenanceReader

	// Gets a provider or author by ID.
	Provider(id ProviderID) (Provider, error)
	Author(id AuthorID) (Author, error)
}

Reader provides read-only access to catalog data.

type RouteAlias added in v0.1.0

type RouteAlias struct {
	ID      RouteAliasID  `json:"id" yaml:"id"`
	Targets []OfferingKey `json:"targets" yaml:"targets"`
}

RouteAlias names a set of candidate offering identities. It intentionally contains no weights, fallback order, tenancy, or routing strategy.

func (RouteAlias) Validate added in v0.1.0

func (a RouteAlias) Validate() error

Validate verifies route identity and exact target uniqueness.

type RouteAliasID added in v0.1.0

type RouteAliasID string

RouteAliasID is a Starport-facing routing identity independent of provider IDs.

type RouteAliasRejection added in v0.1.0

type RouteAliasRejection struct {
	Key    OfferingKey               `json:"key" yaml:"key"`
	Reason RouteAliasRejectionReason `json:"reason" yaml:"reason"`
}

RouteAliasRejection records one ineligible target without hiding it.

type RouteAliasRejectionReason added in v0.1.0

type RouteAliasRejectionReason string

RouteAliasRejectionReason classifies why a target is not currently eligible.

const (
	// RouteAliasRejectedMissing means the offering key is absent from the catalog.
	RouteAliasRejectedMissing RouteAliasRejectionReason = "missing"
	// RouteAliasRejectedUnavailable means the provider marks the offering unavailable.
	RouteAliasRejectedUnavailable RouteAliasRejectionReason = "unavailable"
	// RouteAliasRejectedRetired means the provider retired the offering.
	RouteAliasRejectedRetired RouteAliasRejectionReason = "retired"
)

type RouteAliasResolution added in v0.1.0

type RouteAliasResolution struct {
	AliasID  RouteAliasID          `json:"alias_id" yaml:"alias_id"`
	Eligible []ProviderOffering    `json:"eligible" yaml:"eligible"`
	Rejected []RouteAliasRejection `json:"rejected,omitempty" yaml:"rejected,omitempty"`
}

RouteAliasResolution is a point-in-time materialization against one catalog generation.

type SourceExtension added in v0.1.0

type SourceExtension struct {
	Fields map[string]any `json:"fields,omitempty" yaml:"fields,omitempty"` // Preserved source-specific fields
}

SourceExtension stores controlled non-canonical fields reported by one source.

func (SourceExtension) Copy added in v0.1.0

func (se SourceExtension) Copy() SourceExtension

Copy returns a deep copy of the source extension.

func (SourceExtension) MarshalJSON added in v0.2.0

func (se SourceExtension) MarshalJSON() ([]byte, error)

MarshalJSON canonicalizes source-defined dynamic values. This keeps immutable catalog bytes independent of the evidence representation. The evidence can use concrete provider structs or generic maps from a prior decode.

func (*SourceExtension) UnmarshalJSON added in v0.1.0

func (se *SourceExtension) UnmarshalJSON(data []byte) error

UnmarshalJSON normalizes dynamic extension field types after JSON decoding.

func (*SourceExtension) UnmarshalYAML added in v0.1.0

func (se *SourceExtension) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML normalizes dynamic extension field types after YAML decoding.

type SourceExtensions added in v0.1.0

type SourceExtensions map[string]SourceExtension

SourceExtensions stores source-specific attributes that Starmap preserves without treating as canonical schema fields.

func NormalizeSourceExtensions added in v0.1.0

func NormalizeSourceExtensions(extensions SourceExtensions) SourceExtensions

NormalizeSourceExtensions returns a copy with JSON/YAML-stable dynamic value types for equality checks and sync idempotency.

func (SourceExtensions) Copy added in v0.1.0

Copy returns a deep copy of the source extension map.

type SourceObservationLink struct {
	Source           evidence.SourceID                `json:"source" yaml:"source"`
	ObservationID    string                           `json:"observation_id" yaml:"observation_id"`
	ObservedAt       time.Time                        `json:"observed_at" yaml:"observed_at"`
	Revision         evidence.ObservationRevision     `json:"revision" yaml:"revision"`
	Completeness     evidence.ObservationCompleteness `json:"completeness" yaml:"completeness"`
	Status           evidence.ObservationStatus       `json:"status" yaml:"status"`
	EvidenceChecksum string                           `json:"evidence_checksum" yaml:"evidence_checksum"`
}

SourceObservationLink binds a generation to one immutable source observation. The source pipeline defines the observation schema and retention policy. This link is deliberately small and replay-oriented.

func (SourceObservationLink) Validate added in v0.1.0

func (o SourceObservationLink) Validate() error

Validate verifies one complete source-observation link.

type Tokenizer

type Tokenizer string

Tokenizer represents the tokenizer type used by a model.

const (
	TokenizerClaude   Tokenizer = "claude"
	TokenizerCohere   Tokenizer = "cohere"
	TokenizerDeepSeek Tokenizer = "deepseek"
	TokenizerGPT      Tokenizer = "gpt"
	TokenizerGemini   Tokenizer = "gemini"
	TokenizerGrok     Tokenizer = "grok"
	TokenizerLlama2   Tokenizer = "llama2"
	TokenizerLlama3   Tokenizer = "llama3"
	TokenizerLlama4   Tokenizer = "llama4"
	TokenizerMistral  Tokenizer = "mistral"
	TokenizerNova     Tokenizer = "nova"
	TokenizerQwen     Tokenizer = "qwen"
	TokenizerQwen3    Tokenizer = "qwen3"
	TokenizerRouter   Tokenizer = "router"
	TokenizerYi       Tokenizer = "yi"
	TokenizerUnknown  Tokenizer = "unknown"
)

Tokenizer types.

func (Tokenizer) String

func (t Tokenizer) String() string

String returns text for Tokenizer.

type ToolChoice

type ToolChoice string

ToolChoice represents the strategy for selecting tools. Used in API requests as the "tool_choice" parameter value.

const (
	ToolChoiceAuto     ToolChoice = "auto"
	ToolChoiceNone     ToolChoice = "none"
	ToolChoiceRequired ToolChoice = "required" // Model must call at least one tool before responding
)

Tool choice strategies for controlling tool usage behavior.

func (ToolChoice) String

func (tc ToolChoice) String() string

String returns text for ToolChoice.

type ValuePresence added in v0.2.0

type ValuePresence uint8

ValuePresence describes whether a source supplied a field value.

Missing means the source omitted the field and makes no claim. Unknown means the source explicitly reported that it does not know the value. Known means the source supplied a value, including false, zero, or an empty string.

const (
	// ValueMissing means the source omitted a field and made no claim.
	ValueMissing ValuePresence = iota
	// ValueUnknown means a field was explicitly reported as unknown.
	ValueUnknown
	// ValueKnown means a field has a supplied value, including its zero value.
	ValueKnown
)

Directories

Path Synopsis
Package artifact defines the deterministic distribution format for immutable Starmap catalog generations.
Package artifact defines the deterministic distribution format for immutable Starmap catalog generations.
Package authority defines the executable field policy used by reconciliation.
Package authority defines the executable field policy used by reconciliation.
Package evidence defines neutral source-observation and catalog-review evidence contracts.
Package evidence defines neutral source-observation and catalog-review evidence contracts.
internal
resourcepolicy
Package resourcepolicy owns resource limits and filesystem defaults for the public catalog tree.
Package resourcepolicy owns resource limits and filesystem defaults for the public catalog tree.
Package projection defines post-commit workspace projection results.
Package projection defines post-commit workspace projection results.
Package remote implements the versioned online Starmap-to-Starmap generation protocol and its verified client.
Package remote implements the versioned online Starmap-to-Starmap generation protocol and its verified client.
Package storage provides durable generation-oriented catalog storage.
Package storage provides durable generation-oriented catalog storage.
s3
Package s3 implements storage.ObjectBackend for S3-compatible services.
Package s3 implements storage.ObjectBackend for S3-compatible services.

Jump to

Keyboard shortcuts

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