import type { Effort } from "@oh-my-pi/pi-catalog/effort"; import type { AnthropicCompactionRequest, AnthropicOutputEffort, Context, FetchImpl, Message, Model, ServiceTier, SimpleStreamOptions, StreamFunction, StreamOptions, Usage } from "../types.js"; import { AssistantMessageEventStream } from "../utils/event-stream.js"; import { type RawHttpRequestDump } from "../utils/http-inspector.js"; import { type AnthropicFetchOptions, type AnthropicMessagesClientLike } from "./anthropic-client.js"; import { type FallbackParam, type MessageCreateParamsStreaming, 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 }; type AnthropicCacheControl = NonNullable; export * from "./claude-code-fingerprint.js"; /** * 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; /** * Whether a request to `model` sends the tool `name` for the host to run itself, never dispatching the call to the * client: the same decision `encodeAnthropicToolName` makes on the wire. */ export declare function anthropicHostRunsTool(model: Model<"anthropic-messages">, name: string, headers?: Record): boolean; 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; /** * Send no Claude Code app headers (`x-app: cli`, * `anthropic-dangerous-direct-browser-access`) on an API-key request. For * adapter wrappers that present another client's identity. */ omitClaudeCodeAppHeaders?: 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 sends neither and keeps both off; a `fallback` block in the * response (a gateway opted in) is still persisted as a replay boundary. */ fallbacks?: FallbackParam[]; } export type AnthropicClientOptionsArgs = { model: Model<"anthropic-messages">; apiKey: string; extraBetas?: string[]; stream?: boolean; interleavedThinking?: boolean; headers?: Record; dynamicHeaders?: Record; isOAuth?: boolean; /** See {@link AnthropicOptions.omitClaudeCodeAppHeaders}. */ omitClaudeCodeAppHeaders?: boolean; hasTools?: boolean; /** Whether a tool in ANTHROPIC_BUFFERED_INPUT_TOOLS is present; suppresses the request-wide fine-grained streaming beta. */ hasBufferedInputTools?: boolean; thinkingEnabled?: boolean; thinkingDisplay?: AnthropicThinkingDisplay; disableStrictTools?: boolean; /** * Withhold the prompt-cache betas (see `buildClaudeCodeBetas`). Set when the * request carries no breakpoint at all, and also when it carries breakpoints * stripped of `ttl`/`scope`: both betas govern those options, so a body * without them must advertise neither. */ dropPromptCacheBetas?: 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; }; 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; /** * Warn once for the signed thinking blocks the API dropped from one request * after the conversation prefix changed: the count and first path at warn, * every path at debug. One prefix change can drop hundreds of blocks in a * single request, which would otherwise flood the log one line per block. */ export declare function logDroppedThinking(provider: string, model: string, paths: Array): void; /** * 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 conversational wire user turn, used as the billing fingerprint seed. */ firstUserMessageText?: string; /** * Cache lifetime shared by the OAuth system breakpoint and later message * breakpoints. Omitted → the identity block keeps its default `ephemeral` * breakpoint; see `dropCacheControl` to emit none at all. */ cacheControl?: AnthropicCacheControl; /** * Emit no `cache_control` on any block: the endpoint rejected the field. * Distinct from an undefined `cacheControl`, which only means "default". */ dropCacheControl?: boolean; }; export declare function buildAnthropicSystemBlocks(systemPrompt: readonly string[] | undefined, options?: SystemBlockOptions): AnthropicSystemBlock[] | undefined; 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; }; /** * The effort whose thinking allowance an on-demand compaction request over * `messages` gets. It sends no effort change of its own, so once an earlier * request recorded an effort, the one it left in force applies, even when * `requested` differs or is off. When that request named none, the API's * per-model default applies, which is not known here: the request gets the * largest effort's allowance (`max_tokens` is a cap, not spend). Without a * recorded effort the request sets its own. */ export declare function resolveAnthropicCompactionEffort(model: Model<"anthropic-messages">, messages: readonly Message[], requested: Effort | undefined): Effort | undefined; /** * 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; /** * Route Bedrock's on-demand Anthropic compaction through the shared Messages * stream consumer while keeping source-provider identity and pricing. */ export declare function streamBedrockAnthropicCompaction(sourceModel: Model<"bedrock-converse-stream">, context: Context, options: AnthropicOptions, prepareRequest: (params: MessageCreateParamsStreaming, betas: readonly string[]) => Promise<{ payload: unknown; rawRequestDump: RawHttpRequestDump; }>, createClient: (getPayload: () => unknown) => AnthropicMessagesClientLike, prepareOptions: (options: AnthropicOptions) => AnthropicOptions, forceThinkingOffFields?: Record): AssistantMessageEventStream; /** * A single Anthropic conversation turn, including the mid-conversation * `system` role (Opus 4.8+ and Fable/Mythos 5). */ export type AnthropicMessageParam = MessageParam; /** History serialization choices {@link convertAnthropicMessages} applies to a request. */ export type AnthropicConversionOptions = { serverSideFallbackEnabled?: boolean; replayCompaction?: boolean; replayLegacyCompaction?: boolean; dropAllThinking?: boolean; thinkingEnabled?: boolean; droppedThinkingBlocks?: ReadonlySet; omitDemotedReasoning?: boolean; credentialId?: number; /** On-demand compaction request: it ends inside the conversation, so it gets nothing live requests lack there. */ compactionRequest?: AnthropicCompactionRequest; }; /** * 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, and only on the * official endpoint, 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 requests that don't send the beta, and its turn keeps one model's * reasoning (see {@link collapseFallbackSegments}). * * `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). * * `opts.thinkingEnabled` — the CURRENT request enables thinking. Combined with * `model.compat.requiresThinkingPresence` this pads assistant turns that carry * no thinking block at all (see the guard below). * * `opts.omitDemotedReasoning` — leave out other models' reasoning that would * replay as text. Unsigned blocks beside signed thinking in one turn are the * turn's own and keep their text replay. */ export declare function convertAnthropicMessages(messages: Message[], model: Model<"anthropic-messages">, isOAuthToken: boolean, opts?: AnthropicConversionOptions): AnthropicMessageParam[]; /** * Normalize a tool parameter schema into an Anthropic `input_schema`: root * combinators fold into the root object ({@link foldAnthropicRootCombinators}), * then {@link normalizeAnthropicToolSchemaNode} applies the keyword whitelist. */ export declare function normalizeAnthropicToolSchema(schema: unknown): unknown;