Model providers
Available LLM provider adapters and OAuth helper surfaces.
Provider adapters implement LLMProvider for the agent loop. They translate Yolk messages/tools into vendor requests and normalize text, reasoning, tool calls, usage, retries, and provider errors back into Yolk events.
For copy-paste provider layer setup, see Use model providers.
Available providers
| Provider | Factory | Auth | Notes |
|---|---|---|---|
| OpenAI-compatible chat | makeOpenAiProviderLayer | API key | Chat Completions-style endpoint; OpenAiProviderLayer can read its API key and output limit through Effect Config. |
| Vercel AI Gateway | makeVercelAiGatewayProviderLayer | API key or OIDC | OpenAI-compatible Gateway endpoint with provider routing and model fallbacks. |
| OpenCode Go | makeOpenCodeGoProviderLayer | API key | Host-selected Chat Completions, Messages, or Responses protocol. |
| OpenAI Codex | makeOpenAiCodexProviderLayer | OAuthAccessToken | Responses API adapter with reasoning summaries and OAuth broker helpers. |
| Anthropic Claude Code | makeAnthropicClaudeProviderLayer | OAuthAccessToken | Claude Code-compatible adapter with Claude OAuth broker helpers. |
| xAI Grok subscription | makeXAiGrokProviderLayer | OAuthAccessToken | Responses adapter for Grok consumer subscriptions through the xAI CLI proxy. |
| Faux provider | FauxProvider.layer(...) | none | Test-only deterministic provider from @yolk-sdk/agent/loop/testing. |
Provider output-token limits are host-owned when supported. OpenAI-compatible chat, Vercel AI Gateway, OpenCode Go, Anthropic, and Grok require limits; ChatGPT Codex does not expose one. Yolk does not maintain a model-limit catalog or apply hidden fallbacks.
OpenAI-compatible chat
import { Layer, Redacted } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeOpenAiProviderLayer } from '@yolk-sdk/agent/providers/openai/provider'
const ProviderLayer = makeOpenAiProviderLayer({
apiKey: Redacted.make(hostOpenAiApiKey),
maxCompletionTokens: hostModelConfig.maxOutputTokens
}).pipe(Layer.provide(FetchHttpClient.layer))Use chatCompletionsUrl for generic OpenAI-compatible endpoints. Prefer the dedicated adapter below
for correct Vercel Gateway error attribution and routing options. The native endpoint receives
reasoningEffort as reasoning_effort; a compatible endpoint needs reasoningEffortFormat, or a
request with an effort fails with a validation_error.
Vercel AI Gateway
This is a server-side configuration fragment. The host supplies credentials and model policy:
import { Layer, Redacted } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeVercelAiGatewayProviderLayer } from '@yolk-sdk/agent/providers/vercel/ai-gateway-provider'
const ProviderLayer = makeVercelAiGatewayProviderLayer({
apiKey: Redacted.make(hostGatewayApiKeyOrOidcToken),
maxCompletionTokens: hostModelConfig.maxOutputTokens,
fallbackModels: hostFallbackModelIds,
routing: { order: ['vertex', 'anthropic'] },
extraHeaders: {
'http-referer': hostPublicAppUrl,
'x-title': hostAppName
}
}).pipe(Layer.provide(FetchHttpClient.layer))The adapter uses https://ai-gateway.vercel.sh/v1/chat/completions and defaults to a single JSON
completion. Set factory option streaming: true for SSE deltas. Independently set
reasoningContent: true to preserve compatible models' reasoning_content output (and the normalized reasoning thinking field some gateways emit, with reasoning_content taking precedence) and assistant
replay; streamed reasoning then surfaces as reasoning events, and replay spends input tokens.
Both options default to false. It lowers maxCompletionTokens to Gateway max_tokens. A run-level
reasoningEffort becomes { reasoning: { effort } } by default; reasoningEffortFormat: 'reasoning-effort' sends the literal field instead (e.g. for DeepSeek-style hosts, with an optional thinking: { type: 'enabled' | 'disabled' } toggle merged into the request body), and 'omit' never sends the effort and never fails. The host must
offer only effort values supported by its selected model. Pass model ids such as provider/model;
query Vercel's model catalog instead of hard-coding an SDK model union. VercelAiGatewayProviderLayer tries
AI_GATEWAY_API_KEY, then VERCEL_OIDC_TOKEN, and also reads integer
AI_GATEWAY_MAX_COMPLETION_TOKENS. Required auth and JSON headers override extraHeaders. Override
chatCompletionsUrl only with a trusted proxy because it receives the Bearer credential. Gateway
finish_reason values length and content_filter fail as non-retryable invalid_response rather
than reporting partial or filtered output as complete.
Gateway enables native PDF user-message parts by default; set supportsPdfAttachments: false to
disable them. URL-backed PDFs are fetched and buffered by the host-provided HttpClient before the
Gateway request, so hosts must authorize destinations, bound the download, control redirects and
credentials, and sanitize logs. See Bound PDF attachment fetches.
OpenCode Go
Use makeOpenCodeGoProviderLayer from @yolk-sdk/agent/providers/opencode/go-provider with a
redacted API key, explicit protocol, and host-owned maxOutputTokens. See
Go configuration.
| Protocol | Endpoint suffix | Authentication | Transport |
|---|---|---|---|
chat-completions | /chat/completions | Bearer API key | SSE (streaming: true), normalized into events |
messages | /messages | x-api-key | SSE or JSON response |
responses | /responses | Bearer API key | SSE or JSON response |
All endpoints default to https://opencode.ai/inference/go/v1. Choose the protocol advertised for the
selected model in OpenCode's Go catalog; model availability
can change. Pass the API model ID without the opencode-go/ CLI prefix. Yolk neither fetches the
catalog nor infers protocols or limits from model names.
Messages uses native system instructions and tool names, not Claude Code OAuth fingerprints.
Responses supports a host output limit and does not send Codex account or originator headers.
Go pins each x-opencode-session to one upstream server, so a retry under the same session reaches
the server that just failed. When a response is malformed (a Chat Completions parser code such as
invalid_stream_json, a chat response that is not SSE, or a chat or Responses stream missing its
terminal event) before any event was emitted, the adapter sends the request once more under
<session>.reroute, giving up that request's cached prefix; model decisions such as length are
never retried. Go requires x-opencode-session on every request (Chat Completions refuse one
without it with 400 MissingSessionID), and caches prompts per session. The session is the request
cacheKey, else the x-opencode-session extra header; a request with neither gets a fresh id of
its own, so it is accepted but shares no cache with other requests. Pass cacheKey to cache a
conversation. For a stuck upstream server, wrap the Go provider with withFirstEventDeadline (from
@yolk-sdk/agent/loop; suggested timeoutMs defaultFirstEventTimeoutMs, 90 s), under your
fallback route if you have one, or set LoopConfig.firstEventTimeoutMs: a stream with no output
within it is sent again once under the same session, as Go asks for a stable one per conversation,
and a second stall fails non-retryable (responseIssue: 'first_event_timeout'), for the fallback
model. Errors read OpenCode Go <cause>, plus : returned <status> for a failed HTTP response, in
Yolk's words only, beside provider.kind, provider.status and provider.providerCode. A Messages
or Responses stream cut before its terminal event that is not re-routed (output had begun, or the
re-routed request was cut too) fails as non-retryable invalid_response with
responseIssue: 'missing_done', the loop's incomplete stream (Responses keep
providerCode: 'incomplete_stream').
Go reports safe failures under provider ID opencode_go. Credentials, model capabilities, supported
reasoning efforts, allowance polling/persistence, and UI remain host-owned. Read allowance with
fetchOpenCodeGoSubscriptionUsage from @yolk-sdk/agent/providers/opencode/usage.
OpenAI Codex
import { Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeOpenAiCodexProviderLayer } from '@yolk-sdk/agent/providers/openai/codex-provider'
const ProviderLayer = makeOpenAiCodexProviderLayer({
token: hostOAuthAccessToken,
defaultReasoningEffort: 'medium',
reasoningSummary: 'auto'
}).pipe(Layer.provide(FetchHttpClient.layer))The ChatGPT subscription endpoint rejects vendor max_output_tokens, so the adapter does not expose
an output-token limit. The optional deprecated maxOutputTokens field is ignored for compatibility.
Codex completes a final response (streamed response.completed or a JSON body) whose output is
missing or misses a required key, decided from the decode issue (a missing key under output),
never from the error message. It reads output item by item: valid items still count, so a function
call the stream never emitted still runs, and the stop reason is tool_use when any call was
emitted, otherwise stop; items that do not decode are dropped. A function call that does not decode
must replay one the stream already emitted (same call_id or item id), and a message that does not
decode and carries text must be one whose text already streamed: otherwise the response fails as a non-retryable
invalid_response, since ending the turn would lose that call or answer. The response's usage is
reported when it decodes; a streamed Done is marked usageUnavailable only when it is missing or
does not decode. Unrelated invalid responses still fail. A stream cut before response.completed also completes (EOF
compatibility), so Codex never reports missing_done; this is not generic kernel missing_done
recovery and does not replay tools.
OAuth helpers live in @yolk-sdk/agent/providers/openai and the exact @yolk-sdk/agent/providers/openai/codex subpath:
makeOpenAiCodexBrokerRequestmakeOpenAiCodexTokenBrokerClienttoOpenAiCodexOAuthAccessTokenopenAiCodexProviderId- OpenAI Codex OAuth URLs/constants
fetchOpenAiCodexSubscriptionUsagefrom@yolk-sdk/agent/providers/openai/codex-usage
xAI Grok subscription
Configuration fragment (the host supplies the token, model policy, and HTTP layer):
import { Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeXAiGrokProviderLayer } from '@yolk-sdk/agent/providers/xai/grok-provider'
const ProviderLayer = makeXAiGrokProviderLayer({
token: hostOAuthAccessToken,
maxOutputTokens: hostModelConfig.maxOutputTokens,
clientVersion: hostGrokCliClientVersion
}).pipe(Layer.provide(FetchHttpClient.layer))clientVersion is required and sent as x-grok-client-version: the CLI proxy version-gates
requests and rejects missing or outdated client versions with HTTP 426. The host owns the value and
should keep it current with the minimum Grok CLI version the proxy accepts.
Grok requires response.completed: a stream that ends without it emits no Done and fails as
non-retryable invalid_response with providerCode: 'incomplete_stream' and
responseIssue: 'missing_done', the loop's incomplete stream (earlier releases left
responseIssue unset), so harness hosts continue or recover the turn instead of failing the run.
This adapter sends consumer OAuth credentials only to the xAI CLI proxy by default. It does not use
XAI_API_KEY or https://api.x.ai/v1. OAuth helpers live in
@yolk-sdk/agent/providers/xai and @yolk-sdk/agent/providers/xai/grok:
makeXAiGrokAuthorizationUrlmakeXAiGrokBrokerRequestmakeXAiGrokTokenBrokerClientparseXAiGrokAuthorizationCodetoXAiGrokOAuthAccessTokenxAiGrokProviderId- Grok browser-PKCE/device-flow URLs and constants
fetchXAiGrokSubscriptionUsagefrom@yolk-sdk/agent/providers/xai/usage
The public xAI CLI client uses a fixed loopback callback. The package exports browser-PKCE and
device-flow constants only; your host must implement the callback listener or complete device-code
request/polling, state/nonce and PKCE verification, token exchange, refresh serialization, secure
storage, token freshness/provider checks, and model discovery. Only override responsesUrl with a
trusted proxy because it receives the OAuth bearer. xAI controls the public CLI OAuth client and the
private, unsupported proxy contract; both may change and should be used only when permitted by xAI's
terms.
Anthropic Claude Code
import { Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeAnthropicClaudeProviderLayer } from '@yolk-sdk/agent/providers/anthropic/claude-provider'
const ProviderLayer = makeAnthropicClaudeProviderLayer({
token: hostOAuthAccessToken,
maxTokens: hostModelConfig.maxOutputTokens
}).pipe(Layer.provide(FetchHttpClient.layer))Like native Messages, Claude requires message_stop: a stream that ends without it, even after a
message_delta with a stop reason, emits no Done and fails as non-retryable invalid_response
with responseIssue: 'missing_done' (earlier releases completed it as a normal answer).
OAuth helpers live in @yolk-sdk/agent/providers/anthropic and the exact @yolk-sdk/agent/providers/anthropic/claude subpath:
makeAnthropicClaudeAuthorizationUrlmakeAnthropicClaudeBrokerRequestmakeAnthropicClaudeTokenBrokerClientparseAnthropicClaudeAuthorizationCodetoAnthropicClaudeOAuthAccessTokenanthropicClaudeProviderId- Claude OAuth URLs/constants
fetchAnthropicClaudeSubscriptionUsagefrom@yolk-sdk/agent/providers/anthropic/usage
Thinking
Claude Opus 5 and later think by default but return thinking blocks without text unless asked.
thinking: { display: 'summarized' } requests adaptive thinking summaries, streamed as reasoning
deltas. Optional prefixMismatchBehavior ('drop_block' or 'error', sent with the
thinking-binding-controls-2026-08-01 beta) decides what Anthropic does with replayed thinking whose
earlier system prompt, tools or messages changed. Without thinking, no thinking field is sent.
Either way the provider keeps each thinking block's signature, or a redacted block's data, on
AssistantReasoningPart.replay and sends the turn back exactly as produced on later requests, so
tool-use turns keep their reasoning. Never edit, truncate or reorder a reasoning part that has
replay (Anthropic rejects modified thinking); hosts that rewrite history per request can skip parts
whose replay.provider is anthropicClaudeReasoningReplayProvider. Reasoning from another provider
is never sent to Claude, and native Messages transports neither capture nor replay signatures.
Prompt caching
Agent turns resend the whole conversation, so every adapter asks its provider to reuse the repeated prefix. It is always on:
| Provider | What the adapter sends |
|---|---|
| Anthropic | cache_control on the last tool, the conversation end, and the previous request's end |
| OpenAI Codex, Grok | prompt_cache_key plus the session header (session-id, x-grok-conv-id) |
| Vercel AI Gateway | providerOptions.gateway.caching: 'auto' and x-session-affinity |
| OpenCode Go | x-opencode-session, required (see above); Messages also gets the Anthropic markers |
Pass a stable conversation identity such as the session id as cacheKey on run, runRuntime, or
LLMRequest; it travels in HTTP headers, so keep it printable ASCII. The generic OpenAI-compatible
chat provider sends nothing unless its config sets cacheKeyHeaders. Claude caches entries for five
minutes; set promptCacheTtl: '1h' on makeAnthropicClaudeProviderLayer for sessions that idle
between turns.
A cache hit needs a byte-identical prefix. Keep the system prompt and tool list stable within a
conversation and never rewrite earlier messages per request: put per-request facts such as fresh
signed URLs or the current time in LLMRequest.turnContext. Adapters append it after the
conversation (Anthropic after every breakpoint; Gateway's automatic markers still read the prefix
before it). Loop hosts set it by decorating LLMProvider. LLMRequest.toolChoice: 'none' forbids
tool calls but keeps the tool definitions; on Anthropic a changed tool_choice invalidates the
cached messages. Read the outcome from AgentInputUsage.cacheRead and cacheWrite. See
docs/adr/0008-prompt-caching.md in the repository for the design.
Read subscription allowance
Claude, Codex, Grok, and OpenCode Go subscription connections can expose current allowance percentages and
reset windows. Claude normalizes aggregate five-hour and seven-day windows plus model-scoped
weekly limits (seven-day-<model>, with models naming the model they limit); Codex normalizes primary
and secondary rate-limit windows; Grok normalizes its aggregate shared credit allowance. Additional
provider-specific buckets are ignored. The usage adapters use private provider endpoints, so treat
snapshots as best-effort and keep failures isolated from core agent execution. Each fetcher accepts
an optional url that replaces the default endpoint; point it only at a trusted proxy or a local
emulator, because the credential is sent there.
This server-side fragment reads Codex allowance using a fresh host-owned token:
import { Effect } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { fetchOpenAiCodexSubscriptionUsage } from '@yolk-sdk/agent/providers/openai/codex-usage'
const snapshotEffect = fetchOpenAiCodexSubscriptionUsage(hostOAuthAccessToken, {
requestTimeoutMs: 10_000
}).pipe(Effect.provide(FetchHttpClient.layer))Use fetchAnthropicClaudeSubscriptionUsage for Claude. For Grok, call
fetchXAiGrokSubscriptionUsage(token, { xAiUserId, clientVersion }). xAiUserId must be the
authenticated xAI user_id; the adapter does not reinterpret generic OAuthAccessToken.accountId.
clientVersion must truthfully identify your host integration rather than impersonate an official
Grok release. The adapter reports its programmatic request as headless.
For Go, call fetchOpenCodeGoSubscriptionUsage(Redacted.make(hostOpenCodeGoApiKey), options) from
@yolk-sdk/agent/providers/opencode/usage. Unlike the OAuth adapters, it uses a Bearer API key at
https://opencode.ai/inference/go/v1/usage. The API key must belong to the subscription's user and workspace;
403 means the key is not entitled to Go usage. It returns five-hour, seven-day, and monthly
windows, preserving the provider's absolute reset times. Monthly resets are subscription-anniversary
based, not calendar-month boundaries. Missing/invalid percentages are omitted rather than filled
with zero. No browser cookies or console scraping are needed.
Claude and Go now set windowDurationMinutes on their fixed rolling windows (300 for five-hour,
10080 for seven-day), as Codex and Grok already did; Go's monthly window has none.
Shared snapshot and safe error schemas live in
@yolk-sdk/agent/providers/subscription-usage. Hosts own polling, credential refresh, labels,
persistence, stale-data policy, thresholds, notifications, and UI. These snapshots report
subscription allowance, not protocol AgentUsage token accounting.
When an account-wide subscription quota is spent, the provider fails the request as rate_limit
and may attach ProviderErrorInfo.quotaResetsAtMs (epoch milliseconds of the reset). Claude reads
it from its rate-limit headers, and Responses providers from a usage_limit_reached error (which
ChatGPT Codex sends). It is absent for transient rate limits, a Claude model-scoped limit alone, and
a reset that is missing, in the past, or more than a year ahead. To spread requests over several accounts of one provider and fail over
when one runs out, see Share subscription accounts.
Test provider
import { FauxProvider, Reply } from '@yolk-sdk/agent/loop/testing'
const ProviderLayer = FauxProvider.layer(Reply.text('Hello from a deterministic test.'))Use this in tests and examples only. It is not a runtime provider.
Host responsibilities
- Store and refresh provider credentials.
- Choose models per user/session/run.
- Provide
HttpClientand provider layers to the loop. - Keep raw provider error bodies and secrets out of protocol events.
- Persist usage and typed provider failure metadata if your app needs it.