{"modulePath":"github.com/memcode-ai/memcode","version":"v0.56.16","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package provider\n\nPackage provider defines the (model, embedding, edit-apply) boundaries the engine talks to, plus the default Claude model tiers. v1 wires NO implementations here — these are the seams the model-backed phases (understand, learn, agent) plug into. Defaults are recorded now so the tiered strategy is explicit and configurable.\n\n## Constants\n\n```go\nconst (\n\t// EnvEndpointURL is the FULL compat base including any path prefix\n\t// (Groq-style), e.g. http://localhost:11434/v1 — {base}/chat/completions is\n\t// the turn endpoint. Setting it (with no memcode token) puts the CLI in\n\t// endpoint mode.\n\tEnvEndpointURL = \"MEMCODE_ENDPOINT_URL\"\n\t// EnvEndpointKey is the endpoint's optional bearer credential; unset sends\n\t// no Authorization header (a keyless local endpoint).\n\tEnvEndpointKey = \"MEMCODE_ENDPOINT_KEY\"\n\t// EnvEndpointModel is the endpoint's INITIAL model id — used until a /model\n\t// choice is remembered for the endpoint (config wins once one exists).\n\tEnvEndpointModel = \"MEMCODE_ENDPOINT_MODEL\"\n\t// EnvEndpointContextWindow / EnvEndpointMaxOutput declare the endpoint's\n\t// token limits (optional): the context window input+output share, and the\n\t// largest output it accepts. Unset = unknown; requests go out unclamped.\n\tEnvEndpointContextWindow = \"MEMCODE_ENDPOINT_CONTEXT_WINDOW\"\n\tEnvEndpointMaxOutput     = \"MEMCODE_ENDPOINT_MAX_OUTPUT\"\n)\n```\n\n```go\nconst (\n\tEnvAPIURL   = \"MEMCODE_API_URL\"\n\tEnvAPIToken = \"MEMCODE_API_TOKEN\"\n\n\t// TokenPrefix marks org-scoped gateway keys minted by /login — the ONLY\n\t// kind of credential that exists. Its presence in the stored token IS the\n\t// local logged-in signal (zero network at boot).\n\tTokenPrefix = \"memcode_\"\n\n\t// DefaultAPIURL is the production memcode gateway.\n\tDefaultAPIURL = \"https://code.memcode.ai\"\n)\n```\n\\--- gateway connection ---\n\nThe CLI has exactly ONE backend: the memcode gateway (cli → api → llms). Hosted provider keys, BYOK storage, and metering live SERVER-side in the api module; the wire adapters and routing policy ship in this binary (the CLI is the agent — shared providers/\\*, llm selection). The endpoint defaults to production; MEMCODE\\_API\\_URL is a DEV OVERRIDE for pointing at a locally running gateway (\\`go run ./api\\`), never a requirement.\n\n```go\nconst EnvCredentialSource = \"MEMCODE_CREDENTIAL_SOURCE\"\n```\nEnvCredentialSource names the explicitly-selected credential source. Empty = own exported keys only (the ambient path). Set to a subscription source (\"copilot\", …) — by the first-run wizard or by hand — to activate a login that lives in another tool's files/keychain, which never auto-activates.\n\n```go\nconst EnvCredentials = \"MEMCODE_CREDENTIALS\"\n```\nEnvCredentials is the ordered CONSENT LIST of attached credential sources (\"claude,codex\"). It replaces the single-value MEMCODE\\_CREDENTIAL\\_SOURCE: with subscriptions as family lanes there is no \"the\" source anymore — every listed source the user has consented to attaches as a lane. The old var still reads as a one-item list and is migrated (rewritten to this var, old one deleted) the next time \\`memcode auth\\` writes; consent semantics are unchanged — a subscription NEVER activates from ambient state alone.\n\n## Variables\n\n```go\nvar ErrGatewayOnly = errors.New(\"not available on a custom endpoint — this needs the memcode gateway (run /login)\")\n```\nErrGatewayOnly is returned by the side-channel capabilities (websearch / webfetch / advisor) in endpoint mode: they are memcode gateway services with no compat equivalent. Callers already degrade on error (webfetch falls back to the local fetch; the web\\_search tool def isn't advertised off-gateway).\n\n```go\nvar ErrNoEndpointModel = errors.New(\"no model selected for this endpoint — pick one with /model, or set MEMCODE_ENDPOINT_MODEL\")\n```\nErrNoEndpointModel is returned when a turn reaches an endpoint transport with no model anywhere (no session pin, no endpoint default).\n\n```go\nvar ErrNotLoggedIn = fmt.Errorf(\"not signed in — run /login to connect to memcode.ai\")\n```\nErrNotLoggedIn is returned by the lazy provider for any model-backed call made before /login. The TUI shows its own gate before dispatch; this is the backstop for any path that slips through.\n\n## Functions\n\n```go\nfunc APITokenSource() string\n```\nAPITokenSource reports where the gateway token resolves from, for diagnostics (e.g. \\`memcode doctor\\`) — \"environment\" or the global config path — or \"\" if none is found. Call it BEFORE LoadDotEnv so an already-loaded file isn't misreported as the process environment.\n\n```go\nfunc APIURL() string\n```\nAPIURL resolves the gateway endpoint: the MEMCODE\\_API\\_URL override if set, otherwise production.\n\n```go\nfunc AttachedSources() []string\n```\nAttachedSources returns the ordered, canonicalized, deduplicated consent list. MEMCODE\\_CREDENTIALS wins; the legacy single-value var reads as a one-item list so pre-migration installs keep working. Unknown tokens are dropped (the boot warning surfaces them via SelectedSourcesUnresolved's resolution pass, not here).\n\n```go\nfunc BackendServingLabel(backend string) string\n```\nBackendServingLabel renders the per-turn \"via X\" for a lane-stamped backend, \"\" for gateway/exclusive stamps (callers fall back to \"memcode\" or the exclusive endpoint's name).\n\n```go\nfunc ByokDelete(ctx context.Context, providerID string) error\n```\nByokDelete removes the user's key for a provider.\n\n```go\nfunc ByokList(ctx context.Context) (cloudclient.ByokKeys, error)\n```\nByokList fetches the provider roster + the user's masked key rows.\n\n```go\nfunc ByokPut(ctx context.Context, providerID, key string) (cloudclient.ByokPutResult, error)\n```\nByokPut stores/replaces the user's key for a provider (gateway live-probes it first). The caller is responsible for redacting the key from any UI/log surfaces BEFORE calling.\n\n```go\nfunc ByokValidate(ctx context.Context, providerID string) (bool, string, error)\n```\nByokValidate live-probes the stored key.\n\n```go\nfunc CatalogKnows(id string) bool\n```\nCatalogKnows reports whether the embedded catalog has a real entry for a model id — the cost-display gate: uncataloged (local) models show token counts, not a $ figure priced off the defaults card.\n\n```go\nfunc CatalogWindow(id string) int\n```\nCatalogWindow returns the embedded catalog's context window for a model id it KNOWS (exact id or label) — 0 otherwise. Endpoint mode keys on it for the /model picker's window column and the pin's meter sizing: known ids get real numbers, unknown local models get blank, never a made-up default.\n\n```go\nfunc ComposedForEstimate(r wire.Request) wire.Request\n```\nComposedForEstimate returns r as the transport will send it, with the doctrine composed into the system prompt, for sizing a request before dispatch. A request that is already composed, or fails to compose, comes back unchanged.\n\n```go\nfunc ConventionalKey(base string) string\n```\nConventionalKey returns the standard env var's value for a known provider host, \"\" for local/unknown endpoints (a keyless Ollama stays keyless).\n\n```go\nfunc DefaultModel(t Tier) string\n```\nDefaultModel returns the default model id for a tier.\n\n\tplanner, reviewer        -\u003e Sol    (hard reasoning — the frontier tier)\n\tcoder, synthesizer       -\u003e Terra  (the everyday default)\n\tclassifier               -\u003e Luna   (the reducer's cheap, frequent router)\n\n```go\nfunc DisplayName(id string) string\n```\nShortModel maps a model id back to its short alias for display (the inverse of ResolveAlias). Unknown ids are returned unchanged. DisplayName is the human name of a model for the footer and the served-by line (\"Gemini 4 Carbon\", \"Opus 5.5\", \"Grok 4.7\") from the catalog, falling back to ShortModel for ids the catalog doesn't name.\n\n```go\nfunc EffectiveModel(s string) string\n```\nEffectiveModel resolves a configured tier value (alias or model id) to the model REQUESTED of the gateway. Model policy is the gateway's call — it may re-target a request at the self-hosted pool — but the requested id still matters: it names the tier intent and prices the counterfactual.\n\n```go\nfunc EndpointModels(ctx context.Context, ep Endpoint) []string\n```\nEndpointModels lists the endpoint's model ids via GET {base}/models (part of the compat standard — OpenAI, Groq, Ollama, LM Studio, vLLM all serve it). When the base was configured WITHOUT its /v1 path prefix, {base}/models 404s on most local runtimes — one retry at {base}/v1/models covers that without the CLI ever rewriting the configured base for turns. Errors (endpoint lacks the route entirely) return nil — the /model picker then falls back to the config list / free-text entry.\n\n```go\nfunc EndpointName(base string) string\n```\nEndpointName derives a short display name from a base URL — the host (with port) for a valid URL, the raw string otherwise. Config-listed endpoints carry their own names; this covers the env-defined ones.\n\n```go\nfunc ErrNotConnected() error\n```\nErrNotConnected is the no-backend error. The FIRST thing a fresh install hits, so it leads with the command that fixes it — \\`memcode login\\` opens the browser and writes the token itself; the env-file and local-endpoint details are the advanced paths, not the onboarding path.\n\n```go\nfunc ExplicitCredentialSource() bool\n```\nExplicitCredentialSource reports the user has actively selected a credential source (memcode auth …) — the consent signal that lets a subscription login outrank other backends.\n\n```go\nfunc FriendlyError(err error) string\n```\nFriendlyError renders a model-call failure for a person: a plain lead keyed on the HTTP status, then the provider's own message pulled out of the JSON body (\"Rate limited by the provider (HTTP 429): Number of request tokens has exceeded your per-minute rate limit\") instead of the SDK's raw \\`POST \"https://…\": 429 Too Many Requests {\"type\":\"error\",…}\\` dump. Errors that already speak plainly (ErrNoLane, ErrLaneExhausted, sentinels) pass through. Nothing parseable ⇒ the raw text, whitespace-collapsed and bounded.\n\n```go\nfunc GlobalEnvPath() string\n```\nGlobalEnvPath returns the user-level secrets file: $XDG\\_CONFIG\\_HOME/memcode/.env if XDG\\_CONFIG\\_HOME is set, otherwise ~/.config/memcode/.env. Returns \"\" if no home directory can be determined.\n\n```go\nfunc LaneBackendVendor(backend string) (vendor, kind string, ok bool)\n```\nLaneBackendVendor maps a per-turn Backend stamp to its lane identity: (\"anthropic\",\"sub\",true) for \"claude-sub\", (\"openai\",\"ownkey\",true) for \"ownkey:openai\", ok=false for gateway/exclusive stamps.\n\n```go\nfunc LoadDotEnv()\n```\nLoadDotEnv loads KEY=VALUE pairs into the process environment WITHOUT overriding variables already set, from the user-global file only (GlobalEnvPath, e.g. ~/.config/memcode/.env).\n\nThe working repo's .env is DELIBERATELY not read. That file belongs to the project, not the agent, and honoring it meant a cloned repo could silently hijack the agent: its MEMCODE\\_API\\_URL/MEMCODE\\_ENDPOINT\\_URL would redirect the whole conversation to an arbitrary endpoint, and an app's OPENAI\\_API\\_KEY meant for the app would get picked up and billed by the agent. Credentials come from the exported environment or the memcode-owned global file, never from the repo being worked on.\n\nPrecedence: real exported env \u003e global file. Best-effort: a missing file is not an error. Secrets live in the gitignored global env file, never in .memcode config or the database.\n\n```go\nfunc Lookup(key string) string\n```\nLookup returns key from the environment, else from the global file, without touching the environment: for library code that needs one setting (the API token) and must not change what the rest of the process sees.\n\n```go\nfunc OwnKeyVendor(baseURL string) (string, bool)\n```\nOwnKeyVendor reports the vendor name when a base URL is a direct-provider host memcode dials with an exported key (\"anthropic\", \"openai\"), ok=false for a generic/local endpoint. Lets diagnostics name an own-key backend for what it is instead of calling it a nameless \"custom endpoint\".\n\n```go\nfunc PinFrom(ctx context.Context) string\n```\nPinFrom returns the session's pinned model stamped by WithPin, or \"\".\n\n```go\nfunc ResolveAlias(s string) string\n```\nResolveAlias maps the short aliases (opus|sonnet|haiku|sol|terra|luna) to model ids. The Claude aliases (opus|sonnet|haiku) are kept for backward compat with existing configs; the GPT-5.6 aliases (sol|terra|luna) are the current tiers. Any other value is treated as a literal model id and returned unchanged.\n\n```go\nfunc SelectedSourceUnresolved() (string, bool)\n```\nSelectedSourceUnresolved reports a credential source the user explicitly selected that did NOT resolve to a live login (expired token, signed out of the host tool). The TUI surfaces this at boot: serving silently falling back to another credential is exactly the failure users cannot see.\n\n```go\nfunc SelectedSourcesUnresolved() []string\n```\nSelectedSourcesUnresolved lists attached sources whose login did NOT resolve (expired token, signed out of the host tool). Boot warns per source: serving silently missing a consented lane is the failure users cannot see.\n\n```go\nfunc ServingLabel(name string) string\n```\nServingLabel maps an endpoint's internal name to the word a user chose in the auth wizard — the \"via X\" in the TUI's served-by line. Empty for endpoints that aren't a subscription source (their Name already reads fine).\n\n```go\nfunc SetRetryNotify(prov ModelProvider, fn func(attempt int, err error, delay time.Duration))\n```\nSetRetryNotify wires a retry-notify callback into the gateway transport (if the provider is the SDK client, which it is in production). No-op for any provider that doesn't support it (test fakes, a future local backend) — those just get silent retry. This is the seam the runtime uses to surface \"⊙ retrying…\" in the TUI without coupling itself to the SDK's concrete client type.\n\n```go\nfunc ShortModel(id string) string\n```\n\n```go\nfunc SourceVendor(source string) string\n```\nSourceVendor returns the catalog vendor a canonical source serves, \"\" for unknown sources.\n\n```go\nfunc SubscriptionEndpointName(name string) bool\n```\nSubscriptionEndpointName reports whether an endpoint name is one of the wizard-selected subscription sources (vs a custom endpoint or own key).\n\n```go\nfunc WithPin(ctx context.Context, label string) context.Context\n```\nWithPin stamps the session's pinned model on ctx so web search/fetch ride the same credential lane as the session's turns: on a Claude subscription they run on it instead of the gateway's side channel.\n\n## Types\n\n```go\ntype Advisor interface {\n\tAdvise(ctx context.Context, question, effort string) (string, error)\n}\n```\nAdvisor is an optional capability: a provider that can ask a second-opinion model (a different vendor) to advise the best path forward. Type-assert for it.\n\n```go\ntype Applier interface {\n\tApply(ctx context.Context, path string, edit Edit) (ApplyResult, error)\n}\n```\nApplier merges an edit into a file. v1 = anchored search/replace; a fast-apply model can be swapped in later without touching callers.\n\n```go\ntype ApplyResult struct {\n\tDiff    string\n\tApplied bool\n}\n```\nApplyResult reports the outcome of applying an Edit.\n\n```go\ntype Connector interface {\n\tConnected() bool\n\tSetCredentials(url, token string)\n}\n```\nConnector is the credential-swap capability the TUI needs from a provider: present on \\*Lazy, absent on test fakes (which count as connected). This is the seam runtime.Session.Connected forwards through — and since Phase C, Connected means hosted-OR-endpoint (any usable backend); Endpointer (above) is the sibling seam that says WHICH.\n\n```go\ntype Edit struct {\n\tOldString  string\n\tNewString  string\n\tReplaceAll bool\n}\n```\nEdit is an anchored search/replace edit (see the Agent Runtime Contract).\n\n```go\ntype Endpoint struct {\n\tName    string   // short display name (\"ollama\", or the host:port for env endpoints)\n\tBaseURL string   // full compat base incl. any path prefix (http://localhost:11434/v1)\n\tKey     string   // optional bearer; \"\" = no Authorization header\n\tModel   string   // session model id (\"\" = resolve via GET {base}/models or /model)\n\tModels  []string // optional curated picker list / allowlist from config\n\n\t// Headers are extra request headers a subscription backend requires to\n\t// accept the turn (a Copilot endpoint's Editor-Version / integration id).\n\t// Set only by the credential sources; empty for a normal endpoint. Carried\n\t// through to the compat transport.\n\tHeaders map[string]string\n\n\t// Tokens, when set, supplies a LIVE credential that supersedes Key per\n\t// request (a Claude subscription token expires mid-session or is replaced\n\t// by a Claude Code re-auth). nil for static keys.\n\tTokens TokenSource\n\n\t// Limits are the endpoint's declared token budgets (env or config), the\n\t// default for every model it serves; ModelLimits overrides per model id.\n\t// Zero fields are unknown. The runner fits each request inside them before\n\t// dispatch, so a small-window server never gets a request it must reject.\n\tLimits      Limits\n\tModelLimits map[string]Limits\n}\n```\nEndpoint describes one arbitrary OpenAI-compatible endpoint. Resolved from the environment (EndpointFromEnv) or from the project config's named endpoint list (config.ResolveEndpoint merges the two).\n\n```go\nfunc EndpointFromEnv() (Endpoint, bool)\n```\nEndpointFromEnv resolves the env-configured endpoint (the dotenv chain loads MEMCODE\\_ENDPOINT\\_\\* like every other knob). ok=false when no URL is set.\n\n```go\nfunc ResolveCredentialSource(name string) (Endpoint, bool)\n```\nResolveCredentialSource reports whether a named subscription source resolves to a live login right now. Used by the autonomous task runner as a PREFLIGHT: a runtime that cannot authenticate is a runtime failure and may be swapped, but only before any work has been done.\n\nIt resolves rather than merely checking presence, because a stale token file is present and useless, and finding that out after spawning a child is finding it out too late.\n\n```go\nfunc (e Endpoint) LimitsFor(model string) Limits\n```\nLimitsFor resolves the budget for model: its per-model entry, field by field over the endpoint default, with the catalog's window for a model the catalog knows when nothing was declared.\n\n```go\ntype Endpointer interface {\n\tEndpoint() (Endpoint, bool)\n}\n```\nEndpointer is the endpoint-mode introspection capability, sibling to Connector: present on \\*Lazy (and the raw conn), absent on test fakes. The runtime forwards it (Session.Endpoint) so the TUI can drive the /model picker, cost display, and capability gating off the ACTIVE backend rather than env sniffing.\n\n```go\ntype ErrLaneExhausted struct {\n\tLane        LaneInfo\n\tStatus      int\n\tResetAt     time.Time // zero when unknown\n\tCanFallback bool      // a gateway base exists for a consented reissue\n\tErr         error\n}\n```\nErrLaneExhausted: a lane's credential hit its quota/rate window (HTTP 429/402 after the adapter's own retries). The provider NEVER reroutes on its own — the runtime raises the fallback-choice card and, on consent, reissues via CompleteOnGateway/StreamOnGateway.\n\n```go\nfunc (e *ErrLaneExhausted) Error() string\n```\n\n```go\nfunc (e *ErrLaneExhausted) Unwrap() error\n```\n\n```go\ntype ErrNoLane struct {\n\tModel    string\n\tVendor   string\n\tAttached []LaneInfo\n}\n```\nErrNoLane: the turn's model belongs to a vendor with no serving path — no gateway login and no lane for that family. Terminal for the fallback walk; the message carries the remedies.\n\n```go\nfunc (e *ErrNoLane) Error() string\n```\n\n```go\ntype LaneInfo struct {\n\tVendor string // \"anthropic\" | \"openai\" | \"grok\"\n\tName   string // endpoint name: \"claude-sub\", \"codex\", \"ownkey:anthropic\", …\n\tKind   string // \"sub\" | \"ownkey\"\n\tModel  string // the lane's default model id\n}\n```\nLaneInfo is the UI/ledger surface of an attached lane.\n\n```go\ntype Laner interface {\n\tLanes() []LaneInfo\n\tGatewayPresent() bool\n}\n```\nLaner is the policy-side seam over the lane set: selection consults it to prefer $0 subscription vendors and to clamp signed-out resolution to attached families.\n\n```go\ntype Lazy struct {\n\t// contains filtered or unexported fields\n}\n```\nLazy is a ModelProvider whose backend connection may be ABSENT at construction: the TUI always opens (mandatory-login boot), and /login swaps real credentials in without a restart. All capability methods forward to the inner connection (the compat turn transport + the gateway side-channel client, or the compat transport alone in endpoint mode — see wire.go), or fail with ErrNotLoggedIn while signed out. Safe for concurrent use (atomic pointer swap).\n\n```go\nfunc NewFromEnvLazy(endpoints ...Endpoint) *Lazy\n```\nNewFromEnvLazy constructs the lazy provider. Backend selection (one-wire Phase C): a real login (a memcode\\_-prefixed org key — the local logged-in signal) → the hosted gateway; else a configured endpoint (the caller's resolved config endpoint, or MEMCODE\\_ENDPOINT\\_URL) → that endpoint on the compat transport; else family lanes from attached subscriptions / own keys; else signed out — the TUI opens on the sign-in card. Unlike NewFromEnv it never fails — signed-out is a valid state for the TUI.\n\n```go\nfunc (l *Lazy) Advise(ctx context.Context, question, effort string) (string, error)\n```\n\n```go\nfunc (l *Lazy) ClearCredentials()\n```\nClearCredentials drops the gateway client (the /logout path). With a custom endpoint configured the connection falls BACK to it — the same backend selection boot applies — so signing out of memcode returns to endpoint mode, not dead air; otherwise subsequent model calls fail with ErrNotLoggedIn until the next SetCredentials.\n\n```go\nfunc (l *Lazy) Complete(ctx context.Context, r wire.Request) (wire.Response, error)\n```\n\n```go\nfunc (l *Lazy) CompleteOnGateway(ctx context.Context, r wire.Request) (wire.Response, error)\n```\nCompleteOnGateway forces a turn onto the gateway base, bypassing lane dispatch — the consented-fallback path after an ErrLaneExhausted card.\n\n```go\nfunc (l *Lazy) Connected() bool\n```\nConnected reports whether a usable backend is present — hosted gateway credentials, a configured custom endpoint, or at least one family lane.\n\n```go\nfunc (l *Lazy) Endpoint() (Endpoint, bool)\n```\nEndpoint reports the ACTIVE custom endpoint, ok=false when hosted or signed out. This is the one backend-mode signal the runtime/TUI key on (via Session.Endpoint) — capability gating, the /model picker, cost display.\n\n```go\nfunc (l *Lazy) GatewayPresent() bool\n```\nGatewayPresent reports a live hosted-gateway base (side channels exist). False in exclusive-endpoint mode and when signed out.\n\n```go\nfunc (l *Lazy) Lanes() []LaneInfo\n```\nLanes reports the attached family lanes for UI/policy consumers (the provider.Laner seam). Empty in exclusive-endpoint mode and plain hosted.\n\n```go\nfunc (l *Lazy) PlannedBackend(pin string) string\n```\nPlannedBackend reports the provenance stamp the next turn on pin routes to: a lane's backendName (\"claude-sub\", \"ownkey:openai\", …), \"\" for the base (gateway or exclusive endpoint) or no serving path. It runs route itself — pure, no dispatch — so the prediction can never drift from real routing.\n\n```go\nfunc (l *Lazy) SetCredentials(url, token string)\n```\nSetCredentials swaps in a fresh gateway connection (the /login success path). A retry-notify callback registered before login is re-applied.\n\n```go\nfunc (l *Lazy) SetRetryNotify(fn func(attempt int, err error, delay time.Duration))\n```\nSetRetryNotify satisfies the retryNotifier seam: applied to the current client if present, and remembered for the client /login constructs later.\n\n```go\nfunc (l *Lazy) SignedIn() bool\n```\nSignedIn reports whether the memcode gateway itself is connected: a hosted client, not a custom endpoint and not an attached subscription lane. A Claude login keeps Connected true after /logout, so /login and /whoami ask this.\n\n```go\nfunc (l *Lazy) Stream(ctx context.Context, r wire.Request, h wire.StreamHandler) (wire.Response, error)\n```\n\n```go\nfunc (l *Lazy) StreamOnGateway(ctx context.Context, r wire.Request, h wire.StreamHandler) (wire.Response, error)\n```\nStreamOnGateway is CompleteOnGateway's streaming twin.\n\n```go\nfunc (l *Lazy) WebFetch(ctx context.Context, url string) (string, error)\n```\n\n```go\nfunc (l *Lazy) WebSearch(ctx context.Context, query string) (string, error)\n```\n\n```go\ntype Limits struct {\n\tContextWindow int `json:\"context_window,omitempty\"`\n\tMaxOutput     int `json:\"max_output_tokens,omitempty\"`\n}\n```\nLimits is one model's token budget on an endpoint. 0 = unknown.\n\n```go\ntype ModelFact = memcode.ModelFact\n```\n\n```go\ntype ModelProvider interface {\n\tComplete(ctx context.Context, r wire.Request) (wire.Response, error)\n}\n```\nModelProvider performs reasoning/generation calls (Claude in v1).\n\n```go\nfunc NewFromEnv(endpoints ...Endpoint) (ModelProvider, error)\n```\nNewFromEnv constructs the backend connection from the environment — the ONE place the connection story lives. Call it at the cmd boundary after LoadDotEnv. Backend selection: a memcode token → the hosted gateway at {api}/v1; else a configured endpoint (MEMCODE\\_ENDPOINT\\_URL, or a resolved config endpoint passed by the caller) → the same compat transport pointed at it; else the signed-out error. ONE turn transport either way (wire.go). The variadic endpoint lets callers that load project config pass its resolved endpoint without this package importing config.\n\n```go\ntype ModelsInfo = memcode.ModelsInfo\n```\n\n```go\nfunc FetchModels(ctx context.Context) (ModelsInfo, error)\n```\nFetchModels asks the gateway for the routing control plane, resolving the endpoint + credential from the environment the way every CLI surface does. Every successful fetch also refreshes the pin list CachedPins serves, so the boot fetch is what lets /model open instantly.\n\n```go\ntype PinnableModel = memcode.PinnableModel\n```\n\n```go\nfunc AvailablePins(ctx context.Context) []PinnableModel\n```\nAvailablePins asks the gateway which concrete models the /model picker may offer (the pinnable subset of the servable list). On gateway outage or a lane-only session it falls back to CachedPins, so /model remains a real picker instead of collapsing to free-text.\n\n```go\nfunc CachedPins() []PinnableModel\n```\nCachedPins returns the picker rows without touching the network: the last list the gateway gave, or the embedded catalog before any fetch succeeded.\n\n```go\ntype Planner interface {\n\tPlannedBackend(pin string) string\n}\n```\nPlanner is the UI-side seam over route: what WILL serve the next turn on a pin, before it runs — so the footer names the lane up front instead of echoing whatever served last.\n\n```go\ntype Streamer interface {\n\tStream(ctx context.Context, r wire.Request, h wire.StreamHandler) (wire.Response, error)\n}\n```\nStreamer is an optional capability: a provider that can stream a completion, emitting text/usage as they arrive while still returning the fully assembled Response. Callers type-assert for it and fall back to Complete otherwise.\n\n(Capability interfaces live at their consuming boundary — here, the CLI — not in the shared protocol package; the wire types they reference are common's.)\n\n```go\ntype Tier string\n```\nTier names the role of a model call. Each maps to a sensible default model but is overridable via config.\n\n```go\nconst (\n\tTierPlanner     Tier = \"planner\"\n\tTierCoder       Tier = \"coder\"\n\tTierReviewer    Tier = \"reviewer\"\n\tTierSynthesizer Tier = \"synthesizer\"\n\tTierClassifier  Tier = \"classifier\"\n)\n```\n\n```go\ntype TokenSource interface {\n\tToken() (string, error)\n\tRejected(tok string) (string, error)\n}\n```\nTokenSource is a live, self-healing credential: Token returns the current one; Rejected is told the API refused tok and returns a replacement.\n\n```go\ntype WebFetcher interface {\n\tWebFetch(ctx context.Context, url string) (string, error)\n}\n```\nWebFetcher is an optional capability: a provider that can fetch a specific URL server-side (text/PDF; not JS-rendered pages) and return its readable content.\n\n```go\ntype WebSearcher interface {\n\tWebSearch(ctx context.Context, query string) (string, error)\n}\n```\nWebSearcher is an optional capability: a provider that can answer a query using server-side web search, returning a synthesized text answer. Type-assert for it.\n\n","path":"github.com/memcode-ai/memcode/internal/provider","name":"provider","synopsis":"Package provider defines the (model, embedding, edit-apply) boundaries the engine talks to, plus the default Claude model tiers.","isRedistributable":true}
