import Anthropic, { type ClientOptions as AnthropicSdkClientOptions } from "@anthropic-ai/sdk"; import type { MessageCreateParamsStreaming, MessageParam } from "@anthropic-ai/sdk/resources/messages"; import type { FetchImpl, Message, Model, ProviderSessionState, ServiceTier, SimpleStreamOptions, StreamFunction, StreamOptions, Usage } from "../types"; import { type RawHttpRequestDump } from "../utils/http-inspector"; export type AnthropicHeaderOptions = { apiKey: string; baseUrl?: string; isOAuth?: boolean; extraBetas?: string[]; stream?: boolean; modelHeaders?: Record; isCloudflareAiGateway?: boolean; /** * Attach ZCode client "source" headers (User-Agent: ZCode/, X-Title, * X-ZCode-Agent: glm, X-Platform, etc.) so api.z.ai recognizes the caller as * the ZCode client, exactly like ZCode's `buildZCodeSourceHeaders` does for * GLM providers. glm-zcode only. */ zcodeSourceHeaders?: boolean; }; export declare function normalizeAnthropicBaseUrl(baseUrl?: string): string | undefined; export declare function buildBetaHeader(baseBetas: string[], extraBetas: string[]): string; /** * Replicates ZCode's `buildZCodeSourceHeaders()` + GLM `X-ZCode-Agent` tag * (host bundle `Bl` / `buildConnectivitySourceHeaders` for GLM providers), so * api.z.ai sees gjc's glm-zcode requests as the ZCode client. Dynamic values * (platform/arch, locale, timezone, OS version) are resolved at runtime exactly * as ZCode does; printable-ASCII-only and conditionally omitted when empty. */ export declare function buildZCodeSourceHeaders(): Record; export declare function buildAnthropicHeaders(options: AnthropicHeaderOptions): Record; type AnthropicCacheControl = { type: "ephemeral"; ttl?: "1h" | "5m"; }; /** * 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; export declare function isAnthropicFastModeUnsupportedError(error: unknown): boolean; export declare function isAnthropicThinkingBlockMutationError(error: unknown): boolean; /** * 400 shape where a replayed `thinking`/`redacted_thinking` block fails signature * validation, e.g. `messages.5.content.24: Invalid \`signature\` in \`thinking\` block`. * Unlike the latest-assistant mutation error above, the cited block can sit anywhere * in the replayed history, so recovery must repair every assistant message rather * than only the latest one. */ export declare function isAnthropicThinkingSignatureInvalidError(error: unknown): boolean; /** * CLIProxyAPI replaces Anthropic's rejection body wholesale instead of forwarding * it: the client only ever sees * `{"type":"error","error":{"type":"api_error","message":"An error occurred while * processing the request."}}`, delivered as an in-stream SSE `error` event on an * HTTP 200 response, so neither the status nor the message survives. Captured CPA * traces for that masked shape carry the thinking-integrity 400 upstream (issue * #3900), and the generic body matches no transient phrase either, so the turn * dies unrecoverably. Nothing in the payload names the cause; callers must pair * this with a request that actually replays signed thinking blocks before * treating it as a thinking-replay rejection. */ export declare function isAnthropicMaskedProxyRejection(error: unknown): boolean; /** * Anthropic rejects a request carrying more than four `cache_control` * breakpoints. An Anthropic-compatible gateway may attach its own block-level * markers before forwarding, and those never appear in the params we serialize, * so no amount of local counting can predict the total. The rejection is the * only evidence that our generated marker is one too many, and it is worth * exactly one retry with generated caching suppressed. * * Our own pre-flight `validateCacheControls` failure is deliberately not * matched: it carries no `invalid_request_error` wording, so a local bug stays * loud instead of being silently retried. */ export declare function isAnthropicCacheBreakpointOverflowError(error: unknown): boolean; export type AnthropicContextManagementInjectionDiagnostic = { strategy: string; message: string; captureNote: string; }; /** * Diagnose a context-management strategy named by an Anthropic 400 but absent * from the body GJC sent. This mismatch is evidence of intermediary mutation, * not permission to silently enable thinking or retry the request. */ export declare function diagnoseAnthropicContextManagementInjection(error: unknown, dump: RawHttpRequestDump | undefined): AnthropicContextManagementInjectionDiagnostic | undefined; export interface CpaToolAliasRestoreFailure { /** The rejected tool-call name exactly as CPA quoted it. */ alias: string; /** * Base tool name parsed out of the alias (`mcp_____` * → ``), when the alias shape is well-formed. `undefined` for a * malformed alias — callers must then fall back to direct discovery and * never invent a name. */ baseName?: string; } /** * Classifies the CPA alias-restore signature and extracts the rejected alias * plus its base tool name. Claims only statusless in-stream SSE error events * and HTTP 5xx failures: a non-5xx status carrying this text is not the * observed CPA delivery shape and is left to the other classifiers. */ export declare function parseCpaToolAliasRestoreFailure(error: unknown): CpaToolAliasRestoreFailure | undefined; export declare function isCpaToolAliasRestoreFailure(error: unknown): boolean; export declare const claudeCodeVersion = "2.1.219"; export declare const claudeCodeEntrypoint = "sdk-cli"; export declare const claudeToolPrefix: string; export declare const claudeCodeSystemInstruction = "You are a Claude agent, built on Anthropic's Claude Agent SDK."; export declare function mapStainlessOs(platform: string): "MacOS" | "Windows" | "Linux" | "FreeBSD" | `Other::${string}`; export declare function mapStainlessArch(arch: string): "x64" | "arm64" | "x86" | `other::${string}`; export declare const claudeCodeHeaders: { readonly "X-Stainless-Retry-Count": "0"; readonly "X-Stainless-Runtime-Version": "v24.3.0"; readonly "X-Stainless-Package-Version": "0.74.0"; readonly "X-Stainless-Runtime": "node"; readonly "X-Stainless-Lang": "js"; readonly "X-Stainless-Arch": "arm64" | "x64" | "x86" | `other::${string}`; readonly "X-Stainless-Os": "FreeBSD" | "Linux" | "MacOS" | "Windows" | `Other::${string}`; readonly "X-Stainless-Timeout": "600"; }; export declare function isClaudeCloakingUserId(userId: string): boolean; export declare function generateClaudeCloakingUserId(): string; export declare const applyClaudeToolPrefix: (name: string, prefixOverride?: string) => string; export declare const stripClaudeToolPrefix: (name: string, prefixOverride?: string) => string; export type AnthropicEffort = "low" | "medium" | "high" | "xhigh" | "max"; export type AnthropicThinkingDisplay = "summarized" | "omitted"; export interface AnthropicOptions extends StreamOptions { /** * Enable extended thinking. * For Opus 4.6+: uses adaptive thinking (Anthropic model 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 Opus 4.6+ which uses adaptive thinking. */ thinkingBudgetTokens?: number; /** * Effort level for adaptive thinking (Opus 4.6+ only). * Controls how much thinking Anthropic model allocates: * - "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 * 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 client instance. When provided, skips internal client * construction entirely. Use this to inject alternative SDK clients such as * `AnthropicVertex` that shares the same messaging API. */ client?: Anthropic; } export type AnthropicClientOptionsArgs = { model: Model<"anthropic-messages">; apiKey: string; extraBetas?: string[]; stream?: boolean; interleavedThinking?: boolean; headers?: Record; dynamicHeaders?: Record; isOAuth?: boolean; hasTools?: boolean; onSseEvent?: AnthropicOptions["onSseEvent"]; fetch?: FetchImpl; requestMaxRetries?: number; maxRetryDelayMs?: number; streamFirstEventTimeoutMs?: number; streamIdleTimeoutMs?: number; }; export type AnthropicClientOptionsResult = { isOAuthToken: boolean; apiKey: string | null; authToken?: string | null; baseURL?: string; maxRetries: number; timeout?: number; dangerouslyAllowBrowser: boolean; defaultHeaders: Record; logLevel: AnthropicSdkClientOptions["logLevel"]; fetch?: AnthropicSdkClientOptions["fetch"]; fetchOptions?: AnthropicSdkClientOptions["fetchOptions"]; }; export declare function resolveGlmZcodeAnthropicBaseUrl(): string; 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. Only sets fields that were reported, so * a `message_delta` that omits `cache_creation` does not clobber the breakdown * established at `message_start`. */ export declare function applyAnthropicUsageExtras(usage: Usage, source: AnthropicUsageLike): void; export declare const streamAnthropic: StreamFunction<"anthropic-messages">; export type AnthropicSystemBlock = { type: "text"; text: string; cache_control?: AnthropicCacheControl; }; type SystemBlockOptions = { includeClaudeCodeInstruction?: boolean; extraInstructions?: string[]; billingPayload?: unknown; 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; export declare function normalizeCacheControlTtlOrdering(params: MessageCreateParamsStreaming): void; export declare function convertAnthropicMessages(messages: Message[], model: Model<"anthropic-messages">, isOAuthToken: boolean, options?: { repairLatestAssistantThinking?: boolean; repairAllAssistantThinking?: boolean; }): MessageParam[]; /** * Normalize a JSON Schema node for Anthropic tool `input_schema`. * * Applies the full whitelist semantics from the Anthropic Python SDK's * `lib/_parse/_transform.py::transform_schema`: * * 1. Universal keys (`$ref`, `$defs`, `type`, `anyOf`/`oneOf`/`allOf`, `enum`, `const`, * `description`, `title`, `default`, `nullable`) are preserved on every node. * 2. Per-type keys are kept additively (object → `properties`/`required`/`additionalProperties`, * array → `items`/`prefixItems` plus `minItems` only when 0 or 1, string → `format` * only when in the supported value set). * 3. Everything else is demoted into the node's `description` as `\n\n{key: value, ...}` * so the model still sees the constraint as a natural-language hint. * * Object nodes default to `additionalProperties: false`, but explicit open-map * declarations (`additionalProperties: true` or a schema literal — Zod's * `z.record(z.string(), z.unknown())` produces `{}`) are preserved. The strict-mode * pass downstream demotes those shapes to non-strict instead of fabricating a closed * object, so callers like the resolve tool keep working open-map semantics. */ export declare function normalizeAnthropicToolSchema(schema: unknown): unknown; export {};