import { a as UserHome, c as hasAnyCredential, i as UserDetection, l as isExpired, n as DetectedCredential, o as detectAllUsers, r as ProviderDetection, s as detectCredentials, t as DetectOptions } from "./detect-CV6kT9tO.js"; //#region src/errors.d.ts type ErrorCode = "auth" | "rate_limit" | "overloaded" | "context_length" | "invalid_request" | "not_found" | "server" | "network" | "timeout" | "aborted" | "unknown"; interface CardanErrorOptions { provider?: string; status?: number; retryAfterMs?: number; /** * Absolute time (epoch ms) the rate limit resets, when the provider reports it * (e.g. a subscription window reset). Authoritative and exact — consumers * should honor it as-is rather than capping it like a relative `retryAfterMs`. */ resetAt?: number; raw?: unknown; cause?: unknown; /** Override the default retryability derived from `code`. */ retryable?: boolean; } declare class CardanError extends Error { readonly code: ErrorCode; readonly provider?: string; readonly status?: number; readonly retryable: boolean; readonly retryAfterMs?: number; readonly resetAt?: number; /** Raw provider error body, for debugging. */ readonly raw?: unknown; constructor(code: ErrorCode, message: string, options?: CardanErrorOptions); } declare function isCardanError(error: unknown): error is CardanError; /** Message + code pulled from a provider wire error payload. */ interface ExtractedProviderError { code: ErrorCode; message: string; /** Provider's original type/code string when present. */ type?: string; } /** * Maps a provider's error type/code string (Anthropic `error.type`, OpenAI * `error.code` / event `code`, etc.) onto a cardan {@link ErrorCode}. */ declare function codeFromProviderType(type: string | undefined): ErrorCode | undefined; /** * Pull message + {@link ErrorCode} from common provider wire shapes: * - `{ error: { type?, code?, message? } }` (Anthropic, many OpenAI-like) * - `{ type: "error", error: { … } }` (nested stream error) * - `{ type: "error", message, code }` (OpenAI Responses SSE `error`) * - bare `{ message, type/code }` or a string * * Never returns a bare `"stream error"` when a type/code is available — the * fallback is `stream error ()` so callers can still diagnose. */ declare function extractProviderError(raw: unknown): ExtractedProviderError; /** * Build a non-retryable stream {@link CardanError} from a provider event/chunk. * Adapters pass the raw SSE payload (or its `error` field) so the message and * code come from the wire rather than a generic `"stream error"`. */ declare function streamCardanError(raw: unknown, provider: string, options?: { retryable?: boolean; }): CardanError; //#endregion //#region src/schema.d.ts /** A plain JSON Schema object. Not validated by cardan. */ type JsonSchema = Record; /** * Minimal structural view of a zod 4 schema. Detection is duck-typed so zod * stays an optional peer dependency. The `parse` return type carries the * inferred output, letting {@link Infer} recover it without importing zod. */ interface ZodLikeSchema { _zod: unknown; parse(data: unknown): T$1; } type SchemaInput = JsonSchema | ZodLikeSchema; /** * The value type a schema validates to: a zod schema resolves to its parsed * output type; a plain JSON Schema (which carries no static type) resolves to * `unknown`. */ type Infer = S extends ZodLikeSchema ? T : unknown; //#endregion //#region src/types.d.ts type Role = "system" | "user" | "assistant" | "tool"; interface TextPart { type: "text"; text: string; /** * Opaque provider replay metadata attached to this part (Gemini * `thoughtSignature`). Preserved verbatim and sent back when replaying to * the same provider; other providers ignore it. */ signature?: string; /** * Web sources backing this run of text, when the provider anchors citations * to answer spans (Anthropic web search). Present only on the cited run; the * full de-duplicated set is also on {@link GenerateResult.citations}. Replay * to the provider ignores this field. */ citations?: WebCitation[]; } interface ImagePart { type: "image"; mimeType: string; data: Uint8Array | URL; } interface ToolCallPart { type: "tool_call"; /** * Provider-assigned call id (e.g. `toolu_…`, `call_…`). Preserved verbatim. * Providers that omit ids (Gemini 2.x) get a synthesized `cardan_call_…` * id, which the adapter strips when replaying to that provider. */ id: string; name: string; args: unknown; /** * Opaque provider replay metadata attached to this part (Gemini * `thoughtSignature`; mandatory for Gemini 3 function-calling replay). */ signature?: string; } interface ToolResultPart { type: "tool_result"; /** Must match the `id` of the corresponding tool_call. */ callId: string; result: unknown; isError?: boolean; } interface ThinkingPart { type: "thinking"; text: string; /** * Provider item id (OpenAI `rs_…`). OpenAI replay requires both `id` and * `signature`; parts missing either are dropped when replaying there. */ id?: string; /** * Provider signature required to replay the thinking block (Anthropic * signature, OpenAI `encrypted_content`). Thinking parts without a * signature are dropped when replaying to providers that require one. */ signature?: string; /** * True when the provider returned the block in redacted/encrypted form * (Anthropic `redacted_thinking`); `signature` then holds the opaque data. */ redacted?: boolean; } /** * A provider-native content block cardan does not model generically (Anthropic * `server_tool_use` / `web_search_tool_result`), carried verbatim so the turn * that produced it can be replayed unchanged. Anthropic validates an assistant * turn as a whole and rejects one whose signed blocks lost their surrounding * context, so a server-tool turn is only replayable if these blocks survive the * round trip. Only the Anthropic adapter produces them — the others validate * replay state per item (OpenAI reasoning id + `encrypted_content`, Gemini * per-part `thoughtSignature`) and keep their unmapped blocks in `raw` only. * Replayed only to the provider named here; everyone else drops it. */ interface ProviderBlockPart { type: "provider_block"; /** Provider that produced the block ({@link Provider.name}). */ provider: string; /** The raw block, exactly as the provider returned it. */ block: unknown; } type ContentPart = TextPart | ImagePart | ToolCallPart | ToolResultPart | ThinkingPart | ProviderBlockPart; interface Message { role: Role; content: ContentPart[]; } /** Convenience constructor: wraps a string into a single text part. */ declare function textMessage(role: Role, text: string): Message; /** * Token usage. Totals always present; provider-specific breakdowns go in * `details` (e.g. `cache_read`, `cache_write`, `reasoning`). Missing fields * are treated as 0. */ interface Usage { input: { total: number; details: Record; }; output: { total: number; details: Record; }; } declare function emptyUsage(): Usage; /** * One subscription rate-limit window's state, as reported by the provider on * every response (no extra request or scope needed). `utilization` is the * fraction (0..1) of the window consumed — the proactive signal — and * `resetAt` (epoch ms) is when it refills. */ interface RateLimitWindow { /** Fraction of the window consumed, 0..1. */ utilization: number; /** When the window resets, epoch ms. */ resetAt: number; /** Provider status for this window, e.g. `allowed` | `allowed_warning` | `rejected`. */ status: string; } /** * One counter-style throttle window, from OpenAI-wire `x-ratelimit-*` response * headers (`limit`/`remaining` pairs for requests and tokens). Short rolling * windows (typically per-minute) — a live throughput view, not subscription * quota. */ interface RateLimitCounter { /** Window capacity (`x-ratelimit-limit-*`). */ limit: number; /** Capacity left in the current window (`x-ratelimit-remaining-*`). */ remaining: number; /** When the counter refills, epoch ms (`x-ratelimit-reset-*`), if reported. */ resetAt?: number; } /** * Subscription rate-limit snapshot. Anthropic (Claude.ai OAuth) fills this from * unified response headers (5h + 7d); xAI Grok OAuth fills `sevenDay` from * `GET /v1/billing?format=credits` (SuperGrok weekly pool). Fields are present * only when the provider reports them. Surfaced so callers (and * {@link Provider} pools) can observe remaining quota — the pool still only * cools members on real rate-limit errors, not soft-warning snapshots. */ interface RateLimitStatus { /** Which window is currently binding (e.g. `five_hour` | `seven_day`), if reported. */ representative?: string; /** Representative status across windows (the binding window's status). */ status?: string; /** Representative window reset, epoch ms (the binding window's reset). */ resetAt?: number; /** The rolling 5-hour subscription window (Anthropic). */ fiveHour?: RateLimitWindow; /** The rolling 7-day window (Anthropic headers / SuperGrok weekly pool). */ sevenDay?: RateLimitWindow; /** Requests-per-window counter (OpenAI-wire `x-ratelimit-*-requests`). */ requests?: RateLimitCounter; /** Tokens-per-window counter (OpenAI-wire `x-ratelimit-*-tokens`). */ tokens?: RateLimitCounter; } /** * Why generation ended. Success is not always completion: * - `stop` — normal end (end of turn / stop sequence) * - `length` — hit max output tokens or the model's output window; content may * be partial. Callers that care about completeness should treat this as * incomplete (see {@link isIncompleteFinish}) rather than a clean success * - `tool_calls` — model asked for tool use; continue the tool loop * - `refusal` — model / provider refused (safety, content filter, …) * - `other` — provider-specific or unknown terminal reason * * Adapters report the provider's stop reason and keep any partial output; * they do **not** throw on `length`/`refusal`. Product layers decide whether * that counts as an error, whether tools may run, and what to show the user. */ type FinishReason = "stop" | "length" | "tool_calls" | "refusal" | "other"; /** True when generation ended without a normal completion. Partial output may * still be present on the result / stream. `tool_calls` is a normal mid-loop * terminal and is not incomplete. */ declare function isIncompleteFinish(reason: FinishReason | undefined | null): boolean; type StreamEvent = /** * A run of visible text. `signature` (Gemini `thoughtSignature`) closes the * text part: it carries opaque replay state, so collection must not merge * further deltas into a signed part. */ { type: "text_delta"; text: string; signature?: string; } /** * Web sources backing the visible text emitted since the last text break. * Providers that anchor citations to answer spans (Anthropic) emit this when * a cited text block closes; it closes the open text part so the sources stay * pinned to the claim they back. The same sources are also aggregated into the * `finish` event's flat `citations` list. */ | { type: "text_citations"; citations: WebCitation[]; } /** A run of thinking-summary text; `signature` closes the part (see above). */ | { type: "thinking_delta"; text: string; signature?: string; } /** Emitted when a thinking block closes with a replay signature. */ | { type: "thinking_signature"; signature: string; id?: string; } /** Emitted once per tool call, when its arguments are complete. */ | { type: "tool_call"; id: string; name: string; args: unknown; signature?: string; } /** * A closed provider-native block cardan does not model generically; collected * into a {@link ProviderBlockPart} so the turn stays replayable verbatim. */ | { type: "provider_block"; provider: string; block: unknown; } | { type: "finish"; reason: FinishReason; usage: Usage; /** Web-search sources gathered this turn, if web search ran. */ citations?: WebCitation[]; /** Subscription rate-limit snapshot from the response headers, if reported. */ rateLimit?: RateLimitStatus; /** Label of the pool member that served the request (pool providers only). */ poolMember?: string; }; interface Tool { name: string; description?: string; /** JSON Schema object or zod schema describing the arguments. */ parameters?: SchemaInput; } type ToolChoice = "auto" | "none" | "required" | { name: string; }; /** * Built-in web-search controls. Web search is a *server-side* tool: the * provider runs the searches and returns a finished answer with citations, so * it never round-trips through the caller like a normal `Tool`. Each adapter * routes this to its own native mechanism (Anthropic/OpenAI/xAI server tools, * Gemini grounding, Groq built-in tools) and maps only the fields it supports, * silently ignoring the rest; provider-specific knobs go through * `providerOptions`. Requesting web search on a model that cannot do it raises * `invalid_request`. */ interface WebSearchOptions { /** Cap on searches per turn. Anthropic only; others ignore. */ maxUses?: number; /** Restrict results to these domains (no scheme). Anthropic/OpenAI/xAI (xAI ≤5). */ allowedDomains?: string[]; /** Exclude these domains (no scheme). Anthropic/OpenAI/xAI (xAI ≤5). */ blockedDomains?: string[]; /** Approximate user location to localize results. Anthropic/OpenAI. */ userLocation?: { /** Two-letter ISO country code (e.g. `US`). */ country?: string; city?: string; region?: string; /** IANA timezone (e.g. `America/New_York`). */ timezone?: string; }; /** How much search context to feed the model. OpenAI only; others ignore. */ contextSize?: "low" | "medium" | "high"; } /** A web source the model cited. The lowest common denominator across providers. */ interface WebCitation { url: string; title?: string; /** The quoted span the citation backs, when the provider exposes one. */ snippet?: string; } /** * Prompt-caching controls. Caching reuses the computation of a repeated prompt * prefix to cut input cost and latency. **Providers differ in what this needs:** * * - **Anthropic** is the only provider that requires *client-side* opt-in — the * adapter places `cache_control` breakpoints on the last system block and the * last message so a growing conversation caches its stable prefix. `ttl` picks * the breakpoint lifetime (`"5m"` default, `"1h"` for longer-lived prefixes, * which costs more to write — 2× vs 1.25× base input). * - **OpenAI / xAI** cache automatically; `key` is forwarded as the Responses * API `prompt_cache_key` (both run on that API) to pin repeat requests to the * same cached prefix and raise the hit rate. `ttl` is ignored. * - **Gemini / Groq / Modal** cache automatically with nothing to configure; * this option is a no-op (cache hits still surface in `usage`). * * Caching is **off unless this is set** — `true` enables it with defaults. * * **Scope — stateless prefix caching only.** Every provider above caches by * matching a repeated prompt *prefix* the client resends each request; the * client holds no cache state. Gemini *also* offers explicit, *named* context * caching (`caches.create()` → a `CachedContent` resource you reference and * lifecycle-manage, billed by per-hour storage over its TTL). That is a * stateful management-plane feature, not a per-request hint, so it is * deliberately out of scope here (cardan stays lean — like files/batch). If you * need it, create the cache yourself and pass `providerOptions: * { cachedContent: "cachedContents/…" }`; cardan won't manage its lifecycle or * bill its storage. Should a real need arise, add a separate `caches.*` surface * rather than overloading this option. */ interface CacheOptions { /** Breakpoint lifetime. Anthropic only; `"5m"` (default) or `"1h"`. */ ttl?: "5m" | "1h"; /** * Stable cache key to route repeat requests to the same cached prefix (e.g. a * conversation id), sent as the Responses API `prompt_cache_key`. OpenAI / xAI * only; other providers ignore it. */ key?: string; } type ReasoningEffort = "low" | "medium" | "high" | "xhigh" | "max"; interface RetryOptions { /** Number of retries after the initial attempt. Default 2. */ maxRetries: number; /** Base delay for exponential backoff. Default 1000. */ initialDelayMs: number; /** Backoff ceiling. Default 30000. */ maxDelayMs: number; } declare const DEFAULT_RETRY: RetryOptions; interface GenerateOptions { /** Model name without provider prefix (adapters), e.g. `claude-opus-5`. */ model: string; messages: Message[]; tools?: Tool[]; toolChoice?: ToolChoice; /** * Enable the provider's built-in web search. `true` uses defaults; pass a * {@link WebSearchOptions} object to tune it. Server-side — the provider * runs the searches and returns citations on the result. */ webSearch?: boolean | WebSearchOptions; /** * Enable prompt caching. `true` uses defaults; pass {@link CacheOptions} to * set the TTL (Anthropic) or a cache key (OpenAI/xAI). Off when omitted. Most * providers cache automatically — see {@link CacheOptions} for what each does. */ cache?: boolean | CacheOptions; /** Structured output: constrain the response to a JSON schema. */ output?: { schema: S; }; maxOutputTokens?: number; temperature?: number; topP?: number; stopSequences?: string[]; /** * Reasoning/thinking control; adapters map to provider parameters. * Enabled whenever this object is present unless `enabled: false`; passing * `effort` implies `enabled: true`, and `enabled: true` without `effort` * enables at the provider's default effort. */ reasoning?: { enabled?: boolean; effort?: ReasoningEffort; }; /** * Run the request in the provider's background mode (OpenAI / xAI Responses * only; ignored by other adapters). `undefined` (default) auto-enables it * for high-effort reasoning (`high`/`xhigh`/`max`), where long generations * risk idle-connection drops; `true`/`false` force it on/off. Background * decouples execution from the HTTP connection (and forces `store: true`): * `generate` creates the response then polls it to completion, `stream` * resumes a dropped SSE via `starting_after` instead of failing. */ background?: boolean; /** * Provider-specific request fields, shallow-merged into the outgoing * request body last (escape hatch; overrides adapter defaults). */ providerOptions?: Record; /** * Per-attempt timeout in milliseconds; `undefined`/`0` (default) means no * timeout. Applies to each HTTP attempt (retries reset it) and bounds the * wait until the response begins (headers arrive). For non-streaming * `generate` the server only responds once generation finishes, so this * effectively caps total generation time; for `stream` it bounds connection * setup only (bound a mid-stream stall with `signal`). For a hard ceiling * across retries, pass `signal: AbortSignal.timeout(ms)`. */ timeoutMs?: number; signal?: AbortSignal; /** Override retry behavior; `false` disables retries. */ retry?: Partial | false; /** * Pool-only: label of the preferred pool member for this request (e.g. to * keep a conversation on the account holding its prompt cache). When the * member is ready it serves the request; when it's cooling down, unknown, or * the provider is not a pool, the hint is ignored and normal rotation * applies. The member that actually served is reported back as * {@link GenerateResult.poolMember} / the `finish` event's `poolMember`. */ poolMember?: string; } interface GenerateResult { /** Assistant message (text / thinking / tool_call parts). */ message: Message; finishReason: FinishReason; usage: Usage; /** * The assistant reply's visible text: its `text` parts joined with "\n", * excluding thinking and tool calls. Convenience over walking * `message.content`; empty string when the turn produced no text. */ text: string; /** Parsed (and zod-validated, if applicable) structured output. */ output?: T$1; /** Web-search sources the model cited, if web search ran. */ citations?: WebCitation[]; /** Subscription rate-limit snapshot from the response headers, if reported. */ rateLimit?: RateLimitStatus; /** Label of the pool member that served the request (pool providers only). */ poolMember?: string; /** Raw provider response body, for debugging/forward-compat. */ raw: unknown; } interface EmbedOptions { model: string; input: string[]; providerOptions?: Record; /** Per-attempt timeout (ms); `undefined`/`0` (default) means none. See {@link GenerateOptions.timeoutMs}. */ timeoutMs?: number; signal?: AbortSignal; retry?: Partial | false; } interface EmbedResult { embeddings: number[][]; usage: Usage; raw: unknown; } interface ImageGenerateOptions { model: string; prompt: string; /** Images to produce. Provider-capped (xAI: 10). Defaults to 1. */ n?: number; /** e.g. `1:1`, `16:9`, `auto`. Omit on an edit to keep the input's shape. */ aspectRatio?: string; /** Provider resolution tier, e.g. `1k` / `2k`. */ resolution?: string; /** * Reference images to edit instead of generating from text alone. A `URL` is * handed to the provider to fetch; bytes are inlined. xAI accepts at most 3. */ referenceImages?: ImagePart[]; providerOptions?: Record; /** Per-attempt timeout (ms). Image generation is slow; providers default high. */ timeoutMs?: number; signal?: AbortSignal; retry?: Partial | false; } interface GeneratedImage { mimeType: string; data: Uint8Array; /** Prompt the provider actually rendered, when it reports one. */ revisedPrompt?: string; } interface ImageGenerateResult { images: GeneratedImage[]; /** Provider-reported list price for this request, in USD, when reported. */ costUsd?: number; /** Model the provider resolved the request to, when reported. */ model?: string; raw: unknown; } /** * One logical request observed by {@link TelemetryOptions.onRequest}. Fired * once per `generate` / `stream` / `embed` after any pool failover or * per-attempt retries — pool switches are internal to the provider. */ interface TelemetryEvent { /** Routing prefix, e.g. `"anthropic"` (includes a pooled provider under that slot). */ provider: string; /** Model id without the provider prefix. */ model: string; op: "generate" | "stream" | "embed"; ok: boolean; /** Wall-clock duration in milliseconds. For `stream`, starts at the first `next()`. */ durationMs: number; /** When `!ok`: `CardanError.code`, or `"unknown"` for non-cardan throws. */ errorCode?: ErrorCode; /** `CardanError.status` when present. */ status?: number; /** `CardanError.retryAfterMs` when present. */ retryAfterMs?: number; /** `CardanError.resetAt` when present. */ resetAt?: number; /** `generate`: `result.usage`; `stream`: `finish` event usage; `embed`: omit. */ usage?: Usage; } /** Global observer for every request routed through a {@link Cardan} client. */ interface TelemetryOptions { /** * Invoked once per logical request. Exceptions are swallowed so a broken * observer cannot affect the request. */ onRequest?(event: TelemetryEvent): void; } interface Provider { readonly name: string; generate(options: GenerateOptions): Promise; stream(options: GenerateOptions): AsyncIterable; /** Only providers that offer embeddings implement this. */ embed?(options: EmbedOptions): Promise; /** Only providers that offer image generation implement this. */ generateImage?(options: ImageGenerateOptions): Promise; /** * Last-known subscription rate-limit snapshot from the most recent response * that reported it, or `undefined`. A live, overwritten-on-each-request view * of remaining quota — not an accumulator. Only providers that expose * subscription rate-limit headers implement this. */ readonly rateLimit?: RateLimitStatus; /** * Drop the last-known rate-limit snapshot. Optional — only providers that * cache subscription/throttle headers implement this. Used by admin clear * paths (see {@link PoolProvider.clearMemberLimits}) so a stale * rejected/exhausted mark can be force-cleared before its natural reset. */ clearRateLimit?(): void; } //#endregion //#region src/providers/anthropic.d.ts /** Known Anthropic model ids — literal-only, drives editor autocomplete. */ type AnthropicModelId = "claude-fable-5" | "claude-opus-5" | "claude-sonnet-5" | "claude-haiku-4-5"; type AnthropicModel = AnthropicModelId | (string & {}); /** * A Claude.ai subscription OAuth credential set, as stored by the Claude CLI in * `~/.claude/.credentials.json` (`claudeAiOauth`). */ interface OAuthCredentials { /** Short-lived bearer token sent to the Messages API. */ accessToken: string; /** * Mints new access tokens; rotates on every refresh. Absent for inference-only * tokens (e.g. `claude setup-token`), which are long-lived and not refreshable. */ refreshToken?: string | null; /** Epoch ms. Absent means unknown — no proactive refresh, refresh on 401 only. */ expiresAt?: number | null; scopes?: string[]; } /** Authenticate with a Claude.ai subscription token instead of an API key. */ interface AnthropicOAuthOptions { credentials: OAuthCredentials; /** * Called after each successful refresh with the rotated credentials. Persist * them — the previous refresh token stops working once a new one is issued. */ onRefresh?: (credentials: Required) => void | Promise; /** * Re-read credentials from the persistence layer before a network refresh; * externally rotated credentials are adopted without a token-endpoint call. */ reload?: () => OAuthCredentials | undefined | Promise; /** Override the OAuth token endpoint. */ tokenUrl?: string; /** Override the OAuth client id. */ clientId?: string; /** Scopes requested on refresh. */ refreshScopes?: string[]; /** Override the system identity prefix the subscription grant expects. */ identity?: string; } /** * Experimental, unsupported knobs for local debugging only. Not covered by * semver — any of these may change behavior or be removed without notice, and * they are intentionally undocumented for normal use. Do not ship them. */ interface AnthropicExperimentalOptions { /** * Skip injecting the mandatory Claude Code identity system block in OAuth * (subscription) mode. That block is normally *required* for the subscription * grant to be accepted, so enabling this will most likely make the API reject * the request — it exists only to probe what happens when the identity is * withheld. No effect in API-key mode. */ omitOAuthIdentity?: boolean; } interface AnthropicProviderOptions { /** Defaults to the `ANTHROPIC_API_KEY` environment variable. */ apiKey?: string; /** * Authenticate with a Claude.ai subscription OAuth token (Pro/Max/Team/ * Enterprise) instead of an API key, so requests bill against the subscription * rather than pay-per-token API credits. Mutually exclusive with `apiKey` * (takes precedence). Bearer auth, the `oauth-2025-04-20` beta, and the * required Claude Code identity system block are all applied automatically. * * Pass a bare token string as shorthand for `{ credentials: { accessToken } }` * — handy for a `claude setup-token` token; use the object form when you need * a refresh token, `onRefresh`, etc. */ oauth?: string | AnthropicOAuthOptions; /** Defaults to `https://api.anthropic.com`. */ baseUrl?: string; /** `anthropic-version` header. Defaults to `2023-06-01`. */ version?: string; /** Extra headers on every request (e.g. `anthropic-beta`). */ headers?: Record; /** Custom fetch implementation (testing, proxies). */ fetch?: typeof globalThis.fetch; /** Default retry behavior for all requests; `false` disables. */ retry?: Partial | false; /** Default per-attempt timeout (ms) for all requests; `0`/undefined disables. */ timeoutMs?: number; /** * Experimental debugging knobs. Unsupported and not for normal use — see * {@link AnthropicExperimentalOptions}. */ experimental?: AnthropicExperimentalOptions; } declare class AnthropicProvider implements Provider { readonly name = "anthropic"; private readonly options; private readonly fetch; private readonly oauth?; private lastRateLimit?; /** * The subscription rate-limit snapshot from responses that carried the * unified headers (OAuth/subscription requests), or `undefined` if none has * been seen yet. A per-field last-known view: each response updates the fields * it reports and leaves the rest intact. This matters because some responses * carry only a partial header set — e.g. a `representative: "overage"` reply * omits the `5h`/`7d` window headers — and a missing field means "unknown", * not "reset to zero", so the prior window snapshot must survive it. */ get rateLimit(): RateLimitStatus | undefined; /** Drop the last-known snapshot (admin force-clear of a stale rejected mark). */ clearRateLimit(): void; /** * Merge a freshly parsed snapshot into the last-known one, preserving fields * the new snapshot omits. A partial header set (missing `5h`/`7d` windows) * reports "unknown" for those windows, so keeping the prior values is correct * — replacing wholesale would erase live quota data on every overage reply. */ private recordRateLimit; constructor(options?: AnthropicProviderOptions); /** * Picks the auth path. Precedence (most explicit first): config `oauth` > * config `apiKey` > env `CLAUDE_CODE_OAUTH_TOKEN` > env `ANTHROPIC_API_KEY` * (the last is handled lazily in `apiKey()`). Returning a `ClaudeOAuthAuth` * selects the Bearer/subscription path; `undefined` falls back to API key. */ private resolveOAuth; generate(options: GenerateOptions): Promise; stream(options: GenerateOptions): AsyncIterable; private apiKey; /** Auth + version headers for a request, including any user-supplied headers. */ private requestHeaders; private request; private httpError; private buildRequestBody; /** * Parses one streamed response. Yields cardan events, accumulates `usage` * and `citations` into the passed cumulative collectors, and returns the * turn's stop reason plus the raw assistant content blocks — the latter so a * `pause_turn` can be resumed by replaying them verbatim. It does *not* emit * the `finish` event; the caller does, once the turn really ends. */ private parseStreamTurn; } //#endregion //#region src/providers/google.d.ts /** Known Google model ids — literal-only, drives editor autocomplete. */ type GoogleModelId = "gemini-3.6-flash" | "gemini-3.5-flash-lite" | "gemini-3.1-pro-preview" | "gemini-3-flash-preview" | "gemini-embedding-001"; type GoogleModel = GoogleModelId | (string & {}); interface GoogleProviderOptions { /** Defaults to `GEMINI_API_KEY`, falling back to `GOOGLE_API_KEY`. */ apiKey?: string; /** Defaults to `https://generativelanguage.googleapis.com`. */ baseUrl?: string; /** API version path segment. Defaults to `v1beta`. */ apiVersion?: string; /** Extra headers on every request. */ headers?: Record; /** Custom fetch implementation (testing, proxies). */ fetch?: typeof globalThis.fetch; /** Default retry behavior for all requests; `false` disables. */ retry?: Partial | false; /** Default per-attempt timeout (ms) for all requests; `0`/undefined disables. */ timeoutMs?: number; } declare class GoogleProvider implements Provider { readonly name = "google"; private readonly options; private readonly fetch; constructor(options?: GoogleProviderOptions); generate(options: GenerateOptions): Promise; stream(options: GenerateOptions): AsyncIterable; embed(options: EmbedOptions): Promise; private apiKey; private modelUrl; private request; private httpError; private buildRequestBody; private parseResponse; private parseStream; } //#endregion //#region src/providers/groq.d.ts /** Known Groq model ids — literal-only, drives editor autocomplete. */ type GroqModelId = "openai/gpt-oss-120b" | "openai/gpt-oss-20b" | "openai/gpt-oss-safeguard-20b" | "qwen/qwen3-32b" | "llama-3.3-70b-versatile" | "llama-3.1-8b-instant" | "meta-llama/llama-4-scout-17b-16e-instruct" | "groq/compound" | "groq/compound-mini"; type GroqModel = GroqModelId | (string & {}); interface GroqProviderOptions { /** Defaults to the `GROQ_API_KEY` environment variable. */ apiKey?: string; /** Defaults to `https://api.groq.com/openai`. */ baseUrl?: string; /** Extra headers on every request. */ headers?: Record; /** Custom fetch implementation (testing, proxies). */ fetch?: typeof globalThis.fetch; /** Default retry behavior for all requests; `false` disables. */ retry?: Partial | false; /** Default per-attempt timeout (ms) for all requests; `0`/undefined disables. */ timeoutMs?: number; } /** * Groq adapter built on the **Chat Completions** API * (`/openai/v1/chat/completions`) — Groq's stable primary interface. Groq's * Responses API is beta and rejects `store`/`include`, so the stateless * Responses design used for OpenAI/xAI does not transfer. * * Capability notes: * - reasoning models (gpt-oss, qwen3) always get `reasoning_format: "parsed"` * so thinking lands in `message.reasoning` (mapped to a thinking part) * instead of `` tags in the text, and tool use / JSON mode stay * valid. Thinking parts carry no signature and are dropped on replay * (Chat Completions has no reasoning replay format); * - `reasoning.effort` maps to `reasoning_effort`: gpt-oss grades * `low`/`medium`/`high` (`xhigh`/`max` cap to `high`); qwen3 only knows * `none`/`default`, so graded efforts are omitted there. * `reasoning.enabled: false` maps to `"none"`, which only qwen3 accepts — * gpt-oss cannot disable reasoning. Omit `reasoning` entirely for * non-reasoning models (Groq rejects the parameters); * - structured output sends `response_format.json_schema`; `strict: true` * (constrained decoding) only where supported (gpt-oss), other models get * best-effort mode — zod schemas still validate client-side either way. * Models without json_schema support (e.g. llama-3.x) reject the request; * - prompt caching is automatic; cache hits surface as * `usage.input.details.cache_read`; * - Groq offers no embeddings API; `embed` throws `invalid_request`. */ declare class GroqProvider implements Provider { readonly name: string; private readonly options; private readonly fetch; private lastRateLimit?; /** * The throttle-counter snapshot from the most recent response that carried * `x-ratelimit-*` headers, or `undefined` if none has been seen yet. A * last-known view, overwritten on each such response — not an accumulator. */ get rateLimit(): RateLimitStatus | undefined; /** Drop the last-known snapshot (admin force-clear of a stale rejected mark). */ clearRateLimit(): void; constructor(options?: GroqProviderOptions); generate(options: GenerateOptions): Promise; stream(options: GenerateOptions): AsyncIterable; embed(_options: EmbedOptions): Promise; private apiKey; private request; private httpError; protected buildRequestBody(options: GenerateOptions, stream: boolean): Promise>; private parseResponse; private parseStream; } //#endregion //#region src/providers/modal.d.ts /** Models are whatever the caller deployed; there is no known-model list. */ type ModalModel = string; interface ModalProviderOptions { /** * Deployment root URL (e.g. `https://workspace--app-serve.modal.run`); cardan * appends `/v1/chat/completions`, so do NOT include a trailing `/v1`. Resolved * as `baseUrl` > `MODAL_BASE_URL` > the us-west-2 Modal gateway default * ({@link DEFAULT_BASE_URL}). */ baseUrl?: string; /** * Bearer token for servers started with an API key (vLLM `--api-key`, * SGLang `--api-key`). Defaults to the `MODAL_API_KEY` environment * variable. Optional — endpoints may be unauthenticated. */ apiKey?: string; /** * Modal Proxy Auth Token, sent as the `Modal-Key` / `Modal-Secret` headers * for endpoints deployed with `requires_proxy_auth=True`. Defaults to the * `MODAL_KEY` / `MODAL_SECRET` environment variables (cardan's convention, * named after the headers). Optional. */ proxyAuth?: { tokenId: string; tokenSecret: string; }; /** Extra headers on every request. */ headers?: Record; /** Custom fetch implementation (testing, proxies). */ fetch?: typeof globalThis.fetch; /** Default retry behavior for all requests; `false` disables. */ retry?: Partial | false; /** Default per-attempt timeout (ms) for all requests; `0`/undefined disables. */ timeoutMs?: number; } /** * Modal adapter for self-deployed models behind Modal web endpoints. Modal's * documented LLM serving pattern wraps vLLM/SGLang with `@modal.web_server`, * exposing the **Chat Completions** API (`/v1/chat/completions`) — not the * Responses API — so this adapter speaks Chat Completions, including the * `reasoning_content` extension both servers use for reasoning models. * * Capability notes: * - `baseUrl` is required (each deployment has its own `*.modal.run` URL); * - both auth schemes are optional and may be combined: `apiKey` becomes an * `Authorization: Bearer` header (vLLM/SGLang `--api-key`), `proxyAuth` * becomes `Modal-Key`/`Modal-Secret` headers (Modal Proxy Auth Tokens); * - thinking parts are not replayable in Chat Completions and are dropped * when converting messages; responses map `reasoning_content` to a * thinking part (no signature, so it never replays anywhere); * - `reasoning.effort` maps to `reasoning_effort` (`xhigh`/`max` cap to * `high`); servers/models without support reject it — omit `reasoning` * then. `reasoning.enabled` has no generic Chat Completions mapping and is * ignored; use `providerOptions` for model-specific switches (e.g. * `chat_template_kwargs: { enable_thinking: false }` on vLLM); * - sends `max_tokens` (not `max_completion_tokens`) for maximal * compatibility with self-hosted servers; * - streaming requests `stream_options: { include_usage: true }`; servers * that ignore it yield zero usage; * - `embed` targets `/v1/embeddings` and only works if the deployment serves * an embedding model. */ declare class ModalProvider implements Provider { readonly name: string; private readonly options; private readonly fetch; constructor(options?: ModalProviderOptions); generate(options: GenerateOptions): Promise; stream(options: GenerateOptions): AsyncIterable; embed(options: EmbedOptions): Promise; private baseUrl; private authHeaders; private request; private httpError; private buildRequestBody; private parseResponse; private parseStream; } //#endregion //#region src/providers/openai.d.ts /** Known OpenAI model ids — literal-only, drives editor autocomplete. */ type OpenAIModelId = "gpt-5.6" | "gpt-5.6-sol" | "gpt-5.6-terra" | "gpt-5.6-luna" | "gpt-5.4-nano" | "gpt-5.3-codex" | "o3" | "o4-mini" | "text-embedding-3-small" | "text-embedding-3-large"; type OpenAIModel = OpenAIModelId | (string & {}); interface OpenAIProviderOptions { /** Defaults to the `OPENAI_API_KEY` environment variable. */ apiKey?: string; /** Defaults to `https://api.openai.com`. */ baseUrl?: string; /** Extra headers on every request (e.g. `OpenAI-Organization`). */ headers?: Record; /** Custom fetch implementation (testing, proxies). */ fetch?: typeof globalThis.fetch; /** Default retry behavior for all requests; `false` disables. */ retry?: Partial | false; /** Default per-attempt timeout (ms) for all requests; `0`/undefined disables. */ timeoutMs?: number; } interface OpenAIItem { type?: string; [key: string]: unknown; } interface OpenAIUsage { input_tokens?: number; input_tokens_details?: { cached_tokens?: number; }; output_tokens?: number; output_tokens_details?: { reasoning_tokens?: number; }; } interface OpenAIResponseBody { id?: string; status?: string; output?: OpenAIItem[]; usage?: OpenAIUsage; error?: { code?: string; message?: string; } | null; incomplete_details?: { reason?: string; } | null; /** Top-level citation list emitted by some Responses-compatible servers (xAI). */ citations?: unknown; } /** * OpenAI adapter built on the **Responses API** (`/v1/responses`), used * statelessly: every request sends `store: false` plus * `include: ["reasoning.encrypted_content"]`, so multi-turn context is * replayed from `messages` and reasoning survives across turns without * server-side storage (override via `providerOptions` if you want `store`). * * Capability notes: * - the Responses API has no stop-sequence parameter; `stopSequences` is * ignored; * - reasoning effort is mapped per model family (see * {@link convertReasoning}): gpt-5.6 accepts `max` as distinct from * `xhigh`; Codex tops at `xhigh`; o-series tops at `high`; * `enabled: false` → `effort: "none"` only on gpt-5.1+, otherwise the * `reasoning` field is omitted (o-series / Codex reject `none`). * * Providers with Responses-compatible APIs (xAI) subclass this adapter and * override the protected hooks (base URL, API key env var, sampling-param * support, reasoning mapping). */ declare class OpenAIProvider implements Provider { readonly name: string; protected readonly defaultBaseUrl: string; protected readonly apiKeyEnv: string; /** * Whether the provider reports `reasoning_tokens` *on top of* `output_tokens` * (xAI: `total = input + output + reasoning`) rather than *inside* it (OpenAI: * reasoning is a subset of `output_tokens`). When true, {@link mapUsage} folds * reasoning into `output.total` so billing reflects the true output count. */ protected readonly reasoningIsAdditive: boolean; private readonly options; protected readonly fetch: typeof globalThis.fetch; constructor(options?: OpenAIProviderOptions); generate(options: GenerateOptions): Promise; stream(options: GenerateOptions): AsyncIterable; embed(options: EmbedOptions): Promise; protected apiKey(): string; private request; private requestGet; private httpError; private buildRequestBody; /** * Resolves whether to run in background mode: explicit `background` wins; * otherwise auto-enable for high-effort reasoning (`high`/`xhigh`/`max`), * whose long generations are the ones at risk of idle-connection drops. */ protected resolveBackground(options: GenerateOptions): boolean; /** * Reasoning models reject sampling parameters (`temperature`, `top_p`); the * adapter drops them instead of failing the request. The `*chat*` variants * (e.g. `gpt-5.6-terra-chat-latest`) are non-reasoning and keep them. */ protected supportsSamplingParams(model: string): boolean; /** Whether `model` supports the built-in web-search tool. */ protected supportsWebSearch(model: string): boolean; /** Builds the Responses API `web_search` tool entry from generic options. */ protected buildWebSearchTool(options: WebSearchOptions): Record; /** Extracts web-search citations from a finished response. */ protected extractCitations(raw: OpenAIResponseBody): WebCitation[]; /** * Map generic reasoning options onto the Responses API `reasoning` object. * Returning undefined omits the field. Per-model ceilings and the `none` * switch live here so callers can use the full cardan effort scale. */ protected convertReasoning(reasoning: NonNullable, model: string): Record | undefined; private parseResponse; private parseStream; /** * Maps one parsed SSE event to zero or more {@link StreamEvent}s; `done` is * set once the terminal `response.completed`/`response.incomplete` arrives. * Throws on `response.failed`/`error`. Shared by the plain and background * streaming paths. */ private mapStreamEvent; /** Polls a background response until it leaves `queued`/`in_progress`. */ private pollBackground; /** * Streams a background response, transparently reconnecting a dropped SSE via * `GET /v1/responses/{id}?stream=true&starting_after=` so a * cut connection no longer fails the whole run. The caller's `signal` bounds * the total time and is honored as a hard stop (no resume after abort). */ private streamBackground; /** Opens an SSE request and returns its body, retrying like other requests. */ private openStream; /** A mid-stream failure is resumable only when it's a connection drop. */ private canResume; } //#endregion //#region src/providers/xai.d.ts /** Known xAI model ids — literal-only, drives editor autocomplete. */ type XAIModelId = "grok-4.5" | "grok-4.20-0309-reasoning" | "grok-4.20-0309-non-reasoning" | "grok-4.20-multi-agent-0309" | "grok-4-fast-reasoning" | "grok-4-fast-non-reasoning" | "grok-code-fast-1"; type XAIModel = XAIModelId | (string & {}); interface XAIProviderOptions { /** Defaults to the `XAI_API_KEY` environment variable. */ apiKey?: string; /** Defaults to `https://api.x.ai`. */ baseUrl?: string; /** Extra headers on every request. */ headers?: Record; /** Custom fetch implementation (testing, proxies). */ fetch?: typeof globalThis.fetch; /** Default retry behavior for all requests; `false` disables. */ retry?: Partial | false; /** Default per-attempt timeout (ms) for all requests; `0`/undefined disables. */ timeoutMs?: number; } /** * xAI Grok adapter. xAI's Responses API (`/v1/responses`) is wire-compatible * with OpenAI's (their Chat Completions endpoint is documented as legacy), so * this subclasses the OpenAI adapter and only overrides the capability hooks. * Like the OpenAI adapter it runs statelessly: `store: false` + * `include: ["reasoning.encrypted_content"]`, with context replayed from * `messages` (override via `providerOptions`). * * Capability notes: * - `reasoning.effort` accepts `low`/`medium`/`high` on grok-4.5+ (verified * against grok-4.5); older/fast SKUs omit the field. `none` is rejected * (`reasoning_effort value none`), so reasoning cannot be disabled — the * `reasoning` field is simply omitted instead. `xhigh`/`max` cap to `high`. * No `summary` parameter is sent — xAI always returns detailed reasoning * summaries for reasoning models. * - grok models accept `temperature`/`top_p` even when reasoning. * - xAI offers no embeddings API; `embed` throws `invalid_request`. * - `background` is never sent: xAI's Responses API rejects it (`Argument not * supported: background`). The mechanism is OpenAI-only, so the auto-background * behavior inherited from the OpenAI adapter is disabled here. */ declare class XAIProvider extends OpenAIProvider { readonly name: string; protected readonly defaultBaseUrl: string; protected readonly apiKeyEnv: string; protected readonly reasoningIsAdditive: boolean; /** Kept for the image path, which builds its own request (not via OpenAIProvider). */ private readonly imageOptions; constructor(options?: XAIProviderOptions); protected supportsSamplingParams(): boolean; /** xAI's Responses API rejects `background`; the mechanism is OpenAI-only. */ protected resolveBackground(): boolean; protected convertReasoning(reasoning: NonNullable, model: string): Record | undefined; protected supportsWebSearch(model: string): boolean; /** * xAI's `web_search` tool diverges from OpenAI's: domain filters live in * `filters` (capped at five, allowed/excluded mutually exclusive) and there * is no `search_context_size`/`user_location`. */ protected buildWebSearchTool(options: WebSearchOptions): Record; /** xAI also reports sources as a top-level `citations` list on the response. */ protected extractCitations(raw: OpenAIResponseBody): WebCitation[]; embed(_options: EmbedOptions): Promise; /** Imagine image generation / editing, billed to the API key. */ generateImage(options: ImageGenerateOptions): Promise; } //#endregion //#region src/providers/xai-oauth.d.ts /** * The `~/.grok/auth.json` scope key under which `grok login` stores the OIDC * session token: `{ "": { "key": , "refresh_token": ... } }`. * The scope is `{issuer}::{client_id}`; the `::` suffix is the OAuth client id * (not an audience). Override the parts via `issuer` / `clientId` if yours differ. */ declare const GROK_AUTH_SCOPE = "https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"; /** * SuperGrok **weekly** usage pool (shared across Chat / Build / Imagine / …), * from `GET /v1/billing?format=credits` — what the CLI's `/usage show` reads. * * Distinct from bare `GET /v1/billing` (monthly credit ledger) and from * per-response `x-ratelimit-*` throttle counters. */ interface XAISubscriptionUsage { /** Fraction of the weekly pool consumed, 0..1. */ utilization: number; /** Same as utilization × 100 (`creditUsagePercent`). */ percent: number; /** Period kind from the API, e.g. `USAGE_PERIOD_TYPE_WEEKLY`. */ periodType: string; /** Current period start, epoch ms. */ periodStart?: number; /** Current period end (reset time), epoch ms. */ periodEnd?: number; /** Per-product share of the pool (percent 0..100 when reported). */ products: Array<{ product: string; usagePercent?: number; }>; /** Extra Usage Credits balance (prepaid), credits. */ prepaidBalance: number; /** On-demand overage cap; `0` = disabled. */ onDemandCap: number; /** On-demand credits used this period. */ onDemandUsed: number; /** Unified billing user (shared weekly pool across products). */ isUnified: boolean; /** * Same snapshot as {@link RateLimitStatus} for pool / ops observability — * populates `sevenDay` (+ representative/status/resetAt). */ rateLimit: RateLimitStatus; /** Raw `config` object from the response, for forward-compat. */ raw: unknown; } /** A Grok CLI OAuth credential set, as stored in `~/.grok/auth.json`. */ interface XAIOAuthCredentials { /** Bearer sent to the proxy — the `key` field in `~/.grok/auth.json`. */ accessToken: string; /** Mints new access tokens; rotates on refresh. Absent = refresh disabled. */ refreshToken?: string | null; /** Epoch ms. Absent means unknown — no proactive refresh, refresh on 401 only. */ expiresAt?: number | null; } interface XAIOAuthProviderOptions { /** The `grok login` credential set (from `~/.grok/auth.json`). */ credentials: XAIOAuthCredentials; /** * Called after each successful refresh with the rotated credentials. Persist * them back to `~/.grok/auth.json` — the old refresh token stops working once * a new one is issued. */ onRefresh?: (credentials: Required) => void | Promise; /** * Re-read credentials from the persistence layer before a network refresh; * externally rotated credentials are adopted without a token-endpoint call. */ reload?: () => XAIOAuthCredentials | undefined | Promise; /** * OAuth2/OIDC issuer whose token endpoint is resolved via discovery * (default `https://auth.x.ai`). Ignored when {@link tokenUrl} is set. For a * Grok credential this is the file's `oidc_issuer`. */ issuer?: string; /** Skip discovery and POST the refresh grant to this token endpoint directly. */ tokenUrl?: string; /** * OAuth client id for the refresh grant (default the Grok CLI public client). * For a Grok credential this is the file's `oidc_client_id`. */ clientId?: string; /** Team-login principal type, forwarded on refresh when set (personal = omit). */ principalType?: string; /** Team-login principal id, forwarded on refresh when set (personal = omit). */ principalId?: string; /** Override the proxy base URL (default `cli-chat-proxy.grok.com`). */ baseUrl?: string; /** Override the Imagine base URL (default `api.x.ai`). */ imagineBaseUrl?: string; /** * CLI version sent as `x-grok-client-version` (default `0.2.93`). The proxy * 426s clients below its floor (>= 0.1.202 when verified); raise this if the * proxy starts rejecting the default. */ clientVersion?: string; /** Client surface sent as `x-grok-client-surface` (default `grok-shell`). */ clientSurface?: string; /** Extra headers on every request. */ headers?: Record; /** Custom fetch implementation (testing, proxies). */ fetch?: typeof globalThis.fetch; /** Default retry behavior for all requests; `false` disables. */ retry?: Partial | false; /** Default per-attempt timeout (ms) for all requests; `0`/undefined disables. */ timeoutMs?: number; } /** * Grok CLI subscription provider. Speaks Chat Completions against the CLI chat * proxy with the `grok login` OAuth token. Pass standard xAI model ids * (e.g. `grok-4.5`); the proxy also accepts the CLI's own `grok-build`. * * Quota: call {@link subscriptionUsage} (or rely on ops refresh) to load the * weekly SuperGrok pool into {@link rateLimit}.`sevenDay` — same shape pool * members and Anthropic OAuth already expose for observability. */ declare class XAIOAuthProvider extends GroqProvider { readonly name: string; private readonly proxyBase; private readonly imagineBase; private readonly authedFetch; private readonly imageDefaults; /** Last weekly-pool snapshot, merged into {@link rateLimit}. */ private lastSubscriptionLimit?; constructor(options: XAIOAuthProviderOptions); /** * Weekly subscription pool + last-seen `x-ratelimit-*` throttle counters. * Pool / ops read this via {@link Provider.rateLimit} and * {@link PoolProvider.rateLimits}. */ get rateLimit(): RateLimitStatus | undefined; /** Drop throttle + weekly-pool snapshots (admin force-clear). */ clearRateLimit(): void; /** * Fetch the SuperGrok weekly usage pool (`GET /v1/billing?format=credits`) * and cache it on {@link rateLimit}. Safe to call from ops / admin; not * required on every chat turn. */ subscriptionUsage(): Promise; /** * Imagine image generation / editing on the subscription. Unlike chat, this * goes direct to `api.x.ai` (the chat proxy has no image endpoints); the * OAuth bearer authenticates there and usage is metered to the account. */ generateImage(options: ImageGenerateOptions): Promise; /** * Unlike Groq (which side-channels usage via `x_groq.usage`), the CLI proxy * follows stock Chat Completions semantics: streaming responses carry no * usage unless `stream_options.include_usage` is requested, so without this * every streamed turn reports zero tokens. */ protected buildRequestBody(options: GenerateOptions, stream: boolean): Promise>; } /** Convenience factory mirroring the other cardan provider constructors. */ declare function createXAIOAuthProvider(options: XAIOAuthProviderOptions): Provider; //#endregion //#region src/conversation.d.ts /** * The slice of {@link Cardan} a conversation drives. Any `provider/model` * router with a `generate` is enough; `Cardan` satisfies it structurally. */ interface ConversationClient { generate(options: Omit & { model: ModelId; }): Promise; } /** Per-call telemetry, emitted once per `generate` (success or failure). The * consumer decides how to format/route it — cardan itself logs nothing. */ interface CallInfo { /** `label` or `label/step`, for log prefixes. */ tag?: string; model: ModelId; /** Wall-clock duration in milliseconds. */ ms: number; usage: Usage; /** Number of web-search citations gathered this call. */ citations: number; /** Present on success. */ finishReason?: FinishReason; /** Present on failure (the thrown value). */ error?: unknown; } /** Per-turn options. Every key is a default the conversation can carry (set at * construction or reassigned on `defaults`) and override per `ask`; none is * privileged — `model` and `tools` are merged the same way. */ interface AskOptions extends Omit, "model" | "messages" | "tools"> { /** `provider/model`; overrides the conversation default for this turn. */ model?: ModelId; /** Client-side tools; when present, `ask` loops model↔tools until it stops. */ tools?: ToolHandler[]; /** Max model↔tool round-trips before forcing a tool-free conclusion. */ maxRounds?: number; /** After the tool loop, rewrite the round-trips it appended so their bulky raw * tool outputs aren't replayed on later turns. `true` uses the default * {@link redactToolResults} compactor (keeps the tool-use trace, blanks the * result payloads); pass your own {@link Compactor} to customize (e.g. * {@link dropToolRounds}, or an LLM summary). */ compact?: boolean | Compactor; /** Phase tag for per-call telemetry (e.g. "research", "structure"). */ step?: string; } interface ConversationOptions extends AskOptions { /** Default `provider/model` for every turn; required at construction. */ model: ModelId; /** Optional system prompt, prepended as the first turn. */ system?: string; /** Purpose tag for per-call telemetry (e.g. "screen", "investigate "). */ label?: string; /** Telemetry sink invoked once per `generate`. */ onCall?(info: CallInfo): void; } /** A client-side tool: its cardan declaration plus a handler that runs when the * model calls it. `run` returns the text result fed back to the model. Prefer * {@link defineTool} so `args` is typed from the schema. */ interface ToolHandler { tool: Tool; run(args: unknown, signal?: AbortSignal): string | Promise; } /** Build a {@link ToolHandler} whose `run` receives args typed from `parameters` * (a zod schema infers the type; a plain JSON Schema yields `unknown`). */ declare function defineTool(spec: { name: string; description?: string; parameters: S; }, run: (args: Infer, signal?: AbortSignal) => string | Promise): ToolHandler; /** Rewrites the region a tool loop appended after this turn's user prompt — the * assistant tool-call rounds, the tool results, and the final tool-free * conclusion — into a shorter replacement spliced back in its place. Keep any * `tool_call` paired with its `tool_result` (or rely on message normalization * to backfill a result) so the transcript stays replayable. */ type Compactor = (region: Message[]) => Message[]; /** Default compactor: keep the whole tool-use trace (the calls and the final * conclusion) but replace each tool result's payload with a short placeholder. * The model still sees that it reached the conclusion *by using tools* — only * the bulky raw bodies (page text, etc.) are shed — so later turns won't * mistake the conclusion for innate knowledge, and raw content can't trip * provider content filters on replay. */ declare const redactToolResults: Compactor; /** Aggressive compactor: drop the tool-use trace entirely, keeping only the * model's final conclusion. Smallest transcript, but later turns can no longer * tell the conclusion came from tool use. */ declare const dropToolRounds: Compactor; /** A running transcript over a {@link ConversationClient}: hold the message * history and collapse the repeated "push user → generate → push assistant" * dance into one call. Multi-step workflows read cleanly: * * const c = cardan.conversation({ model }); * await c.ask("research …", { webSearch: true, tools, compact: true }); * const { output } = await c.ask("emit JSON …", { output: { schema } }); */ declare class Conversation { /** Full transcript, mutated in place across turns (replayable to the model). */ readonly messages: Message[]; /** Generation defaults carried across turns; each `ask` merges call options * over these. Reassign any key (e.g. `defaults.model`) to change it for all * later turns. */ defaults: AskOptions; /** Purpose tag for per-call telemetry; reassignable. */ label?: string; private readonly client; private readonly onCall?; constructor(client: ConversationClient, options: ConversationOptions); /** Branch this conversation: a new `Conversation` sharing the same client and * defaults but with an independent copy of the transcript. Diverging turns on * the fork never touch this one — use it before fanning out in parallel so * branches don't mutate a shared `messages` array. `overrides` tweak the * fork's defaults/label/onCall (a `system` override is ignored, since the copy * already carries the original system turn). */ fork(overrides?: Partial): Conversation; /** Append a user text turn, generate, append the assistant reply, return it. * When `options.tools` are present, loop model↔tools until the model stops * (optionally compacting the intermediate rounds afterwards). */ ask(text: string, options?: AskOptions): Promise>>; /** Generate against the current transcript and append the reply. No new user * turn is added. `gen` holds the merged per-turn options; `rawTools` are the * cardan tool declarations for this call (none for a plain turn). */ private generateOnce; /** Loop: generate → run any tool calls → feed results back, until the model * stops calling tools. The final round (at maxRounds) forbids tools so the * model must produce a prose conclusion — guaranteeing the last message * carries no dangling tool call. */ private runToolLoop; } //#endregion //#region src/agent.d.ts /** * Cross-session memory for an {@link Agent} — what it carries *between* * conversations (a transcript is within one). cardan only decides *when* to call * these (recall before a run, observe after); where and how to store, and whether * to summarize, is the caller's implementation. Not a vector store. */ interface Memory { /** Text appended to the system prompt before a run. */ recall(): string | Promise; /** Update memory after a completed run, given its result. */ observe(result: GenerateResult): void | Promise; } /** An agent's fixed identity. Pass to {@link Cardan.agent}. */ interface AgentSpec { /** Identity label; used as the conversation's telemetry tag. */ name: string; system?: string; /** Default model; may be omitted only if every `run`/`conversation` passes one. */ model?: ModelId; /** Client-side tools the agent may call (auto tool-loop in `run`). */ tools?: ToolHandler[]; memory?: Memory; /** Telemetry sink forwarded to every conversation the agent starts. */ onCall?(info: CallInfo): void; } declare class Agent { private readonly client; readonly spec: AgentSpec; constructor(client: ConversationClient, spec: AgentSpec); /** * Start a fresh {@link Conversation} pre-configured with this agent's identity, * for callers who drive the turns themselves (mid-run / conditional steering). * Does **not** apply `memory`: under manual driving the observe timing is * undefined — use {@link run} for the recall→act→observe loop, or inject memory * into `system` yourself. */ conversation(options?: AskOptions): Conversation; /** * Run one closed task: recall memory → `ask` (auto tool-loop if the agent has * tools) → observe → return. The returned result's `usage` is the * **accumulated** total across every generate this run made (tool-loop rounds * included), not just the last turn — so reading it gives the task's full cost. */ run(input: string, options?: AskOptions): Promise; /** Resolve ConversationOptions from the spec: model (per-call override wins), * system (+ recalled memory), tools, telemetry tag, and onCall sink. */ private buildOptions; } //#endregion //#region src/concurrency.d.ts /** * Concurrency-limited parallel map. Runs `fn` over `items` with at most * `concurrency` tasks in flight at once (default: unlimited), preserving input * order in the result. Fail-fast: the first rejection rejects the whole call * (already-running tasks are left to settle). The `signal` is checked before * each task starts *and* forwarded to `fn` as its third argument, so the work * itself (e.g. a `conversation.ask`) can be cancelled mid-flight — pass it on. * * This is the recommended way to fan work out *inside* a single workflow node * (e.g. research N items concurrently), as opposed to graph-level fan-out. */ declare function parallel(items: readonly T$1[], fn: (item: T$1, index: number, signal?: AbortSignal) => R | Promise, options?: { concurrency?: number; signal?: AbortSignal; }): Promise; //#endregion //#region src/pool.d.ts /** * A pool member: an underlying provider, its rotation weight, and a label. * The provider already carries its own credentials (api key / OAuth), so the * pool only decides *which* member serves a request and *when* to switch. */ interface PoolMember { /** A fully configured provider (e.g. `new AnthropicProvider({ oauth })`). */ provider: Provider; /** * Relative weight; the member appears this many times in the rotation. * Must be a positive integer. Default 1. */ weight?: number; /** * Human-readable id used in failover logs. Never the secret — defaults to * `${provider.name}[${index}]`. */ label?: string; } /** Passed to {@link PoolOptions.onFailover} on each account switch. */ interface PoolFailoverInfo { /** Provider name shared by the pool members. */ provider: string; /** Label of the member that just failed. */ fromLabel: string; /** Label of the member being switched to. */ toLabel: string; /** 0-based index of the failed attempt within this request. */ attempt: number; /** The error that triggered the switch. */ error: CardanError; } /** Pool tuning shared by every pool, independent of its members. */ interface PoolBehavior { /** * Max number of account switches on failure. Default: distinct members − 1 * (each member is tried at most once per request). `0` disables failover. */ maxFailovers?: number; /** * Decides whether an error should trigger a switch to the next account. * Default: `rate_limit | auth | server | network | timeout`. `aborted` is * always treated as non-failover (caller-initiated cancellation). */ shouldFailover?: (error: CardanError) => boolean; /** * Cap on the cooldown derived from an error's *relative* `retryAfterMs`, in ms. * Default 15 min. Bounds an over-long or hostile `Retry-After`; a member is * re-tried after at most this long even if the header asked for more. An * *absolute* `error.resetAt` (e.g. a subscription window reset) is exact and is * honored as-is, not capped. */ maxCooldownMs?: number; /** * Called on each switch. When set, it *replaces* the default `console.warn` * (so structured logging / metrics don't double up with console noise). */ onFailover?: (info: PoolFailoverInfo) => void; } /** * A pool member: either a bare provider (weight 1, auto-labeled) or a * {@link PoolMember} when you need a custom weight or label. */ type PoolMemberInput = Provider | PoolMember; interface PoolOptions extends PoolBehavior { /** Pool members; at least one required. */ members: PoolMemberInput[]; } /** * An account pool that satisfies the {@link Provider} interface, so it can be * used directly or injected via `new Cardan({ providers: { anthropic: pool } })`. * * On construction it generates a fixed, evenly interleaved rotation from the * members' weights; each request takes the next slot round-robin. On a * failover-class error it switches to the next *distinct* member and retries, * emitting a warning. Since the pool owns the cross-account retry, it disables * the underlying provider's own retry per attempt when ≥2 members are tried, or * on an all-cooling last-ditch attempt (avoids hanging on a long Retry-After). * A single ready member still preserves the caller's retry. For `stream`, a * switch is only possible before the first event is yielded. * * A request may pin a member by label via `GenerateOptions.poolMember` (e.g. * to stay on the account holding a conversation's prompt cache). A ready * pinned member serves first (failover order is unchanged after it); a cooling * or unknown label falls back to normal rotation. Pinning that displaces the * rotation's own pick puts *debt* on the pinned member, and unpinned requests * repay it by moving that member to the back of the attempt order until the * debt drains — usage stays roughly balanced without hard guarantees (debt is * capped at {@link PIN_DEBT_CAP} × weight). The member that actually served is * reported on `GenerateResult.poolMember` / the `finish` event. */ declare class PoolProvider implements Provider { readonly name: string; embed?: (options: EmbedOptions) => Promise; generateImage?: (options: ImageGenerateOptions) => Promise; private readonly members; private readonly sequence; private readonly maxFailovers; private readonly maxCooldownMs; private readonly shouldFailover; private readonly onFailover?; /** Per-(member, model) cooldown deadlines (epoch ms), from a relative `retryAfterMs`; keyed by {@link cooldownKey}. */ private readonly cooldowns; /** Per-member cooldown deadlines (epoch ms), from an account-wide absolute `resetAt`; keyed by member index. */ private readonly memberCooldowns; /** Outstanding pinned serves per member index, repaid by unpinned requests. */ private readonly pinDebt; /** Administratively disabled member indexes (see {@link setDisabledMembers}). */ private readonly disabledMembers; private cursor; constructor(options: PoolOptions); /** * Each member's last-known subscription rate-limit snapshot (see * {@link Provider.rateLimit}), by label — a live view of remaining quota per * account, for observability. The pool itself never acts on these: it only * cools a member on a real rate-limit error (see {@link recordCooldown}), * never on a soft-warning snapshot, so a member with quota left keeps serving. */ rateLimits(): Array<{ label: string; rateLimit: RateLimitStatus | undefined; }>; /** * Replace the set of administratively disabled members, matched by label * (unknown labels are ignored). Disabled members are skipped by selection, * failover, and the all-cooling last-ditch try, and a `poolMember` pin to * one falls back to rotation — until a later call re-enables them. Requests * fail with `invalid_request` when every member is disabled. */ setDisabledMembers(labels: Iterable): void; /** * Force-clear a member's cooldowns and last-known rate-limit snapshot so an * admin can re-admit a subscription account marked rejected/exhausted before * its natural reset. Clears the member-wide cooldown, every per-model * cooldown for that member, and calls {@link Provider.clearRateLimit} when * the underlying provider implements it. Unknown labels are no-ops * (`false`). Does not re-enable an administratively disabled member. */ clearMemberLimits(label: string): boolean; generate(options: GenerateOptions): Promise; stream(options: GenerateOptions): AsyncIterable; /** * Shared failover loop for unary calls (`generate`, `embed`, `generateImage`). * Tries members in rotation order, switching on failover-class errors until one succeeds * or the attempts run out. Returns the member that served alongside the * value so callers can report it. */ private runWithFailover; /** * Picks the members to try for one request to `model`. Walks the rotation from * the next round-robin slot, skipping members still cooling for this model; * the ready ones (capped by `maxFailovers + 1`) are returned. If *all* are * cooling, returns just the soonest-to-recover member as a last-ditch attempt * (`allCooling: true`) — it may have reset early. * * `prefer` pins a member by label: when it's ready it is moved to the front * (recording debt if it displaced the rotation's own pick); a cooling or * unknown label is ignored. Unpinned requests repay outstanding debt by * rotating an indebted front member to the back of the attempt order. */ private plan; /** Charge a pinned serve that displaced the rotation's own pick. */ private recordPinDebt; /** * Repay pin debt on an unpinned request: while the member up next carries * debt, decrement it and move the member to the back. Reorder only — an * indebted member stays available for failover, it just loses priority. */ private repayPinDebt; /** * The effective cooldown deadline for `(member, model)` — the later of the * member-wide cooldown (from an account-wide `resetAt`) and the per-model one * (from a relative `retryAfterMs`) — or `undefined` if neither is active. * Expired entries are thawed (deleted) as a side effect. */ private coolingUntil; /** * Records a cooldown for a member after a failover-class error. An account-wide * absolute `error.resetAt` (e.g. a subscription window reset) cools the *whole * member* across every model, honored exactly. Otherwise a relative * `error.retryAfterMs` cools just `(member, model)`, capped by `maxCooldownMs` * against an over-long/hostile header. A stale (past) `resetAt` falls through to * `retryAfterMs`. With neither signal the member is left in rotation (no blind * cooldown) — a transient fault isn't necessarily an account problem. */ private recordCooldown; /** * Built when every member is cooling for `model` and the last-ditch try failed. * Message is user-safe: no member labels (those may be internal env names). */ private allCoolingError; private isFailover; private emitFailover; } declare function createPool(options: PoolOptions): PoolProvider; //#endregion //#region src/local-oauth.d.ts /** Subscription prefixes that have a local CLI credential file. */ type LocalOAuthPrefix = "anthropic" | "xai"; interface LocalOAuthIO { readFile(path: string): string | undefined; /** Must throw on failure — silent no-ops lose rotated refresh tokens. */ writeFile(path: string, contents: string): void; } interface LocalOAuthMemberBase { /** Ops / pool label (never a secret). */ label: string; /** Absolute credential path when file-backed. */ path?: string; /** True when a refresh token is present (proactive + on-401 refresh). */ canRefresh: boolean; } /** File- or env-backed subscription member (discriminated on {@link prefix}). */ type LocalOAuthMember = (LocalOAuthMemberBase & { prefix: "anthropic"; provider: AnthropicProvider; }) | (LocalOAuthMemberBase & { prefix: "xai"; provider: XAIOAuthProvider; }); /** A bare access token to merge with file-backed members (e.g. from env). */ interface LocalOAuthTokenInput { prefix: LocalOAuthPrefix; accessToken: string; label?: string; } interface LoadLocalOAuthOptions { /** Home directory to scan (default: runtime `os.homedir()`). */ home?: string; /** Which prefixes to load; default both. */ prefixes?: LocalOAuthPrefix[]; /** * Scan CLI credential files under `home` (default `true`). Set `false` to * use only {@link env} / {@link tokens} (e.g. long-lived setup-tokens). */ files?: boolean; /** Injected I/O (tests). Runtime defaults use `node:fs`. */ io?: Partial; /** * Extra bare access tokens (no refresh), typically from env. Deduped against * file credentials by access-token value — **file-backed wins** when equal * (keeps the refreshable member). */ tokens?: LocalOAuthTokenInput[]; /** * Bare env tokens to merge (no refresh). Each **base** name expands to every * set sibling in the process env: `BASE`, `BASE1`, `BASE2`, … `BASE10`, … * (see {@link expandEnvFamily}). Prefix is inferred from the name * (`CLAUDE_CODE_*` → anthropic, `GROK_BUILD_*` → xai). * * - `true` (default): use each loaded prefix's standard base * (`CLAUDE_CODE_OAUTH_TOKEN` / `GROK_BUILD_OAUTH_TOKEN`). * - `false`: do not read env tokens. * - `string` / `string[]`: treat each entry as a base family name. */ env?: boolean | string | string[]; } /** * Shape-based write-back for Claude Code / Grok CLI credential files. * Matches the entry by its current access token field, updates in place, * preserves unrelated keys. Throws when the file or entry cannot be updated * so {@link OAuthTokenManager} surfaces a persistence warning. */ declare function persistLocalOAuth(path: string, prefix: LocalOAuthPrefix, previousAccessToken: string, next: { accessToken: string; refreshToken: string; expiresAt: number | null; }, io: LocalOAuthIO): void; /** * Load subscription OAuth members from CLI credential files (with refresh * write-back) plus optional bare env / explicit tokens. * * Dedupes by access-token value: file-backed members are inserted first so * they beat a matching bare env token (keeps the refreshable member). */ declare function loadLocalOAuth(options?: LoadLocalOAuthOptions): Promise; /** * Members for one prefix only (convenience filter over {@link loadLocalOAuth}). */ declare function loadLocalOAuthPrefix(prefix: "anthropic", options?: Omit): Promise>>; declare function loadLocalOAuthPrefix(prefix: "xai", options?: Omit): Promise>>; /** * Build a {@link PoolProvider} over local OAuth members for one prefix. * Returns `undefined` when there are no members. Always pools (including a * single member) so cooldown and `rateLimits()` are uniform. */ declare function localOAuthPool(prefix: LocalOAuthPrefix, options?: Omit & PoolBehavior): Promise; //#endregion //#region src/env.d.ts /** * Reads an environment variable on Node (`process.env`) or Deno * (`Deno.env`), without depending on either runtime's types or APIs. * Returns undefined when unavailable (e.g. permission-restricted Deno). */ declare function readEnv(name: string): string | undefined; /** * Names of all environment variables visible to this process (Node * `process.env` keys, or Deno `Deno.env.toObject()`). Empty when unavailable. */ declare function listEnvNames(): string[]; /** * Expand a base env name to every **set** sibling in the environment: * exact `BASE`, plus `BASE1`, `BASE2`, … `BASE10`, … (one or more trailing * digits). Order: bare first, then by numeric suffix ascending. * * Used so multi-account pools don't hard-code `TOKEN1`/`TOKEN2` — set as many * numbered vars as you need. */ declare function expandEnvFamily(base: string, names?: readonly string[]): string[]; //#endregion //#region src/normalize.d.ts /** * Normalizes a message sequence into the canonical shape adapters rely on: * * - every tool_result is relocated into a `tool` message immediately after * the assistant message containing its tool_call, in call order; * - dangling tool_calls (call without result) get a synthesized error * result, so resumed/aborted conversations stay replayable; * - a tool_result without a matching tool_call throws (`invalid_request`), * as does a duplicate result for the same call id; * - blank unsigned text parts are dropped (some providers, e.g. Anthropic, * reject empty text blocks; a blank part carries no meaning for any of * them). Signed text parts are kept — a signature must be replayed * verbatim. A message left with no parts is dropped entirely; * - consecutive messages with the same role are merged. */ declare function normalizeMessages(input: Message[]): Message[]; //#endregion //#region src/stream.d.ts /** * Accumulates a stream into a GenerateResult-shaped value. Consecutive * deltas of the same kind collapse into one part; tool calls and thinking * signatures are attached in order. */ declare function collectStream(stream: AsyncIterable): Promise>; /** * Collects a stream into just the assistant `Message`, ready to push back into * the next request's `messages`. Replay-critical state (thinking signatures, * encrypted reasoning content, tool-call signatures) is preserved, so this is * the recommended way to capture a streamed turn for multi-turn replay — much * safer than reassembling a message from raw stream events by hand. */ declare function collectStreamToMessage(stream: AsyncIterable): Promise; //#endregion //#region src/index.d.ts /** * `provider/model` string. Split on the first `/` only — the remainder is * passed verbatim to the provider (model names may themselves contain `/`). */ type ModelId = `anthropic/${AnthropicModelId}` | `google/${GoogleModelId}` | `groq/${GroqModelId}` | `openai/${OpenAIModelId}` | `xai/${XAIModelId}` | (`${string}/${string}` & {}); interface CardanConfig { anthropic?: AnthropicProviderOptions; google?: GoogleProviderOptions; groq?: GroqProviderOptions; /** Self-deployed models on Modal; `baseUrl` is per-deployment. */ modal?: ModalProviderOptions; openai?: OpenAIProviderOptions; xai?: XAIProviderOptions; /** Grok Build subscription (`grok login`) for the `xai` prefix; see auth precedence. */ xaiOAuth?: XAIOAuthProviderOptions; /** Additional or overriding providers, keyed by prefix. */ providers?: Record; /** * Global observer fired once per logical `generate` / `stream` / `embed` * (after pool failover / per-attempt retries). Absent = no instrumentation. */ telemetry?: TelemetryOptions; } type Prefixed = Omit & { model: ModelId; }; declare class Cardan { private readonly config; private readonly cache; constructor(config?: CardanConfig); provider(name: string): Provider; /** * Selects the `xai` auth path. Precedence (most explicit first): config * `xaiOAuth` > config `xai.apiKey` > env `GROK_BUILD_OAUTH_TOKEN` * (Grok Build subscription) > env `XAI_API_KEY`. A bare env token is * inference-only (no refresh); pass `xaiOAuth` for the refreshable flow. */ private resolveXAI; generate(options: Prefixed>): Promise>>; stream(options: Prefixed): AsyncIterable; /** Start a stateful {@link Conversation} bound to this client's config. */ conversation(options: ConversationOptions): Conversation; /** Build an {@link Agent}: a reusable identity (+ optional cross-session memory) * over this client. The agent has no runtime of its own — it builds * Conversations on demand. */ agent(spec: AgentSpec): Agent; embed(options: Prefixed): Promise; private route; /** Fire `telemetry.onRequest`, swallowing observer failures. */ private emitTelemetry; /** * Wrap a provider stream: one telemetry event on normal completion, throw, * or early consumer abandon (`return` before finish → `ok: true`, no usage). * `durationMs` starts at the first `next()`. */ private streamWithTelemetry; } declare function createCardan(config?: CardanConfig): Cardan; //#endregion export { Agent, type AgentSpec, type AnthropicExperimentalOptions, type AnthropicModel, type AnthropicModelId, type AnthropicOAuthOptions, AnthropicProvider, type AnthropicProviderOptions, type AskOptions, type CallInfo, Cardan, CardanConfig, CardanError, type Compactor, type ContentPart, Conversation, type ConversationClient, type ConversationOptions, DEFAULT_RETRY, type DetectOptions, type DetectedCredential, type EmbedOptions, type EmbedResult, type ErrorCode, type ExtractedProviderError, type FinishReason, GROK_AUTH_SCOPE, type GenerateOptions, type GenerateResult, type GeneratedImage, type GoogleModel, type GoogleModelId, GoogleProvider, type GoogleProviderOptions, type GroqModel, type GroqModelId, GroqProvider, type GroqProviderOptions, type ImageGenerateOptions, type ImageGenerateResult, type ImagePart, type Infer, type JsonSchema, type LoadLocalOAuthOptions, type LocalOAuthIO, type LocalOAuthMember, type LocalOAuthPrefix, type LocalOAuthTokenInput, type Memory, type Message, type ModalModel, ModalProvider, type ModalProviderOptions, ModelId, type OAuthCredentials, type OpenAIModel, type OpenAIModelId, OpenAIProvider, type OpenAIProviderOptions, type PoolBehavior, type PoolFailoverInfo, type PoolMember, type PoolMemberInput, type PoolOptions, PoolProvider, type Provider, type ProviderBlockPart, type ProviderDetection, type RateLimitCounter, type RateLimitStatus, type RateLimitWindow, type ReasoningEffort, type RetryOptions, type Role, type SchemaInput, type StreamEvent, type TelemetryEvent, type TelemetryOptions, type TextPart, type ThinkingPart, type Tool, type ToolCallPart, type ToolChoice, type ToolHandler, type ToolResultPart, type Usage, type UserDetection, type UserHome, type WebCitation, type WebSearchOptions, type XAIModel, type XAIModelId, type XAIOAuthCredentials, XAIOAuthProvider, type XAIOAuthProviderOptions, XAIProvider, type XAIProviderOptions, type XAISubscriptionUsage, type ZodLikeSchema, codeFromProviderType, collectStream, collectStreamToMessage, createCardan, createPool, createXAIOAuthProvider, defineTool, detectAllUsers, detectCredentials, dropToolRounds, emptyUsage, expandEnvFamily, extractProviderError, hasAnyCredential, isCardanError, isExpired, isIncompleteFinish, listEnvNames, loadLocalOAuth, loadLocalOAuthPrefix, localOAuthPool, normalizeMessages, parallel, persistLocalOAuth, readEnv, redactToolResults, streamCardanError, textMessage };