config

package
v1.2.1 Latest Latest
Warning

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

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

README

Configuration package

The configuration package owns source precedence, platform paths, decoding, and validation. Loading reads process state but does not change it.

Source precedence

Starport resolves each value in this order:

  1. A STARPORT_ process environment variable.
  2. The first environment file that defines the value.
  3. A built-in default.

The standard loader reads one platform file named config.env. It uses these locations:

Platform File
Linux and other Unix systems $XDG_CONFIG_HOME/starport/config.env, or $HOME/.config/starport/config.env when XDG_CONFIG_HOME is empty
macOS $HOME/Library/Application Support/starport/config.env
Windows %AppData%\starport\config.env

os.UserConfigDir supplies the platform root. Tests can inject a different root and environment map without changing global process state.

Managed paths

The platform configuration directory owns these defaults:

Concept Relative path
Environment file config.env
Badger data data/badger
Rate-limit rules rate_limits.yaml

Starport resolves a configured relative path from the platform configuration directory. An absolute path remains unchanged. This rule makes file behavior independent of the directory that starts the process.

Secure local defaults

The HTTP server listens on 127.0.0.1:8080. CORS and rate-limit hot reload are off until an operator enables them. A supplied credential master key must contain at least 32 bytes.

starport init --provider openai and starport init --provider ollama create the standard local file with mode 0600. Initialization creates the credential master key and the first named identity. It does not replace an existing file or identity store.

The container image explicitly listens on 0.0.0.0 because publishing a container port is an operator action. It also stores Badger data under /var/lib/starport/data/badger. Its writable configuration root is /var/lib/starport/config.

Environment variables

All external fields use the STARPORT_ prefix. For example:

STARPORT_SERVER_PORT=8080
STARPORT_STORAGE_MODE=badger
STARPORT_LOGGING_LEVEL=info

Use the configuration reference for the complete field list. Starmap acquisition credentials stay separate from Starport inference credentials.

Provider credential references

The active Starmap catalog defines each provider field. Without an explicit reference, Starport checks its conventional environment names first. It then checks the derived STARPORT_<PROVIDER>_<FIELD> value.

Set STARPORT_<PROVIDER>_<FIELD>_REFERENCE to select an explicit env:, file:, Google Cloud Secret Manager, Azure Key Vault, AWS Secrets Manager, Vault KV v2, or OpenBao KV v2 source. The reference precedes ambient values. Set the matching _REFERENCE_FALLBACK_AMBIENT value to true only when a typed not_configured result can use ambient discovery. Other source failures stay terminal.

The credential resolver owns initial resolution, caching, single-flight work, refresh, revocation, and expiry. Secret-store network access does not occur on a warmed cache hit. Direct-source material has a five-minute refresh interval by default. Set STARPORT_CREDENTIAL_SOURCES_REMOTE_REFRESH_INTERVAL to a different positive duration.

Inspection

Use these commands to inspect the resolved configuration:

starport config paths
starport config show
starport config validate

config show uses the configuration schema to replace each secret and URL with <redacted>. Loader errors report only the failed loading stage. These commands never show configured values in an error and never change process or file state. With --json, validation writes valid: false and a safe loading stage before it returns a nonzero status.

starport doctor uses the same loader. Passive diagnosis does not open storage. It does not send provider inference.

A selected cloud identity can use its authentication network during credential resolution. A selected direct secret reference can do the same. starport doctor --probe opens configured storage through a write-blocking adapter and checks the stored catalog and identity state. If Badger needs writable recovery, the probe skips storage inspection and gives recovery instructions. It also skips this inspection on platforms where Badger does not support read-only mode.

Rate-limit reload

To enable rule reload, set both values:

STARPORT_RATE_LIMITING_ENABLE_HOT_RELOAD=true
STARPORT_RATE_LIMITING_CONFIG_PATH=/absolute/path/to/rate_limits.yaml

Starport requires the rules file after an operator enables reload. The hot reloader watches its directory and also checks the file at the configured interval.

Documentation

Overview

Package config provides configuration management for Starport. It supports loading configuration from environment variables and .env files, with comprehensive validation and hot reload capabilities for rate limiting rules.

Index

Constants

View Source
const (
	// CatalogSourcePublic reads the public Starmap publication channel.
	CatalogSourcePublic = "public"
	// CatalogSourceGitHub reads a signed GitHub release channel.
	CatalogSourceGitHub = "github"
	// CatalogSourceStarmap reads an upstream Starmap deployment.
	CatalogSourceStarmap = "starmap"
	// CatalogSourceFile reads a catalog file on this machine.
	CatalogSourceFile = "file"
	// CatalogSourceEmbedded reads the catalog the binary carries.
	CatalogSourceEmbedded = "embedded"
)

Catalog source kinds. They are the closed set the Starmap settings contract names. Each kind selects where one connected runtime reads its catalog.

View Source
const (
	// CatalogStartupPreferSource starts on the embedded catalog when the
	// source does not answer, and adopts the source when it answers.
	CatalogStartupPreferSource = "prefer_source"
	// CatalogStartupRequireSource refuses to start until the source answers.
	CatalogStartupRequireSource = "require_source"
)

Catalog startup policies. They decide what startup does when the source answers with nothing.

View Source
const (
	// TelemetryMetricsOn serves GET /metrics to every caller. It is the
	// default: the labels carry no caller identity, so the scrape exposes
	// deployment aggregates, not tenant activity.
	TelemetryMetricsOn = "on"
	// TelemetryMetricsAdmin requires the admin scope on GET /metrics.
	TelemetryMetricsAdmin = "admin"
	// TelemetryMetricsOff removes the route.
	TelemetryMetricsOff = "off"
)

Metrics exposure modes for TelemetryConfig.

View Source
const (
	// AuthModeRequired refuses every request that carries no valid gateway
	// API key. It is the default, and the zero value resolves to it.
	AuthModeRequired = authmode.Required
	// AuthModeDisabled serves every request without checking for a key. The
	// key check does not run at all, so a request carrying a key is treated
	// exactly like one that carries none.
	AuthModeDisabled = authmode.Disabled
)
View Source
const (
	// BlobBackendFilesystem stores file bytes under a directory on this node.
	BlobBackendFilesystem = "filesystem"

	// BlobBackendObjectStore stores file bytes in an S3-compatible object
	// store. One client reaches AWS S3, Cloudflare R2, MinIO, and Backblaze B2.
	BlobBackendObjectStore = "objectstore"
)

The blob backends an operator can select. The words match the ones internal/blob reports from Store.Backend, so a startup line and a configuration file spell the same thing.

View Source
const (
	DefaultRetention     = 30 * 24 * time.Hour
	DefaultSweepInterval = time.Hour
)

DefaultRetention is the window an absent setting selects, and DefaultSweepInterval is how often the reclaim pass runs.

View Source
const (
	// DefaultAssetRetention is a day. It is short beside the file store's month
	// on purpose: a generated video is an answer a caller collects rather than a
	// document it keeps, and both provider families publish their own links with
	// windows measured in hours.
	DefaultAssetRetention = 24 * time.Hour

	// DefaultMaxAssetBytes is 256 MiB.
	DefaultMaxAssetBytes int64 = 256 << 20

	// DefaultJobSweepInterval is how often the reclaim pass runs.
	DefaultJobSweepInterval = time.Hour
)

The windows and bounds an absent setting selects.

View Source
const DefaultCatalogSourceChannel = "catalog/v1"

DefaultCatalogSourceChannel is the publication channel of the repository.

View Source
const DefaultCatalogSourceRepository = "agentstation/starmap"

DefaultCatalogSourceRepository is the signed publication repository.

View Source
const DefaultMaxRequestSize int64 = 33554432

DefaultMaxRequestSize is the largest request body the gateway reads, in bytes. A caller attaches media as base64 inside the JSON body, and base64 grows a payload by a third, so the limit has to hold the grown form. The largest media file the provider APIs commonly accept is a 25 MB audio file, which reaches about 33,333,336 bytes as base64. This value clears that with room for the surrounding request.

The tag on MaxRequestSize repeats the number because a struct tag holds a literal. TestBodyLimitDefaultMatchesItsConstant proves the two agree.

View Source
const DefaultMaxUploadBytes int64 = 512 << 20

DefaultMaxUploadBytes is the upload bound an absent setting selects. It matches the cap OpenAI publishes, so an SDK that already refuses a larger file refuses it before the request leaves the client.

Variables

View Source
var (
	// ErrCredentialAliasCollision reports an ambiguous catalog-derived
	// environment name. Validation completes before any value lookup.
	ErrCredentialAliasCollision = errors.New("provider credential environment alias is ambiguous")
)
View Source
var ErrIncompleteBlobConfig = errors.New("config: the object store configuration is incomplete")

ErrIncompleteBlobConfig reports an object store selection that names too little to reach a bucket.

An incomplete selection refuses startup rather than falling back to the filesystem. A deployment that asked for a shared store and silently got a per-node directory would serve a file on one node and a not-found result on the next, and nothing in the request path would say why.

Functions

func OperatorError added in v1.0.1

func OperatorError(err error) error

OperatorError returns an error that is safe to show without configured values. It preserves the original error for programmatic inspection.

func Redacted added in v1.0.1

func Redacted(cfg *Config) map[string]any

Redacted returns an inspectable configuration tree without secret values.

func ResolveStateDirectory added in v1.2.1

func ResolveStateDirectory(configured string) (string, error)

ResolveStateDirectory returns the catalog state directory of this process. An operator value wins. An empty value resolves to the user state root, which is process-local: it is never the workspace path and never a storage path, so two instances that share a volume still hold two identities. A process with no user home directory has no state root, so the error names the two settings that supply one.

Types

type AuditConfig added in v1.2.0

type AuditConfig struct {
	// Retention is how long an audit record stays before the trail prunes
	// it. The 9600h default is the audit package's 400-day window.
	Retention time.Duration `env:"RETENTION,default=9600h"`
}

AuditConfig bounds the admin audit trail.

func (*AuditConfig) RetentionWindow added in v1.2.0

func (c *AuditConfig) RetentionWindow() time.Duration

RetentionWindow returns the configured retention, falling back to the audit package's default when the value is absent or non-positive.

type AuthMode added in v1.1.0

type AuthMode = authmode.Mode

AuthMode selects whether a request must carry a gateway API key.

The type is an alias and not a second spelling. A configuration value, a command-line flag, and the console switch all state the same decision, and internal/authmode owns it so the three cannot drift apart.

type BadgerConfig

type BadgerConfig struct {
	Path           string        `env:"PATH,overwrite"`
	SyncWrites     bool          `env:"SYNC_WRITES,default=false"`
	Compression    string        `env:"COMPRESSION,default=snappy"`
	GCInterval     time.Duration `env:"GC_INTERVAL,default=5m"`
	GCDiscardRatio float64       `env:"GC_DISCARD_RATIO,default=0.5"`
	// contains filtered or unexported fields
}

BadgerConfig defines Badger DB settings

func (*BadgerConfig) Validate

func (c *BadgerConfig) Validate() error

Validate validates BadgerConfig

type CacheConfig

type CacheConfig struct {
	Enabled bool `env:"ENABLED,default=true"`
}

CacheConfig defines cache settings

type CatalogConfig

type CatalogConfig struct {
	// Source selects the catalog source kind.
	Source string `env:"SOURCE,default=public"`

	// SourceURL is the safe source endpoint, or the file identity when the
	// source kind is a file.
	SourceURL string `env:"SOURCE_URL" redact:"url"`

	// SourceAPIKey authenticates this instance to an upstream Starmap
	// deployment. It is not a provider credential.
	SourceAPIKey string `env:"SOURCE_API_KEY" secret:"true"`

	// SourceRepository names the signed publication repository.
	SourceRepository string `env:"SOURCE_REPOSITORY,default=agentstation/starmap"`

	// SourceChannel names the publication channel of that repository.
	SourceChannel string `env:"SOURCE_CHANNEL,default=catalog/v1"`

	// SourceSignerWorkflow names the workflow that must have signed a
	// publication. Empty selects the publisher preset.
	SourceSignerWorkflow string `env:"SOURCE_SIGNER_WORKFLOW"`

	// SourceToken is an optional GitHub API token. It raises the anonymous
	// rate limit and reads a private repository.
	SourceToken string `env:"SOURCE_TOKEN" secret:"true"`

	// SourcePollInterval bounds how often this instance asks the source for
	// a newer publication.
	SourcePollInterval time.Duration `env:"SOURCE_POLL_INTERVAL,default=1h"`

	// SourceStartupPolicy decides what startup does without a source answer.
	SourceStartupPolicy string `env:"SOURCE_STARTUP_POLICY,default=prefer_source"`

	// SourceMaxAge is the oldest publication this instance accepts.
	SourceMaxAge time.Duration `env:"SOURCE_MAX_AGE,default=6h"`

	// SourceMaxHops bounds the publication chain this instance follows.
	SourceMaxHops int `env:"SOURCE_MAX_HOPS,default=8"`

	// AcquisitionEnabled decides whether this instance observes providers.
	AcquisitionEnabled bool `env:"ACQUISITION_ENABLED,default=true"`

	// AcquisitionInterval is the period between provider observations. Zero
	// means one observation at startup and no repeat.
	AcquisitionInterval time.Duration `env:"ACQUISITION_INTERVAL,default=4h"`

	// WorkspacePath is an optional local catalog workspace directory. It
	// holds catalog files an operator supplies. It is never the state
	// directory, because a workspace can sit on a volume many instances share.
	WorkspacePath string `env:"WORKSPACE_PATH"`

	// StateDirectory is where this process keeps the state the connected
	// runtime retains: the layer store, the instance identity seed, and the
	// source discovery record. It must belong to one process on one machine,
	// because two processes that share a seed derive one instance identity and
	// the runtime lease then fences nothing. An empty value resolves to the
	// process-local user state directory.
	StateDirectory string `env:"STATE_DIR"`

	// StartupSpread spreads the first source read of a fleet, so many
	// instances that start together do not ask at the same moment.
	StartupSpread time.Duration `env:"STARTUP_SPREAD,default=15m"`

	// TransferIdleTimeout ends a transfer that stops making progress.
	TransferIdleTimeout time.Duration `env:"TRANSFER_IDLE_TIMEOUT,default=2m"`

	// TransferMaxDuration bounds one complete transfer. Zero is invalid,
	// because a transfer without a bound never ends.
	TransferMaxDuration time.Duration `env:"TRANSFER_MAX_DURATION,default=60m"`

	// RefreshTimeout is an added cap on one refresh run. Zero adds no cap,
	// and the transfer bounds alone end a run that does not progress.
	RefreshTimeout time.Duration `env:"REFRESH_TIMEOUT,default=0s"`
	// contains filtered or unexported fields
}

CatalogConfig holds the canonical Starmap catalog settings. Starport uses the suffixes Starmap names, with the gateway prefix. One connected runtime reads one source and, when acquisition is enabled, observes providers on its own schedule.

Catalog-acquisition credentials stay separate from inference credentials: SourceAPIKey speaks the Starmap protocol, and SourceToken reads a GitHub release. Neither one pays a provider.

func DefaultCatalogConfig added in v1.2.1

func DefaultCatalogConfig() CatalogConfig

DefaultCatalogConfig returns the canonical catalog settings. It states the same values the environment tags name, so a caller that builds a configuration without the environment starts from the shipped contract.

func (CatalogConfig) StateDirectoryIsScratch added in v1.2.1

func (c CatalogConfig) StateDirectoryIsScratch() bool

StateDirectoryIsScratch reports whether the development composition owns the state directory as session scratch. The loader then leaves the value empty, and the composition fills it with a directory it removes on close. An operator value is never scratch.

func (*CatalogConfig) Validate

func (c *CatalogConfig) Validate() error

Validate refuses a catalog setting the runtime cannot honor.

type Config

type Config struct {
	Server            ServerConfig            `env:",prefix=SERVER_"`
	Storage           StorageConfig           `env:",prefix=STORAGE_"`
	Catalog           CatalogConfig           `env:",prefix=CATALOG_"`
	CredentialSources CredentialSourcesConfig `env:",prefix=CREDENTIAL_SOURCES_"`
	Providers         ProvidersConfig
	RateLimiting      RateLimitingConfig  `env:",prefix=RATE_LIMITING_"`
	Security          SecurityConfig      `env:",prefix=SECURITY_"`
	Logging           LoggingConfig       `env:",prefix=LOGGING_"`
	Cache             CacheConfig         `env:",prefix=CACHE_"`
	Files             FilesConfig         `env:",prefix=FILES_"`
	Jobs              JobsConfig          `env:",prefix=JOBS_"`
	Console           ConsoleConfig       `env:",prefix=CONSOLE_"`
	Identity          IdentityConfig      `env:",prefix=IDENTITY_"`
	Telemetry         TelemetryConfig     `env:",prefix=TELEMETRY_"`
	Audit             AuditConfig         `env:",prefix=AUDIT_"`
	Events            EventsConfig        `env:",prefix=EVENTS_"`
	Guardrails        GuardrailsConfig    `env:",prefix=GUARDRAILS_"`
	SemanticCache     SemanticCacheConfig `env:",prefix=SEMANTIC_CACHE_"`
	// contains filtered or unexported fields
}

Config represents the complete application configuration

func LoadDevelopment added in v1.0.3

func LoadDevelopment(ctx context.Context, overrides ...Override) (*Config, error)

LoadDevelopment loads process environment settings without a configuration file and applies the guarded development runtime contract.

func LoadWithDefaults

func LoadWithDefaults(ctx context.Context, overrides ...Override) (*Config, error)

LoadWithDefaults loads configuration from the standard sources.

func (*Config) AuthModeSource added in v1.1.0

func (c *Config) AuthModeSource() authmode.Source

AuthModeSource names where the stated authentication mode came from, or SourceUnset when nobody stated one. Startup passes it to authmode.Resolve, which decides whether a mode an operator stored from the console applies.

func (*Config) ConfigureDevelopmentRuntime added in v1.0.3

func (c *Config) ConfigureDevelopmentRuntime()

ConfigureDevelopmentRuntime selects process-local settings that cannot expose a development gateway or create persistent state.

func (*Config) EnableProvider added in v1.0.2

func (c *Config) EnableProvider(providerID catalogs.ProviderID)

EnableProvider marks one exact catalog provider for operator credential resolution. Catalog membership and adapter activation remain independent.

func (*Config) ResolveProviderRuntime added in v1.0.3

func (c *Config) ResolveProviderRuntime(
	ctx context.Context,
	provider catalogs.Provider,
	explicit ProviderConfig,
	refresh bool,
) (ProviderConfig, bool, error)

ResolveProviderRuntime resolves one catalog provider. Refresh bypasses a fresh cache entry but preserves valid cached material after a transient source failure.

func (*Config) ResolveProviderSet added in v1.0.2

func (c *Config) ResolveProviderSet(
	ctx context.Context,
	providers catalogs.ProvidersReader,
	settings ProvidersConfig,
) (ProvidersConfig, error)

ResolveProviderSet resolves one deployment-owned provider configuration against an exact catalog without changing the supplied settings.

func (*Config) ResolveProviderSetLocalIsolated added in v1.0.3

func (c *Config) ResolveProviderSetLocalIsolated(
	ctx context.Context,
	providers catalogs.ProvidersReader,
	settings ProvidersConfig,
) (ProvidersConfig, []ProviderResolutionFailure, error)

ResolveProviderSetLocalIsolated resolves startup-local environment fields without contacting a remote secret source or cloud identity endpoint. The background reconciler owns external source discovery.

func (*Config) ResolveProviders added in v1.0.2

func (c *Config) ResolveProviders(ctx context.Context, providers catalogs.ProvidersReader) error

ResolveProviders resolves named inference material from the active Starmap provider collection. It validates the complete alias namespace before the first environment read.

func (*Config) Validate

func (c *Config) Validate() error

Validate performs validation on the configuration

func (*Config) ValidateProviderCredentialContracts added in v1.0.3

func (c *Config) ValidateProviderCredentialContracts(
	providers []catalogs.Provider,
) error

ValidateProviderCredentialContracts validates the catalog-wide inference credential namespace before any source access.

type ConsoleConfig added in v1.1.0

type ConsoleConfig struct {
	Enabled bool `env:"ENABLED,default=true"`
}

ConsoleConfig defines settings for the embedded web console

type CredentialReference added in v1.0.2

type CredentialReference struct {
	Reference       string `json:"reference"`
	FallbackAmbient bool   `json:"fallback_ambient,omitempty"`
}

CredentialReference selects one explicit source for a catalog credential field. Ambient fallback applies only to a not-configured source result.

type CredentialSourcesConfig added in v1.0.2

type CredentialSourcesConfig struct {
	// RemoteRefreshInterval is the period between reads of a remote secret
	// store that holds an inference credential.
	RemoteRefreshInterval time.Duration `env:"REMOTE_REFRESH_INTERVAL,default=5m"`

	// ReconcileInterval is the period between reconciliations of the direct
	// secret sources.
	ReconcileInterval time.Duration `env:"RECONCILE_INTERVAL,default=1m"`

	// ReconcileTimeout bounds one reconciliation.
	ReconcileTimeout time.Duration `env:"RECONCILE_TIMEOUT,default=10s"`
}

CredentialSourcesConfig defines the lifecycle of a direct inference secret source. It owns inference credentials alone. The catalog settings in catalog.go own catalog acquisition, and the two never share a variable.

func (*CredentialSourcesConfig) Validate added in v1.0.2

func (c *CredentialSourcesConfig) Validate() error

Validate validates the direct inference secret-source lifecycle.

type EventsConfig added in v1.2.0

type EventsConfig struct {
	// WebhookURLs is a comma-separated list of receiver endpoints. Every
	// configured endpoint receives every event. Empty keeps webhooks off.
	WebhookURLs string `env:"WEBHOOK_URLS"`
	// WebhookSecret signs each delivery. A receiver verifies the
	// X-Starport-Signature header with it. Empty signs with the empty
	// secret, which authenticates nothing; set it with any endpoint.
	WebhookSecret string `env:"WEBHOOK_SECRET"`
}

EventsConfig names the outbound webhook surface. Webhooks stay off until an endpoint is configured, per the active-exporter rule: nothing pushes out of an unconfigured deployment.

func (*EventsConfig) Endpoints added in v1.2.0

func (c *EventsConfig) Endpoints() []string

Endpoints returns the configured receiver URLs, trimmed, without empties. A nil or unconfigured receiver set means webhooks are off.

type FilesConfig added in v1.1.0

type FilesConfig struct {
	// Backend names the store. An absent value selects the filesystem, which
	// needs nothing configured and serves one node.
	Backend string `env:"BACKEND,default=filesystem"`

	// Path roots the filesystem backend. An absent value puts the objects in
	// the platform data directory, beside the record store.
	Path string `env:"PATH"`

	// MaxUploadBytes bounds one upload. It is a deployment decision rather
	// than a wire-format one: the same request that a shared object store
	// absorbs can fill the disk of a single node. FIL6 adds the separate
	// bound on what one account may keep stored at once.
	MaxUploadBytes int64 `env:"MAX_UPLOAD_BYTES,default=536870912"`

	// Retention is how long a stored file stays readable. Every file expires,
	// and an upload may ask for a shorter window but never a longer one.
	Retention time.Duration `env:"RETENTION,default=720h"`

	// SweepInterval is how often the gateway reclaims expired and abandoned
	// files. It is a floor on how long deleted bytes survive, not on how long
	// a file reads: an expired file reads as not found the moment it expires.
	SweepInterval time.Duration `env:"SWEEP_INTERVAL,default=1h"`

	ObjectStore ObjectStoreConfig `env:",prefix=OBJECT_STORE_"`
}

FilesConfig selects where uploaded file bytes land.

func (*FilesConfig) RetentionWindow added in v1.1.0

func (c *FilesConfig) RetentionWindow() time.Duration

RetentionWindow reports how long a stored file stays readable.

func (*FilesConfig) SelectedBackend added in v1.1.0

func (c *FilesConfig) SelectedBackend() string

SelectedBackend reports the backend this configuration names, with the filesystem standing in for an absent value.

func (*FilesConfig) SweepEvery added in v1.1.0

func (c *FilesConfig) SweepEvery() time.Duration

SweepEvery reports how often the reclaim pass runs.

func (*FilesConfig) UploadBound added in v1.1.0

func (c *FilesConfig) UploadBound() int64

UploadBound reports the bound one upload may reach, with the default standing in for an absent or nonsense value.

func (*FilesConfig) Validate added in v1.1.0

func (c *FilesConfig) Validate() error

Validate reports a selection this build cannot open.

type GuardrailsConfig added in v1.2.0

type GuardrailsConfig struct {
	// Checks is a comma-separated list of registered check names, run in
	// the order written. A name no build registers is a startup error.
	// Empty keeps guardrails off.
	Checks string `env:"CHECKS"`
	// PIIMode picks what a PII finding does: redact or refuse. Empty
	// redacts.
	PIIMode string `env:"PII_MODE"`
	// ModerationModel names the catalog moderation model the moderation
	// check calls through the account's own routing. Naming the
	// moderation check without a model is a startup error.
	ModerationModel string `env:"MODERATION_MODEL"`
	// ModerationThreshold refuses when any category scores at or above
	// it. Zero takes the built-in default.
	ModerationThreshold float64 `env:"MODERATION_THRESHOLD"`
	// ModerationThresholds overrides the threshold per category, as
	// comma-separated name=score pairs: "violence=0.8,self-harm=0.2".
	ModerationThresholds string `env:"MODERATION_THRESHOLDS"`
}

GuardrailsConfig names the checks the deployment's guardrail pipeline runs, in order, and what the built-in checks read. Guardrails stay off until a check is configured, and an unconfigured deployment adds no cost on the request path.

func (*GuardrailsConfig) CategoryThresholds added in v1.2.0

func (c *GuardrailsConfig) CategoryThresholds() (map[string]float64, error)

CategoryThresholds parses the per-category threshold overrides. A pair that does not read as name=score is a startup error, not a silent skip. Nil means no override is configured.

func (*GuardrailsConfig) Names added in v1.2.0

func (c *GuardrailsConfig) Names() []string

Names returns the configured check names, trimmed, without empties, in order. A nil or unconfigured receiver means guardrails are off.

type IdentityConfig added in v1.1.0

type IdentityConfig struct {
	CallbackBaseURL string               `env:"CALLBACK_BASE_URL" redact:"url"`
	OAuth           OAuthIdentityConfig  `env:",prefix=OAUTH_"`
	WorkOS          WorkOSIdentityConfig `env:",prefix=WORKOS_"`
}

IdentityConfig defines how people authenticate to the console through an external identity provider. CallbackBaseURL is the address every provider sends the browser back to — scheme and host, no path — and is shared by every acquisition path.

func (IdentityConfig) Enabled added in v1.1.0

func (c IdentityConfig) Enabled() bool

Enabled reports whether any acquisition path is configured.

func (IdentityConfig) RuntimeAcquisition added in v1.1.0

func (c IdentityConfig) RuntimeAcquisition() identity.AcquisitionConfig

RuntimeAcquisition projects the operator's settings into the identity contract. A half-configured path is passed through rather than dropped, so the acquisition path can refuse it with a named error instead of this projection silently turning it off.

type JobsConfig added in v1.1.0

type JobsConfig struct {
	// AssetRetention is how long a finished asset stays readable, measured from
	// the moment this gateway stored it. A caller that comes back past it reads
	// that the asset expired rather than that the job never produced one.
	AssetRetention time.Duration `env:"ASSET_RETENTION,default=24h"`

	// MaxAssetBytes bounds one stored asset. Without it a provider's decision
	// about how large its own answer is would size this deployment's storage.
	MaxAssetBytes int64 `env:"MAX_ASSET_BYTES,default=268435456"`

	// SweepInterval is how often the gateway reclaims expired asset storage. It
	// is a floor on how long expired bytes survive on disk, not on how long an
	// asset reads: an expired asset stops reading the moment it expires.
	SweepInterval time.Duration `env:"SWEEP_INTERVAL,default=1h"`
}

JobsConfig sizes what a gateway keeps for work that outlives its request.

A provider serves a finished video from a link that expires, so Starport fetches the bytes and answers for them itself. Bytes with no stated window turn a gateway into unbounded storage that no operator sized, which is what these three settings exist to stop.

func (*JobsConfig) AssetBound added in v1.1.0

func (c *JobsConfig) AssetBound() int64

AssetBound reports the largest asset this deployment stores.

func (*JobsConfig) AssetRetentionWindow added in v1.1.0

func (c *JobsConfig) AssetRetentionWindow() time.Duration

AssetRetentionWindow reports how long a stored asset stays readable.

func (*JobsConfig) SweepEvery added in v1.1.0

func (c *JobsConfig) SweepEvery() time.Duration

SweepEvery reports how often the reclaim pass runs.

type Loader

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

Loader reads configuration without changing process state.

func NewLoader

func NewLoader() *Loader

NewLoader creates a loader for the process environment and platform paths.

func (*Loader) Load

func (l *Loader) Load(ctx context.Context, overrides ...Override) (*Config, error)

Load resolves configuration sources, applies defaults and any overrides, and validates the result.

func (*Loader) LoadDevelopment added in v1.0.3

func (l *Loader) LoadDevelopment(ctx context.Context, overrides ...Override) (*Config, error)

LoadDevelopment reads process settings, applies the guarded development runtime contract and any overrides, and validates the result.

func (*Loader) WithEnvFiles

func (l *Loader) WithEnvFiles(files ...string) *Loader

WithEnvFiles sets environment files in descending precedence order. An empty list disables file loading.

func (*Loader) WithEnvironment added in v1.0.1

func (l *Loader) WithEnvironment(values map[string]string) *Loader

WithEnvironment replaces the process environment source.

func (*Loader) WithPaths added in v1.0.1

func (l *Loader) WithPaths(paths Paths) *Loader

WithPaths replaces platform path resolution.

type LoggingConfig

type LoggingConfig struct {
	Level      string `env:"LEVEL,default=info"`
	Format     string `env:"FORMAT,default=json"`
	Output     string `env:"OUTPUT,default=stdout"`
	FilePath   string `env:"FILE_PATH"`
	MaxSize    int    `env:"MAX_SIZE,default=100"`
	MaxBackups int    `env:"MAX_BACKUPS,default=3"`
	MaxAge     int    `env:"MAX_AGE,default=7"`
	Compress   bool   `env:"COMPRESS,default=true"`
}

LoggingConfig defines logging settings

func (*LoggingConfig) Validate

func (c *LoggingConfig) Validate() error

Validate validates LoggingConfig

type OAuthApplicationConfig added in v1.1.0

type OAuthApplicationConfig struct {
	ClientID     string `env:"CLIENT_ID"`
	ClientSecret string `env:"CLIENT_SECRET" secret:"true"`
}

OAuthApplicationConfig is one registered OAuth application's credential pair.

type OAuthIdentityConfig added in v1.1.0

type OAuthIdentityConfig struct {
	Google OAuthApplicationConfig `env:",prefix=GOOGLE_"`
	GitHub OAuthApplicationConfig `env:",prefix=GITHUB_"`
}

OAuthIdentityConfig names the OAuth applications an operator registered. Each provider is on when both halves of its application credential are set.

func (OAuthIdentityConfig) Enabled added in v1.1.0

func (c OAuthIdentityConfig) Enabled() bool

Enabled reports whether any OAuth provider is configured.

type ObjectStoreConfig added in v1.1.0

type ObjectStoreConfig struct {
	// Bucket names the bucket. It is the one field with no default.
	Bucket string `env:"BUCKET"`

	// Region names the region. AWS S3 needs it. Another implementation
	// usually accepts any value beside an explicit endpoint.
	Region string `env:"REGION"`

	// Endpoint addresses an implementation other than AWS S3. An absent value
	// selects the AWS endpoint for the region.
	Endpoint string `env:"ENDPOINT" redact:"url"`

	// Prefix scopes every key this deployment writes, so one bucket can hold
	// more than one deployment.
	Prefix string `env:"PREFIX"`

	// AccessKeyID and SecretAccessKey state static credentials. Both absent
	// selects the ambient AWS credential chain, which is the usual choice on
	// an instance that carries a role.
	AccessKeyID     string `env:"ACCESS_KEY_ID" secret:"true"`
	SecretAccessKey string `env:"SECRET_ACCESS_KEY" secret:"true"`
}

ObjectStoreConfig addresses one S3-compatible bucket.

The two key fields carry the `secret` tag, so Redacted removes them from every inspection the console and the CLI print. No error this package returns names them either.

type Override added in v1.1.0

type Override func(*Config)

Override is one decision a caller made outside the environment, applied after configuration sources are read and before validation runs. A command line flag is the reason it exists: a flag has to meet exactly the same validation an environment value meets, or the checks that read it prove nothing about the flag.

func AllowRemoteWithoutAuthentication added in v1.1.0

func AllowRemoteWithoutAuthentication() Override

AllowRemoteWithoutAuthentication acknowledges that an unauthenticated gateway may bind an address the network can reach. Alone it changes nothing; it only lifts the tripwire that DisableAuthentication would otherwise trip.

func DisableAuthentication added in v1.1.0

func DisableAuthentication() Override

DisableAuthentication turns off the gateway API key check. It carries the same weight as STARPORT_SECURITY_AUTH_MODE=disabled, including the exposure tripwire that refuses a non-loopback bind address. It also records that a flag, not the environment, decided: the two write the same field, and a mode an operator stored from the console yields to either, so startup has to be able to name which one it is honoring.

type Paths added in v1.0.1

type Paths struct {
	ConfigDir  string `json:"config_dir"`
	ConfigFile string `json:"config_file"`
	DataDir    string `json:"data_dir"`
	BadgerDir  string `json:"badger_dir"`
	// SQLiteFile holds the embedded relational database. It sits in the data
	// directory beside the Badger store: the same machine state, the other
	// shape.
	SQLiteFile string `json:"sqlite_file"`
	// FilesDir roots the filesystem blob backend. It sits in the data
	// directory beside the record store, because the bytes are state this
	// machine holds rather than a decision an operator wrote down.
	FilesDir string `json:"files_dir"`
	// LocalTokenFile holds this machine's local admin token. It sits in the
	// data directory rather than beside the configuration file, because it is
	// state this machine generated and not a decision an operator wrote down.
	LocalTokenFile string `json:"local_token_file"`
	// WelcomeStampFile records that this machine has been told how to open the
	// console. It exists so the greeting prints once: an operator who has run
	// the gateway before is not a new operator, and a banner that repeats every
	// start is one an experienced reader learns to skip past the day they
	// needed it.
	WelcomeStampFile string `json:"welcome_stamp_file"`
}

Paths contains the platform-owned files and directories that Starport uses.

func PathsForConfigDir added in v1.0.1

func PathsForConfigDir(configDir string) Paths

PathsForConfigDir derives all managed paths from one configuration directory.

func PlatformPaths added in v1.0.1

func PlatformPaths() (Paths, error)

PlatformPaths resolves the current user's Starport paths.

type ProviderConfig

type ProviderConfig struct {
	BaseURL              string                                                     `redact:"url"`
	CredentialReferences map[catalogs.ProviderCredentialFieldID]CredentialReference `json:"credential_references,omitempty"`
	Material             credentials.Material                                       `json:"-"`
	CredentialSource     credentials.MaterialSource                                 `json:"-"`
	Timeout              time.Duration                                              `json:"timeout"`
	MaxConnections       int                                                        `json:"max_connections"`
	Enabled              bool                                                       `json:"enabled"`
}

ProviderConfig defines settings for a single LLM provider

func (*ProviderConfig) Validate

func (c *ProviderConfig) Validate() error

Validate validates ProviderConfig.

type ProviderEntry

type ProviderEntry struct {
	ProviderID catalogs.ProviderID
	Config     ProviderConfig
}

ProviderEntry binds external operator configuration to one exact Starmap provider ID.

type ProviderResolutionFailure added in v1.0.3

type ProviderResolutionFailure struct {
	ProviderID catalogs.ProviderID
	Err        error
}

ProviderResolutionFailure identifies one provider whose inference material could not be resolved. It contains no credential material.

type ProvidersConfig

type ProvidersConfig map[catalogs.ProviderID]ProviderConfig

ProvidersConfig stores inference settings by exact Starmap provider ID. Provider membership comes from the active catalog, not this map.

func CloneProvidersConfig added in v1.0.2

func CloneProvidersConfig(source ProvidersConfig) ProvidersConfig

CloneProvidersConfig returns a caller-owned copy of deployment provider settings. Material and source values are immutable handles.

func (ProvidersConfig) Entries

func (c ProvidersConfig) Entries() []ProviderEntry

Entries returns all supported external configuration slots. Adapter semantics and provider membership remain outside the configuration package.

func (*ProvidersConfig) Validate

func (c *ProvidersConfig) Validate() error

Validate validates each active provider configuration.

type RateLimitingConfig

type RateLimitingConfig struct {
	DefaultRequestsPerMinute int           `env:"DEFAULT_REQUESTS_PER_MINUTE,default=60"`
	WindowSize               time.Duration `env:"WINDOW_SIZE,default=1m"`
}

RateLimitingConfig defines the global default request window. Per-key request limits and budgets live on the identity record and beat these defaults.

func (*RateLimitingConfig) Validate

func (c *RateLimitingConfig) Validate() error

Validate validates RateLimitingConfig

type RemovedSettingError added in v1.2.1

type RemovedSettingError struct {
	// Name is the complete environment variable the deployment still sets.
	Name string
	// Replacement is the complete environment variable to set instead.
	Replacement string
	// Reason states what changed.
	Reason string
}

RemovedSettingError reports one environment variable this gateway no longer reads. It names the setting that replaced the removed one, so an operator repairs the deployment without a search.

func RemovedCatalogSettings added in v1.2.1

func RemovedCatalogSettings() []RemovedSettingError

RemovedCatalogSettings returns every removed catalog variable with its replacement. Documentation and startup read the same list.

func (*RemovedSettingError) Error added in v1.2.1

func (e *RemovedSettingError) Error() string

Error states the removed variable and its replacement.

type SQLConfig added in v1.1.0

type SQLConfig struct {
	Mode     string            `env:"MODE,default=sqlite"`
	SQLite   SQLiteConfig      `env:",prefix=SQLITE_"`
	Postgres SQLPostgresConfig `env:",prefix=POSTGRES_"`
	MySQL    SQLMySQLConfig    `env:",prefix=MYSQL_"`
}

SQLConfig defines relational store settings.

func (*SQLConfig) Validate added in v1.1.0

func (c *SQLConfig) Validate() error

Validate validates SQLConfig

type SQLMySQLConfig added in v1.1.0

type SQLMySQLConfig struct {
	DSN string `env:"DSN" secret:"true"`
}

SQLMySQLConfig defines the MySQL connect's settings. The DSN embeds the password, so inspection redacts it whole.

type SQLPostgresConfig added in v1.1.0

type SQLPostgresConfig struct {
	URL string `env:"URL" redact:"url"`
}

SQLPostgresConfig defines the PostgreSQL connect's settings.

type SQLiteConfig added in v1.1.0

type SQLiteConfig struct {
	Path string `env:"PATH,overwrite"`
}

SQLiteConfig defines the embedded relational store's settings. An empty path keeps the database in memory, which is the development runtime's choice.

type SecurityConfig

type SecurityConfig struct {
	MasterKey          string `env:"MASTER_KEY" secret:"true"`
	TLSCertPath        string `env:"TLS_CERT_PATH"`
	TLSKeyPath         string `env:"TLS_KEY_PATH"`
	EnableTLS          bool   `env:"ENABLE_TLS,default=false"`
	AllowedOrigins     string `env:"ALLOWED_ORIGINS"`
	EnableCORS         bool   `env:"ENABLE_CORS,default=false"`
	JWTSecret          string `env:"JWT_SECRET" secret:"true"`
	APIKeyHeader       string `env:"API_KEY_HEADER,default=Authorization"`
	EnableRateLimiting bool   `env:"ENABLE_RATE_LIMITING,default=true"`

	// AuthMode selects whether the gateway requires a gateway API key. It
	// carries no default, so an unset value stays empty and startup can tell
	// "the operator said required" from "the operator said nothing". Only the
	// second yields to a mode an operator stored from the console.
	AuthMode AuthMode `env:"AUTH_MODE"`
	// AllowRemoteNoAuth is the second, explicit acknowledgment that an
	// unauthenticated gateway may bind an address the network can reach.
	// Without it, startup refuses that combination; see the tripwire in
	// validation.go.
	AllowRemoteNoAuth bool `env:"ALLOW_REMOTE_NO_AUTH,default=false"`
	// UnauthenticatedScopes lists the scopes a request holds while AuthMode
	// is disabled. An empty list means the built-in default, which is every
	// account scope and never admin. An operator who wants the admin plane
	// open without a key has to name "admin" here.
	UnauthenticatedScopes []string `env:"UNAUTHENTICATED_SCOPES"`
	// LocalTokenPath is the file holding this machine's local admin token.
	//
	// It carries no environment tag on purpose. The gateway reads it from here
	// and the CLI reads it from Paths, and both derive from one function, so
	// the two cannot disagree about where the credential lives. A second knob
	// for this one file would make disagreeing possible, and a CLI that rotates
	// a token the running gateway never reads is worse than no command at all.
	// An operator who needs the file elsewhere moves everything with
	// STARPORT_CONFIG_DIR.
	LocalTokenPath string `json:"local_token_path"`
	// contains filtered or unexported fields
}

SecurityConfig defines security settings

func (SecurityConfig) LocalTokenReadOnly added in v1.1.0

func (c SecurityConfig) LocalTokenReadOnly() bool

LocalTokenReadOnly reports whether this process must not write the local admin token file: read the machine's token if it exists, hold an ephemeral one otherwise.

func (*SecurityConfig) Validate

func (c *SecurityConfig) Validate() error

Validate validates SecurityConfig

type SemanticCacheConfig added in v1.2.0

type SemanticCacheConfig struct {
	// Enabled turns the layer on for the deployment. A request still opts
	// in per call with the X-Semantic-Cache header.
	Enabled bool `env:"ENABLED"`
	// Model names the catalog embedding model that embeds the canonical
	// prompt text through the gateway's own embeddings path. Enabling the
	// layer without a model is a startup error.
	Model string `env:"MODEL"`
	// Threshold is the minimum cosine similarity that answers, in (0, 1].
	// Zero takes the built-in default.
	Threshold float64 `env:"THRESHOLD"`
	// MaxEntries bounds the vectors one similarity scope holds. Zero takes
	// the built-in default.
	MaxEntries int `env:"MAX_ENTRIES"`
}

SemanticCacheConfig turns on the semantic_cache layer: the opt-in similarity index beside the exact response cache. The layer stays off until an operator enables it, and every request still opts in per call, so an unconfigured deployment pays nothing for it.

func (*SemanticCacheConfig) Validate added in v1.2.0

func (c *SemanticCacheConfig) Validate() error

Validate refuses a semantic cache the gateway could not run: enabling it without an embedding model, a threshold outside (0, 1], or a negative bound. A disabled section validates as written so a later enable does not surprise.

type ServerConfig

type ServerConfig struct {
	Port              int           `env:"PORT,default=8080"`
	Host              string        `env:"HOST,default=127.0.0.1"`
	ReadTimeout       time.Duration `env:"READ_TIMEOUT,default=30s"`
	WriteTimeout      time.Duration `env:"WRITE_TIMEOUT,default=30s"`
	IdleTimeout       time.Duration `env:"IDLE_TIMEOUT,default=120s"`
	RequestTimeout    time.Duration `env:"REQUEST_TIMEOUT,default=60s"`
	MaxRequestSize    int64         `env:"MAX_REQUEST_SIZE,default=33554432"`
	MaxHeaderBytes    int           `env:"MAX_HEADER_BYTES,default=1048576"`
	ShutdownTimeout   time.Duration `env:"SHUTDOWN_TIMEOUT,default=30s"`
	EnableProfiling   bool          `env:"ENABLE_PROFILING,default=false"`
	EnableHealthCheck bool          `env:"ENABLE_HEALTH_CHECK,default=true"`
}

ServerConfig defines HTTP server settings

func (*ServerConfig) Validate

func (c *ServerConfig) Validate() error

Validate validates ServerConfig

type StorageConfig

type StorageConfig struct {
	Mode   string       `env:"MODE,default=badger"`
	Badger BadgerConfig `env:",prefix=BADGER_"`
	Valkey ValkeyConfig `env:",prefix=VALKEY_"`
	SQL    SQLConfig    `env:",prefix=SQL_"`
}

StorageConfig defines storage backend settings. Mode selects the key-value store; SQL selects its relational twin, which pairs an embedded SQLite database with a network connect the way Badger pairs with Valkey.

func (StorageConfig) Distributed added in v1.2.0

func (c StorageConfig) Distributed() bool

Distributed reports whether the runtime key-value store is one that replicas share. Shared provider health publication turns on with it.

func (StorageConfig) RuntimeSQL added in v1.1.0

func (c StorageConfig) RuntimeSQL() sqlstore.Config

RuntimeSQL projects the relational settings into the sqlstore contract, the way RuntimeStorage projects the key-value ones.

func (StorageConfig) RuntimeStorage added in v1.0.1

func (c StorageConfig) RuntimeStorage() storage.Config

RuntimeStorage projects external storage settings into the storage adapter contract.

func (*StorageConfig) Validate

func (c *StorageConfig) Validate() error

Validate validates StorageConfig

type TelemetryConfig added in v1.2.0

type TelemetryConfig struct {
	// Metrics states who may read the Prometheus scrape at GET /metrics:
	// "on" (default), "admin", or "off".
	Metrics string `env:"METRICS,default=on"`

	// TracesEndpoint holds the OTLP endpoint the standard OpenTelemetry
	// environment names. The variables are OTEL_EXPORTER_OTLP_ENDPOINT and
	// OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, deliberately unprefixed: they are
	// the cross-vendor contract every collector documents. Empty means the
	// tracer stays a no-op. The loader fills this field; it carries no env
	// tag because the gateway prefix does not apply.
	TracesEndpoint string

	// UsageExport names where finalized usage records stream. An http or
	// https URL posts NDJSON batches; any other value is a file path that
	// NDJSON lines append to. Empty means no export.
	UsageExport string `env:"USAGE_EXPORT"`
}

TelemetryConfig selects the observability export surfaces. The metric vocabulary itself lives in internal/telemetry; this section only states which surfaces a deployment serves.

func (TelemetryConfig) Validate added in v1.2.0

func (c TelemetryConfig) Validate() error

Validate refuses a metrics mode the router would silently read as "on".

type ValkeyConfig

type ValkeyConfig struct {
	URL            string        `env:"URL,default=valkey://localhost:6379" redact:"url"`
	MaxConnections int           `env:"MAX_CONNECTIONS,default=50"`
	MinIdleConns   int           `env:"MIN_IDLE_CONNS,default=10"`
	DialTimeout    time.Duration `env:"DIAL_TIMEOUT,default=5s"`
	ReadTimeout    time.Duration `env:"READ_TIMEOUT,default=3s"`
	WriteTimeout   time.Duration `env:"WRITE_TIMEOUT,default=3s"`
	IdleTimeout    time.Duration `env:"IDLE_TIMEOUT,default=5m"`
	ClusterMode    bool          `env:"CLUSTER_MODE,default=false"`
	Password       string        `env:"PASSWORD" secret:"true"`
}

ValkeyConfig defines Valkey/Redis settings

func (*ValkeyConfig) Validate

func (c *ValkeyConfig) Validate() error

Validate validates ValkeyConfig

type WorkOSIdentityConfig added in v1.1.0

type WorkOSIdentityConfig struct {
	APIKey       string `env:"API_KEY" secret:"true"`
	ClientID     string `env:"CLIENT_ID"`
	Organization string `env:"ORGANIZATION"`
	Connection   string `env:"CONNECTION"`
}

WorkOSIdentityConfig is the enterprise SSO broker's settings. APIKey and ClientID come from the WorkOS dashboard; Organization or Connection names which enterprise directory people arrive from.

Jump to

Keyboard shortcuts

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