import type { AnthropicOutputEffort, FetchImpl, Message, Model, ServiceTier, SimpleStreamOptions, StreamFunction, StreamOptions, Usage } from "../types.js"; import { type AnthropicFetchOptions, type AnthropicMessagesClientLike } from "./anthropic-client.js"; import { type FallbackParam, type MessageParam, type TextBlockParam } from "./anthropic-wire.js"; import { resolvesToOfficialAnthropicEndpoint, supportsAnthropicCompaction, supportsAnthropicCompactionOnClient } from "./anthropic-compaction.js"; import { applyClaudeToolPrefix, deriveClaudeDeviceId, generateClaudeCloakingUserId, isClaudeCloakingUserId, resolveAnthropicMetadataUserId, stripClaudeToolPrefix } from "./anthropic-identity.js"; import { clearAnthropicFastModeFallback, isAnthropicFastModeFallbackDisabled, normalizeAnthropicBaseUrl } from "./anthropic-state.js"; export { applyClaudeToolPrefix, clearAnthropicFastModeFallback, deriveClaudeDeviceId, generateClaudeCloakingUserId, isAnthropicFastModeFallbackDisabled, isClaudeCloakingUserId, normalizeAnthropicBaseUrl, resolveAnthropicMetadataUserId, stripClaudeToolPrefix, }; export { resolvesToOfficialAnthropicEndpoint, supportsAnthropicCompaction, supportsAnthropicCompactionOnClient }; export type AnthropicHeaderOptions = { apiKey: string; baseUrl?: string; isOAuth?: boolean; extraBetas?: string[]; stream?: boolean; modelHeaders?: Record; isCloudflareAiGateway?: boolean; claudeCodeSessionId?: string; claudeCodeBetas?: readonly string[]; /** Allow explicit fingerprint headers to replace OAuth defaults on non-official endpoints. */ allowAnthropicHeaderOverrides?: boolean; }; export declare function buildBetaHeader(baseBetas: readonly string[], extraBetas: readonly string[]): string; export declare function buildAnthropicHeaders(options: AnthropicHeaderOptions): Record; type AnthropicCacheControl = NonNullable; export * from "./claude-code-fingerprint.js"; /** Maps Node's platform identifier to the Stainless wire value. */ export declare function mapStainlessOs(platform: string): "MacOS" | "Windows" | "Linux" | "FreeBSD" | `Other::${string}`; /** Maps Node's architecture identifier to the Stainless wire value. */ export declare function mapStainlessArch(arch: string): "x64" | "arm64" | "x86" | `other::${string}`; /** Static headers emitted by Claude Code's CLI runtime. */ export declare const claudeCodeHeaders: { "X-Stainless-Arch": "arm64" | "x64" | "x86" | `other::${string}`; "X-Stainless-Lang": string; "X-Stainless-OS": "FreeBSD" | "Linux" | "MacOS" | "Windows" | `Other::${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 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; sessionId?: string; /** Working-identity cache key for this credential+host; undefined off the Copilot path. */ copilotCacheKey?: string; /** * Build-time cache provenance for the wrapper: the cached value the * outgoing headers were built from, or `null` when the cache was empty at * build. `undefined` rereads the cache at dispatch. */ copilotCacheSnapshot?: string | null; }; 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; 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; /** Detects the preserved-thinking error caused by rewriting a signed block's conversation prefix. */ export declare function isThinkingPrefixBindingError(message: string): boolean; export declare function isInvalidThinkingSignatureError(message: string): boolean; /** * Prepend a pointed remediation to a thinking-signature rejection 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: retry benign empty completions before they reach the agent * loop. The inner attempt owns Anthropic provider-failure retries. */ export declare const streamAnthropic: StreamFunction<"anthropic-messages">; export type AnthropicSystemBlock = { type: "text"; text: string; cache_control?: AnthropicCacheControl; }; type SystemBlockOptions = { includeClaudeCodeInstruction?: boolean; extraInstructions?: string[]; /** Text of the first user message — used as fingerprint seed for the billing header. */ firstUserMessageText?: string; /** Cache lifetime shared by the OAuth system breakpoint and later message breakpoints. */ cacheControl?: AnthropicCacheControl; }; 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; /** * True when enabled thinking on `model` is budget thinking * (`thinking.type: "enabled"` with `budget_tokens`) rather than adaptive. */ export declare function usesBudgetThinking(model: Model<"anthropic-messages">): boolean; /** The most output tokens a request to `model` may ask for (`max_tokens` ceiling). */ export declare function anthropicOutputLimit(model: Model<"anthropic-messages">): number; /** * The `max_tokens` and thinking budget of budget thinking: `max_tokens` * rises to leave {@link OUTPUT_FALLBACK_BUFFER} visible output tokens after * the budget, within `maxAllowedTokens`, and the budget shrinks when that * ceiling leaves less (a non-positive budget means the ceiling is too low). */ export declare function budgetThinkingOutput(maxTokens: number | undefined, budgetTokens: number, maxAllowedTokens: number): { maxTokens: number; budgetTokens: number; }; /** * Whether the conversation has stopped being thinking-led, so routes with * `compat.stripThinkingHistory` drop the budget `thinking` config and replay * history without thinking blocks. Exported so the factory-droid provider can * gate its header-level interleaved beta on the same decision. */ export declare function shouldStripThinkingHistory(messages: readonly Message[]): boolean; /** * 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. * * `opts.replayCompaction` — replay a user-role compaction summary that * carries an {@link AnthropicCompactionPayload} from this provider as a * native `compaction` block instead of its text. The API drops every block * before the compaction block, so the assistant turn carrying it may open * the conversation; the request must send the compaction beta (the stream * entry point adds it whenever such a payload is present). */ export declare function convertAnthropicMessages(messages: Message[], model: Model<"anthropic-messages">, isOAuthToken: boolean, opts?: { serverSideFallbackEnabled?: boolean; replayCompaction?: boolean; replayLegacyCompaction?: boolean; dropAllThinking?: boolean; droppedThinkingBlocks?: ReadonlySet; credentialId?: number; }): AnthropicMessageParam[]; export declare function normalizeAnthropicToolSchema(schema: unknown): unknown;