provider

package
v1.5.70 Latest Latest
Warning

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

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

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

Documentation

Overview

This file implements the Anthropic Messages API streaming decoder (US-008). It is a stateful Decoder (see transport.go) that translates Anthropic SSE event payloads into the provider-agnostic AssistantMessageEvent set, accumulating a partial AssistantMessage as deltas arrive.

Anthropic streams a fixed event sequence:

message_start        → seeds id/model and initial usage (input tokens)
content_block_start  → opens a text / thinking / tool_use block at an index
content_block_delta  → text_delta / thinking_delta / signature_delta /
                       input_json_delta append to the open block
content_block_stop   → closes the block (tool_use JSON is parsed here)
message_delta        → carries the final stop_reason and output-token usage
message_stop         → terminal; the accumulated message is emitted as done
error                → a runtime error payload → terminal error event

Per the dual failure model (FR-13) the decoder never panics: malformed payloads and Anthropic `error` events are surfaced as a returned error (which the transport turns into a terminal StreamErrorEvent) rather than crashing.

This file implements credential resolution (US-012): API key lookup from environment variables and a config file (per provider), plus an OAuth token source that refreshes short-lived tokens on expiry. The resolver satisfies the LoopConfig.GetAPIKey shape (func(ctx, provider) string) so the agent loop can obtain a fresh key per request.

Security (FR: secret values are not written to logs): secret values are never logged or embedded in error messages. Errors and String()/redaction helpers reference credentials by key name / provider only.

This file holds the shared disk-cache plumbing for the two model catalogs golder keeps under the golder home directory:

  • the models.dev reasoning ladder catalog (reasoning.go)
  • the provider model list (modelcatalog.go)

Both are JSON files written opportunistically and read best-effort: a missing, unreadable, or corrupt file never surfaces an error, it just means "no cache". Both share one freshness window (catalogTTL) so a long-lived install refreshes its provider metadata about once a day in total.

This file implements the credential-hygiene primitives from issue #568 (ported from dsh's credential handling):

  • ScrubEnv: derive a child-process environment with credential-shaped variables removed, so a spawned process (sub-agent, plugin) does not inherit secrets it does not need. Mirrors dsh's stdio bridge, which "deliberately removes ambient variables whose names usually identify credentials and all DSH_* variables"; golder scrubs credential-shaped names and all GOLDER_* internals. Explicit allow entries are re-injected last, so a parent can still hand a child exactly the one key it needs.
  • CredentialFile: an AES-256-GCM encrypted named-credential store at $GOLDER_HOME/.credentials.yaml (mode 0600). Config files reference a credential by NAME; the literal secret is only present after authenticated decryption in memory.

This file implements the Gemini v1beta wire: POST {base}/models/{model}:streamGenerateContent?alt=sse, the third driver beside the OpenAI-family and Anthropic-Messages ones. It is scoped to what the agent loop uses — text, thought parts, function calls, usage and the terminal stop reason — and reports images as unsupported through the model metadata until the inlineData shape is added.

This file persists the provider model lists fetched by /model (issue #566), so the list is requested about once per catalogTTL (24h) per provider and endpoint instead of once per session. It shares the file plumbing and the TTL with the reasoning ladder catalog (catalogcache.go), keeping the two caches one mechanism.

A cache key is the provider name plus the effective base URL, so a --base-url override (or a self-hosted endpoint) never serves another endpoint's list. Entries are independent: each carries its own checked_at.

This file implements online model discovery (issue #566, ported from dsh's "Fetch available models"): asking an endpoint which models it serves, so the /model catalog and switching can follow a provider's real lineup.

Both wire formats golder speaks expose a plain GET for it:

  • OpenAI-compatible (and Responses) gateways: GET {base}/models
  • Anthropic Messages: GET {base}/v1/models

and both answer {"data":[{"id": ...}]}, so one parser serves both. Auth follows each protocol's request convention (Bearer for OpenAI-compatible, x-api-key + anthropic-version for Anthropic). A local endpoint that needs no key is fine: the key is sent only when non-empty.

This file implements the OpenAI-compatible streaming decoder (US-009): a stateful Decoder (see transport.go) for the OpenAI Chat Completions SSE stream, which is also the wire format spoken by most third-party gateways (OpenRouter, Groq, together, local servers, …). Selecting the base URL is a transport concern (NewRequest builds the *http.Request), so this decoder is base-URL agnostic and reused across every OpenAI-compatible provider.

OpenAI streams a sequence of chat.completion.chunk objects:

{"choices":[{"delta":{"role":"assistant"}}]}                 → first chunk
{"choices":[{"delta":{"content":"Hel"}}]}                    → text delta
{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1",
    "function":{"name":"f","arguments":"{\"a\":"}}}]}]}       → tool-call delta
{"choices":[{"finish_reason":"tool_calls"}]}                 → stop reason
{"usage":{"prompt_tokens":10,"completion_tokens":5}}         → final usage
[DONE]                                                        → transport-level

Per the dual failure model (FR-13) the decoder never panics: malformed payloads surface as a returned error which the transport turns into a terminal StreamErrorEvent.

This file defines the provider streaming abstraction (US-003/US-007 base): the StreamFn contract, the per-delta AssistantMessageEvent set, and the AssistantMessageEventStream (a specialization of EventStream) that a provider pushes deltas onto while yielding a final AssistantMessage.

Contract (FR-13): a StreamFn never expresses a request failure by returning an error. Runtime failures are encoded as an error event plus a terminal assistant message (stopReason=error/aborted + errorMessage). The returned error is reserved for the earliest "could not even build the stream" case.

This file defines the unified Provider interface and its dual failure model (US-007). A Provider turns a CompletionRequest into a stream of AssistantMessageEvents. Failures follow the same contract as StreamFn (FR-13):

  • "cannot even build the stream" (bad config, missing model) → returned error.
  • any runtime failure once streaming has begun → a terminal StreamErrorEvent carrying an assistant message with stopReason=error/aborted, after which the stream is closed. It is never a returned error.

Model carries provider-agnostic capability metadata so the loop and UI can reason about a model without knowing the concrete provider.

This file implements the first concrete Providers (US-013): Bedrock, OpenRouter, and Ollama. Each satisfies the Provider interface by building an *http.Request and delegating to the shared transport (StreamRequest) with a provider-appropriate Decoder — no bespoke HTTP/SSE handling per provider.

Two backing driver shapes cover all three:

  • openAICompatDriver — POSTs to {baseURL}/chat/completions in the OpenAI Chat Completions wire format, decoded by OpenAIDecoder. OpenRouter and Ollama are instances of it; it is the generic OpenAI-compatible layer, reusable for any gateway (Groq, together, local servers, …).
  • anthropicCompatDriver — POSTs the Anthropic Messages wire format, decoded by AnthropicDecoder. Bedrock rides this: Anthropic-on-Bedrock speaks the Messages API, so the decoder is reused wholesale.

Failures follow the dual failure model (FR-13): only the earliest "cannot build the stream" case (missing key, bad request construction) is a returned error; every runtime failure rides the stream as a terminal error event, which StreamRequest already guarantees.

Security (US-012 / US-026): API keys are referenced by provider name in any error; secret values are never logged or embedded in error text.

This file owns everything about reasoning effort: the mapping from golder's unified ThinkingLevel onto each gateway's wire effort value, and the models.dev catalog that says which levels a model actually advertises.

The mapping half is pure: no IO, no global state. The catalog half fetches and caches models.dev's metadata, because the gateways golder talks to do not expose it themselves (opencode-go's /models returns only id/object/created/owned_by). They live together because they are one decision: WireReasoningEffort reads the catalog and falls back to the hand-maintained ladders in this same file.

golder's unified ladder (off < minimal < low < medium < high < xhigh < max) is wider than any single gateway's. Every wire driver — Chat Completions (`reasoning_effort`) and Responses (`reasoning.effort`) — calls WireReasoningEffort, so a model is mapped identically no matter which protocol carries its request.

A model's accepted ladder resolves in layers:

  1. the models.dev catalog entry for (provider, model), when it has one,
  2. the provider's own ReasoningLadders (registry.go), for gateway quirks,
  3. sharedReasoningLadders, for model families that behave the same on every gateway,
  4. defaultReasoningLadder, the conservative common denominator.

A requested level above the ladder's top clamps down to its top rung (a model with a real max keeps it); a level below its bottom clamps up to the bottom rung. off/empty omits the field so the gateway keeps its own default, and a catalog model marked as non-reasoning gets no effort field at all.

The catalog is one JSON document keyed by provider. golder extracts only the providers it can route to (the built-in registry, using each spec's ModelsDevID) and keeps just each model's reasoning flag plus its effort-type values, so a full fetch is a few tens of KB on disk. It is cached at $GOLDER_HOME/reasoning-catalog.json (or ~/.golder/reasoning-catalog.json) with the shared catalogTTL: a session never blocks on the network for it, and the fetch happens at most once per TTL instead of once per session. Refreshes are conditional (If-None-Match), so an unchanged upstream catalog answers 304 and costs no body. Missing, stale, or corrupt caches degrade silently to the hand-maintained ladders.

This file defines the central provider registry (US-001): a single source of truth for every built-in provider — its name, the environment variables that carry its API key (in precedence order), its default base URL, wire protocol, auth scheme, extra headers, provider-specific base-URL override env vars, and its model-facing behavior (which model-id prefixes infer it, which models.dev entry describes it, and any reasoning-effort ladder quirks its gateway has).

Adding or supporting a provider should be ONE entry in providerRegistry: transport metadata first, then the optional behavior fields. Anything a provider does not declare falls back to the shared defaults — ResolveProvider builds the driver from the spec, InferProviderFromModel reads ModelPrefixes, the reasoning catalog reads ModelsDevID, and WireReasoningEffort consults ReasoningLadders before the model-family table in reasoning.go. The only per-provider code left is special-auth composition (special_auth.go), which needs request signing rather than metadata.

The registry is deliberately additive and self-contained: later nodes wire auth resolution (auth.go), the --provider flag (main.go), base_url overrides, and per-provider construction (providers.go) to READ from it. This node only introduces the data + a lookup, so it does not change existing behavior.

Data source: the PRD "Technical Considerations" table (tasks/prd-provider-env-parity.md), derived from pi's env-api-keys.ts and the per-provider *.models.ts files.

Security: the registry holds only env var NAMES, never secret values. Keys are resolved from the environment at request time (see auth.go) and never logged.

This file implements the OpenAI Responses API driver (US-003, #539), the backing for --protocol openai/resp_api. Unlike openAICompatDriver (which hand-rolls the Chat Completions wire format), this driver speaks the Responses API (POST {base_url}/responses) via the official github.com/openai/openai-go SDK.

This milestone covers streaming text: a plain prompt in, assistant text out, consumed from the Responses SSE stream and mapped into golder's AssistantMessage the same way OpenAIDecoder does (API/Provider tags, Usage, ResponseID/ResponseModel, StopReason=end_turn). Tools (#541) and images/reasoning (#542) layer on later.

Failure model (FR-13): only the earliest "cannot build the stream" case (missing API key) is a returned error. Every runtime failure — including a non-2xx from the endpoint — rides the returned stream as a terminal StreamErrorEvent, matching the chat driver's observable behavior.

Base URL + auth: the SDK client is pointed at the resolved base_url and given the resolved key via option.WithBaseURL / option.WithAPIKey rather than reading the environment, so ResolveBaseURL precedence is preserved. A custom *http.Client may be injected (option.WithHTTPClient) for tests.

This file implements parameter validation and endpoint construction for the "special auth" providers (US-007 / FR-12): Azure OpenAI, Amazon Bedrock, Google Vertex, and Cloudflare (Workers AI + AI Gateway). Unlike the generic bearer/x-api-key providers, each of these composes its endpoint from several environment variables and/or needs a non-standard credential path, so a dedicated resolver validates the required parameters and builds the concrete base URL before handing off to the shared OpenAI-/Anthropic-compatible driver.

Scope note (PRD Non-Goals): AWS SigV4 request signing is NOT implemented. Bedrock supports only the AWS_BEARER_TOKEN_BEDROCK bearer path; other AWS credential sources (AWS_PROFILE, AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY) are only *detected* so that a clear, actionable error is returned instead of an opaque auth failure.

Security: this file reads env var NAMES and composes URLs from non-secret parameters (region, resource name, account id, …). Secret values (API keys, bearer tokens) are never logged or embedded in error text — errors name the absent env var, never a value.

This file implements the shared transport driver (US-007 support): a provider-agnostic layer that turns an HTTP request into a stream of StreamEvents. Each provider degenerates to a stateful Decoder; the transport owns HTTP + SSE line parsing + retry + dual watchdogs + the dual failure model.

The design mirrors pi's providerio: the transport never returns a runtime failure as a Go error once streaming has begun — it rides the stream as a terminal StreamErrorEvent. Only the earliest "cannot build the stream" case (bad request construction) is a returned error.

Index

Constants

View Source
const (
	StreamEventStart    = "start"
	StreamEventText     = "text"
	StreamEventThinking = "thinking"
	StreamEventToolCall = "toolcall"
	StreamEventDone     = "done"
	StreamEventError    = "error"
	StreamEventNotice   = "notice"
)

AssistantMessageEvent kinds.

View Source
const (
	ProtocolOpenAI    = "openai"
	ProtocolAnthropic = "anthropic"
)

Protocol values.

View Source
const (
	AuthBearer  = "bearer"
	AuthXAPIKey = "x-api-key"
	AuthAWS     = "aws"
	AuthAzure   = "azure"
	AuthSpecial = "special"
)

AuthScheme values.

View Source
const (
	StreamCutIdle      = "idle"
	StreamCutStall     = "stall"
	StreamCutTruncated = "truncated"
	StreamCutSilent    = "silent"
	// StreamCutConnect is the failure that never became a stream: the request
	// reached no response at all. It is a cut — nothing was produced, and a fresh
	// request is the fix — but its own kind, because the sentence and the retry
	// reason differ from a stream that died mid-answer.
	StreamCutConnect = "connect"
	// StreamCutUpstream is a failure the provider declared on a healthy stream:
	// the server accepted the request (a response id may exist) and then ended it
	// with an error event instead of an answer. It is a cut because nothing an
	// answer could duplicate was produced, and it is its own kind because the
	// connection was fine — the server behind it failed.
	StreamCutUpstream = "upstream"
)

The cut kinds carried by StreamNoticeEvent/ProviderNoticeEvent. They are the vocabulary a front-end localizes, so they stay stable strings.

View Source
const (
	StreamPhaseFirstToken = "first-token"
	StreamPhaseStream     = "stream"
)

Watchdog phases: the two windows are different questions, and a person reading the failure needs to know which one expired. "No answer started" means the model never began (a long prefill, a queued request, a silent think); "output stopped" means it began and then went quiet (a mid-stream hang).

View Source
const ExtraSessionID = "session_id"

ExtraSessionID is the StreamConfig.Extra key carrying the golder session id (see RunConfig.SessionID) from the loop to the provider drivers. It is opaque to every other layer.

View Source
const OpencodeSessionHeader = "x-opencode-session"

OpencodeSessionHeader carries the client session id to opencode's Zen endpoints. The Go endpoint (modelList "lite") rejects requests without it (400 MissingSessionID: "cannot be routed efficiently"), using the value for sticky upstream routing. The full Zen endpoint tolerates its absence.

View Source
const ProtocolGemini = "gemini"

ProtocolGemini is the selector for the Gemini v1beta wire. Selection knows the wire (see ModelWire), but the driver does not exist yet, so a run that selects it reports that plainly instead of silently using another wire.

View Source
const ProtocolOpenAIResponses = "openai/resp_api"

ProtocolOpenAIResponses is the canonical selector for the OpenAI Responses API wire format (POST {base_url}/responses). It is distinct from ProtocolOpenAI (Chat Completions) so ResolveProvider can route to the SDK-based Responses driver.

View Source
const StreamNoticeRetry = "retry"

StreamNoticeRetry is the notice kind for a stream that is being re-issued.

Variables

View Source
var ErrCredentialExists = errors.New("named credential already exists")
View Source
var ErrUsageUnsupported = errors.New("no quota endpoint is known for this provider")

ErrUsageUnsupported reports a provider with no usage endpoint.

View Source
var ProcessSessionID = sync.OnceValue(func() string {
	return fmt.Sprintf("golder-%d-%d", os.Getpid(), time.Now().Unix())
})

ProcessSessionID returns a stable per-process session identity for callers that need the opencode sticky-routing header but have no real session id (e.g. the risk reviewer, or a process-isolated sub-agent). Sharing one affinity bucket with the process's runs is the desired routing behavior there anyway.

WirePriority is the fixed preference order, used both for probing and for the adaptive fallback when a gateway rejects a model's current wire: Responses, Messages, Chat, then the Gemini v1beta wire.

Functions

func APIKeyEnvHint

func APIKeyEnvHint(name string) string

APIKeyEnvHint returns a human-readable hint naming the environment variable(s) that satisfy the provider's credential check, for embedding in missing-key errors (issue #564: "openrouter: missing API key" alone leaves the user guessing what to set). Unknown providers fall back to the generic <PROVIDER>_API_KEY convention.

func AllowsProtocol added in v1.3.1

func AllowsProtocol(spec ProviderSpec, canonical string) bool

AllowsProtocol reports whether an explicit protocol selection is legal for a provider: its own registered Protocol, the Responses upgrade every OpenAI-wired gateway is assumed to serve, or a wire variant the spec declares (see ProviderSpec.WireVariants). It is the single rule behind both the resolver's conflict error and the display path's protocol label, so what `/provider` and the banner call a gateway's protocol and what a run can actually select cannot disagree.

func BaseURLEnvVars

func BaseURLEnvVars(spec ProviderSpec) []string

BaseURLEnvVars lists endpoint override variables in resolution order.

func BrowserProxyServer added in v1.5.39

func BrowserProxyServer() (string, error)

BrowserProxyServer returns the explicit Chromium proxy when the person enabled browser routing with /proxy browser on. Unlike provider transports, Chromium receives the address in argv: credentials and URL paths are refused so they cannot leak through process listings or become ambiguous flags.

func BrowserProxyStatus added in v1.5.39

func BrowserProxyStatus() string

func CachedModelCatalog

func CachedModelCatalog(key string) (ids []string, fresh bool)

CachedModelCatalog returns the cached list for key and whether it is still fresh (younger than catalogTTL). A nil list with fresh=false means "no usable cache": either nothing was ever stored, or the stored entry is stale (callers may still use the list as a fallback when a refetch fails).

func CanonicalizeModel

func CanonicalizeModel(model string) string

CanonicalizeModel maps a bare built-in provider name (e.g. "zai", "DEEPSEEK") to that provider's DefaultModel (e.g. "glm-4.7"), so a user who types the provider alone gets its default model instead of the literal id being sent to OpenRouter (issue #564). Any other id — a real model id, an unknown name, a "provider/model" routed id — is returned unchanged.

The mapping is exact-match on the trimmed, lowercased id against the built-in provider registry; a model id that happens to equal a provider name is not a meaningful OpenRouter id, so the ambiguity is harmless.

func CompareModelVersion added in v1.3.2

func CompareModelVersion(a, b string) int

CompareModelVersion orders two ids of the same family by version, negative when a is older. It reads the numeric runs of each id, so "deepseek-v4.1-flash" > "deepseek-v4", "gpt-5.6" > "gpt-5", "glm-5.3" > "glm-4". A model that carries a version beats one that does not, and when the numbers tie the shorter id wins — the plain release is the family's name, its suffixed variants are derivatives ("gpt-5" > "gpt-5-mini"). It is a naming heuristic, used only to pick the representative model a family probe asks about.

func ContextWindowFor added in v1.2.13

func ContextWindowFor(providerName, model string) int

ContextWindowFor returns the context-token budget models.dev lists for (providerName, model), or 0 when it has no value. Lookups read the reasoning catalog's in-memory/disk copy, so they never block on the network; callers fall back to cli.DefaultContextWindow on 0 (unknown provider, custom base-URL model, or a catalog that has not been fetched yet). A case-only mismatch between the gateway's model id and models.dev's brand casing still matches.

func CreateCredential added in v1.5.62

func CreateCredential(path, name, value string) error

CreateCredential writes a new named credential without overwriting an existing value, including when another process creates the name concurrently.

func CredentialFilePath

func CredentialFilePath() string

CredentialFilePath returns the named-credential file location: .credentials.yaml in the golder state root ($GOLDER_HOME, else ~/.golder). An unresolvable root returns "".

func CredentialFilePermissionsWarn

func CredentialFilePermissionsWarn(path string) bool

CredentialFilePermissionsWarn reports whether the credential file's mode is more permissive than 0600 (group/other access), so the caller can warn without failing.

func CredentialNames added in v1.5.49

func CredentialNames(path string) ([]string, error)

CredentialNames lists stored references without exposing their values.

func DeleteCredential added in v1.5.49

func DeleteCredential(path, name string) error

DeleteCredential removes one named credential. A missing file or name is a no-op so a settings UI can make Remove idempotent.

func DisplayURL

func DisplayURL(raw string) string

DisplayURL omits credentials, query strings and fragments from UI output.

func EffectiveProtocol

func EffectiveProtocol(providerName, model, protocol string) string

EffectiveProtocol reports the wire protocol a run will actually speak for the given provider selection, model id, and explicit --protocol flag. It mirrors ResolveNamedProvider's effective-protocol computation without its driver construction or errors, so the startup banner can display the real wire format (a multi-protocol gateway such as opencode-go shows openai/resp_api for a deepseek model and openai/chat for anything else). An explicit protocol wins when it is valid and compatible with the provider; otherwise the wire comes from SelectWire — the model's native wire when the provider serves it, the provider's registered wire otherwise. Unknown providers, unknown protocols, and incompatible pairs yield "" so the caller falls back to its placeholder instead of displaying a misleading value.

func EnsureReasoningCatalog

func EnsureReasoningCatalog(ctx context.Context) error

EnsureReasoningCatalog refreshes the catalog when the in-memory or on-disk copy is missing or older than the TTL, and loads it into memory. Concurrent callers serialize; the loser of the race re-checks freshness and returns without a second fetch. Network errors leave the existing cache untouched.

func EnvCredentialVar

func EnvCredentialVar(provider string) (string, bool)

EnvCredentialVar reports the name of the environment variable holding a credential for a provider, without returning its value. Candidates come from the provider registry (EnvVars, in precedence order), then the generic <PROVIDER>_API_KEY fallback. A variable that is set but empty does not count. The name is safe to display; the value never leaves this call.

func FallbackModelCatalog added in v1.4.2

func FallbackModelCatalog(providerName string) []string

FallbackModelCatalog returns a copy of the bundled list for providerName, or nil when that provider has no snapshot. A copy keeps callers from mutating the table shared by every session.

func FetchProviderModels

func FetchProviderModels(ctx context.Context, providerName, baseURL, protocol, apiKey string) ([]string, error)

FetchProviderModels uses the same provider identity for routing as chat requests, even when baseURL points at a user-configured relay.

func FetchUsage added in v1.3.3

func FetchUsage(ctx context.Context, req UsageRequest) (string, error)

FetchUsage queries the account's quota and renders it as the text a slash command prints. It returns ErrUsageUnsupported (wrapped with the provider name) for a provider that has no endpoint.

func HTTPClientFor added in v1.3.0

func HTTPClientFor(name, baseURL string) *http.Client

HTTPClientFor returns the client a request to name/baseURL should use: the user's proxy when this provider is selected for proxying, a direct client otherwise. It exists so a caller outside this package — the decision-model reviewer — inherits the same routing rules as every provider request instead of building its own client and silently bypassing the user's proxy settings.

The returned client is shared per route; treat it as read-only.

func InferProviderFromModel

func InferProviderFromModel(model string) (string, bool)

InferProviderFromModel guesses the built-in provider name that serves a given model id, based on the id's well-known name prefix (e.g. "claude-*" → anthropic, "deepseek-*" → deepseek). This is what lets `golder -m claude-opus-4-8` reach the Anthropic API without the user spelling out the provider or its wire protocol (ResolveProvider step 3).

The mapping is deliberately conservative: only names that unambiguously identify a single built-in provider are inferred. Ambiguous families served by many gateways (notably "llama-*", "qwq-*", "gemma-*", "mixtral-*") are NOT inferred — they return ok=false so the caller falls through to its existing default (OpenRouter). The prefixes live in the registry (ProviderSpec.ModelPrefixes), in registry order; a test pins that no two providers claim overlapping prefixes, so the order only matters for determinism. Matching is case-insensitive.

func IsDecisionModel added in v1.3.2

func IsDecisionModel(model string) bool

IsDecisionModel reports whether a model id names a decision model — TypeSafe's System One (jev / systemone) — rather than a conversation model. Decision models answer typed questions and share nothing with the chat wires, so the run path refuses them; the judge reaches them through its own client. Some gateways list one beside their chat models, which is why the check is on the model, not on the provider.

func IsProviderName

func IsProviderName(id string) bool

IsProviderName reports whether id is exactly a built-in provider name (case-insensitive, surrounding whitespace tolerated).

func IsSpecialAuthProvider

func IsSpecialAuthProvider(spec ProviderSpec) bool

IsSpecialAuthProvider reports whether a provider spec needs the bespoke endpoint-construction / credential-validation handled by ResolveSpecialProvider, rather than the generic driver wiring. It matches the multi-parameter auth schemes (azure/aws/special) and the two Cloudflare providers (which keep a standard auth scheme but still compose their endpoint from env vars).

func KnownReasoningLevels

func KnownReasoningLevels(providerName, model string) []agentcore.ThinkingLevel

KnownReasoningLevels returns the catalog's explicit effort list for a model, or nil when the catalog has nothing definitive (unknown model, no effort option, or no reasoning). Unlike ReasoningLevels it never falls back to the family table, so callers can tell "models.dev says so" apart from "unknown" when annotating UI.

func LoadCredentialFile

func LoadCredentialFile(path string) (map[string]string, error)

LoadCredentialFile reads an encrypted named-credential file. Legacy plaintext YAML mappings remain readable and are migrated on the next save.

func ModelCatalogCacheKey

func ModelCatalogCacheKey(providerName, baseURL string) string

ModelCatalogCacheKey identifies a model catalog by provider and effective endpoint. The base URL is normalized (trimmed, trailing slash dropped) so the same endpoint always maps to one entry.

func ModelFamily added in v1.3.2

func ModelFamily(model string) string

ModelFamily groups model ids a vendor ships as one line: "deepseek-v4.1-flash" and "deepseek-v4-pro" are both the deepseek family. The probe uses it so one confirmed model answers for its siblings — a gateway routes a family the same way, and the first model asked pays for the answer. A routed id ("google/gemini-…") is grouped by its model half.

func ModelSeries added in v1.3.2

func ModelSeries(model string) string

ModelSeries groups a model id by the vendor that ships it — the "series" a person picks by. OpenAI's ids span gpt-, codex- and the o-series but are one series; everything else falls back to its leading name (glm, qwen, kimi, …).

func NeedsProxy

func NeedsProxy(name, rawURL string) bool

func NewOpenAIResponsesProvider

func NewOpenAIResponsesProvider(name, baseURL string, models []Model) *responsesDriver

NewOpenAIResponsesProvider builds a Responses API provider targeting baseURL. baseURL must be the fully resolved endpoint (e.g. https://api.openai.com/v1); the SDK appends the /responses path.

func NormalizeProtocol

func NormalizeProtocol(raw string) (string, error)

NormalizeProtocol maps a raw --protocol / protocol value to a canonical internal selector. Input is trimmed and lower-cased before matching. An empty value stays empty (unset → model-id heuristics). Recognized values normalize to ProtocolOpenAI, ProtocolOpenAIResponses, or ProtocolAnthropic. Any other value is an error naming the accepted set, so a typo surfaces to the caller for exit-code mapping instead of silently falling through.

func OrderModelIDs added in v1.3.2

func OrderModelIDs(ids []string) []string

OrderModelIDs sorts ids for a picker: grouped by series (alphabetically) and, inside a series, newest version first; ties fall back to the id so the order is stable across calls.

func ProtocolChoices added in v1.3.1

func ProtocolChoices(spec ProviderSpec) string

ProtocolChoices renders the protocol values an explicit --protocol may name for this provider — quoted, comma-separated — for a conflict error: the registered protocol, the Responses upgrade when it applies, and every declared wire variant.

func ProtocolLabel

func ProtocolLabel(raw string) string

ProtocolLabel maps a raw --protocol value to the human-facing label shown in the startup banner's Protocol row, so the displayed wire format matches what golder actually speaks. It differs from NormalizeProtocol in one deliberate way: the bare "openai" input is surfaced as "openai/chat", making the Chat Completions variant explicit rather than ambiguous. "openai/resp_api" and "anthropic" pass through as themselves.

An empty input returns empty (the banner then falls back to "—" or the provider name, so an unset protocol on a named/inferred provider is not mislabeled). An unrecognized value returns the trimmed input verbatim — the label is presentation-only and must never fail; a real typo is already rejected upstream by NormalizeProtocol during resolution.

func ProviderNames

func ProviderNames() []string

ProviderNames returns all built-in provider names in registry order.

func ProxySettings

func ProxySettings() (config.ProxyConfig, error)

ProxySettings returns the user's provider selection, preserving the old OpenCode defaults until the first explicit selection is saved.

func ProxyStatus

func ProxyStatus(name, baseURL string) string

func ProxyURL

func ProxyURL() string

ProxyURL is an address only; setting it never enables every provider.

func ReasoningLevels

func ReasoningLevels(providerName, model string) []agentcore.ThinkingLevel

ReasoningLevels returns the selectable reasoning levels for a model: the models.dev catalog's effort list when it has one, else the family ladder. An empty (nil) return means the catalog says the model does not reason, so there is nothing to select and the wire sends no effort field. The result is never mutated; callers must not modify it.

func ResolveBaseURL

func ResolveBaseURL(spec ProviderSpec, flagBaseURL string, env func(string) string) string

ResolveBaseURL determines the effective base URL for a selected provider, applying the base_url override precedence (US-004 / FR-8, FR-9). The first non-empty source wins, in this order:

  1. flagBaseURL — the explicit --base-url/-u flag (highest).
  2. provider-specific base-url env var(s) from spec.BaseURLEnvVars, in the order the registry declares them (e.g. AZURE_OPENAI_BASE_URL).
  3. the generic <PROVIDER>_BASE_URL env var, where <PROVIDER> is the provider name uppercased with '-' rewritten to '_' (e.g. zai-coding-cn → ZAI_CODING_CN_BASE_URL).
  4. spec.DefaultBaseURL — the registry default (lowest).

Values are trimmed of surrounding whitespace before the non-empty check, so a whitespace-only env var does not shadow a lower-precedence source. Environment lookups go through the injected env func so callers control the environment.

func ResolveCredentialReference

func ResolveCredentialReference(path, name string) (string, error)

ResolveCredentialReference loads the named-credential file and returns the secret stored under name. Config files should carry the name only; the literal secret exists here alone.

func SaveCredential added in v1.5.49

func SaveCredential(path, name, value string) error

SaveCredential atomically creates or replaces one named credential. The containing directory is private and the resulting file is always mode 0600. Secret values are never included in returned errors.

func ScrubEnv

func ScrubEnv(parent []string, allow map[string]string) []string

ScrubEnv filters a parent environment for a child process: every credential-shaped variable and every GOLDER_* internal is dropped, then the allow entries are appended (so a parent can hand a child exactly the one credential it needs, under a name that would otherwise be scrubbed). Malformed parent entries (no "=") are dropped. The result is safe to assign to os/exec's cmd.Env.

func ScrubsCredentialVar

func ScrubsCredentialVar(name string) bool

ScrubsCredentialVar reports whether an environment variable name is credential-shaped and should be stripped from child-process environments. All GOLDER_* internals are scrubbed too (they are golder's own state, not a child's business); PATH/HOME and other ordinary names never match.

func SessionHeaderValue

func SessionHeaderValue(providerName string, extra map[string]any) string

SessionHeaderValue returns the x-opencode-session value for a request, or "" when no header should be sent. Only providers whose name starts with "opencode" ever send it (mirroring opencode's own client, which gates on model.providerID.startsWith("opencode")); every other provider ignores the session id entirely.

func StartBackgroundReasoningCatalogRefresh

func StartBackgroundReasoningCatalogRefresh()

StartBackgroundReasoningCatalogRefresh refreshes a stale or missing catalog in a goroutine so startup never blocks on models.dev. It returns immediately and swallows errors: a failed refresh leaves the previous cache in place.

func StoreModelCatalog

func StoreModelCatalog(key string, ids []string)

StoreModelCatalog records a freshly fetched list for key.

func UsageHint added in v1.3.3

func UsageHint(providerName string) string

UsageHint is the explanation printed for a provider without an endpoint. It names what is supported and why a relay cannot answer the question.

func UsageSupported added in v1.3.3

func UsageSupported(name string) bool

UsageSupported reports whether a provider has a usage endpoint, so a caller can decide whether to try before it builds a credential.

func ValidateProxyURL

func ValidateProxyURL(raw string) error

func WireNative added in v1.3.2

func WireNative(spec ProviderSpec, model string) bool

WireNative reports whether the provider serves the model's native wire, which is the condition that makes SelectWire's choice unambiguous.

func WireReasoningEffort

func WireReasoningEffort(providerName, model string, level agentcore.ThinkingLevel) string

WireReasoningEffort maps the unified level onto the effort value to send for model. Both the Chat Completions and the Responses driver call it, so they agree by construction. providerName keys the models.dev catalog; an empty providerName simply skips the catalog lookup. An empty return means "omit the field": off/unset (or an unknown level) leaves the gateway's default behavior untouched, and a catalog model marked non-reasoning is never sent an effort at all.

func WithSessionExtra

func WithSessionExtra(extra map[string]any, sid string) map[string]any

WithSessionExtra returns a copy of extra carrying the session id under ExtraSessionID. It is a no-op (returns extra unchanged) when sid is empty or an id is already present, so an explicit value always wins and shared maps are never mutated.

Types

type APIKeyConfig

type APIKeyConfig struct {
	// Keys maps provider name → API key.
	Keys map[string]string `json:"keys"`
}

APIKeyConfig is the on-disk config-file shape: a map of provider name to API key. It is parsed from JSON and holds only static keys (OAuth lives in TokenSource). Values are secrets and must not be logged.

func LoadAPIKeyConfig

func LoadAPIKeyConfig(data []byte) (*APIKeyConfig, error)

LoadAPIKeyConfig parses an APIKeyConfig from JSON bytes (e.g. a config file).

type AnthropicDecoder

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

AnthropicDecoder is the stateful SSE decoder for the Anthropic Messages API. It implements the transport Decoder interface. It is not safe for concurrent use — the transport drives it from a single goroutine.

func NewAnthropicDecoder

func NewAnthropicDecoder() *AnthropicDecoder

NewAnthropicDecoder builds a fresh decoder for one streamed response.

func (*AnthropicDecoder) Decode

func (d *AnthropicDecoder) Decode(payload []byte) ([]StreamEvent, error)

Decode turns one Anthropic SSE data payload into zero or more StreamEvents.

func (*AnthropicDecoder) Finish

func (d *AnthropicDecoder) Finish() ([]StreamEvent, error)

Finish flushes a terminal done event if the stream ended without an explicit message_stop (e.g. a clean EOF mid-stream), so a partial response is still delivered rather than lost.

func (*AnthropicDecoder) Terminal added in v1.3.4

func (d *AnthropicDecoder) Terminal() bool

Terminal reports whether the wire's end marker has been decoded: message_delta carries the final stop_reason, and message_stop ends the stream. A transport error after either lost framing, not answer content.

type AssistantMessageEvent

type AssistantMessageEvent interface {

	// EventKind returns the delta discriminant.
	EventKind() string
	// contains filtered or unexported methods
}

AssistantMessageEvent is the sealed interface for provider stream deltas. The loop dispatches on EventKind; the raw event is also surfaced to consumers via MessageUpdateEvent.AssistantMessageEvent.

type AssistantMessageEventStream

AssistantMessageEventStream is the provider-level stream: deltas of type AssistantMessageEvent with a final AssistantMessage result. isComplete fires on done/error; extractResult takes the terminal event's message.

func NewAssistantMessageEventStream

func NewAssistantMessageEventStream(buffer int) *AssistantMessageEventStream

NewAssistantMessageEventStream builds a provider stream wired with the done/error completion callbacks.

func StreamRequest

StreamRequest runs cfg as a transport stream. Per the dual failure model it returns an error only when the very first request cannot be built or the initial connection can never be established; every runtime failure once streaming begins rides the returned stream as a terminal StreamErrorEvent.

type CompletionRequest

type CompletionRequest struct {
	// Model is the provider-specific model id to complete against.
	Model string
	// Context is the shaped request (system prompt, LLM-bound messages, tools).
	Context LlmContext
	// Config carries per-request options (API key, thinking level, extras).
	Config StreamConfig
}

CompletionRequest is the provider-agnostic input to StreamCompletion: the model id, the shaped LLM context, and per-request options.

type CredentialStatus

type CredentialStatus struct {
	// OAuth reports a registered OAuth token source (auto-refreshing).
	OAuth bool
	// Override reports an explicit key (--api-key).
	Override bool
	// EnvVar names the environment variable holding a value, or "" for none.
	EnvVar string
	// Config reports a key in the config-file layer.
	Config bool
}

CredentialStatus reports which credential sources hold a value for a provider, in resolution priority order. It is a presence probe: no secret value is retrieved or returned, only which layer can supply one.

func (CredentialStatus) Available

func (s CredentialStatus) Available() bool

Available reports whether any layer can supply a credential.

func (CredentialStatus) Source

func (s CredentialStatus) Source() string

Source returns a short, value-free label for the highest-priority layer that holds a credential, or "" when none does. Env sources return the variable name (safe to display), never the value.

type CredentialStore

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

CredentialStore resolves API keys per provider from three layers, in order: OAuth token source (if registered), environment variable, config file. It implements the LoopConfig.GetAPIKey shape via GetAPIKey.

It is safe for concurrent use.

func NewCredentialStore

func NewCredentialStore(config *APIKeyConfig) *CredentialStore

NewCredentialStore builds a store over an optional config file. A nil config is treated as empty.

func (*CredentialStore) ClearOverride added in v1.5.49

func (c *CredentialStore) ClearOverride(provider string)

ClearOverride removes one explicit static override so resolution falls back to OAuth, the inherited environment and config. It never affects another provider.

func (*CredentialStore) GetAPIKey

func (c *CredentialStore) GetAPIKey(ctx context.Context, provider string) string

GetAPIKey resolves the API key for a provider. Resolution order: OAuth token (refreshed on expiry) → explicit override (--api-key) → environment variable → config file. Returns "" when no credential is available. This matches LoopConfig.GetAPIKey so it can be assigned directly.

On OAuth refresh failure it falls back to override/env/config rather than returning a secret-bearing error; the empty return lets the caller fall back to a static key. It never logs secret values.

func (*CredentialStore) HasCredential

func (c *CredentialStore) HasCredential(ctx context.Context, provider string) bool

HasCredential reports whether any credential (OAuth/env/config) is available for a provider, without exposing the value.

func (*CredentialStore) RegisterOAuth

func (c *CredentialStore) RegisterOAuth(provider string, src *TokenSource)

RegisterOAuth registers an OAuth TokenSource for a provider. Once registered, GetAPIKey prefers the (auto-refreshing) OAuth token over static keys.

func (*CredentialStore) SetOverride

func (c *CredentialStore) SetOverride(provider, key string)

SetOverride records an explicit API key for a provider that wins over the environment variable and config file (but not a live OAuth token, which is auto-refreshed). It is the seam for a CLI --api-key flag: an empty key is ignored so a bare flag does not clobber env/config resolution.

func (*CredentialStore) Status

func (c *CredentialStore) Status(provider string) CredentialStatus

Status probes the credential layers for a provider without reading any secret into a caller-visible value. A nil store (or empty config) reports no config/override/OAuth source; the env layer is always probed.

type Decoder

type Decoder interface {
	// Decode turns one SSE data payload into zero or more StreamEvents. A
	// returned error is treated as a runtime stream failure (terminal error
	// event), never a panic.
	Decode(payload []byte) ([]StreamEvent, error)
	// Finish flushes any trailing state, returning a final batch of events.
	Finish() ([]StreamEvent, error)
}

Decoder is the per-provider stateful SSE payload decoder. The transport calls Decode for every complete SSE data payload (one event's worth of bytes) and Finish once the stream ends so the decoder can flush any buffered terminal event.

type GeminiDecoder added in v1.3.2

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

GeminiDecoder turns v1beta SSE chunks into StreamEvents. Each chunk carries complete parts (v1beta does not stream inside a part), so the decoder appends text/thought and realizes function calls as they arrive.

func NewGeminiDecoder added in v1.3.2

func NewGeminiDecoder() *GeminiDecoder

func (*GeminiDecoder) Decode added in v1.3.2

func (d *GeminiDecoder) Decode(payload []byte) ([]StreamEvent, error)

Decode turns one v1beta SSE payload into events.

func (*GeminiDecoder) Finish added in v1.3.2

func (d *GeminiDecoder) Finish() ([]StreamEvent, error)

Finish emits the terminal done event (idempotent).

func (*GeminiDecoder) Terminal added in v1.3.4

func (d *GeminiDecoder) Terminal() bool

Terminal reports whether a candidate carried finishReason. A transport error after that point lost HTTP framing, not answer content.

type LlmContext

type LlmContext struct {
	SystemPrompt string
	Messages     agentcore.MessageList
	Tools        []agentcore.AgentTool
}

LlmContext is the shaped request handed to a StreamFn: the system prompt, the LLM-bound messages (UI-only messages already filtered), and the tools.

type Model

type Model struct {
	// Provider is the provider name (e.g. "anthropic", "openai").
	Provider string `json:"provider"`
	// ID is the provider-specific model id (e.g. "claude-opus-4-8").
	ID string `json:"id"`
	// DisplayName is a human-friendly label; falls back to ID when empty.
	DisplayName string `json:"displayName,omitempty"`
	// ContextWindow is the maximum input+output token window, 0 if unknown.
	ContextWindow int `json:"contextWindow,omitempty"`
	// MaxOutputTokens is the max tokens the model may emit per response, 0 if
	// unknown.
	MaxOutputTokens int `json:"maxOutputTokens,omitempty"`
	// SupportsThinking reports whether the model exposes a reasoning/thinking
	// channel.
	SupportsThinking bool `json:"supportsThinking,omitempty"`
	// SupportsTools reports whether the model can call tools.
	SupportsTools bool `json:"supportsTools,omitempty"`
	// SupportsImages reports whether the model accepts image (multimodal) input.
	// When false, an image block in the request is reported as a hard error
	// rather than silently dropped, so the user learns the model cannot see it.
	SupportsImages bool `json:"supportsImages,omitempty"`
}

Model is provider-agnostic metadata describing a single model's identity and capabilities. Providers construct these; the loop/UI consume them.

type ModelWireRule added in v1.3.3

type ModelWireRule struct {
	Match string
	Wire  Wire
}

ModelWireRule pins a model family to one wire on a gateway. Match is a case-insensitive substring of the model id; the first matching rule wins.

type OAuthToken

type OAuthToken struct {
	AccessToken  string
	RefreshToken string
	Expiry       time.Time
}

OAuthToken is the result of an OAuth exchange/refresh. Values are secrets.

type OpenAIDecoder

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

OpenAIDecoder is the stateful SSE decoder for the OpenAI Chat Completions API and compatible gateways. It implements the transport Decoder interface and is not safe for concurrent use — the transport drives it from one goroutine.

func NewOpenAIDecoder

func NewOpenAIDecoder() *OpenAIDecoder

NewOpenAIDecoder builds a fresh decoder for one streamed response.

func (*OpenAIDecoder) Decode

func (d *OpenAIDecoder) Decode(payload []byte) ([]StreamEvent, error)

Decode turns one OpenAI SSE data payload into zero or more StreamEvents.

func (*OpenAIDecoder) DoneOnMarker added in v1.3.4

func (d *OpenAIDecoder) DoneOnMarker() bool

DoneOnMarker reports that [DONE] ends the Chat wire. The SSE reader consumes the marker before Decode, so the transport asks the decoder whether to end the stream there instead of waiting for the server to close.

func (*OpenAIDecoder) Finish

func (d *OpenAIDecoder) Finish() ([]StreamEvent, error)

Finish flushes a terminal done event if the stream ended without an explicit terminator, so a partial response is still delivered rather than lost.

func (*OpenAIDecoder) Terminal added in v1.3.4

func (d *OpenAIDecoder) Terminal() bool

Terminal reports whether the response's own end marker has been decoded: a chunk carrying finish_reason. A transport error after that point lost HTTP framing, not answer content, so the transport finishes the stream normally.

type Provider

type Provider interface {
	// Name returns the provider's identifier (matches Model.Provider).
	Name() string
	// Models lists the models this provider can serve.
	Models() []Model
	// StreamCompletion streams a completion for req. Per the dual failure model
	// it returns an error only for the earliest "cannot build the stream" case;
	// all runtime failures ride the returned stream as a terminal error event.
	StreamCompletion(ctx context.Context, req CompletionRequest) (*AssistantMessageEventStream, error)
}

Provider is the unified streaming interface implemented by every backend. It hides per-vendor differences behind a single AssistantMessageEvent stream.

func NewAnthropicProtocolProvider

func NewAnthropicProtocolProvider(name, baseURL, authScheme string, models []Model) Provider

NewAnthropicProtocolProvider builds a named Anthropic-Messages provider whose auth header follows the given registry AuthScheme. It is the target of an explicit --provider selection for any anthropic-protocol built-in (anthropic, minimax, minimax-cn, and — routed generically for now — bedrock/ cloudflare-ai-gateway): the driver identity is the provider's own name (so errors reference it), baseURL is the already-resolved endpoint (spec default or override), and authScheme selects the header shape (see anthropicAuthHeaderFor). Secret values are never logged.

func NewAnthropicProvider

func NewAnthropicProvider(baseURL string, models []Model) Provider

NewAnthropicProvider builds a provider that speaks the Anthropic Messages wire format directly (POST {baseURL}/messages), the target of an explicit --protocol=anthropic selection. baseURL defaults to the public Anthropic API when empty. Auth uses the Anthropic conventions: an x-api-key header plus the required anthropic-version header. The API key resolves by the "anthropic" provider name (ANTHROPIC_API_KEY / CLAUDE_API_KEY, or the --api-key override); secret values are never logged.

func NewBedrockProvider

func NewBedrockProvider(baseURL string, models []Model) Provider

NewBedrockProvider builds the Bedrock provider, reusing the Anthropic Messages decoder (Anthropic-on-Bedrock speaks the Messages wire format). baseURL defaults to a us-east-1 runtime endpoint when empty; real deployments pass the region-specific URL. Auth is a Bearer token (Bedrock API keys); SigV4 signing, when required, is layered by the caller's HTTP client.

func NewGeminiProtocolProvider added in v1.3.2

func NewGeminiProtocolProvider(name, baseURL, authScheme string, models []Model) Provider

NewGeminiProtocolProvider builds a named Gemini-v1beta provider. name is the provider's own name (so errors reference it), baseURL the already-resolved endpoint, and authScheme picks the header: x-goog-api-key for the first-party API, Bearer for gateways that authenticate their Google wire like the rest.

func NewNvidiaProvider

func NewNvidiaProvider(baseURL string, models []Model) Provider

NewNvidiaProvider builds the NVIDIA provider (hosted NIM, OpenAI-compatible, Bearer auth). baseURL defaults to the public integrate endpoint when empty. The API key is resolved by the "nvidia" provider name (NVIDIA_API_KEY); secret values are never logged.

func NewOllamaProvider

func NewOllamaProvider(baseURL string, models []Model) Provider

NewOllamaProvider builds the Ollama provider (local, OpenAI-compatible, no auth). baseURL defaults to the local daemon when empty.

func NewOpenAICompatibleProvider

func NewOpenAICompatibleProvider(baseURL string, models []Model) Provider

NewOpenAICompatibleProvider builds a generic OpenAI-compatible provider for an arbitrary gateway reached by baseURL (Bearer auth). It is the target of an explicit --protocol=openai selection: unlike the preset constructors it has no default endpoint (baseURL must be supplied) and carries the neutral provider name "openai", so an API key resolves from OPENAI_API_KEY (or the --api-key override bound to that name). Secret values are never logged.

func NewOpenAICompatibleProviderAs

func NewOpenAICompatibleProviderAs(name, baseURL string, models []Model) Provider

NewOpenAICompatibleProviderAs builds the same generic driver carrying the given provider name, so errors and per-provider request decoration (e.g. the x-opencode-session header) reference the selected provider instead of the neutral "openai". ResolveNamedProvider uses it for every OpenAI-wired registry entry; API-key resolution still keys on the returned provider name upstream and is unaffected.

func NewOpenRouterProvider

func NewOpenRouterProvider(baseURL string, models []Model) Provider

NewOpenRouterProvider builds the OpenRouter provider — the reference OpenAI-compatible gateway. baseURL defaults to the public endpoint when empty.

func ResolveNamedProvider

func ResolveNamedProvider(name, model, baseURL, protocol string, env func(string) string) (Provider, string, error)

ResolveNamedProvider builds the driver for an explicit --provider selection. It looks the name up in the built-in registry and constructs the wire driver for the effective protocol: "openai" → an OpenAI-compatible (Bearer) driver, "anthropic" → an Anthropic-Messages driver, "openai/resp_api" → the Responses driver, "gemini" → selected but not yet implemented. An explicit --protocol wins; otherwise the wire comes from SelectWire (the model's native wire when the provider serves it). The base URL follows the override precedence in ResolveBaseURL (--base-url > provider-specific env > generic <PROVIDER>_BASE_URL > spec default). The returned provider-name string is the spec name, so downstream API-key resolution reads the provider's own env var (spec.EnvVars).

Special providers with bespoke auth (azure/bedrock/vertex/cloudflare — AuthScheme aws/azure/special, or the cloudflare-* names) are routed to ResolveSpecialProvider, which validates their required env vars and composes the concrete endpoint (node #188).

func ResolveProvider

func ResolveProvider(model, baseURL, protocol, providerName string, env func(string) string) (Provider, string, error)

ResolveProvider maps a model id to a built-in provider. An explicit --provider name wins over every other rule: it selects a built-in provider from the registry and constructs the matching wire driver (see ResolveNamedProvider). When provider is empty, protocol and model-id heuristics apply as before.

When protocol is a non-empty explicit selection ("openai" or "anthropic") it wins over the model-id heuristics: the provider is built directly for that wire format against baseURL, which is how a user points golder at a self-hosted or third-party endpoint and says which protocol it speaks. An "anthropic" selection with no baseURL targets the public Anthropic API.

When protocol is empty, resolution falls back to model-id heuristics:

  1. A bare provider name (e.g. "zai") is canonicalized to that provider's DefaultModel (see CanonicalizeModel, issue #564).
  2. An "ollama/" prefix (or a base URL on the Ollama port) → local Ollama.
  3. An "nvidia/" prefix → NVIDIA NIM (strips the prefix for the wire id).
  4. Model-name inference: with no --base-url, a well-known model-name prefix (e.g. "claude-*", "deepseek-*") selects its first-party built-in provider via ResolveNamedProvider (see InferProviderFromModel).
  5. A bare provider name with no DefaultModel is an error naming the mismatch, rather than a silent OpenRouter fallback that fails later with a misleading missing-API-key error.
  6. Everything else → OpenRouter, the reference OpenAI-compatible gateway.

An unknown protocol value is an error, surfaced to the caller for exit-code mapping rather than silently falling back.

func ResolveSpecialProvider

func ResolveSpecialProvider(spec ProviderSpec, model, flagBaseURL string, env func(string) string) (Provider, error)

ResolveSpecialProvider validates the required parameters for a special-auth provider and constructs the matching wire driver against the composed base URL. flagBaseURL is the explicit --base-url override (highest precedence, wins over any composed default); env resolves environment variables (os.Getenv in production, a fake in tests). A missing required parameter yields an error naming exactly which env var is absent; no network request is made here.

func UnwrapProvider added in v1.3.3

func UnwrapProvider(p Provider) Provider

UnwrapProvider returns the concrete driver behind the wrappers resolution adds: the cut-stream retry (streamretry.go) and the adaptive wire fallback. Resolution tests and diagnostics that need the driver's own type can use it; runtime code should drive the Provider interface.

type ProviderSpec

type ProviderSpec struct {
	// Name is the canonical provider name (e.g. "deepseek", "zai-coding-cn").
	Name string
	// EnvVars lists the environment variables checked (in precedence order) for
	// this provider's API key. The first non-empty value wins.
	EnvVars []string
	// DefaultBaseURL is the provider's default API endpoint. It may be a template
	// (containing placeholders like {region}) for providers whose endpoint is
	// composed from additional parameters (Bedrock, Vertex, Cloudflare, Azure).
	DefaultBaseURL string
	// Protocol is the wire protocol the provider speaks: "openai" (OpenAI Chat
	// Completions) or "anthropic" (Anthropic Messages).
	Protocol string
	// AuthScheme names how credentials are attached: "bearer", "x-api-key",
	// "aws", "azure", or "special".
	AuthScheme string
	// WireVariants are additional wire protocols this gateway is known to serve
	// beyond its registered Protocol, each with the auth scheme that wire takes
	// (a gateway may authenticate its Messages endpoint differently from its
	// OpenAI-family one). An explicit --protocol naming a variant is legal and
	// builds the matching driver under this provider's own name, so per-provider
	// request decoration (the opencode session header, for one) still applies.
	// The registered Protocol stays the default: nothing changes for a user who
	// does not ask. Declare a variant only for a gateway whose other wire has
	// been verified — the registry's word is what turns "explicitly requested"
	// into "known to exist".
	WireVariants []WireVariant
	// ExtraHeaders are provider-specific headers attached to every request (may
	// be nil).
	ExtraHeaders map[string]string
	// BaseURLEnvVars lists provider-specific base-URL override environment
	// variables (e.g. AZURE_OPENAI_BASE_URL), in precedence order. May be empty;
	// the generic <PROVIDER>_BASE_URL convention is handled by callers.
	BaseURLEnvVars []string
	// ForceProxy is the legacy default selection before the user saves /proxy
	// settings. An explicit provider list replaces these defaults completely.
	ForceProxy bool
	// DecisionOnly marks an endpoint that is not a conversation model: it answers
	// the reviewer's typed questions (TypeSafe's System One) and nothing else. It
	// is listed apart from the chat providers and refused as a conversation
	// target, because selecting it would silently break every turn — the wire it
	// speaks is a decision API, not chat completions. It still appears in the
	// registry so its requests follow the same proxy routing as everything else
	// and its key is discovered by the usual credential resolution.
	DecisionOnly bool

	// ModelsDevID is this provider's key in models.dev's api.json (used by the
	// reasoning ladder catalog). Empty means Name.
	ModelsDevID string

	// ModelPrefixes lists the lowercase model-id prefixes that identify this
	// provider when only --model is given (see InferProviderFromModel). Keep
	// entries precise: a prefix that another provider's ids also carry would
	// shadow that provider, and registry order decides ties.
	ModelPrefixes []string

	// ReasoningLadders overrides the shared model-family ladder table
	// (reasoning.go) for this provider's models: the first entry whose Match is
	// a case-insensitive substring of the model id wins, before the family
	// table is consulted. Declare a ladder here only when the gateway diverges
	// from the model family's usual ladder (e.g. a gateway that rejects a level
	// the upstream API accepts). Empty means "no quirks".
	ReasoningLadders []ReasoningLadder

	// ModelWireRules overrides the shared model-family wire table for this
	// gateway: the first rule whose Match is a case-insensitive substring of the
	// model id wins. Declare one for a family the gateway does not serve on its
	// upstream vendor's usual wire (e.g. a domestic model with no Responses
	// endpoint yet). A rule is ignored when the gateway does not declare the
	// wire.
	ModelWireRules []ModelWireRule

	// DefaultModel is the model id a bare provider name resolves to (e.g.
	// "zai" → "glm-4.7", see CanonicalizeModel), so /model <provider> and
	// --model <provider> select a real wire id instead of sending the literal
	// provider name. Every built-in provider declares one (pinned by a registry
	// test), so a /provider switch always moves the model too. Empty remains
	// valid for a spec with no sensible default; a bare name is then reported as
	// a provider/model mismatch instead of guessing.
	DefaultModel string
}

ProviderSpec is the metadata describing one built-in provider. It is the single source of truth consumed by auth resolution, the --provider flag, base_url override handling, and per-provider wiring.

func LookupProviderSpec

func LookupProviderSpec(name string) (ProviderSpec, bool)

LookupProviderSpec returns the ProviderSpec for a provider name and whether it is a known built-in provider. The returned spec is a copy; mutating its slice or map fields is discouraged as they are shared with the registry.

func ProviderSpecs

func ProviderSpecs() []ProviderSpec

ProviderSpecs returns all built-in provider specs in registry (display) order. Callers must not mutate the returned specs' slice/map fields.

type ReasoningLadder

type ReasoningLadder struct {
	Match  string
	Ladder []agentcore.ThinkingLevel
}

ReasoningLadder is one model-family reasoning-effort rule: Match is a case-insensitive substring of the model id, Ladder the effort levels the gateway accepts for it, lowest to highest.

type ReasoningShape added in v1.3.1

type ReasoningShape int

ReasoningShape describes how a model's reasoning is switched on, as models.dev reports it in reasoning_options. The wire consequence differs per shape: a budget-shaped model takes the legacy thinking block (type "enabled" plus a token budget), an effort-shaped one takes the adaptive switch plus an effort level, and a toggle-shaped one takes the adaptive switch with no level.

const (
	// ReasoningShapeUnknown: the catalog says nothing definite (no entry, or no
	// control golder understands). Callers keep their historical wire shape
	// rather than guessing.
	ReasoningShapeUnknown ReasoningShape = iota
	// ReasoningShapeBudget: {"type":"budget_tokens","min":N}.
	ReasoningShapeBudget
	// ReasoningShapeEffort: {"type":"effort","values":[...]}.
	ReasoningShapeEffort
	// ReasoningShapeToggle: {"type":"toggle"} — on/off only.
	ReasoningShapeToggle
)

func ReasoningControl added in v1.3.1

func ReasoningControl(providerName, model string) (ReasoningShape, []agentcore.ThinkingLevel)

ReasoningControl reports the wire shape a model's reasoning takes and, for the effort shape, the levels it accepts (ascending, as the catalog lists them). It reads the same catalog ContextWindowFor does, so it never blocks on the network and returns ReasoningShapeUnknown for a model the catalog does not cover. A case-only difference in the model id still matches.

Precedence when models.dev lists several options — it does for models that kept their legacy controls (claude-opus-4-6 lists effort AND budget_tokens): budget_tokens wins, so a model that still advertises the legacy shape keeps the request golder has always sent. Effort answers when it is the model's modern control: claude-haiku-5-5 lists toggle+effort and rejects the legacy token-budget body outright ("thinking.type.enabled is not supported for this model ... use thinking.type.adaptive and output_config.effort", probed live).

type StreamConfig

type StreamConfig struct {
	APIKey        string
	ThinkingLevel agentcore.ThinkingLevel
	// Extra holds provider-specific options; opaque to the loop.
	Extra map[string]any
}

StreamConfig carries per-request settings for a StreamFn.

type StreamDoneEvent

type StreamDoneEvent struct{ Message agentcore.AssistantMessage }

StreamDoneEvent is the terminal success event; Message is the final response.

func (StreamDoneEvent) EventKind

func (StreamDoneEvent) EventKind() string

type StreamErrorEvent

type StreamErrorEvent struct {
	Message agentcore.AssistantMessage
	Err     error
}

StreamErrorEvent is the terminal failure event; Message carries the terminal assistant message (stopReason=error/aborted + errorMessage).

func (StreamErrorEvent) EventKind

func (StreamErrorEvent) EventKind() string

type StreamEvent

type StreamEvent = AssistantMessageEvent

StreamEvent is the transport-level alias for AssistantMessageEvent. Decoders produce these; the transport forwards them onto the stream. (Decision #25: reuse AssistantMessageEvent rather than a parallel event type.)

type StreamEvidence added in v1.3.3

type StreamEvidence struct {
	// Bytes is everything read from the body, keep-alives included.
	Bytes int64
	// Frames counts data payloads that reached the decoder.
	Frames int
	// KeepAlives counts SSE comment lines (": ping" and friends).
	KeepAlives int
	// LastFrame names the last line kind seen: "comment", "event", "blank",
	// "data", or "none" when nothing arrived.
	LastFrame string
}

StreamEvidence is what a watchdog saw while it waited. It is the difference between "the gateway keeps the socket warm and says nothing" and "nothing arrived at all": with keep-alives counted, the first is visible as bytes and zero content frames.

func (StreamEvidence) String added in v1.3.3

func (e StreamEvidence) String() string

String renders the evidence as the clause a failure sentence appends.

type StreamFn

type StreamFn func(ctx context.Context, model string, llm LlmContext, cfg StreamConfig) (*AssistantMessageEventStream, error)

StreamFn produces a provider stream for a model + shaped context. Per the contract it returns an error only for early "cannot build the stream" failures; all runtime failures ride the returned stream as error events.

func StreamFnFromProvider

func StreamFnFromProvider(p Provider) StreamFn

StreamFnFromProvider adapts a Provider to the loop's StreamFn contract so a Provider can drive streamAssistantResponse directly. The two failure models are identical, so the adaptation is a straight delegation.

type StreamNoticeEvent added in v1.3.3

type StreamNoticeEvent struct {
	// Kind is the notice family; StreamNoticeRetry is the only one today.
	Kind string
	// Provider names the gateway whose stream was cut.
	Provider string
	// Reason is the cut kind: "idle", "stall", "truncated", or "silent".
	Reason string
	// Window is the watchdog window that expired, for idle/stall; zero
	// otherwise.
	Window time.Duration
	// Attempt is the 1-based retry about to start, and MaxAttempts the budget it
	// is counting against; both are zero for notices that are not a retry.
	Attempt     int
	MaxAttempts int
	// Detail carries the watchdog's evidence ("12 keep-alives, last line: comment"),
	// so a front-end can show why the wait is happening without opening the log.
	Detail string
}

StreamNoticeEvent is a non-terminal progress note from the provider layer — something the user should see while the run continues, without becoming part of the assistant message. Today it carries the cut-stream retry: which provider was cut, why, and that a second attempt is starting. It is emitted by the retry wrapper itself (streamretry.go), not by a driver.

func (StreamNoticeEvent) EventKind added in v1.3.3

func (StreamNoticeEvent) EventKind() string

type StreamStartEvent

type StreamStartEvent struct{ Partial agentcore.AssistantMessage }

StreamStartEvent carries the initial (usually empty) partial message.

func (StreamStartEvent) EventKind

func (StreamStartEvent) EventKind() string

type StreamTextEvent

type StreamTextEvent struct{ Partial agentcore.AssistantMessage }

StreamTextEvent carries the partial message after a text delta.

func (StreamTextEvent) EventKind

func (StreamTextEvent) EventKind() string

type StreamThinkingEvent

type StreamThinkingEvent struct{ Partial agentcore.AssistantMessage }

StreamThinkingEvent carries the partial after a thinking delta.

func (StreamThinkingEvent) EventKind

func (StreamThinkingEvent) EventKind() string

type StreamToolCallEvent

type StreamToolCallEvent struct{ Partial agentcore.AssistantMessage }

StreamToolCallEvent carries the partial after a tool-call delta.

func (StreamToolCallEvent) EventKind

func (StreamToolCallEvent) EventKind() string

type StreamWatchdogError added in v1.3.3

type StreamWatchdogError struct {
	// Sink is errStreamIdle or errStreamStall.
	Sink error
	// Phase is StreamPhaseFirstToken or StreamPhaseStream.
	Phase string
	// Window is the budget that expired.
	Window time.Duration
	// Seen is what the guard observed.
	Seen StreamEvidence
}

StreamWatchdogError is a watchdog failure that carries its phase, window and evidence. It wraps the idle/stall sentinel, so every existing classification (isStreamCutErr, streamCutReason, the retry policy) keeps working unchanged.

func (*StreamWatchdogError) Error added in v1.3.3

func (e *StreamWatchdogError) Error() string

func (*StreamWatchdogError) Unwrap added in v1.3.3

func (e *StreamWatchdogError) Unwrap() error

type TokenSource

type TokenSource struct {

	// Refresh exchanges the current refresh token for a new access token. It
	// returns the new access token, its expiry, and (optionally) a rotated
	// refresh token. Required for a TokenSource to refresh; nil means the token
	// is static and never refreshed.
	Refresh func(ctx context.Context, refreshToken string) (OAuthToken, error)
	// Now is injectable for testing; defaults to time.Now.
	Now func() time.Time
	// Leeway refreshes the token this long before its actual expiry to avoid
	// racing the boundary. Defaults to 30s.
	Leeway time.Duration
	// contains filtered or unexported fields
}

TokenSource yields an access token, refreshing it when expired. It models an OAuth credential whose access token is short-lived (FR-15: getApiKey refreshes on expiry). It is safe for concurrent use.

func NewTokenSource

func NewTokenSource(initial OAuthToken, refresh func(ctx context.Context, refreshToken string) (OAuthToken, error)) *TokenSource

NewTokenSource builds a TokenSource seeded with an initial token and a refresh function. refresh may be nil for a static (never-expiring) token.

func (*TokenSource) Token

func (t *TokenSource) Token(ctx context.Context) (string, error)

Token returns a valid access token, refreshing it when expired. It errors if a refresh is needed but no Refresh func is set, or if Refresh fails. The returned error never contains the token value.

type TransportConfig

type TransportConfig struct {
	// Client is the HTTP client; defaults to http.DefaultClient when nil.
	Client *http.Client
	// NewRequest builds a fresh *http.Request for each connection attempt. It is
	// called once per connect (initial + reconnects) so retries never replay a
	// consumed body — the caller owns idempotent request construction.
	NewRequest func(ctx context.Context) (*http.Request, error)
	// Decoder converts SSE payloads to StreamEvents (required).
	Decoder Decoder
	// RetryBody, when non-nil, is consulted once for a 4xx rejection with the
	// upstream status and response body: returning true re-issues the request,
	// which the caller has corrected (its NewRequest closure reads whatever body
	// it now points at). It exists for a model newer than the provider catalog:
	// the gateway answers 400 naming the body shape it accepts, and one
	// re-issued request is cheaper than a failed turn — and than blocking a run
	// on a catalog fetch.
	RetryBody func(status int, body []byte) bool
	// MaxConnectRetries bounds connect-only retries (default 2).
	MaxConnectRetries int
}

TransportConfig configures a single StreamRequest run.

type UsageRequest added in v1.3.3

type UsageRequest struct {
	Provider string
	BaseURL  string
	APIKey   string
	// Now defaults to time.Now; tests set it so reset times render stably.
	Now time.Time
}

UsageRequest is one usage lookup: the provider identity, the effective base URL, and the credential the conversation is already using.

type Wire added in v1.3.2

type Wire string

Wire is one API dialect. The values are the wires golder speaks today (Responses, Messages, Chat Completions) or has a selector for (Gemini v1beta). The constant order is also the selection priority: a model that a provider can serve more than one way is reached the richest way first. The relative order is fixed — responses > messages > v1beta > chat — and a provider may serve any subset of it.

const (
	WireResponses Wire = "responses"
	WireMessages  Wire = "messages"
	WireGemini    Wire = "v1beta"
	WireChat      Wire = "chat"
)

func CachedWire added in v1.3.2

func CachedWire(providerName, model string) (Wire, bool, bool)

CachedWire returns the wire confirmed for (provider, model) — by the model itself, or by its family — from the process map or the persisted file, and whether a real request produced that answer (see storeServedWire).

func ModelWire added in v1.3.2

func ModelWire(model string) Wire

ModelWire is the model's native wire — the dialect its vendor publishes it on — independent of who serves it. It is deliberately a naming heuristic on the model id (the signal opencode itself uses): GPT, Codex, o-series, Grok and Muse are announced on the Responses API; Claude on Messages; Gemini on the Gemini v1beta API. The domestic families (DeepSeek, GLM, Kimi, Qwen, MiniMax, MiMo, LongCat, Step, Hy) all publish a Responses endpoint today — DeepSeek first, the rest following — so they are Responses-native too; what a *given gateway* actually serves is settled by the lazy probe, not by guessing here. Anything else gets Chat, the dialect every OpenAI-compatible server speaks.

func ProbeWire added in v1.3.2

func ProbeWire(ctx context.Context, client *http.Client, baseURL, apiKey, model string, candidates []Wire, timeout time.Duration) (Wire, error)

ProbeWire asks an endpoint which of the provider's declared wires it actually serves for a model. It is the answer for the case the static tables cannot describe: a gateway that translates a model onto another wire, or serves a family on several. Candidates are tried in the caller's order with one minimal request each; the first one that answers with a 2xx AND a body shaped like that wire's response wins. A 2xx alone is not enough: a gateway's web UI answers unknown paths with 200 + HTML, which is how a root-level /messages used to be mistaken for a working Anthropic endpoint.

Only a rejection settles a question. A candidate that does not answer within timeout has not been refused — it may be a working wire behind a slow relay — so the probe stops there without an answer rather than letting a faster wire behind it claim the model. The caller keeps its static choice, and a wire that really is unsupported is discovered by the request itself (see fallback.go, which records a wire only after that wire served a real request).

client carries the routing the caller's own requests take (HTTPClientFor), so the probe measures the endpoint the run will reach and not a second route. It is copied before the probe's timeout is applied, because a client is shared per route. Nil means a direct client — the explicit choice every provider request makes, so an unproxied endpoint does not inherit the shell's HTTP(S)_PROXY.

The probe is deliberately tiny — a one-token completion, no tools — so the cost is one cheap request per candidate. It is opt-in (see selectWireWithProbe): golder only pays for it when GOLDER_WIRE_PROBE is set, because a run that never needed the answer should not spend it.

func ProviderWires added in v1.3.2

func ProviderWires(spec ProviderSpec) []Wire

ProviderWires is the set of wires a provider serves: its registered protocol, every declared wire variant, and — for an OpenAI-wired provider — the Responses upgrade every such gateway is assumed to serve (the same assumption AllowsProtocol makes). The result is in WirePriority order. It is a capability list, not a rule about models; SelectWire decides which one a run uses.

func SelectWire added in v1.3.2

func SelectWire(spec ProviderSpec, model string) Wire

SelectWire picks the wire a run speaks:

  1. the model's native wire, when the provider serves it;
  2. otherwise the highest-priority wire the provider serves — a gateway that offers only Chat reaches a Responses-native model over Chat, which is exactly what translation gateways do.

An explicit --protocol is not handled here: the resolver validates it with AllowsProtocol and keeps the user's choice verbatim.

type WireReporter added in v1.3.3

type WireReporter interface {
	CurrentWire() Wire
}

WireReporter is implemented by providers (and the wrappers around them) that can name the wire currently serving requests. The status bar reads it to show the protocol actually in use, which is not always the resolved guess: the wire fallback can move a model to another endpoint mid-session, and the reported value changes with it.

type WireVariant added in v1.3.1

type WireVariant struct {
	Protocol   string
	AuthScheme string
	// BaseURL is that wire's own endpoint when it differs from the provider's
	// registered base (opencode-go serves Gemini under …/google/v1beta).
	// Empty means "use the provider's base".
	BaseURL string
}

WireVariant is one extra wire a gateway serves besides its registered Protocol: the protocol selector an explicit --protocol may name, and the auth scheme that wire expects.

Jump to

Keyboard shortcuts

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