import type { Api, FetchImpl, Message, Model, ProviderSessionState, ServiceTier, SimpleStreamOptions, StreamFunction, StreamOptions, Usage } from "../types.js"; import { type AnthropicFetchOptions, type AnthropicMessagesClientLike } from "./anthropic-client.js"; import { type FallbackParam, type MessageParam } from "./anthropic-wire.js"; export type AnthropicHeaderOptions = { apiKey: string; baseUrl?: string; isOAuth?: boolean; extraBetas?: string[]; stream?: boolean; modelHeaders?: Record; isCloudflareAiGateway?: boolean; claudeCodeSessionId?: string; coworkBetas?: readonly string[]; /** Allow explicit fingerprint headers to replace OAuth defaults on non-official endpoints. */ allowAnthropicHeaderOverrides?: boolean; }; export declare function normalizeAnthropicBaseUrl(baseUrl?: string): string | undefined; export declare function buildBetaHeader(baseBetas: readonly string[], extraBetas: readonly string[]): string; export declare function buildAnthropicHeaders(options: AnthropicHeaderOptions): Record; /** * Clears the in-session "server rejected fast mode" sticky flag. Call when the * caller is explicitly re-arming `serviceTier: "priority"` (e.g. user toggled * `/fast on` after a previous turn auto-disabled it) so the next request * actually carries `speed: "fast"` again. No-op when the map or state entry * hasn't been materialized yet. */ export declare function clearAnthropicFastModeFallback(providerSessionState: Map | undefined): void; /** * Whether the direct Anthropic model's endpoint-scoped fast-mode fallback is * currently active. Reading the map directly is intentional: inspection must * not materialize a state entry for a model that has never streamed. */ export declare function isAnthropicFastModeFallbackDisabled(providerSessionState: Map | undefined, model: Model): boolean; export * from "./claude-code-fingerprint.js"; export declare function mapStainlessArch(arch: string): "x64" | "arm64" | "x86" | `other::${string}`; /** Static headers emitted by Cowork's Linux Claude runtime. */ export declare const coworkHeaders: { "X-Stainless-Arch": "arm64" | "x64" | "x86" | `other::${string}`; "X-Stainless-Lang": string; "X-Stainless-OS": string; "X-Stainless-Package-Version": string; "X-Stainless-Retry-Count": string; "X-Stainless-Runtime": string; "X-Stainless-Runtime-Version": string; "X-Stainless-Timeout": string; }; /** * Wraps a fetch implementation to patch the Claude Code billing-header `cch` * attestation into outgoing request bodies. Bodies without the placeholder * pass through untouched, so installing it on every OAuth flow is safe. */ export declare function wrapFetchForCch(base: FetchImpl): FetchImpl; export declare function isClaudeCloakingUserId(userId: string): boolean; export declare function generateClaudeCloakingUserId(): string; export declare function deriveClaudeDeviceId(installId: string, accountId?: string): string; /** * Resolve the `metadata.user_id` field for an Anthropic Messages request. * * For API-key tokens, an explicit caller-supplied `userId` is forwarded * verbatim and `undefined` yields no metadata. For OAuth tokens the value * must match the Claude Code attribution shape (`isClaudeCloakingUserId` or * the `{session_id, account_uuid?, device_id?}` JSON envelope) — anything * else is dropped and a fresh Claude-Code-style JSON id is generated from * `sessionId`/`accountId` so attribution stays consistent across the main * streaming path and provider-specific request builders (e.g. web search). */ export declare function resolveAnthropicMetadataUserId(userId: unknown, isOAuthToken: boolean, sessionId?: string, accountId?: string): string | undefined; export declare const applyClaudeToolPrefix: (name: string) => string; export declare const stripClaudeToolPrefix: (name: string) => string; export type AnthropicOutputEffort = "low" | "medium" | "high" | "xhigh" | "max"; export type AnthropicEffort = AnthropicOutputEffort | "adaptive"; export type AnthropicThinkingDisplay = "summarized" | "omitted"; export interface AnthropicOptions extends StreamOptions { /** * Enable extended thinking. * For adaptive-capable models (Opus 4.6+, Sonnet 4.6+, Fable/Mythos 5): * uses adaptive thinking (Claude decides when/how much to think). For older * models: uses budget-based thinking with thinkingBudgetTokens. */ thinkingEnabled?: boolean; /** * Token budget for extended thinking (older models only). * Ignored for adaptive-capable models. */ thinkingBudgetTokens?: number; /** * Upstream wire model id override for collapsed effort-tier variants. * Serialized as `requestModelId ?? model.requestModelId ?? model.id`. */ requestModelId?: string; /** * Effort level for adaptive thinking. * Controls how much Claude allocates, or uses "adaptive" for MiniMax's * binary adaptive-thinking tag: * - "max": Always thinks with no constraints * - "high": Always thinks, deep reasoning (default) * - "medium": Moderate thinking, may skip for simple queries * - "low": Minimal thinking, skips for simple tasks * - "adaptive": Sends `thinking.type: "adaptive"` without `output_config.effort` * Ignored for older models. */ effort?: AnthropicEffort; /** * Optional reasoning level fallback for direct Anthropic provider usage. * Converted to adaptive effort when effort is not explicitly provided. */ reasoning?: SimpleStreamOptions["reasoning"]; /** * Controls how Anthropic returns thinking content when the selected thinking * transport supports a display option. Defaults to "summarized" where the * API accepts it. */ thinkingDisplay?: AnthropicThinkingDisplay; interleavedThinking?: boolean; toolChoice?: "auto" | "any" | "none" | { type: "tool"; name: string; }; betas?: string[] | string; /** * Realization of `serviceTier: "priority"` on Anthropic models. When * `"priority"`, sets `speed: "fast"` on the request and appends the * `fast-mode-2026-02-01` beta header. Anthropic rejects unsupported models * with `invalid_request_error`, which triggers an in-provider one-shot * fallback (see `fastModeDisabled` provider state). * * Other `ServiceTier` values are currently ignored on this provider. */ serviceTier?: ServiceTier; /** Force OAuth bearer auth mode for proxy tokens that don't match Anthropic token prefixes. */ isOAuth?: boolean; /** * Pre-built Anthropic Messages client. When provided, skips internal client * construction entirely. Accepts any structurally compatible client, * including SDK clients such as `AnthropicVertex`. */ client?: AnthropicMessagesClientLike; /** * Server-side fallback beta chain (`server-side-fallback-2026-06-01`). * When set, `fallbacks` is forwarded on the request body and the beta * header is auto-attached; the response parser then honors mid-stream * `fallback` content blocks and `usage.iterations` for served-model * promotion and per-attempt pricing. Opt-in ONLY — leaving this * undefined preserves the pre-fallback behavior on every code path. */ fallbacks?: FallbackParam[]; } export type AnthropicClientOptionsArgs = { model: Model<"anthropic-messages">; apiKey: string; extraBetas?: string[]; stream?: boolean; interleavedThinking?: boolean; headers?: Record; dynamicHeaders?: Record; isOAuth?: boolean; hasTools?: boolean; thinkingEnabled?: boolean; thinkingDisplay?: AnthropicThinkingDisplay; disableStrictTools?: boolean; fetch?: FetchImpl; maxRetryDelayMs?: number; claudeCodeSessionId?: string; }; export type AnthropicClientOptionsResult = { isOAuthToken: boolean; apiKey: string | null; authToken?: string | null; baseURL?: string; maxRetries: number; maxRetryDelayMs?: number; defaultHeaders: Record; fetch?: FetchImpl; fetchOptions?: AnthropicFetchOptions; }; /** * Returns env-supplied custom headers (`ANTHROPIC_CUSTOM_HEADERS`) when they * should be forwarded to the upstream endpoint. * * Foundry mode forwards them unconditionally. Outside Foundry, they're applied * only when the configured base URL is a non-Anthropic host — i.e. an * enterprise/corporate gateway that may require its own proprietary auth * header. Stock `api.anthropic.com` would reject unknown headers, so they're * omitted there. */ export declare function resolveAnthropicCustomHeadersForBaseUrl(baseUrl: string | undefined): Record | undefined; /** * Whether an Anthropic (or Copilot-over-Anthropic) stream error should be * retried. The classification lives in {@link AIError.isProviderRetryableError}; * this wrapper injects the Copilot-specific model-availability transient check, * which the error module must not import directly. */ export declare function isProviderRetryableError(error: unknown, provider?: string): boolean; export type AnthropicUsageLike = { cache_creation?: { ephemeral_5m_input_tokens?: number | null; ephemeral_1h_input_tokens?: number | null; } | null; server_tool_use?: { web_search_requests?: number | null; web_fetch_requests?: number | null; } | null; }; /** * Capture Anthropic's optional cache-creation TTL breakdown and server-tool-use * counters into the harness Usage shape. Omitted/null fields are no-ops; explicit * zero-valued objects clear prior extras from earlier stream usage snapshots. */ export declare function applyAnthropicUsageExtras(usage: Usage, source: AnthropicUsageLike): void; export declare function isInvalidThinkingSignatureError(message: string): boolean; /** * Prepend a pointed remediation to Anthropic's `Invalid signature in thinking * block` 400 when the model looks like an unmarked custom signing proxy * (opaque baseUrl, `spec.reasoning: true`, no explicit * `compat.replayUnsignedThinking` override). The default is native replay for * the 3p reasoning majority (#2005); this hint turns the misconfigured-proxy * case into a one-line fix instead of a silent retry loop (#4297). */ export declare function maybeAddReplayUnsignedThinkingHint(model: Model<"anthropic-messages">, message: string): string; /** * Public entry: wrap the single-attempt streamer with bounded empty-completion * retries (a benign terminal stop carrying no content/usage would otherwise * stall the agent loop). The inner attempt keeps its own provider-failure retry * loop; this layer only re-issues a fresh request on an empty success. Shared * with the OpenAI-completions provider via `withEmptyCompletionRetry`. */ export declare const streamAnthropic: StreamFunction<"anthropic-messages">; export type AnthropicSystemBlock = { type: "text"; text: string; }; type SystemBlockOptions = { includeClaudeCodeInstruction?: boolean; extraInstructions?: string[]; /** Text of the first user message — used as fingerprint seed for the billing header. */ firstUserMessageText?: string; }; export declare function buildAnthropicSystemBlocks(systemPrompt: readonly string[] | undefined, options?: SystemBlockOptions): AnthropicSystemBlock[] | undefined; export declare function normalizeExtraBetas(betas?: string[] | string): string[]; export declare function buildAnthropicClientOptions(args: AnthropicClientOptionsArgs): AnthropicClientOptionsResult; /** * A single Anthropic conversation turn, including the mid-conversation * `system` role (Opus 4.8+ and Fable/Mythos 5). */ export type AnthropicMessageParam = MessageParam; /** * Serialize omp {@link Message}s to Anthropic wire messages. * * `opts.serverSideFallbackEnabled` — when the CURRENT request itself * opts into the server-side-fallback beta chain. Only then may a persisted * `fallback` content block from a prior turn be replayed on the wire; * otherwise the block is dropped to avoid a 400 on non-fallback requests * that don't send the beta. */ export declare function convertAnthropicMessages(messages: Message[], model: Model<"anthropic-messages">, isOAuthToken: boolean, opts?: { serverSideFallbackEnabled?: boolean; }): AnthropicMessageParam[]; export declare function normalizeAnthropicToolSchema(schema: unknown): unknown;