1
import Anthropic, { type ClientOptions } from "@anthropic-ai/sdk";2
import type {3
BetaInputTransformation,4
BetaStopReason,5
BetaTool,6
BetaCacheControlEphemeral as CacheControlEphemeral,7
BetaContentBlockParam as ContentBlockParam,8
MessageCreateParamsStreaming,9
BetaMessageParam as MessageParam,10
BetaRawMessageStreamEvent as RawMessageStreamEvent,11
BetaRefusalStopDetails as RefusalStopDetails,12
} from "@anthropic-ai/sdk/resources/beta/messages/messages.js";13
import {14
ANTHROPIC_FEDERATION_RULE_ID_ENV,15
ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,16
ANTHROPIC_ORGANIZATION_ID_ENV,17
ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,18
ANTHROPIC_WORKSPACE_ID_ENV,19
} from "../env-api-keys.ts";20
import { calculateCost } from "../models.ts";21
import type {22
Api,23
AssistantMessage,24
CacheRetention,25
ImageContent,26
Message,27
Model,28
ProviderEnv,29
ProviderHeaders,30
SimpleStreamOptions,31
StopReason,32
StreamFunction,33
StreamOptions,34
TextContent,35
ThinkingContent,36
Tool,37
ToolCall,38
ToolResultMessage,39
} from "../types.ts";40
import { appendAssistantMessageDiagnostic } from "../utils/diagnostics.ts";41
import { AssistantMessageEventStream } from "../utils/event-stream.ts";42
import { headersToRecord } from "../utils/headers.ts";43
import { parseJsonWithRepair, parseStreamingJson } from "../utils/json-parse.ts";44
import { getPiUserAgent } from "../utils/pi-user-agent.ts";45
import { getProviderEnvValue } from "../utils/provider-env.ts";46
import { retryProviderRequest } from "../utils/provider-retry.ts";47
import { sanitizeSurrogates } from "../utils/sanitize-unicode.ts";48
import { getSystemMessageText, renderSystemMessageUpdate } from "../utils/text.ts";49
import {50
getCurrentTools,51
getInitialSystemMessage,52
resolveTranscript,53
type TranscriptContext,54
} from "../utils/transcript.ts";56
import {57
getJsonSchemaToolParameters,58
resolveJsonSchemaStrictSampling,59
type UnsupportedStrictSchemaKeywordCheck,60
} from "./constrained-sampling.ts";61
import { buildCopilotDynamicHeaders, hasCopilotVisionInput } from "./github-copilot-headers.ts";62
import { adjustMaxTokensForThinking, buildBaseOptions, clampMaxTokensToContext } from "./simple-options.ts";63
import { transformMessages } from "./transform-messages.ts";65
/**66
* Resolve cache retention preference.67
* Defaults to "short" and uses PI_CACHE_RETENTION for backward compatibility.68
*/69
function resolveCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {70
if (cacheRetention) {71
return cacheRetention;72
}73
if (getProviderEnvValue("PI_CACHE_RETENTION", env) === "long") {74
return "long";75
}76
return "short";77
}79
function getCacheControl(80
model: Model<"anthropic-messages">,81
cacheRetention?: CacheRetention,82
env?: ProviderEnv,83
): { retention: CacheRetention; cacheControl?: CacheControlEphemeral } {84
const retention = resolveCacheRetention(cacheRetention, env);85
if (retention === "none") {86
return { retention };87
}88
const ttl = retention === "long" && getAnthropicCompat(model).supportsLongCacheRetention ? "1h" : undefined;89
return {90
retention,91
cacheControl: { type: "ephemeral", ...(ttl && { ttl }) },92
};93
}95
// Stealth mode: Mimic Claude Code's tool naming exactly96
const claudeCodeVersion = "2.1.280";98
// Claude Code 2.x tool names (canonical casing)99
// Source: https://cchistory.mariozechner.at/data/prompts-2.1.11.md100
// To update: https://github.com/badlogic/cchistory101
const claudeCodeTools = [102
"Read",103
"Write",104
"Edit",105
"Bash",106
"Grep",107
"Glob",108
"AskUserQuestion",109
"EnterPlanMode",110
"ExitPlanMode",111
"KillShell",112
"NotebookEdit",113
"Skill",114
"Task",115
"TaskOutput",116
"TodoWrite",117
"WebFetch",118
"WebSearch",119
];121
const ccToolLookup = new Map(claudeCodeTools.map((t) => [t.toLowerCase(), t]));123
// Convert tool name to CC canonical casing if it matches (case-insensitive)124
const toClaudeCodeName = (name: string) => ccToolLookup.get(name.toLowerCase()) ?? name;125
const fromClaudeCodeName = (name: string, tools?: Tool[]) => {126
if (tools && tools.length > 0) {127
const lowerName = name.toLowerCase();128
const matchedTool = tools.find((tool) => tool.name.toLowerCase() === lowerName);129
if (matchedTool) return matchedTool.name;130
}131
return name;132
};134
/**135
* Convert content blocks to Anthropic API format136
*/137
function convertContentBlocks(content: (TextContent | ImageContent)[]):138
| string139
| Array<140
| { type: "text"; text: string }141
| {142
type: "image";143
source: {144
type: "base64";145
media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp";146
data: string;147
};148
}149
> {150
// If only text blocks, return as concatenated string for simplicity151
const hasImages = content.some((c) => c.type === "image");152
if (!hasImages) {153
return sanitizeSurrogates(content.map((c) => (c as TextContent).text).join("\n"));154
}156
// If we have images, convert to content block array157
const blocks = content.map((block) => {158
if (block.type === "text") {159
return {160
type: "text" as const,161
text: sanitizeSurrogates(block.text),162
};163
}164
return {165
type: "image" as const,166
source: {167
type: "base64" as const,168
media_type: block.mimeType as "image/jpeg" | "image/png" | "image/gif" | "image/webp",169
data: block.data,170
},171
};172
});174
// If only images (no text), add placeholder text block175
const hasText = blocks.some((b) => b.type === "text");176
if (!hasText) {177
blocks.unshift({178
type: "text" as const,179
text: "(see attached image)",180
});181
}183
return blocks;184
}186
export type AnthropicEffort = "low" | "medium" | "high" | "xhigh" | "max";188
export type AnthropicThinkingDisplay = "summarized" | "omitted";190
const FINE_GRAINED_TOOL_STREAMING_BETA = "fine-grained-tool-streaming-2025-05-14";191
const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";192
const SERVER_SIDE_FALLBACK_BETA = "server-side-fallback-2026-07-01";193
const MID_CONVERSATION_OUTPUT_CONFIG_BETA = "mid-conversation-output-config-2026-07-01";194
const THINKING_BINDING_CONTROLS_BETA = "thinking-binding-controls-2026-08-01";195
const INLINE_TOOLS_BETA = "inline-tools-2026-09-15";197
/**198
* Stable deferred tool declared whenever native tool changes are in use. Anthropic adds199
* hidden prompt scaffolding for mid-conversation tool changes; declaring this placeholder200
* from the first request keeps that scaffolding in the cached prefix, so the first tool201
* change does not invalidate the cache (measured: full miss without it). It is never202
* activated and the model cannot see it.203
*/204
const DEFERRED_TOOL_PLACEHOLDER: BetaTool = {205
name: "__pi_deferred_placeholder__",206
description: "Reserved placeholder. Never available. Never call this.",207
input_schema: { type: "object", properties: {}, required: [] },208
defer_loading: true,209
};211
function shouldUseServerSideFallbackBeta(model: Model<"anthropic-messages">): boolean {212
return (model.compat?.allowedFallbackModels?.length ?? 0) > 0;213
}215
function getAnthropicCompat(model: Model<"anthropic-messages">) {216
const isOpenRouter = model.provider === "openrouter" || model.baseUrl.includes("openrouter.ai");217
return {218
supportsEagerToolInputStreaming: model.compat?.supportsEagerToolInputStreaming ?? true,219
supportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,220
sendSessionAffinityHeaders: model.compat?.sendSessionAffinityHeaders ?? isOpenRouter,221
sessionAffinityFormat: model.compat?.sessionAffinityFormat ?? (isOpenRouter ? "openrouter" : undefined),222
supportsCacheControlOnTools: model.compat?.supportsCacheControlOnTools ?? true,223
supportsTemperature: model.compat?.supportsTemperature ?? true,224
allowEmptySignature: model.compat?.allowEmptySignature ?? false,225
supportsStrictTools: model.compat?.supportsStrictTools ?? false,226
supportsMidConvoSystemMessages: model.compat?.supportsMidConvoSystemMessages ?? false,227
supportsMidConvoToolChanges: model.compat?.supportsMidConvoToolChanges ?? false,228
};229
}231
export interface AnthropicOptions extends StreamOptions {232
/**233
* Enable extended thinking.234
* For adaptive thinking models: the model decides when/how much to think.235
* For older models: uses budget-based thinking with thinkingBudgetTokens.236
* Default: undefined (thinking is omitted unless `streamSimple()` maps237
* a simple reasoning level to this option, or callers set it explicitly).238
*/239
thinkingEnabled?: boolean;240
/**241
* Token budget for extended thinking (older models only).242
* Ignored for adaptive thinking models.243
* Default: 1024 when `thinkingEnabled` is true and no budget is provided.244
*/245
thinkingBudgetTokens?: number;246
/**247
* Effort level for adaptive thinking models.248
* Controls how much thinking Claude allocates:249
* - "max": Always thinks with no constraints (Opus 4.6 only)250
* - "xhigh": Highest reasoning level (Opus 4.7+, Fable 5)251
* - "high": Always thinks, deep reasoning252
* - "medium": Moderate thinking, may skip for simple queries253
* - "low": Minimal thinking, skips for simple tasks254
* Ignored for older models.255
* Default: omitted unless `streamSimple()` maps a simple reasoning256
* level to this option.257
*/258
effort?: AnthropicEffort;259
/**260
* Controls how thinking content is returned in API responses.261
* - "summarized": Thinking blocks contain summarized thinking text.262
* - "omitted": Thinking blocks return an empty thinking field; the encrypted263
* signature still travels back for multi-turn continuity. Use for faster264
* time-to-first-text-token when your UI does not surface thinking.265
*266
* Note: Anthropic's API default for Claude Opus 4.7 and Claude Mythos Preview267
* is "omitted". We default to "summarized" here to keep behavior consistent268
* with older Claude 4 models. Set this explicitly to "omitted" to opt in.269
* Default: "summarized" when thinking is enabled.270
*/271
thinkingDisplay?: AnthropicThinkingDisplay;272
/**273
* Whether to request the interleaved thinking beta header for non-adaptive274
* thinking models. Adaptive thinking models have interleaved thinking built in,275
* so the header is skipped for them regardless of this setting.276
* Default: true.277
*/278
interleavedThinking?: boolean;279
/**280
* Anthropic tool choice behavior. String values map to Anthropic's built-in281
* choices; `{ type: "tool", name }` forces a specific tool.282
* Default: omitted (Anthropic default behavior, currently equivalent to auto).283
*/284
toolChoice?: "auto" | "any" | "none" | { type: "tool"; name: string };285
/**286
* Pre-built Anthropic client instance. When provided, skips internal client287
* construction entirely. Use this to inject alternative SDK clients such as288
* `AnthropicVertex` that shares the same messaging API.289
*/290
client?: Anthropic;291
}293
function mergeHeaders(...headerSources: (ProviderHeaders | undefined)[]): ProviderHeaders {294
const merged: ProviderHeaders = {};295
for (const headers of headerSources) {296
if (headers) {297
Object.assign(merged, headers);298
}299
}300
return merged;301
}303
function mergeClientHeaders(...headerSources: (ProviderHeaders | undefined)[]): ProviderHeaders {304
return mergeHeaders({ "User-Agent": getPiUserAgent() }, ...headerSources);305
}307
function hasHeader(headers: ProviderHeaders | undefined, name: string): boolean {308
if (!headers) return false;309
const expected = name.toLowerCase();310
for (const [key, value] of Object.entries(headers)) {311
if (key.toLowerCase() === expected && value !== null && value.trim().length > 0) return true;312
}313
return false;314
}316
function hasRequestAuth(apiKey: string | undefined, headers: ProviderHeaders | undefined): boolean {317
return (318
!!apiKey ||319
hasHeader(headers, "authorization") ||320
hasHeader(headers, "x-api-key") ||321
hasHeader(headers, "cf-aig-authorization")322
);323
}325
function assertRequestAuth(provider: string, apiKey: string | undefined, headers: ProviderHeaders | undefined): void {326
if (!hasRequestAuth(apiKey, headers)) throw new Error(`No API key for provider: ${provider}`);327
}329
/**330
* Anthropic SDK client that never runs the SDK's own credential chain331
* (ANTHROPIC_PROFILE config files, federation env vars). Without this, every332
* client built with `apiKey: null, authToken: null` for header-owned auth would333
* also resolve and exchange SDK credentials behind pi's auth resolver.334
*/335
class PiAnthropic extends Anthropic {336
protected override _shouldResolveDefaultCredentials(): boolean {337
return false;338
}339
}341
type AnthropicFederationConfig = NonNullable<ClientOptions["config"]>;343
/**344
* Workload identity federation config from the ANTHROPIC_* variables the345
* Anthropic SDK documents; the SDK performs the token exchange and refresh.346
* Only for the anthropic provider, since the exchange is an Anthropic API347
* endpoint, and only when no key or auth header was resolved.348
*/349
function getAnthropicFederation(350
model: Model<"anthropic-messages">,351
apiKey: string | undefined,352
headers: ProviderHeaders | undefined,353
env: ProviderEnv | undefined,354
): AnthropicFederationConfig | undefined {355
if (model.provider !== "anthropic" || hasRequestAuth(apiKey, headers)) return undefined;356
const federationRuleId = getProviderEnvValue(ANTHROPIC_FEDERATION_RULE_ID_ENV, env);357
const organizationId = getProviderEnvValue(ANTHROPIC_ORGANIZATION_ID_ENV, env);358
const identityTokenFile = getProviderEnvValue(ANTHROPIC_IDENTITY_TOKEN_FILE_ENV, env);359
if (!federationRuleId || !organizationId || !identityTokenFile) return undefined;360
return {361
organization_id: organizationId,362
workspace_id: getProviderEnvValue(ANTHROPIC_WORKSPACE_ID_ENV, env),363
authentication: {364
type: "oidc_federation",365
federation_rule_id: federationRuleId,366
service_account_id: getProviderEnvValue(ANTHROPIC_SERVICE_ACCOUNT_ID_ENV, env),367
identity_token: { source: "file", path: identityTokenFile },368
},369
};370
}372
/**373
* The SDK caches the federated access token per client, but pi creates a client374
* per request. Keep one client for the current federation config and fetch, and375
* clone it per request with `withOptions()`, which shares the token cache.376
*/377
let federationClient: { key: string; fetch: typeof globalThis.fetch | undefined; client: Anthropic } | undefined;379
interface ServerSentEvent {380
event: string | null;381
data: string;382
raw: string[];383
}385
interface SseDecoderState {386
event: string | null;387
data: string[];388
raw: string[];389
}391
const ANTHROPIC_MESSAGE_EVENTS: ReadonlySet<string> = new Set([392
"message_start",393
"message_delta",394
"message_stop",395
"content_block_start",396
"content_block_delta",397
"content_block_stop",398
]);400
function flushSseEvent(state: SseDecoderState): ServerSentEvent | null {401
if (!state.event && state.data.length === 0) {402
return null;403
}405
const event: ServerSentEvent = {406
event: state.event,407
data: state.data.join("\n"),408
raw: [...state.raw],409
};410
state.event = null;411
state.data = [];412
state.raw = [];413
return event;414
}416
function decodeSseLine(line: string, state: SseDecoderState): ServerSentEvent | null {417
if (line === "") {418
return flushSseEvent(state);419
}421
state.raw.push(line);422
if (line.startsWith(":")) {423
return null;424
}426
const delimiterIndex = line.indexOf(":");427
const fieldName = delimiterIndex === -1 ? line : line.slice(0, delimiterIndex);428
let value = delimiterIndex === -1 ? "" : line.slice(delimiterIndex + 1);429
if (value.startsWith(" ")) {430
value = value.slice(1);431
}433
if (fieldName === "event") {434
state.event = value;435
} else if (fieldName === "data") {436
state.data.push(value);437
}439
return null;440
}442
function nextLineBreakIndex(text: string): number {443
const carriageReturnIndex = text.indexOf("\r");444
const newlineIndex = text.indexOf("\n");445
if (carriageReturnIndex === -1) {446
return newlineIndex;447
}448
if (newlineIndex === -1) {449
return carriageReturnIndex;450
}451
return Math.min(carriageReturnIndex, newlineIndex);452
}454
function consumeLine(text: string): { line: string; rest: string } | null {455
const lineBreakIndex = nextLineBreakIndex(text);456
if (lineBreakIndex === -1) {457
return null;458
}460
let nextIndex = lineBreakIndex + 1;461
if (text[lineBreakIndex] === "\r" && text[nextIndex] === "\n") {462
nextIndex += 1;463
}465
return {466
line: text.slice(0, lineBreakIndex),467
rest: text.slice(nextIndex),468
};469
}471
async function* iterateSseMessages(472
body: ReadableStream<Uint8Array>,473
signal?: AbortSignal,474
): AsyncGenerator<ServerSentEvent> {475
const reader = body.getReader();476
const decoder = new TextDecoder();477
const state: SseDecoderState = { event: null, data: [], raw: [] };478
let buffer = "";480
try {481
while (true) {482
if (signal?.aborted) {483
throw new Error("Request was aborted");484
}486
const { value, done } = await reader.read();487
if (done) {488
break;489
}491
buffer += decoder.decode(value, { stream: true });492
let consumed = consumeLine(buffer);493
while (consumed) {494
buffer = consumed.rest;495
const event = decodeSseLine(consumed.line, state);496
if (event) {497
yield event;498
}499
consumed = consumeLine(buffer);500
}501
}503
buffer += decoder.decode();504
let consumed = consumeLine(buffer);505
while (consumed) {506
buffer = consumed.rest;507
const event = decodeSseLine(consumed.line, state);508
if (event) {509
yield event;510
}511
consumed = consumeLine(buffer);512
}514
if (buffer.length > 0) {515
const event = decodeSseLine(buffer, state);516
if (event) {517
yield event;518
}519
}521
const trailingEvent = flushSseEvent(state);522
if (trailingEvent) {523
yield trailingEvent;524
}525
} finally {526
reader.releaseLock();527
}528
}530
async function* iterateAnthropicEvents(531
response: Response,532
signal?: AbortSignal,533
): AsyncGenerator<RawMessageStreamEvent> {534
if (!response.body) {535
throw new Error("Attempted to iterate over an Anthropic response with no body");536
}538
let sawMessageStart = false;539
let sawMessageEnd = false;541
for await (const sse of iterateSseMessages(response.body, signal)) {542
if (sse.event === "error") {543
throw new Error(sse.data);544
}546
if (!ANTHROPIC_MESSAGE_EVENTS.has(sse.event ?? "")) {547
continue;548
}550
try {551
const event = parseJsonWithRepair<RawMessageStreamEvent>(sse.data);552
if (event.type === "message_start") {553
sawMessageStart = true;554
} else if (event.type === "message_stop") {555
sawMessageEnd = true;556
}557
yield event;558
} catch (error) {559
const message = error instanceof Error ? error.message : String(error);560
throw new Error(561
`Could not parse Anthropic SSE event ${sse.event}: ${message}; data=${sse.data}; raw=${sse.raw.join("\\n")}`,562
);563
}564
}566
if (sawMessageStart && !sawMessageEnd) {567
throw new Error("Anthropic stream ended before message_stop");568
}569
}571
export const stream: StreamFunction<"anthropic-messages", AnthropicOptions> = (572
model: Model<"anthropic-messages">,573
context: TranscriptContext,574
options?: AnthropicOptions,575
): AssistantMessageEventStream => {576
const stream = new AssistantMessageEventStream();577
const normalizedContext = resolveTranscript(context, getAnthropicCompat(model).supportsMidConvoSystemMessages);578
const currentTools = getCurrentTools(normalizedContext.messages);580
(async () => {581
const providerThinkingLevel = model.compat?.supportsMidConvoEffort ? (options?.effort ?? "high") : undefined;582
const output: AssistantMessage = {583
role: "assistant",584
content: [],585
api: model.api as Api,586
provider: model.provider,587
model: model.id,588
...(providerThinkingLevel === undefined ? {} : { providerThinkingLevel }),589
usage: {590
input: 0,591
output: 0,592
cacheRead: 0,593
cacheWrite: 0,594
totalTokens: 0,595
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },596
},597
stopReason: "pending",598
timestamp: Date.now(),599
};601
try {602
let client: Anthropic;603
let isOAuth: boolean;604
let usageModel = model;605
let inputTransformations: BetaInputTransformation[] | undefined;607
if (options?.client) {608
client = options.client;609
isOAuth = false;610
} else {611
const apiKey = options?.apiKey;612
const federation = getAnthropicFederation(model, apiKey, options?.headers, options?.env);613
if (!federation) assertRequestAuth(model.provider, apiKey, options?.headers);615
let copilotDynamicHeaders: Record<string, string> | undefined;616
if (model.provider === "github-copilot") {617
const hasImages = hasCopilotVisionInput(normalizedContext.messages);618
copilotDynamicHeaders = buildCopilotDynamicHeaders({619
messages: normalizedContext.messages,620
hasImages,621
});622
}624
const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);625
const cacheSessionId = cacheRetention === "none" ? undefined : options?.sessionId;627
const created = createClient(628
model,629
apiKey,630
options?.headers,631
options?.fetch,632
copilotDynamicHeaders,633
cacheSessionId,634
federation,635
);636
client = created.client;637
isOAuth = created.isOAuthToken;638
}639
let params = buildParams(model, normalizedContext, isOAuth, options);640
const nextParams = await options?.onPayload?.(params, model);641
if (nextParams !== undefined) {642
params = { ...(nextParams as MessageCreateParamsStreaming), stream: true };643
}644
const requestOptions = {645
...(options?.signal ? { signal: options.signal } : {}),646
...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),647
maxRetries: 0,648
};649
const response = await retryProviderRequest(650
() => client.beta.messages.create(params, requestOptions).asResponse(),651
{652
maxRetries: options?.maxRetries,653
maxRetryDelayMs: options?.maxRetryDelayMs,654
signal: options?.signal,655
},656
);657
await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);658
stream.push({ type: "start", partial: output });660
type Block = (ThinkingContent | TextContent | (ToolCall & { partialJson: string })) & { index: number };661
const blocks = output.content as Block[];663
for await (const event of iterateAnthropicEvents(response, options?.signal)) {664
await options?.onProviderStreamEvent?.(event, model);665
if (event.type === "message_start") {666
output.responseId = event.message.id;667
const transformations = event.message.input_transformations;668
if (Array.isArray(transformations)) inputTransformations = transformations;669
const responseModel = event.message.model;670
if (responseModel !== model.id) output.responseModel = responseModel;671
const fallbackCost =672
responseModel === model.id673
? undefined674
: model.compat?.allowedFallbackModels?.find(675
(fallback) => fallback.provider === model.provider && fallback.model === responseModel,676
)?.cost;677
usageModel = fallbackCost ? { ...model, id: responseModel, cost: fallbackCost } : model;678
// Capture initial token usage from message_start event679
// This ensures we have input token counts even if the stream is aborted early680
output.usage.input = event.message.usage.input_tokens || 0;681
output.usage.output = event.message.usage.output_tokens || 0;682
output.usage.cacheRead = event.message.usage.cache_read_input_tokens || 0;683
output.usage.cacheWrite = event.message.usage.cache_creation_input_tokens || 0;684
output.usage.cacheWrite1h = event.message.usage.cache_creation?.ephemeral_1h_input_tokens || 0;685
// Anthropic doesn't provide total_tokens, compute from components686
output.usage.totalTokens =687
output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;688
calculateCost(usageModel, output.usage);689
} else if (event.type === "content_block_start") {690
if (event.content_block.type === "fallback") {691
if (output.content.length > 0) {692
throw new Error("Anthropic performed an unsupported mid-output model fallback");693
}694
continue;695
}696
if (event.content_block.type === "text") {697
const block: Block = {698
type: "text",699
text: event.content_block.text ?? "",700
index: event.index,701
};702
output.content.push(block);703
stream.push({ type: "text_start", contentIndex: output.content.length - 1, partial: output });704
} else if (event.content_block.type === "thinking") {705
const block: Block = {706
type: "thinking",707
thinking: event.content_block.thinking ?? "",708
thinkingSignature: event.content_block.signature ?? "",709
index: event.index,710
};711
output.content.push(block);712
stream.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output });713
} else if (event.content_block.type === "redacted_thinking") {714
const block: Block = {715
type: "thinking",716
thinking: "[Reasoning redacted]",717
thinkingSignature: event.content_block.data,718
redacted: true,719
index: event.index,720
};721
output.content.push(block);722
stream.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output });723
} else if (event.content_block.type === "tool_use") {724
const block: Block = {725
type: "toolCall",726
id: event.content_block.id,727
name: isOAuth728
? fromClaudeCodeName(event.content_block.name, currentTools)729
: event.content_block.name,730
arguments: (event.content_block.input as Record<string, any>) ?? {},731
partialJson: "",732
index: event.index,733
};734
output.content.push(block);735
stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });736
}737
} else if (event.type === "content_block_delta") {738
if (event.delta.type === "text_delta") {739
const index = blocks.findIndex((b) => b.index === event.index);740
const block = blocks[index];741
if (block && block.type === "text") {742
block.text += event.delta.text;743
stream.push({744
type: "text_delta",745
contentIndex: index,746
delta: event.delta.text,747
partial: output,748
});749
}750
} else if (event.delta.type === "thinking_delta") {751
const index = blocks.findIndex((b) => b.index === event.index);752
const block = blocks[index];753
if (block && block.type === "thinking") {754
block.thinking += event.delta.thinking;755
stream.push({756
type: "thinking_delta",757
contentIndex: index,758
delta: event.delta.thinking,759
partial: output,760
});761
}762
} else if (event.delta.type === "input_json_delta") {763
const index = blocks.findIndex((b) => b.index === event.index);764
const block = blocks[index];765
if (block && block.type === "toolCall") {766
block.partialJson += event.delta.partial_json;767
block.arguments = parseStreamingJson(block.partialJson);768
stream.push({769
type: "toolcall_delta",770
contentIndex: index,771
delta: event.delta.partial_json,772
partial: output,773
});774
}775
} else if (event.delta.type === "signature_delta") {776
const index = blocks.findIndex((b) => b.index === event.index);777
const block = blocks[index];778
if (block && block.type === "thinking") {779
block.thinkingSignature = block.thinkingSignature || "";780
block.thinkingSignature += event.delta.signature;781
}782
}783
} else if (event.type === "content_block_stop") {784
const index = blocks.findIndex((b) => b.index === event.index);785
const block = blocks[index];786
if (block) {787
delete (block as any).index;788
if (block.type === "text") {789
stream.push({790
type: "text_end",791
contentIndex: index,792
content: block.text,793
partial: output,794
});795
} else if (block.type === "thinking") {796
stream.push({797
type: "thinking_end",798
contentIndex: index,799
content: block.thinking,800
partial: output,801
});802
} else if (block.type === "toolCall") {803
block.arguments = parseStreamingJson(block.partialJson);804
// Finalize in-place and strip the scratch buffer so replay only805
// carries parsed arguments.806
delete (block as { partialJson?: string }).partialJson;807
stream.push({808
type: "toolcall_end",809
contentIndex: index,810
toolCall: block,811
partial: output,812
});813
}814
}815
} else if (event.type === "message_delta") {816
const transformations = event.input_transformations;817
if (Array.isArray(transformations)) inputTransformations = transformations;818
if (event.delta.stop_reason) {819
output.rawStopReason = event.delta.stop_reason;820
const stopReasonResult = mapStopReason(event.delta.stop_reason, event.delta.stop_details);821
output.stopReason = stopReasonResult.stopReason;822
if (stopReasonResult.errorMessage) {823
output.errorMessage = stopReasonResult.errorMessage;824
}825
}826
// Only update usage fields if present (not null).827
// Preserves input_tokens from message_start when proxies omit it in message_delta.828
if (event.usage) {829
if (event.usage.input_tokens != null) {830
output.usage.input = event.usage.input_tokens;831
}832
if (event.usage.output_tokens != null) {833
output.usage.output = event.usage.output_tokens;834
}835
if (event.usage.cache_read_input_tokens != null) {836
output.usage.cacheRead = event.usage.cache_read_input_tokens;837
}838
if (event.usage.cache_creation_input_tokens != null) {839
output.usage.cacheWrite = event.usage.cache_creation_input_tokens;840
}841
// Vercel AI Gateway includes the TTL breakdown in deltas, though the SDK only types it on message_start.842
const cacheCreation = (843
event.usage as typeof event.usage & { cache_creation?: { ephemeral_1h_input_tokens?: number } }844
).cache_creation;845
if (cacheCreation?.ephemeral_1h_input_tokens != null) {846
output.usage.cacheWrite1h = cacheCreation.ephemeral_1h_input_tokens;847
}848
// Anthropic reports reasoning tokens as a subset of output tokens.849
const thinkingTokens = event.usage.output_tokens_details?.thinking_tokens;850
if (thinkingTokens != null) {851
output.usage.reasoning = thinkingTokens;852
}853
}854
// Anthropic doesn't provide total_tokens, compute from components855
output.usage.totalTokens =856
output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;857
calculateCost(usageModel, output.usage);858
}859
}861
if (options?.signal?.aborted) {862
throw new Error("Request was aborted");863
}865
if (output.stopReason === "pending") {866
throw new Error("Anthropic stream ended without a stop reason");867
}868
if (output.stopReason === "aborted" || output.stopReason === "error") {869
throw new Error(output.errorMessage || "An unknown error occurred");870
}871
if (inputTransformations && inputTransformations.length > 0) {872
appendAssistantMessageDiagnostic(output, {873
type: "anthropic_input_transformations",874
timestamp: Date.now(),875
details: {876
transformations: inputTransformations.map((transformation) => ({877
type: transformation.type ?? undefined,878
path: transformation.path ?? undefined,879
reason: transformation.reason ?? undefined,880
})),881
},882
});883
}885
stream.push({ type: "done", reason: output.stopReason, message: output });886
stream.end();887
} catch (error) {888
for (const block of output.content) {889
delete (block as { index?: number }).index;890
// partialJson is only a streaming scratch buffer; never persist it.891
delete (block as { partialJson?: string }).partialJson;892
}893
output.stopReason = options?.signal?.aborted ? "aborted" : "error";894
output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);895
stream.push({ type: "error", reason: output.stopReason, error: output });896
stream.end();897
}898
})();900
return stream;901
};903
/**904
* Map ThinkingLevel to Anthropic effort levels for adaptive thinking.905
* Note: effort "max" is available on all adaptive-thinking Claude models, while native906
* "xhigh" is only available on Opus 4.7/4.8, Sonnet 5, and Fable 5.907
*/908
function mapThinkingLevelToEffort(909
model: Model<"anthropic-messages">,910
level: SimpleStreamOptions["reasoning"],911
): AnthropicEffort {912
const mapped = level ? model.thinkingLevelMap?.[level] : undefined;913
if (typeof mapped === "string") return mapped as AnthropicEffort;915
switch (level) {916
case "minimal":917
case "low":918
return "low";919
case "medium":920
return "medium";921
case "high":922
return "high";923
default:924
return "high";925
}926
}928
export const streamSimple: StreamFunction<"anthropic-messages", SimpleStreamOptions> = (929
model: Model<"anthropic-messages">,930
context: TranscriptContext,931
options?: SimpleStreamOptions,932
): AssistantMessageEventStream => {933
if (!getAnthropicFederation(model, options?.apiKey, options?.headers, options?.env)) {934
assertRequestAuth(model.provider, options?.apiKey, options?.headers);935
}937
const base = {938
...buildBaseOptions(model, context, options, options?.apiKey),939
toolChoice: options?.toolChoice,940
} satisfies AnthropicOptions;941
if (!options?.reasoning) {942
return stream(model, context, {943
...base,944
thinkingEnabled: false,945
} satisfies AnthropicOptions);946
}948
// For models with adaptive thinking: use an effort level.949
// For older models: use budget-based thinking.950
if (model.compat?.forceAdaptiveThinking === true) {951
const effort = mapThinkingLevelToEffort(model, options.reasoning);952
return stream(model, context, {953
...base,954
thinkingEnabled: true,955
effort,956
} satisfies AnthropicOptions);957
}959
// Undefined means the caller did not request an output cap; let the helper use the model cap.960
// Do not coerce to 0 here, or the thinking budget would become the entire max_tokens value.961
const adjusted = adjustMaxTokensForThinking(962
base.maxTokens,963
model.maxTokens,964
options.reasoning,965
options.thinkingBudgets,966
);968
const maxTokens = clampMaxTokensToContext(model, context, adjusted.maxTokens);970
return stream(model, context, {971
...base,972
maxTokens,973
thinkingEnabled: true,974
thinkingBudgetTokens: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024)),975
} satisfies AnthropicOptions);976
};978
function isOAuthToken(apiKey: string): boolean {979
return apiKey.includes("sk-ant-oat");980
}982
function createClient(983
model: Model<"anthropic-messages">,984
apiKey: string | undefined,985
optionsHeaders?: ProviderHeaders,986
fetch?: typeof globalThis.fetch,987
dynamicHeaders?: Record<string, string>,988
sessionId?: string,989
federation?: AnthropicFederationConfig,990
): { client: Anthropic; isOAuthToken: boolean } {991
// Copilot: Bearer auth.992
if (model.provider === "github-copilot") {993
const client = new PiAnthropic({994
apiKey: null,995
authToken: apiKey ?? null,996
baseURL: model.baseUrl,997
dangerouslyAllowBrowser: true,998
fetch,999
defaultHeaders: mergeClientHeaders(1000
{1001
accept: "application/json",1002
"anthropic-dangerous-direct-browser-access": "true",1003
},1004
model.headers,1005
dynamicHeaders,1006
optionsHeaders,1007
),1008
});1010
return { client, isOAuthToken: false };1011
}1013
// OAuth: Bearer auth, Claude Code identity headers1014
if (apiKey && isOAuthToken(apiKey)) {1015
const client = new PiAnthropic({1016
apiKey: null,1017
authToken: apiKey,1018
baseURL: model.baseUrl,1019
dangerouslyAllowBrowser: true,1020
fetch,1021
defaultHeaders: mergeClientHeaders(1022
{1023
accept: "application/json",1024
"anthropic-dangerous-direct-browser-access": "true",1025
"user-agent": `claude-cli/${claudeCodeVersion}`,1026
"x-app": "cli",1027
},1028
model.headers,1029
optionsHeaders,1030
),1031
});1033
return { client, isOAuthToken: true };1034
}1036
// API key, header-owned auth, or workload identity federation.1037
const compat = getAnthropicCompat(model);1038
const sessionAffinityHeaders: ProviderHeaders = {};1039
if (sessionId && compat.sendSessionAffinityHeaders) {1040
const header = compat.sessionAffinityFormat === "openrouter" ? "x-session-id" : "x-session-affinity";1041
sessionAffinityHeaders[header] = sessionId;1042
}1043
const defaultHeaders = mergeClientHeaders(1044
{1045
accept: "application/json",1046
"anthropic-dangerous-direct-browser-access": "true",1047
},1048
sessionAffinityHeaders,1049
model.headers,1050
optionsHeaders,1051
);1052
if (federation) {1053
const key = JSON.stringify([model.baseUrl, federation]);1054
if (federationClient?.key !== key || federationClient.fetch !== fetch) {1055
const client = new PiAnthropic({1056
apiKey: null,1057
authToken: null,1058
config: federation,1059
baseURL: model.baseUrl,1060
dangerouslyAllowBrowser: true,1061
fetch,1062
});1063
federationClient = { key, fetch, client };1064
}1065
return { client: federationClient.client.withOptions({ defaultHeaders }), isOAuthToken: false };1066
}1068
const client = new PiAnthropic({1069
apiKey: apiKey ?? null,1070
authToken: null,1071
baseURL: model.baseUrl,1072
dangerouslyAllowBrowser: true,1073
fetch,1074
defaultHeaders,1075
});1077
return { client, isOAuthToken: false };1078
}1080
function getBetaFeatures(1081
model: Model<"anthropic-messages">,1082
context: TranscriptContext,1083
isOAuthToken: boolean,1084
nativeToolChanges: boolean,1085
options?: AnthropicOptions,1086
): NonNullable<MessageCreateParamsStreaming["betas"]> {1087
let configuredFeatures: string | null | undefined;1088
for (const headers of [model.headers, options?.headers]) {1089
for (const [name, value] of Object.entries(headers ?? {})) {1090
if (name.toLowerCase() === "anthropic-beta") configuredFeatures = value;1091
}1092
}1093
if (configuredFeatures === null) return [];1094
if (configuredFeatures !== undefined) {1095
return [1096
...new Set(1097
configuredFeatures1098
.split(",")1099
.map((feature) => feature.trim())1100
.filter((feature) => feature.length > 0),1101
),1102
];1103
}1105
const features: NonNullable<MessageCreateParamsStreaming["betas"]> = [];1106
if (isOAuthToken) features.push("claude-code-20250219", "oauth-2025-04-20");1107
if (shouldUseFineGrainedToolStreamingBeta(model, context)) features.push(FINE_GRAINED_TOOL_STREAMING_BETA);1108
if (1109
model.reasoning &&1110
options?.thinkingEnabled === true &&1111
(options.interleavedThinking ?? true) &&1112
model.compat?.forceAdaptiveThinking !== true1113
) {1114
features.push(INTERLEAVED_THINKING_BETA);1115
}1116
if (shouldUseServerSideFallbackBeta(model)) features.push(SERVER_SIDE_FALLBACK_BETA);1117
if (model.compat?.supportsMidConvoEffort === true) {1118
features.push(MID_CONVERSATION_OUTPUT_CONFIG_BETA, THINKING_BINDING_CONTROLS_BETA);1119
}1120
if (nativeToolChanges) features.push(INLINE_TOOLS_BETA);1121
return [...new Set(features)];1122
}1124
function buildParams(1125
model: Model<"anthropic-messages">,1126
context: TranscriptContext,1127
isOAuthToken: boolean,1128
options?: AnthropicOptions,1129
): MessageCreateParamsStreaming {1130
const { cacheControl } = getCacheControl(model, options?.cacheRetention, options?.env);1131
const compat = getAnthropicCompat(model);1132
const initialSystemMessage = getInitialSystemMessage(context.messages);1133
const initialSystemText = initialSystemMessage ? getSystemMessageText(initialSystemMessage) : "";1134
const transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);1135
const conversationMessages = initialSystemMessage ? transformedMessages.slice(1) : transformedMessages;1136
// Native tool changes keep the request-level tool list fixed and define every later tool1137
// by value in a `tool_addition` block, which also expresses same-name redefinitions.1138
// Anthropic rejects a tool list where every tool is deferred, so there must be an initial1139
// active tool to anchor the placeholder. Otherwise the current tool list is sent.1140
const initialTools = initialSystemMessage?.toolsAdded ?? [];1141
const nativeToolChanges =1142
compat.supportsMidConvoSystemMessages && compat.supportsMidConvoToolChanges && initialTools.length > 0;1143
const converted = convertMessages(1144
conversationMessages,1145
isOAuthToken,1146
cacheControl,1147
compat.allowEmptySignature,1148
model.compat?.supportsMidConvoEffort === true ? model.provider : undefined,1149
nativeToolChanges1150
? (tools) =>1151
convertTools(tools, isOAuthToken, compat.supportsEagerToolInputStreaming, compat.supportsStrictTools)1152
: undefined,1153
);1154
const activeEffort = options?.effort ?? "high";1155
const betaFeatures = getBetaFeatures(model, context, isOAuthToken, nativeToolChanges, options);1156
const params: MessageCreateParamsStreaming = {1157
model: model.id,1158
messages:1159
model.compat?.supportsMidConvoEffort === true1160
? insertThinkingLevelMessages(converted, activeEffort)1161
: converted.messages,1162
max_tokens: options?.maxTokens ?? model.maxTokens,1163
stream: true,1164
...(betaFeatures.length > 0 ? { betas: betaFeatures } : {}),1165
};1167
// For OAuth tokens, we MUST include Claude Code identity1168
if (isOAuthToken) {1169
params.system = [1170
{1171
type: "text",1172
text: "You are Claude Code, Anthropic's official CLI for Claude.",1173
...(cacheControl ? { cache_control: cacheControl } : {}),1174
},1175
];1176
if (initialSystemText) {1177
params.system.push({1178
type: "text",1179
text: sanitizeSurrogates(initialSystemText),1180
...(cacheControl ? { cache_control: cacheControl } : {}),1181
});1182
}1183
} else if (initialSystemText) {1184
// Add cache control to system prompt for non-OAuth tokens1185
params.system = [1186
{1187
type: "text",1188
text: sanitizeSurrogates(initialSystemText),1189
...(cacheControl ? { cache_control: cacheControl } : {}),1190
},1191
];1192
}1194
// Temperature is incompatible with extended thinking and unsupported on Claude Opus 4.7+.1195
if (1196
options?.temperature !== undefined &&1197
!options?.thinkingEnabled &&1198
model.compat?.supportsMidConvoEffort !== true &&1199
compat.supportsTemperature1200
) {1201
params.temperature = options.temperature;1202
}1204
const toolCacheControl = compat.supportsCacheControlOnTools ? cacheControl : undefined;1205
if (nativeToolChanges) {1206
// Initial tools stay active with the cache breakpoint on the last one, followed by the1207
// placeholder. The list never changes afterwards: later tools are defined by value in1208
// `tool_addition` blocks and withdrawn by `tool_removal`, so the cached prefix survives1209
// every tool change.1210
params.tools = [1211
...convertTools(1212
initialTools,1213
isOAuthToken,1214
compat.supportsEagerToolInputStreaming,1215
compat.supportsStrictTools,1216
toolCacheControl,1217
),1218
DEFERRED_TOOL_PLACEHOLDER,1219
];1220
} else {1221
const tools = getCurrentTools(context.messages);1222
if (tools.length > 0) {1223
params.tools = convertTools(1224
tools,1225
isOAuthToken,1226
compat.supportsEagerToolInputStreaming,1227
compat.supportsStrictTools,1228
toolCacheControl,1229
);1230
}1231
}1233
// Managed effort models always use adaptive thinking so prefix mismatches can1234
// be dropped instead of surfacing as persistent 400 responses.1235
if (model.compat?.supportsMidConvoEffort === true) {1236
params.thinking = {1237
type: "adaptive",1238
display: options?.thinkingDisplay ?? "summarized",1239
block_binding: { prefix_mismatch_behavior: "drop_block" },1240
};1241
params.output_config = { effort: "high" };1242
} else if (model.reasoning) {1243
if (options?.thinkingEnabled) {1244
// Default to "summarized" so Opus 4.7 and Mythos Preview behave like1245
// older Claude 4 models (whose API default is also "summarized").1246
const display: AnthropicThinkingDisplay = options.thinkingDisplay ?? "summarized";1247
if (model.compat?.forceAdaptiveThinking === true) {1248
// Adaptive thinking: Claude decides when and how much to think.1249
params.thinking = { type: "adaptive", display };1250
if (options.effort) {1251
params.output_config = { effort: options.effort };1252
}1253
} else {1254
// Budget-based thinking for older models1255
params.thinking = {1256
type: "enabled",1257
budget_tokens: options.thinkingBudgetTokens || 1024,1258
display,1259
};1260
}1261
} else if (options?.thinkingEnabled === false && model.thinkingLevelMap?.off !== null) {1262
params.thinking = { type: "disabled" };1263
}1264
}1266
if (options?.metadata) {1267
const userId = options.metadata.user_id;1268
if (typeof userId === "string") {1269
params.metadata = { user_id: userId };1270
}1271
}1273
if (options?.toolChoice) {1274
if (typeof options.toolChoice === "string") {1275
params.tool_choice = { type: options.toolChoice };1276
} else {1277
params.tool_choice = options.toolChoice;1278
}1279
}1281
const allowedFallbackModels = model.compat?.allowedFallbackModels;1282
if (allowedFallbackModels && allowedFallbackModels.length > 0) {1283
params.fallbacks = allowedFallbackModels.map((fallback) => ({ model: fallback.model }));1284
}1286
return params;1287
}1289
// Normalize tool call IDs to match Anthropic's required pattern and length1290
function normalizeToolCallId(id: string): string {1291
return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);1292
}1294
function convertToolResult(msg: ToolResultMessage): ContentBlockParam {1295
return {1296
type: "tool_result",1297
tool_use_id: msg.toolCallId,1298
content: convertContentBlocks(msg.content),1299
is_error: msg.isError,1300
};1301
}1303
interface ConvertedAnthropicMessages {1304
messages: MessageParam[];1305
assistantLevels: Map<number, AnthropicEffort>;1306
}1308
function convertMessages(1309
transformedMessages: Message[],1310
isOAuthToken: boolean,1311
cacheControl?: CacheControlEphemeral,1312
allowEmptySignature = false,1313
managedProvider?: string,1314
/** Converts tool definitions for native `tool_addition` blocks; undefined when tool changes are not native. */1315
convertToolDefinitions?: (tools: Tool[]) => BetaTool[],1316
): ConvertedAnthropicMessages {1317
const params: MessageParam[] = [];1318
const assistantLevels = new Map<number, AnthropicEffort>();1319
// Later system messages are held back and emitted directly before the next assistant1320
// message (or at the end of the transcript). Anthropic requires `tool_result` blocks to1321
// immediately follow their `tool_use`, so a system message between them is rejected; this1322
// also mirrors where the managed-effort system messages are inserted. As a result an1323
// update placed before a user message in the transcript lands after it on the wire.1324
const pendingSystemMessages: MessageParam[] = [];1325
const flushPendingSystemMessages = (): void => {1326
params.push(...pendingSystemMessages);1327
pendingSystemMessages.length = 0;1328
};1330
for (let i = 0; i < transformedMessages.length; i++) {1331
const msg = transformedMessages[i];1333
if (msg.role === "system") {1334
// Later system messages only reach this point when the model accepts them natively;1335
// otherwise the transcript was collapsed into the leading message before conversion.1336
const text = renderSystemMessageUpdate(msg);1337
const blocks: ContentBlockParam[] = [];1338
if (text.length > 0) blocks.push({ type: "text", text: sanitizeSurrogates(text) });1339
if (convertToolDefinitions) {1340
const added = msg.toolsAdded ?? [];1341
const redefined = new Set(added.map((tool) => tool.name));1342
for (const tool of msg.toolsRemoved ?? []) {1343
// A new definition under the same name replaces the old one, so no removal is needed.1344
if (redefined.has(tool.name)) continue;1345
blocks.push({1346
type: "tool_removal",1347
tool: { type: "tool_reference", name: isOAuthToken ? toClaudeCodeName(tool.name) : tool.name },1348
});1349
}1350
for (const definition of convertToolDefinitions(added)) {1351
blocks.push({ type: "tool_addition", tool: { type: "tool_definition", definition } });1352
}1353
}1354
if (blocks.length > 0) pendingSystemMessages.push({ role: "system", content: blocks });1355
} else if (msg.role === "user") {1356
if (typeof msg.content === "string") {1357
if (msg.content.trim().length > 0) {1358
params.push({1359
role: "user",1360
content: sanitizeSurrogates(msg.content),1361
});1362
}1363
} else {1364
const blocks: ContentBlockParam[] = msg.content.map((item) => {1365
if (item.type === "text") {1366
return {1367
type: "text",1368
text: sanitizeSurrogates(item.text),1369
};1370
} else {1371
return {1372
type: "image",1373
source: {1374
type: "base64",1375
media_type: item.mimeType as "image/jpeg" | "image/png" | "image/gif" | "image/webp",1376
data: item.data,1377
},1378
};1379
}1380
});1381
const filteredBlocks = blocks.filter((b) => {1382
if (b.type === "text") {1383
return b.text.trim().length > 0;1384
}1385
return true;1386
});1387
if (filteredBlocks.length === 0) continue;1388
params.push({1389
role: "user",1390
content: filteredBlocks,1391
});1392
}1393
} else if (msg.role === "assistant") {1394
flushPendingSystemMessages();1395
const blocks: ContentBlockParam[] = [];1397
for (const block of msg.content) {1398
if (block.type === "text") {1399
if (block.text.trim().length === 0) continue;1400
blocks.push({1401
type: "text",1402
text: sanitizeSurrogates(block.text),1403
});1404
} else if (block.type === "thinking") {1405
// Redacted thinking: pass the opaque payload back as redacted_thinking1406
if (block.redacted) {1407
blocks.push({1408
type: "redacted_thinking",1409
data: block.thinkingSignature!,1410
});1411
continue;1412
}1413
const thinkingSignature = block.thinkingSignature;1414
const hasThinkingSignature = !!thinkingSignature && thinkingSignature.trim().length > 0;1415
if (block.thinking.trim().length === 0 && !hasThinkingSignature) continue;1416
// If thinking signature is missing/empty (e.g., from aborted stream),1417
// convert to plain text for Anthropic. Some compatible providers emit1418
// and accept empty signatures, so let marked models preserve the block.1419
if (!hasThinkingSignature) {1420
blocks.push(1421
allowEmptySignature1422
? {1423
type: "thinking",1424
thinking: sanitizeSurrogates(block.thinking),1425
signature: "",1426
}1427
: {1428
type: "text",1429
text: sanitizeSurrogates(block.thinking),1430
},1431
);1432
} else {1433
blocks.push({1434
type: "thinking",1435
thinking: sanitizeSurrogates(block.thinking),1436
signature: thinkingSignature,1437
});1438
}1439
} else if (block.type === "toolCall") {1440
blocks.push({1441
type: "tool_use",1442
id: block.id,1443
name: isOAuthToken ? toClaudeCodeName(block.name) : block.name,1444
input: block.arguments ?? {},1445
});1446
}1447
}1448
if (blocks.length === 0) continue;1449
const messageIndex = params.length;1450
params.push({1451
role: "assistant",1452
content: blocks,1453
});1454
if (1455
managedProvider !== undefined &&1456
msg.api === "anthropic-messages" &&1457
msg.provider === managedProvider &&1458
isAnthropicEffort(msg.providerThinkingLevel)1459
) {1460
assistantLevels.set(messageIndex, msg.providerThinkingLevel);1461
}1462
} else if (msg.role === "toolResult") {1463
// Collect all consecutive toolResult messages, needed for z.ai Anthropic endpoint.1464
const toolResults: ContentBlockParam[] = [];1465
let j = i;1466
while (j < transformedMessages.length && transformedMessages[j].role === "toolResult") {1467
toolResults.push(convertToolResult(transformedMessages[j] as ToolResultMessage));1468
j++;1469
}1471
// Skip the messages we've already processed.1472
i = j - 1;1474
params.push({1475
role: "user",1476
content: toolResults,1477
});1478
}1479
}1481
flushPendingSystemMessages();1483
// Add cache_control to the last user or system message to cache conversation history1484
if (cacheControl && params.length > 0) {1485
const lastMessage = params[params.length - 1];1486
if (lastMessage.role === "user" || lastMessage.role === "system") {1487
if (Array.isArray(lastMessage.content)) {1488
const lastBlock = lastMessage.content[lastMessage.content.length - 1];1489
if (1490
lastBlock &&1491
(lastBlock.type === "text" ||1492
lastBlock.type === "image" ||1493
lastBlock.type === "tool_result" ||1494
lastBlock.type === "tool_addition" ||1495
lastBlock.type === "tool_removal")1496
) {1497
(lastBlock as any).cache_control = cacheControl;1498
}1499
} else if (typeof lastMessage.content === "string") {1500
lastMessage.content = [1501
{1502
type: "text",1503
text: lastMessage.content,1504
cache_control: cacheControl,1505
},1506
] as any;1507
}1508
}1509
}1511
return { messages: params, assistantLevels };1512
}1514
function isAnthropicEffort(value: unknown): value is AnthropicEffort {1515
return value === "low" || value === "medium" || value === "high" || value === "xhigh" || value === "max";1516
}1518
function insertThinkingLevelMessages(1519
converted: ConvertedAnthropicMessages,1520
activeEffort: AnthropicEffort,1521
): MessageParam[] {1522
const messages: MessageParam[] = [];1523
for (let index = 0; index < converted.messages.length; index++) {1524
const historicalEffort = converted.assistantLevels.get(index);1525
if (historicalEffort !== undefined) {1526
messages.push({ role: "system", content: [], output_config: { effort: historicalEffort } });1527
}1528
messages.push(converted.messages[index]);1529
}1530
messages.push({ role: "system", content: [], output_config: { effort: activeEffort } });1531
return messages;1532
}1534
function shouldUseFineGrainedToolStreamingBeta(1535
model: Model<"anthropic-messages">,1536
context: TranscriptContext,1537
): boolean {1538
return getCurrentTools(context.messages).length > 0 && !getAnthropicCompat(model).supportsEagerToolInputStreaming;1539
}1541
// Keywords Anthropic strict tool use rejects with a 400 for the whole request.1542
// https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations1543
const ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS = new Set([1544
"minimum",1545
"maximum",1546
"exclusiveMinimum",1547
"exclusiveMaximum",1548
"multipleOf",1549
"maxItems",1550
"uniqueItems",1551
"minContains",1552
"maxContains",1553
"minProperties",1554
"maxProperties",1555
]);1556
const ANTHROPIC_STRICT_STRING_FORMATS = new Set([1557
"date-time",1558
"time",1559
"date",1560
"duration",1561
"email",1562
"hostname",1563
"uri",1564
"ipv4",1565
"ipv6",1566
"uuid",1567
]);1569
const isAnthropicStrictUnsupportedKeyword: UnsupportedStrictSchemaKeywordCheck = (key, value) => {1570
if (ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS.has(key)) return true;1571
if (key === "minItems") return value !== 0 && value !== 1;1572
if (key === "format") return typeof value !== "string" || !ANTHROPIC_STRICT_STRING_FORMATS.has(value);1573
return false;1574
};1576
function convertTools(1577
tools: Tool[],1578
isOAuthToken: boolean,1579
supportsEagerToolInputStreaming: boolean,1580
supportsStrictTools: boolean,1581
cacheControl?: CacheControlEphemeral,1582
): BetaTool[] {1583
if (!tools) return [];1585
return tools.map((tool, index) => {1586
const strict = resolveJsonSchemaStrictSampling(tool, supportsStrictTools, isAnthropicStrictUnsupportedKeyword);1587
const parameters = getJsonSchemaToolParameters(tool, strict);1588
const schema = parameters as { properties?: unknown; required?: string[] };1589
const legacyInputSchema = {1590
type: "object" as const,1591
properties: schema.properties ?? {},1592
required: schema.required ?? [],1593
};1594
const inputSchema =1595
strict === true1596
? {1597
...(parameters as Record<string, unknown>),1598
...legacyInputSchema,1599
}1600
: legacyInputSchema;1602
return {1603
name: isOAuthToken ? toClaudeCodeName(tool.name) : tool.name,1604
description: tool.description,1605
...(supportsEagerToolInputStreaming ? { eager_input_streaming: true } : {}),1606
...(strict === true ? { strict: true } : {}),1607
input_schema: inputSchema,1608
...(cacheControl && index === tools.length - 1 ? { cache_control: cacheControl } : {}),1609
};1610
});1611
}1613
function mapStopReason(1614
reason: BetaStopReason | string,1615
stopDetails?: RefusalStopDetails | null,1616
): { stopReason: StopReason; errorMessage?: string } {1617
switch (reason) {1618
case "end_turn":1619
return { stopReason: "stop" };1620
case "max_tokens":1621
return { stopReason: "length" };1622
case "tool_use":1623
return { stopReason: "toolUse" };1624
case "refusal":1625
return {1626
stopReason: "error",1627
errorMessage: stopDetails?.explanation || `The model refused to complete the request`,1628
};1629
case "pause_turn": // Stop is good enough -> resubmit1630
return { stopReason: "stop" };1631
case "stop_sequence":1632
return { stopReason: "stop" }; // We don't supply stop sequences, so this should never happen1633
case "sensitive": // Content flagged by safety filters (not yet in SDK types)1634
return { stopReason: "error", errorMessage: "Provider stopped with: sensitive" };1635
default:1636
// Handle unknown stop reasons gracefully (API may add new values)1637
throw new Error(`Unhandled stop reason: ${reason}`);1638
}1639
}