@zyro-sec/ai 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +23 -0
- package/README.md +1810 -2
- package/example/tutorial.ts +284 -0
- package/package.json +40 -4
- package/script/pack.ts +5 -0
- package/script/recording-cost-report.ts +250 -0
- package/script/setup-recording-env.ts +602 -0
- package/src/ai-client.ts +28 -0
- package/src/cache-policy.ts +249 -0
- package/src/decision-client.ts +88 -0
- package/src/decision.ts +335 -0
- package/src/effect.ts +44 -0
- package/src/effort-updates.ts +25 -0
- package/src/embedding-client.ts +46 -0
- package/src/embedding.ts +167 -0
- package/src/experimental/cloudflare-run-extraction.ts +112 -0
- package/src/experimental/extraction.ts +190 -0
- package/src/experimental/realtime.ts +211 -0
- package/src/experimental.ts +51 -0
- package/src/generation.ts +210 -0
- package/src/image-client.ts +89 -0
- package/src/image.ts +236 -0
- package/src/index.ts +363 -0
- package/src/llm.ts +364 -0
- package/src/loop.ts +214 -0
- package/src/media-client.ts +94 -0
- package/src/media-model.ts +129 -0
- package/src/media.ts +408 -0
- package/src/protocols/alibaba-chat.ts +95 -0
- package/src/protocols/alibaba-images.ts +126 -0
- package/src/protocols/alibaba-messages.ts +49 -0
- package/src/protocols/alibaba-responses.ts +86 -0
- package/src/protocols/anthropic-messages.ts +1664 -0
- package/src/protocols/assemblyai-transcription.ts +209 -0
- package/src/protocols/bedrock-converse.ts +984 -0
- package/src/protocols/bedrock-event-stream.ts +147 -0
- package/src/protocols/cartesia-speech.ts +182 -0
- package/src/protocols/cloudflare-run-decisions.ts +55 -0
- package/src/protocols/cloudflare-workers-ai-images.ts +124 -0
- package/src/protocols/cohere-chat.ts +353 -0
- package/src/protocols/deepgram-speech.ts +148 -0
- package/src/protocols/deepgram-transcription.ts +179 -0
- package/src/protocols/elevenlabs-speech.ts +207 -0
- package/src/protocols/elevenlabs-transcription.ts +211 -0
- package/src/protocols/gemini.ts +908 -0
- package/src/protocols/google-decisions.ts +179 -0
- package/src/protocols/google-embed-content.ts +165 -0
- package/src/protocols/google-images.ts +255 -0
- package/src/protocols/google-interactions-video.ts +264 -0
- package/src/protocols/google-interactions.ts +904 -0
- package/src/protocols/google-speech.ts +157 -0
- package/src/protocols/google-transcription.ts +206 -0
- package/src/protocols/google-vertex-predict-embeddings.ts +104 -0
- package/src/protocols/index.ts +21 -0
- package/src/protocols/meta-images.ts +162 -0
- package/src/protocols/meta-messages.ts +67 -0
- package/src/protocols/meta-responses.ts +249 -0
- package/src/protocols/minimax-images.ts +215 -0
- package/src/protocols/minimax-video.ts +406 -0
- package/src/protocols/mistral-chat.ts +768 -0
- package/src/protocols/open-responses-channel.ts +198 -0
- package/src/protocols/open-responses-continuation.ts +218 -0
- package/src/protocols/open-responses.ts +1636 -0
- package/src/protocols/openai-chat.ts +1431 -0
- package/src/protocols/openai-compatible-chat.ts +22 -0
- package/src/protocols/openai-compatible-responses.ts +21 -0
- package/src/protocols/openai-decisions.ts +174 -0
- package/src/protocols/openai-embeddings.ts +105 -0
- package/src/protocols/openai-freeform.ts +287 -0
- package/src/protocols/openai-images.ts +442 -0
- package/src/protocols/openai-responses.ts +442 -0
- package/src/protocols/openai-speech.ts +164 -0
- package/src/protocols/openai-transcription.ts +295 -0
- package/src/protocols/openrouter-video.ts +215 -0
- package/src/protocols/seedance-video.ts +301 -0
- package/src/protocols/shared.ts +552 -0
- package/src/protocols/system-one.ts +335 -0
- package/src/protocols/utils/bedrock-auth.ts +147 -0
- package/src/protocols/utils/bedrock-cache.ts +56 -0
- package/src/protocols/utils/bedrock-media.ts +121 -0
- package/src/protocols/utils/cache.ts +44 -0
- package/src/protocols/utils/claude-model.ts +19 -0
- package/src/protocols/utils/gateway-protocol.ts +92 -0
- package/src/protocols/utils/gemini-generate-content.ts +172 -0
- package/src/protocols/utils/gemini-json-schema.ts +77 -0
- package/src/protocols/utils/image-sizing.ts +117 -0
- package/src/protocols/utils/lifecycle.ts +120 -0
- package/src/protocols/utils/media-input.ts +98 -0
- package/src/protocols/utils/mistral-tool-id.ts +34 -0
- package/src/protocols/utils/open-responses-options.ts +82 -0
- package/src/protocols/utils/partial-json-options.ts +62 -0
- package/src/protocols/utils/partial-json.ts +283 -0
- package/src/protocols/utils/responses-checkpoint.ts +115 -0
- package/src/protocols/utils/responses-compaction.ts +210 -0
- package/src/protocols/utils/responses-hosted-tools.ts +104 -0
- package/src/protocols/utils/speaker-turns.ts +10 -0
- package/src/protocols/utils/speech-stream.ts +111 -0
- package/src/protocols/utils/tool-schema.ts +115 -0
- package/src/protocols/utils/tool-stream.ts +240 -0
- package/src/protocols/venice-chat.ts +356 -0
- package/src/protocols/xai-images.ts +137 -0
- package/src/protocols/xai-responses.ts +106 -0
- package/src/protocols/xai-video.ts +232 -0
- package/src/protocols/zai-chat.ts +71 -0
- package/src/protocols/zai-images.ts +120 -0
- package/src/protocols/zai-messages.ts +34 -0
- package/src/protocols.ts +1 -0
- package/src/provider-error.ts +291 -0
- package/src/provider-package.ts +32 -0
- package/src/providers/alibaba/chat.ts +1 -0
- package/src/providers/alibaba/embeddings.ts +2 -0
- package/src/providers/alibaba/images.ts +2 -0
- package/src/providers/alibaba/messages.ts +3 -0
- package/src/providers/alibaba/responses.ts +3 -0
- package/src/providers/alibaba.ts +177 -0
- package/src/providers/amazon-bedrock/mantle/chat.ts +2 -0
- package/src/providers/amazon-bedrock/mantle/messages.ts +2 -0
- package/src/providers/amazon-bedrock/mantle/responses.ts +2 -0
- package/src/providers/amazon-bedrock/mantle.ts +2 -0
- package/src/providers/amazon-bedrock-mantle.ts +192 -0
- package/src/providers/amazon-bedrock.ts +81 -0
- package/src/providers/anthropic-compatible.ts +80 -0
- package/src/providers/anthropic.ts +66 -0
- package/src/providers/assemblyai.ts +32 -0
- package/src/providers/azure/chat.ts +2 -0
- package/src/providers/azure/embeddings.ts +2 -0
- package/src/providers/azure/images.ts +2 -0
- package/src/providers/azure/messages.ts +2 -0
- package/src/providers/azure/responses.ts +2 -0
- package/src/providers/azure.ts +240 -0
- package/src/providers/baseten/decisions.ts +2 -0
- package/src/providers/baseten.ts +88 -0
- package/src/providers/byteplus/videos.ts +2 -0
- package/src/providers/byteplus.ts +39 -0
- package/src/providers/cartesia.ts +28 -0
- package/src/providers/cerebras.ts +56 -0
- package/src/providers/cloudflare-ai-gateway/decisions.ts +2 -0
- package/src/providers/cloudflare-ai-gateway.ts +199 -0
- package/src/providers/cloudflare-shared.ts +29 -0
- package/src/providers/cloudflare-workers-ai/decisions.ts +2 -0
- package/src/providers/cloudflare-workers-ai/images.ts +2 -0
- package/src/providers/cloudflare-workers-ai.ts +104 -0
- package/src/providers/cohere/chat.ts +8 -0
- package/src/providers/cohere/embeddings.ts +2 -0
- package/src/providers/cohere.ts +72 -0
- package/src/providers/deepgram.ts +33 -0
- package/src/providers/deepinfra/embeddings.ts +2 -0
- package/src/providers/deepinfra.ts +76 -0
- package/src/providers/deepseek.ts +54 -0
- package/src/providers/digitalocean/decisions.ts +2 -0
- package/src/providers/digitalocean/embeddings.ts +2 -0
- package/src/providers/digitalocean/images.ts +2 -0
- package/src/providers/digitalocean/responses.ts +4 -0
- package/src/providers/digitalocean.ts +144 -0
- package/src/providers/elevenlabs.ts +35 -0
- package/src/providers/fireworks/embeddings.ts +2 -0
- package/src/providers/fireworks.ts +66 -0
- package/src/providers/google/decisions.ts +2 -0
- package/src/providers/google/embeddings.ts +2 -0
- package/src/providers/google/images.ts +2 -0
- package/src/providers/google/interactions.ts +13 -0
- package/src/providers/google/videos.ts +2 -0
- package/src/providers/google-vertex/chat.ts +2 -0
- package/src/providers/google-vertex/embeddings.ts +2 -0
- package/src/providers/google-vertex/gemini.ts +2 -0
- package/src/providers/google-vertex/images.ts +2 -0
- package/src/providers/google-vertex/interactions.ts +2 -0
- package/src/providers/google-vertex/messages.ts +2 -0
- package/src/providers/google-vertex/mistral.ts +2 -0
- package/src/providers/google-vertex/responses.ts +2 -0
- package/src/providers/google-vertex-chat.ts +63 -0
- package/src/providers/google-vertex-interactions.ts +104 -0
- package/src/providers/google-vertex-messages.ts +99 -0
- package/src/providers/google-vertex-mistral.ts +79 -0
- package/src/providers/google-vertex-responses.ts +64 -0
- package/src/providers/google-vertex-shared.ts +176 -0
- package/src/providers/google-vertex.ts +228 -0
- package/src/providers/google.ts +121 -0
- package/src/providers/groq.ts +98 -0
- package/src/providers/index.ts +45 -0
- package/src/providers/meta/chat.ts +2 -0
- package/src/providers/meta/images.ts +2 -0
- package/src/providers/meta/messages.ts +2 -0
- package/src/providers/meta/responses.ts +2 -0
- package/src/providers/meta.ts +161 -0
- package/src/providers/minimax/chat.ts +8 -0
- package/src/providers/minimax/images.ts +4 -0
- package/src/providers/minimax/messages.ts +1 -0
- package/src/providers/minimax/responses.ts +8 -0
- package/src/providers/minimax/videos.ts +4 -0
- package/src/providers/minimax.ts +162 -0
- package/src/providers/mistral.ts +40 -0
- package/src/providers/moonshot/chat.ts +1 -0
- package/src/providers/moonshot/messages.ts +8 -0
- package/src/providers/moonshot/responses.ts +8 -0
- package/src/providers/moonshot.ts +134 -0
- package/src/providers/open-responses-options.ts +4 -0
- package/src/providers/openai/chat.ts +2 -0
- package/src/providers/openai/embeddings.ts +2 -0
- package/src/providers/openai/images.ts +2 -0
- package/src/providers/openai/responses.ts +2 -0
- package/src/providers/openai-compatible/decisions.ts +2 -0
- package/src/providers/openai-compatible/embeddings.ts +2 -0
- package/src/providers/openai-compatible/images.ts +2 -0
- package/src/providers/openai-compatible/responses.ts +1 -0
- package/src/providers/openai-compatible-responses.ts +52 -0
- package/src/providers/openai-compatible.ts +108 -0
- package/src/providers/openai-options.ts +66 -0
- package/src/providers/openai.ts +207 -0
- package/src/providers/opencode/decisions.ts +2 -0
- package/src/providers/opencode.ts +45 -0
- package/src/providers/openrouter/decisions.ts +2 -0
- package/src/providers/openrouter/embeddings.ts +2 -0
- package/src/providers/openrouter/images.ts +2 -0
- package/src/providers/openrouter/responses.ts +3 -0
- package/src/providers/openrouter/videos.ts +2 -0
- package/src/providers/openrouter.ts +347 -0
- package/src/providers/settings.ts +54 -0
- package/src/providers/togetherai.ts +53 -0
- package/src/providers/typesafe-ai/decisions.ts +2 -0
- package/src/providers/typesafe-ai.ts +45 -0
- package/src/providers/venice/responses.ts +4 -0
- package/src/providers/venice.ts +93 -0
- package/src/providers/vercel-ai-gateway/chat.ts +2 -0
- package/src/providers/vercel-ai-gateway/decisions.ts +2 -0
- package/src/providers/vercel-ai-gateway/embeddings.ts +2 -0
- package/src/providers/vercel-ai-gateway/images.ts +2 -0
- package/src/providers/vercel-ai-gateway/messages.ts +2 -0
- package/src/providers/vercel-ai-gateway/responses.ts +2 -0
- package/src/providers/vercel-ai-gateway.ts +300 -0
- package/src/providers/volcengine/videos.ts +2 -0
- package/src/providers/volcengine.ts +39 -0
- package/src/providers/xai/images.ts +2 -0
- package/src/providers/xai/videos.ts +2 -0
- package/src/providers/xai.ts +125 -0
- package/src/providers/zai/chat.ts +1 -0
- package/src/providers/zai/images.ts +2 -0
- package/src/providers/zai-coding-plan/chat.ts +1 -0
- package/src/providers/zai-coding-plan/messages.ts +8 -0
- package/src/providers/zai-coding-plan/responses.ts +8 -0
- package/src/providers/zai-coding-plan.ts +86 -0
- package/src/providers/zai.ts +73 -0
- package/src/providers.ts +1 -0
- package/src/public.ts +204 -0
- package/src/route/auth-options.ts +62 -0
- package/src/route/auth.ts +164 -0
- package/src/route/client.ts +700 -0
- package/src/route/decision.ts +150 -0
- package/src/route/embedding.ts +175 -0
- package/src/route/endpoint.ts +63 -0
- package/src/route/executor-service.ts +191 -0
- package/src/route/executor.ts +361 -0
- package/src/route/framing.ts +112 -0
- package/src/route/index.ts +47 -0
- package/src/route/media-protocol.ts +321 -0
- package/src/route/media.ts +507 -0
- package/src/route/protocol.ts +97 -0
- package/src/route/transport/http.ts +103 -0
- package/src/route/transport/index.ts +59 -0
- package/src/route/transport/websocket-channel.ts +51 -0
- package/src/route/transport/websocket.ts +443 -0
- package/src/route.ts +1 -0
- package/src/schema/errors.ts +246 -0
- package/src/schema/events.ts +744 -0
- package/src/schema/ids.ts +24 -0
- package/src/schema/index.ts +5 -0
- package/src/schema/messages.ts +529 -0
- package/src/schema/options.ts +445 -0
- package/src/speech-client.ts +25 -0
- package/src/speech.ts +211 -0
- package/src/testing.ts +218 -0
- package/src/tool-history.ts +91 -0
- package/src/tool-runtime.ts +107 -0
- package/src/tool-updates.ts +139 -0
- package/src/tool.ts +281 -0
- package/src/transcription-client.ts +19 -0
- package/src/transcription.ts +234 -0
- package/src/utils/bytes.ts +9 -0
- package/src/utils/json.ts +5 -0
- package/src/utils/media-type.ts +93 -0
- package/src/utils/provider-codes.ts +43 -0
- package/src/utils/record.ts +3 -0
- package/src/utils/sanitize.ts +33 -0
- package/src/video-client.ts +66 -0
- package/src/video.ts +181 -0
- package/test/adapter.test.ts +180 -0
- package/test/auth-options.types.ts +283 -0
- package/test/auth.test.ts +112 -0
- package/test/cache-policy.test.ts +578 -0
- package/test/compaction-http.test.ts +96 -0
- package/test/compaction.test.ts +107 -0
- package/test/compile.test.ts +600 -0
- package/test/continuation-scenarios.ts +115 -0
- package/test/decision.test.ts +983 -0
- package/test/decision.types.ts +117 -0
- package/test/effort-updates.test.ts +574 -0
- package/test/embedding.test.ts +455 -0
- package/test/endpoint.test.ts +58 -0
- package/test/error-partial.test.ts +140 -0
- package/test/executor.test.ts +1095 -0
- package/test/exports.test.ts +222 -0
- package/test/extraction.test.ts +227 -0
- package/test/fixtures/audio/dialog.mp3 +0 -0
- package/test/fixtures/audio/hello.mp3 +0 -0
- package/test/fixtures/images/edit-source.jpg +0 -0
- package/test/fixtures/media/restroom.png +0 -0
- package/test/fixtures/recordings/alibaba-chat/qwen-3-7-plus-streams-thinking-disabled.json +35 -0
- package/test/fixtures/recordings/alibaba-chat/qwen-3-7-plus-streams-thinking-enabled.json +35 -0
- package/test/fixtures/recordings/alibaba-chat/qwen-3-8-flash-reads-image-bytes.json +34 -0
- package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-obeys-named-tool-choice.json +35 -0
- package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-replays-reasoning-through-a-tool-loop-and-follow-up.json +73 -0
- package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-returns-a-json-object.json +34 -0
- package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-default-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-high-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-low-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-max-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-medium-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-minimal-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-none-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-xhigh-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-images/edits-an-image.json +33 -0
- package/test/fixtures/recordings/alibaba-images/generates-qwen-image-images.json +33 -0
- package/test/fixtures/recordings/alibaba-images/generates-wan-images.json +33 -0
- package/test/fixtures/recordings/alibaba-messages/qwen-3-7-plus-streams-thinking-disabled.json +35 -0
- package/test/fixtures/recordings/alibaba-messages/qwen-3-7-plus-streams-thinking-enabled.json +35 -0
- package/test/fixtures/recordings/alibaba-messages/qwen-3-8-flash-reads-image-bytes.json +34 -0
- package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-follows-a-json-schema.json +34 -0
- package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-obeys-named-tool-choice.json +35 -0
- package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-replays-reasoning-through-a-tool-loop-and-follow-up.json +73 -0
- package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-default-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-high-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-low-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-max-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-medium-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-xhigh-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-7-plus-streams-thinking-disabled.json +35 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-7-plus-streams-thinking-enabled.json +35 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-8-flash-reads-image-bytes.json +34 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-continues-a-stored-response.json +53 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-obeys-named-tool-choice.json +35 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-replays-reasoning-through-a-tool-loop-and-follow-up.json +73 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-default-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-high-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-low-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-max-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-medium-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-minimal-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-none-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-xhigh-effort.json +36 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-uses-hosted-code-interpreter.json +35 -0
- package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-uses-hosted-web-search-and-extraction.json +36 -0
- package/test/fixtures/recordings/anthropic-compatible-messages/minimax-m3-anthropic-compatible-text.json +40 -0
- package/test/fixtures/recordings/anthropic-compatible-messages/minimax-m3-anthropic-compatible-tool-call.json +41 -0
- package/test/fixtures/recordings/anthropic-compatible-messages/minimax-m3-anthropic-compatible-tool-loop.json +60 -0
- package/test/fixtures/recordings/anthropic-messages/anthropic-opus-4-7-image-tool-result.json +43 -0
- package/test/fixtures/recordings/anthropic-messages-cache/keeps-a-long-tool-turn-inside-the-cache-lookback.json +48 -0
- package/test/fixtures/recordings/anthropic-messages-cache/writes-then-reads-cache-control-on-identical-second-call.json +48 -0
- package/test/fixtures/recordings/assemblyai-transcription/uploads-submits-and-polls-a-transcript.json +98 -0
- package/test/fixtures/recordings/azure/chat-streams-text-from-a-foundry-models-url.json +31 -0
- package/test/fixtures/recordings/azure/chat-streams-text.json +28 -0
- package/test/fixtures/recordings/azure/messages-calls-a-tool.json +31 -0
- package/test/fixtures/recordings/azure/messages-streams-text.json +31 -0
- package/test/fixtures/recordings/azure/responses-calls-a-tool.json +31 -0
- package/test/fixtures/recordings/azure/responses-continues-after-a-tool-result.json +31 -0
- package/test/fixtures/recordings/azure/responses-streams-text.json +31 -0
- package/test/fixtures/recordings/baseten-decision/decides-choice-score-and-predicate-questions.json +33 -0
- package/test/fixtures/recordings/bedrock-converse/continues-after-parallel-tool-results.json +36 -0
- package/test/fixtures/recordings/bedrock-converse/drives-a-tool-loop.json +55 -0
- package/test/fixtures/recordings/bedrock-converse/streams-a-tool-call.json +29 -0
- package/test/fixtures/recordings/bedrock-converse/streams-text.json +29 -0
- package/test/fixtures/recordings/bedrock-converse-cache/writes-then-reads-cachepoint-on-identical-second-call.json +48 -0
- package/test/fixtures/recordings/bedrock-converse-options/constrains-claude-output-to-a-json-schema.json +33 -0
- package/test/fixtures/recordings/bedrock-converse-options/sends-claude-effort-with-adaptive-thinking-service-tier-and-request-metadata.json +34 -0
- package/test/fixtures/recordings/bedrock-converse-options/sends-gpt-oss-reasoning-effort-with-the-priority-tier.json +34 -0
- package/test/fixtures/recordings/bedrock-converse-options/sends-nova-2-reasoning-effort.json +34 -0
- package/test/fixtures/recordings/bedrock-converse-thinking-binding/accepts-the-default-binding-with-no-thinking-configured.json +34 -0
- package/test/fixtures/recordings/bedrock-converse-thinking-binding/keeps-a-session-working-after-the-system-prompt-changes.json +71 -0
- package/test/fixtures/recordings/bedrock-mantle/streams-text.json +33 -0
- package/test/fixtures/recordings/bedrock-mantle-messages/applies-mid-conversation-effort-updates-and-thinking-block-binding-on-opus-5-5.json +57 -0
- package/test/fixtures/recordings/bedrock-mantle-messages/lowers-system-updates-to-wrapped-user-text-on-haiku-4-5-with-budget-thinking.json +37 -0
- package/test/fixtures/recordings/bedrock-mantle-messages/replays-signed-thinking-through-a-tool-loop-and-native-system-update.json +59 -0
- package/test/fixtures/recordings/bedrock-mantle-messages/strips-unsupported-mid-conversation-effort-updates-on-opus-5-0.json +37 -0
- package/test/fixtures/recordings/cartesia-speech/generates-speech.json +34 -0
- package/test/fixtures/recordings/cartesia-speech/streams-speech-with-timestamps.json +33 -0
- package/test/fixtures/recordings/cerebras-chat/cerebras-gpt-oss-120b-text.json +32 -0
- package/test/fixtures/recordings/cerebras-chat/cerebras-gpt-oss-120b-tool-call.json +32 -0
- package/test/fixtures/recordings/cerebras-chat/cerebras-gpt-oss-120b-tool-loop.json +50 -0
- package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-claude-haiku-4-5-text.json +38 -0
- package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-claude-haiku-4-5-tool-loop.json +58 -0
- package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-openai-gpt-5-nano-text.json +37 -0
- package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-openai-gpt-5-nano-tool-loop.json +56 -0
- package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-workers-ai-gpt-oss-20b-tools-tool-call.json +32 -0
- package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-workers-ai-llama-3-1-8b-text.json +32 -0
- package/test/fixtures/recordings/cloudflare-ai-gateway-decision/decides-choice-score-and-predicate-questions.json +33 -0
- package/test/fixtures/recordings/cloudflare-workers-ai/cloudflare-workers-ai-gpt-oss-20b-tools-tool-call.json +32 -0
- package/test/fixtures/recordings/cloudflare-workers-ai/cloudflare-workers-ai-llama-3-1-8b-text.json +32 -0
- package/test/fixtures/recordings/cloudflare-workers-ai-decision/decides-choice-score-and-predicate-questions.json +33 -0
- package/test/fixtures/recordings/cloudflare-workers-ai-extraction/extracts-invoice-fields.json +33 -0
- package/test/fixtures/recordings/cloudflare-workers-ai-images/generates-a-flux-2-image-from-multipart-fields.json +32 -0
- package/test/fixtures/recordings/cloudflare-workers-ai-images/generates-a-raw-binary-image.json +33 -0
- package/test/fixtures/recordings/cohere/continues-a-native-tool-call.json +49 -0
- package/test/fixtures/recordings/cohere/streams-compatible-chat-reasoning.json +31 -0
- package/test/fixtures/recordings/cohere/streams-native-text-and-usage.json +31 -0
- package/test/fixtures/recordings/cohere/streams-native-thinking-with-a-budget.json +31 -0
- package/test/fixtures/recordings/cohere-embedding/embeds-text-through-the-compatibility-api.json +33 -0
- package/test/fixtures/recordings/deepgram-speech/generates-speech.json +36 -0
- package/test/fixtures/recordings/deepgram-speech/streams-speech.json +36 -0
- package/test/fixtures/recordings/deepgram-transcription/splits-utterances-at-speaker-changes.json +32 -0
- package/test/fixtures/recordings/deepgram-transcription/transcribes-raw-audio-with-speakers-and-word-timestamps.json +50 -0
- package/test/fixtures/recordings/deepinfra-chat/deepinfra-llama-3-3-70b-text.json +32 -0
- package/test/fixtures/recordings/deepinfra-chat/deepinfra-llama-3-3-70b-tool-call.json +32 -0
- package/test/fixtures/recordings/deepinfra-chat/deepinfra-llama-3-3-70b-tool-loop.json +50 -0
- package/test/fixtures/recordings/digitalocean-chat/gpt-nano-continues-a-tool-call-with-cache-markers.json +54 -0
- package/test/fixtures/recordings/digitalocean-chat/gpt-nano-reuses-a-cached-prompt.json +53 -0
- package/test/fixtures/recordings/digitalocean-chat/haiku-continues-a-tool-call-with-cache-markers.json +54 -0
- package/test/fixtures/recordings/digitalocean-chat/haiku-reuses-a-cached-prompt.json +53 -0
- package/test/fixtures/recordings/digitalocean-decision/decides-choice-score-and-predicate-questions.json +33 -0
- package/test/fixtures/recordings/digitalocean-responses/calls-a-freeform-text-tool.json +35 -0
- package/test/fixtures/recordings/digitalocean-responses/continues-a-tool-call.json +53 -0
- package/test/fixtures/recordings/digitalocean-responses/streams-text.json +35 -0
- package/test/fixtures/recordings/elevenlabs-speech/generates-speech.json +35 -0
- package/test/fixtures/recordings/elevenlabs-speech/streams-speech-with-timestamps.json +34 -0
- package/test/fixtures/recordings/elevenlabs-transcription/groups-diarized-words-into-speaker-turns.json +32 -0
- package/test/fixtures/recordings/elevenlabs-transcription/transcribes-audio-with-word-timestamps.json +50 -0
- package/test/fixtures/recordings/gemini/gemini-2-5-flash-image.json +32 -0
- package/test/fixtures/recordings/gemini-cache/reports-cachedcontenttokencount-on-identical-second-call.json +46 -0
- package/test/fixtures/recordings/google-decision/decides-choice-score-and-predicate-questions.json +33 -0
- package/test/fixtures/recordings/google-embedding/embeds-an-image-and-text-into-one-vector-each.json +32 -0
- package/test/fixtures/recordings/google-embedding/embeds-text-through-batchembedcontents.json +32 -0
- package/test/fixtures/recordings/google-embedding/maps-inputtype-to-a-task-type-for-gemini-embedding-001.json +50 -0
- package/test/fixtures/recordings/google-images/edits-an-image.json +28 -0
- package/test/fixtures/recordings/google-images/generates-an-image.json +28 -0
- package/test/fixtures/recordings/google-interactions/continues-tool-results-with-previous-interaction-id.json +66 -0
- package/test/fixtures/recordings/google-interactions/replays-native-tool-results-and-signatures-statelessly.json +50 -0
- package/test/fixtures/recordings/google-interactions/streams-reasoning-and-retains-thought-signatures.json +32 -0
- package/test/fixtures/recordings/google-interactions/streams-text-and-reports-usage.json +32 -0
- package/test/fixtures/recordings/google-interactions-video/generates-a-video.json +96 -0
- package/test/fixtures/recordings/google-speech/generates-speech.json +32 -0
- package/test/fixtures/recordings/google-speech/streams-speech.json +32 -0
- package/test/fixtures/recordings/google-transcription/streams-speaker-turns.json +32 -0
- package/test/fixtures/recordings/google-transcription/transcribes-with-speakers-and-word-timestamps.json +32 -0
- package/test/fixtures/recordings/google-vertex/calls-a-tool.json +32 -0
- package/test/fixtures/recordings/google-vertex/continues-after-a-tool-result.json +32 -0
- package/test/fixtures/recordings/google-vertex/streams-text.json +32 -0
- package/test/fixtures/recordings/google-vertex-embedding/embeds-gemini-embedding-001-one-text-per-predict-request.json +50 -0
- package/test/fixtures/recordings/google-vertex-embedding/embeds-text-through-predict.json +32 -0
- package/test/fixtures/recordings/groq-chat/continues-qwen-parallel-tool-calls.json +47 -0
- package/test/fixtures/recordings/groq-chat/replays-gpt-oss-reasoning-through-a-tool-loop.json +47 -0
- package/test/fixtures/recordings/groq-chat/streams-qwen-parsed-reasoning.json +29 -0
- package/test/fixtures/recordings/groq-chat/streams-text-with-usage.json +29 -0
- package/test/fixtures/recordings/meta-chat/continues-a-generated-tool-call.json +56 -0
- package/test/fixtures/recordings/meta-chat/streams-text-with-default-reasoning.json +37 -0
- package/test/fixtures/recordings/meta-chat/streams-text-with-high-reasoning.json +29 -0
- package/test/fixtures/recordings/meta-chat/streams-text-with-low-reasoning.json +29 -0
- package/test/fixtures/recordings/meta-chat/streams-text-with-max-reasoning.json +29 -0
- package/test/fixtures/recordings/meta-chat/streams-text-with-medium-reasoning.json +37 -0
- package/test/fixtures/recordings/meta-chat/streams-text-with-minimal-reasoning.json +37 -0
- package/test/fixtures/recordings/meta-chat/streams-text-with-xhigh-reasoning.json +29 -0
- package/test/fixtures/recordings/meta-images/edits-image-bytes-and-returns-png.json +29 -0
- package/test/fixtures/recordings/meta-images/generates-default-webp-bytes.json +29 -0
- package/test/fixtures/recordings/meta-images/replays-a-signed-image-handle-for-a-responses-edit.json +55 -0
- package/test/fixtures/recordings/meta-messages/replays-encrypted-thinking-through-a-tool-loop.json +54 -0
- package/test/fixtures/recordings/meta-messages/streams-text-with-adaptive-thinking.json +36 -0
- package/test/fixtures/recordings/meta-messages/streams-text-with-enabled-thinking.json +36 -0
- package/test/fixtures/recordings/meta-responses/replays-encrypted-reasoning-through-a-tool-loop.json +56 -0
- package/test/fixtures/recordings/meta-responses/streams-text-with-default-reasoning.json +37 -0
- package/test/fixtures/recordings/meta-responses/streams-text-with-high-reasoning.json +37 -0
- package/test/fixtures/recordings/meta-responses/streams-text-with-low-reasoning.json +37 -0
- package/test/fixtures/recordings/meta-responses/streams-text-with-max-reasoning.json +37 -0
- package/test/fixtures/recordings/meta-responses/streams-text-with-medium-reasoning.json +37 -0
- package/test/fixtures/recordings/meta-responses/streams-text-with-minimal-reasoning.json +37 -0
- package/test/fixtures/recordings/meta-responses/streams-text-with-xhigh-reasoning.json +37 -0
- package/test/fixtures/recordings/meta-search/searches-and-replays-grounded-messages.json +56 -0
- package/test/fixtures/recordings/meta-search/searches-and-replays-grounded-responses.json +56 -0
- package/test/fixtures/recordings/minimax-chat/m3-continues-a-tool-loop-with-default-thinking.json +56 -0
- package/test/fixtures/recordings/minimax-chat/m3-streams-text-with-thinking-disabled.json +36 -0
- package/test/fixtures/recordings/minimax-images/generates-an-image.json +32 -0
- package/test/fixtures/recordings/minimax-images/generates-from-a-subject-reference.json +32 -0
- package/test/fixtures/recordings/minimax-messages/m2-7-streams-default-thinking.json +36 -0
- package/test/fixtures/recordings/minimax-messages/m3-continues-a-tool-loop-with-adaptive-thinking.json +56 -0
- package/test/fixtures/recordings/minimax-messages/m3-generates-a-named-tool-call-with-default-thinking-off.json +36 -0
- package/test/fixtures/recordings/minimax-messages/m3-streams-adaptive-thinking.json +36 -0
- package/test/fixtures/recordings/minimax-messages/m3-streams-text-with-thinking-disabled.json +36 -0
- package/test/fixtures/recordings/minimax-responses/m3-continues-a-tool-loop-with-effort-minimal.json +56 -0
- package/test/fixtures/recordings/minimax-responses/m3-streams-text-with-effort-none.json +36 -0
- package/test/fixtures/recordings/minimax-video/generates-a-hailuo-video-from-a-first-frame.json +176 -0
- package/test/fixtures/recordings/minimax-video/generates-an-h3-video.json +96 -0
- package/test/fixtures/recordings/mistral-chat/drives-a-tool-loop.json +54 -0
- package/test/fixtures/recordings/mistral-chat/replays-native-reasoning.json +47 -0
- package/test/fixtures/recordings/mistral-chat/streams-text-with-usage.json +29 -0
- package/test/fixtures/recordings/mistral-chat-glm/streams-an-indexed-tool-call.json +36 -0
- package/test/fixtures/recordings/moonshot-chat/k3-reads-image-bytes.json +29 -0
- package/test/fixtures/recordings/moonshot-chat/k3-respects-tool-choice-none.json +29 -0
- package/test/fixtures/recordings/moonshot-chat/k3-respects-tool-choice-required.json +29 -0
- package/test/fixtures/recordings/moonshot-chat/k3-returns-native-structured-output.json +29 -0
- package/test/fixtures/recordings/moonshot-chat/k3-streams-text-with-default-effort.json +29 -0
- package/test/fixtures/recordings/moonshot-chat/k3-streams-text-with-high-effort.json +29 -0
- package/test/fixtures/recordings/moonshot-chat/k3-streams-text-with-low-effort.json +29 -0
- package/test/fixtures/recordings/moonshot-chat/k3-streams-text-with-max-effort.json +29 -0
- package/test/fixtures/recordings/moonshot-chat/kimi-k2-6-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
- package/test/fixtures/recordings/moonshot-chat/kimi-k2-6-streams-text-with-default-thinking.json +29 -0
- package/test/fixtures/recordings/moonshot-chat/kimi-k2-6-streams-text-with-disabled-thinking.json +29 -0
- package/test/fixtures/recordings/moonshot-chat/kimi-k2-6-streams-text-with-enabled-thinking.json +29 -0
- package/test/fixtures/recordings/moonshot-chat/kimi-k2-7-code-highspeed-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
- package/test/fixtures/recordings/moonshot-chat/kimi-k2-7-code-highspeed-streams-text-with-default-thinking.json +29 -0
- package/test/fixtures/recordings/moonshot-chat/kimi-k2-7-code-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
- package/test/fixtures/recordings/moonshot-chat/kimi-k2-7-code-streams-text-with-default-thinking.json +29 -0
- package/test/fixtures/recordings/moonshot-chat/kimi-k3-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
- package/test/fixtures/recordings/moonshot-messages/k3-reads-image-bytes.json +36 -0
- package/test/fixtures/recordings/moonshot-messages/k3-respects-tool-choice-none.json +36 -0
- package/test/fixtures/recordings/moonshot-messages/k3-respects-tool-choice-required.json +36 -0
- package/test/fixtures/recordings/moonshot-messages/k3-returns-native-structured-output.json +35 -0
- package/test/fixtures/recordings/moonshot-messages/k3-streams-text-with-default-effort.json +36 -0
- package/test/fixtures/recordings/moonshot-messages/k3-streams-text-with-high-effort.json +36 -0
- package/test/fixtures/recordings/moonshot-messages/k3-streams-text-with-low-effort.json +36 -0
- package/test/fixtures/recordings/moonshot-messages/k3-streams-text-with-max-effort.json +36 -0
- package/test/fixtures/recordings/moonshot-messages/kimi-k3-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
- package/test/fixtures/recordings/moonshot-responses/k3-reads-image-bytes.json +36 -0
- package/test/fixtures/recordings/moonshot-responses/k3-rejects-unsupported-tool-choice-none.json +36 -0
- package/test/fixtures/recordings/moonshot-responses/k3-rejects-unsupported-tool-choice-required.json +36 -0
- package/test/fixtures/recordings/moonshot-responses/k3-returns-native-structured-output.json +35 -0
- package/test/fixtures/recordings/moonshot-responses/k3-streams-text-with-default-effort.json +36 -0
- package/test/fixtures/recordings/moonshot-responses/k3-streams-text-with-high-effort.json +36 -0
- package/test/fixtures/recordings/moonshot-responses/k3-streams-text-with-low-effort.json +36 -0
- package/test/fixtures/recordings/moonshot-responses/k3-streams-text-with-max-effort.json +36 -0
- package/test/fixtures/recordings/moonshot-responses/kimi-k3-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
- package/test/fixtures/recordings/openai-compatible-chat/gemini-parallel-tool-signatures.json +54 -0
- package/test/fixtures/recordings/openai-compatible-chat/togetherai-streams-text.json +28 -0
- package/test/fixtures/recordings/openai-compatible-chat/togetherai-streams-tool-call.json +28 -0
- package/test/fixtures/recordings/openai-decision/decides-choice-score-and-predicate-questions-about-json-state.json +33 -0
- package/test/fixtures/recordings/openai-embedding/embeds-text-with-requested-dimensions.json +33 -0
- package/test/fixtures/recordings/openai-images/edits-an-image.json +28 -0
- package/test/fixtures/recordings/openai-images/generates-an-image.json +28 -0
- package/test/fixtures/recordings/openai-images/streams-a-partial-image-before-the-final-image.json +32 -0
- package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-image-tool-result.json +42 -0
- package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-reasoning-continuation.json +58 -0
- package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-reasoning.json +38 -0
- package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-tool-loop.json +57 -0
- package/test/fixtures/recordings/openai-responses-cache/caches-the-system-prompt-on-gpt-6-2-sol.json +51 -0
- package/test/fixtures/recordings/openai-responses-cache/reports-cached-tokens-on-identical-second-call.json +51 -0
- package/test/fixtures/recordings/openai-responses-images/generates-and-edits-an-image-with-the-hosted-tool.json +50 -0
- package/test/fixtures/recordings/openai-responses-websocket/continues-a-tool-call-over-one-socket.json +588 -0
- package/test/fixtures/recordings/openai-responses-websocket/reconstructs-full-context-after-reconnect.json +167 -0
- package/test/fixtures/recordings/openai-responses-websocket/recovers-from-explicit-continuation-rejection.json +167 -0
- package/test/fixtures/recordings/openai-speech/generates-speech.json +33 -0
- package/test/fixtures/recordings/openai-speech/streams-speech.json +32 -0
- package/test/fixtures/recordings/openai-transcription/diarizes-speakers-into-segments.json +32 -0
- package/test/fixtures/recordings/openai-transcription/returns-whisper-word-timestamps.json +32 -0
- package/test/fixtures/recordings/openai-transcription/streams-text-deltas.json +32 -0
- package/test/fixtures/recordings/openai-transcription/transcribes-with-a-language-hint.json +32 -0
- package/test/fixtures/recordings/opencode-decision/decides-choice-score-and-predicate-questions.json +33 -0
- package/test/fixtures/recordings/openrouter-decision/decides-choice-score-and-predicate-questions.json +33 -0
- package/test/fixtures/recordings/openrouter-images/edits-an-image-through-input-references.json +32 -0
- package/test/fixtures/recordings/openrouter-images/renders-flux-3-from-an-aspect-ratio-and-tier.json +32 -0
- package/test/fixtures/recordings/openrouter-images/renders-gemini-at-the-requested-2k-tier.json +32 -0
- package/test/fixtures/recordings/openrouter-reasoning-tool-loop.json +55 -0
- package/test/fixtures/recordings/openrouter-reasoning.json +29 -0
- package/test/fixtures/recordings/openrouter-responses/calls-a-freeform-text-tool.json +35 -0
- package/test/fixtures/recordings/openrouter-responses/continues-a-tool-call.json +53 -0
- package/test/fixtures/recordings/openrouter-responses/streams-text.json +35 -0
- package/test/fixtures/recordings/openrouter-video/generates-a-video.json +113 -0
- package/test/fixtures/recordings/pdf/anthropic-tool-result.json +28 -0
- package/test/fixtures/recordings/pdf/anthropic-user-input.json +28 -0
- package/test/fixtures/recordings/pdf/bedrock-tool-result.json +29 -0
- package/test/fixtures/recordings/pdf/bedrock-user-input.json +29 -0
- package/test/fixtures/recordings/pdf/gemini-tool-result.json +53 -0
- package/test/fixtures/recordings/pdf/gemini-user-input.json +28 -0
- package/test/fixtures/recordings/pdf/openai-tool-result.json +35 -0
- package/test/fixtures/recordings/pdf/openai-user-input.json +34 -0
- package/test/fixtures/recordings/pdf/xai-tool-result.json +35 -0
- package/test/fixtures/recordings/pdf/xai-user-input.json +34 -0
- package/test/fixtures/recordings/typesafe-decision/decides-choice-score-and-predicate-questions.json +33 -0
- package/test/fixtures/recordings/venice-chat/claude-opus-4-8-preserves-reasoning-through-a-tool-loop-and-follow-up.json +75 -0
- package/test/fixtures/recordings/venice-chat/deepseek-v4-flash-preserves-reasoning-through-a-tool-loop-and-follow-up.json +75 -0
- package/test/fixtures/recordings/venice-chat/gemini-3-1-pro-preview-preserves-reasoning-through-a-tool-loop-and-follow-up.json +75 -0
- package/test/fixtures/recordings/venice-chat/gemini-preserves-per-call-signatures-through-parallel-tools.json +71 -0
- package/test/fixtures/recordings/venice-chat/openai-gpt-54-mini-preserves-reasoning-through-a-tool-loop-and-follow-up.json +75 -0
- package/test/fixtures/recordings/venice-chat/qwen-disables-reasoning.json +35 -0
- package/test/fixtures/recordings/venice-chat/surfaces-venice-model-errors.json +33 -0
- package/test/fixtures/recordings/venice-responses/calls-a-freeform-text-tool.json +35 -0
- package/test/fixtures/recordings/venice-responses/continues-a-tool-call.json +53 -0
- package/test/fixtures/recordings/venice-responses/streams-text.json +35 -0
- package/test/fixtures/recordings/vercel-ai-gateway-images/generates-an-image.json +32 -0
- package/test/fixtures/recordings/vercel-ai-gateway-images/sizes-grok-through-xai-provider-options.json +32 -0
- package/test/fixtures/recordings/vercel-ai-gateway-reasoning-tool-loop.json +55 -0
- package/test/fixtures/recordings/vercel-ai-gateway-reasoning.json +29 -0
- package/test/fixtures/recordings/vercel-native/automatically-caches-distinct-claude-system-blocks.json +49 -0
- package/test/fixtures/recordings/vercel-native/continues-chat-claude-reasoning-and-tools.json +49 -0
- package/test/fixtures/recordings/vercel-native/continues-chat-muse-reasoning-and-tools.json +49 -0
- package/test/fixtures/recordings/vercel-native/continues-messages-claude-reasoning-and-tools.json +49 -0
- package/test/fixtures/recordings/vercel-native/continues-messages-deepseek-reasoning-and-tools.json +49 -0
- package/test/fixtures/recordings/vercel-native/continues-messages-gemini-reasoning-and-tools.json +49 -0
- package/test/fixtures/recordings/vercel-native/continues-responses-gpt-reasoning-and-tools.json +49 -0
- package/test/fixtures/recordings/vercel-native/continues-responses-grok-reasoning-and-tools.json +49 -0
- package/test/fixtures/recordings/vercel-native/rejects-invalid-credentials-without-retryable-classification.json +31 -0
- package/test/fixtures/recordings/xai-images/edits-an-image.json +28 -0
- package/test/fixtures/recordings/xai-images/generates-an-image.json +28 -0
- package/test/fixtures/recordings/xai-video/generates-a-video.json +129 -0
- package/test/fixtures/recordings/zai-chat/glm-4-5-calls-a-tool-without-streaming-arguments.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-4-7-streams-thinking-disabled.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-4-7-streams-thinking-enabled.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-2-streams-high-effort.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-2-streams-low-effort.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-2-streams-max-effort.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-2-streams-medium-effort.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-2-streams-minimal-effort.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-2-streams-none-effort.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-2-streams-thinking-disabled.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-2-streams-thinking-enabled.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-2-streams-xhigh-effort.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-3-flash-reads-image-bytes.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-3-preserves-reasoning-through-a-tool-loop-and-follow-up.json +64 -0
- package/test/fixtures/recordings/zai-chat/glm-5-3-rejects-disabled-thinking.json +27 -0
- package/test/fixtures/recordings/zai-chat/glm-5-3-returns-a-json-object.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-3-streams-default-effort.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-3-streams-high-effort.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-3-streams-low-effort.json +28 -0
- package/test/fixtures/recordings/zai-chat/glm-5-3-streams-max-effort.json +28 -0
- package/test/fixtures/recordings/zai-images/generates-an-image.json +28 -0
- package/test/generate-object.test.ts +281 -0
- package/test/generation.test.ts +191 -0
- package/test/google-interactions-video.test.ts +351 -0
- package/test/http-hooks.test.ts +137 -0
- package/test/http-timeout.test.ts +287 -0
- package/test/image-job.test.ts +199 -0
- package/test/image-sizing.test.ts +47 -0
- package/test/image.test.ts +1114 -0
- package/test/image.types.ts +203 -0
- package/test/keyless-auth.test.ts +85 -0
- package/test/lib/effect.ts +50 -0
- package/test/lib/env.ts +30 -0
- package/test/lib/http.ts +141 -0
- package/test/lib/image.ts +29 -0
- package/test/lib/openai-chunks.ts +27 -0
- package/test/lib/sse.ts +20 -0
- package/test/lib/tool-runtime.ts +152 -0
- package/test/llm-option-types.types.ts +153 -0
- package/test/llm.test.ts +286 -0
- package/test/loop-steps.test.ts +77 -0
- package/test/loop-tools.types.ts +79 -0
- package/test/loop.test.ts +425 -0
- package/test/media-input.test.ts +98 -0
- package/test/media-usage.test.ts +13 -0
- package/test/media.test.ts +340 -0
- package/test/minimax-video.test.ts +553 -0
- package/test/openai-freeform.test.ts +252 -0
- package/test/openrouter-video.test.ts +294 -0
- package/test/partial-json.test.ts +58 -0
- package/test/promise-parity.types.ts +83 -0
- package/test/promise.test.ts +632 -0
- package/test/provider/alibaba-capabilities.recorded.test.ts +253 -0
- package/test/provider/alibaba-images.recorded.test.ts +71 -0
- package/test/provider/alibaba-images.test.ts +199 -0
- package/test/provider/alibaba.recorded.test.ts +165 -0
- package/test/provider/alibaba.test.ts +419 -0
- package/test/provider/anthropic-compaction.test.ts +171 -0
- package/test/provider/anthropic-messages-cache.recorded.test.ts +111 -0
- package/test/provider/anthropic-messages.recorded.test.ts +45 -0
- package/test/provider/anthropic-messages.test.ts +2609 -0
- package/test/provider/anthropic-thinking-binding.test.ts +65 -0
- package/test/provider/assemblyai-transcription.recorded.test.ts +39 -0
- package/test/provider/azure.recorded.test.ts +139 -0
- package/test/provider/azure.test.ts +48 -0
- package/test/provider/bedrock-converse-cache.recorded.test.ts +61 -0
- package/test/provider/bedrock-converse-cache.test.ts +168 -0
- package/test/provider/bedrock-converse-options.recorded.test.ts +119 -0
- package/test/provider/bedrock-converse-options.test.ts +149 -0
- package/test/provider/bedrock-converse-thinking-binding.recorded.test.ts +103 -0
- package/test/provider/bedrock-converse-thinking-binding.test.ts +107 -0
- package/test/provider/bedrock-converse.test.ts +2548 -0
- package/test/provider/bedrock-mantle.test.ts +444 -0
- package/test/provider/bedrock-mistral-ids.test.ts +86 -0
- package/test/provider/cartesia-speech.recorded.test.ts +47 -0
- package/test/provider/checkpoint.test.ts +324 -0
- package/test/provider/cloudflare-workers-ai-images.recorded.test.ts +57 -0
- package/test/provider/cloudflare-workers-ai-images.test.ts +155 -0
- package/test/provider/cloudflare.test.ts +330 -0
- package/test/provider/cohere.recorded.test.ts +94 -0
- package/test/provider/cohere.test.ts +301 -0
- package/test/provider/compaction-websocket.test.ts +50 -0
- package/test/provider/compaction.recorded.test.ts +89 -0
- package/test/provider/compaction.test.ts +178 -0
- package/test/provider/conversation-lowering.test.ts +31 -0
- package/test/provider/decision.recorded.test.ts +211 -0
- package/test/provider/deepgram-speech.recorded.test.ts +41 -0
- package/test/provider/deepgram-transcription.recorded.test.ts +47 -0
- package/test/provider/digitalocean.recorded.test.ts +78 -0
- package/test/provider/digitalocean.test.ts +123 -0
- package/test/provider/elevenlabs-speech.recorded.test.ts +54 -0
- package/test/provider/elevenlabs-transcription.recorded.test.ts +50 -0
- package/test/provider/embedding.recorded.test.ts +109 -0
- package/test/provider/empty-tool-choice.test.ts +80 -0
- package/test/provider/error-retention.test.ts +158 -0
- package/test/provider/explicit-compaction.test.ts +503 -0
- package/test/provider/extraction.recorded.test.ts +46 -0
- package/test/provider/freeform-tools.test.ts +446 -0
- package/test/provider/gemini-cache.recorded.test.ts +49 -0
- package/test/provider/gemini-openai-chat.recorded.test.ts +69 -0
- package/test/provider/gemini.test.ts +2336 -0
- package/test/provider/golden.recorded.test.ts +287 -0
- package/test/provider/google-images.recorded.test.ts +53 -0
- package/test/provider/google-interactions-video.recorded.test.ts +48 -0
- package/test/provider/google-interactions.recorded.test.ts +169 -0
- package/test/provider/google-interactions.test.ts +593 -0
- package/test/provider/google-speech.recorded.test.ts +45 -0
- package/test/provider/google-transcription.recorded.test.ts +54 -0
- package/test/provider/google-vertex-interactions.test.ts +307 -0
- package/test/provider/google-vertex.recorded.test.ts +75 -0
- package/test/provider/google-vertex.test.ts +595 -0
- package/test/provider/groq.recorded.test.ts +187 -0
- package/test/provider/groq.test.ts +134 -0
- package/test/provider/image-detail.test.ts +58 -0
- package/test/provider/media-entrypoints.test.ts +618 -0
- package/test/provider/meta-capabilities.test.ts +216 -0
- package/test/provider/meta-images.recorded.test.ts +119 -0
- package/test/provider/meta-messages.recorded.test.ts +121 -0
- package/test/provider/meta-search.recorded.test.ts +97 -0
- package/test/provider/meta.recorded.test.ts +182 -0
- package/test/provider/meta.test.ts +140 -0
- package/test/provider/minimax-images.recorded.test.ts +52 -0
- package/test/provider/minimax-images.test.ts +236 -0
- package/test/provider/minimax-video.recorded.test.ts +83 -0
- package/test/provider/minimax.recorded.test.ts +257 -0
- package/test/provider/minimax.test.ts +110 -0
- package/test/provider/missing-tool-input.test.ts +73 -0
- package/test/provider/mistral-chat.test.ts +757 -0
- package/test/provider/mistral.recorded.test.ts +170 -0
- package/test/provider/moonshot-capabilities.recorded.test.ts +131 -0
- package/test/provider/moonshot.recorded.test.ts +191 -0
- package/test/provider/moonshot.test.ts +218 -0
- package/test/provider/native-providers.test.ts +299 -0
- package/test/provider/open-responses-errors.test.ts +141 -0
- package/test/provider/open-responses-finals.test.ts +209 -0
- package/test/provider/open-responses-lifecycle.test.ts +526 -0
- package/test/provider/open-responses-replay.test.ts +120 -0
- package/test/provider/openai-chat-reasoning.recorded.test.ts +154 -0
- package/test/provider/openai-chat.test.ts +2505 -0
- package/test/provider/openai-compatible-chat.test.ts +819 -0
- package/test/provider/openai-compatible-responses.test.ts +1139 -0
- package/test/provider/openai-images.recorded.test.ts +91 -0
- package/test/provider/openai-responses-cache.recorded.test.ts +68 -0
- package/test/provider/openai-responses-images.recorded.test.ts +66 -0
- package/test/provider/openai-responses-websocket.recorded.test.ts +221 -0
- package/test/provider/openai-responses.test.ts +5414 -0
- package/test/provider/openai-speech.recorded.test.ts +38 -0
- package/test/provider/openai-transcription.recorded.test.ts +91 -0
- package/test/provider/openrouter-images.recorded.test.ts +76 -0
- package/test/provider/openrouter-video.recorded.test.ts +53 -0
- package/test/provider/openrouter.test.ts +656 -0
- package/test/provider/pdf.recorded.test.ts +211 -0
- package/test/provider/queued-recording.ts +10 -0
- package/test/provider/responses-routes.recorded.test.ts +91 -0
- package/test/provider/seedance-video.recorded.test.ts +52 -0
- package/test/provider/speech-recording.ts +19 -0
- package/test/provider/transcription-recording.ts +41 -0
- package/test/provider/venice.recorded.test.ts +237 -0
- package/test/provider/venice.test.ts +373 -0
- package/test/provider/vercel-ai-gateway-images.recorded.test.ts +55 -0
- package/test/provider/vercel-ai-gateway.recorded.test.ts +125 -0
- package/test/provider/vercel-ai-gateway.test.ts +303 -0
- package/test/provider/xai-images.recorded.test.ts +54 -0
- package/test/provider/xai-images.test.ts +109 -0
- package/test/provider/xai-responses.test.ts +339 -0
- package/test/provider/xai-video.recorded.test.ts +54 -0
- package/test/provider/zai-capabilities.recorded.test.ts +156 -0
- package/test/provider/zai-images.recorded.test.ts +33 -0
- package/test/provider/zai-images.test.ts +163 -0
- package/test/provider/zai.recorded.test.ts +115 -0
- package/test/provider/zai.test.ts +374 -0
- package/test/provider-api-methods.types.ts +8 -0
- package/test/provider-error.test.ts +800 -0
- package/test/provider-model.types.ts +37 -0
- package/test/provider-options/alibaba.types.ts +46 -0
- package/test/provider-options/amazon-bedrock.types.ts +33 -0
- package/test/provider-options/anthropic-compatible.types.ts +13 -0
- package/test/provider-options/anthropic.types.ts +30 -0
- package/test/provider-options/azure.types.ts +13 -0
- package/test/provider-options/checkpoint.types.ts +150 -0
- package/test/provider-options/cloudflare.types.ts +13 -0
- package/test/provider-options/compaction.types.ts +146 -0
- package/test/provider-options/google-vertex-chat.types.ts +7 -0
- package/test/provider-options/google-vertex-interactions.types.ts +29 -0
- package/test/provider-options/google-vertex-messages.types.ts +13 -0
- package/test/provider-options/google-vertex-responses.types.ts +14 -0
- package/test/provider-options/google-vertex.types.ts +17 -0
- package/test/provider-options/google.types.ts +43 -0
- package/test/provider-options/minimax.types.ts +33 -0
- package/test/provider-options/mistral.types.ts +24 -0
- package/test/provider-options/moonshot.types.ts +45 -0
- package/test/provider-options/openai-compatible-responses.types.ts +17 -0
- package/test/provider-options/openai-compatible.types.ts +13 -0
- package/test/provider-options/openai.types.ts +27 -0
- package/test/provider-options/openrouter.types.ts +55 -0
- package/test/provider-options/venice.types.ts +39 -0
- package/test/provider-options/vercel-ai-gateway.types.ts +30 -0
- package/test/provider-options/xai.types.ts +14 -0
- package/test/provider-options/zai.types.ts +42 -0
- package/test/provider-package.test.ts +586 -0
- package/test/raw-events.test.ts +75 -0
- package/test/realtime.test.ts +172 -0
- package/test/recorded-golden.ts +104 -0
- package/test/recorded-runner.ts +101 -0
- package/test/recorded-scenarios.ts +468 -0
- package/test/recorded-test.ts +127 -0
- package/test/recorded-utils.ts +56 -0
- package/test/request-encoding.test.ts +57 -0
- package/test/request-transport.test.ts +74 -0
- package/test/response.test.ts +203 -0
- package/test/route.test.ts +225 -0
- package/test/sanitize.test.ts +80 -0
- package/test/schema.test.ts +412 -0
- package/test/seedance-video.test.ts +418 -0
- package/test/speech.test.ts +297 -0
- package/test/speech.types.ts +33 -0
- package/test/testing.test.ts +372 -0
- package/test/tool-history.test.ts +162 -0
- package/test/tool-runtime.test.ts +926 -0
- package/test/tool-schema-projection.test.ts +427 -0
- package/test/tool-stream.test.ts +252 -0
- package/test/tool-updates.test.ts +849 -0
- package/test/tool.types.ts +131 -0
- package/test/transcription.test.ts +618 -0
- package/test/transcription.types.ts +44 -0
- package/test/video.test.ts +447 -0
- package/test/video.types.ts +110 -0
- package/tsconfig.build.json +8 -0
- package/tsconfig.json +17 -0
- package/tsconfig.types.json +16 -0
|
@@ -0,0 +1,1664 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer"
|
|
2
|
+
import { Effect, Option, Schema, SchemaGetter } from "effect"
|
|
3
|
+
import { Tool } from "@zyro-sec/schema/tool"
|
|
4
|
+
import { Route } from "../route/client.js"
|
|
5
|
+
import { Auth } from "../route/auth.js"
|
|
6
|
+
import { Endpoint } from "../route/endpoint.js"
|
|
7
|
+
import { Framing } from "../route/framing.js"
|
|
8
|
+
import { Protocol } from "../route/protocol.js"
|
|
9
|
+
import { Headers } from "effect/http"
|
|
10
|
+
import { HttpTransport } from "../route/transport/index.js"
|
|
11
|
+
import {
|
|
12
|
+
AIError,
|
|
13
|
+
CacheTTL,
|
|
14
|
+
type LLMRequest,
|
|
15
|
+
LLMEvent,
|
|
16
|
+
mergeJsonRecords,
|
|
17
|
+
Usage,
|
|
18
|
+
type CacheHint,
|
|
19
|
+
type FinishReasonDetails,
|
|
20
|
+
type FinishReason,
|
|
21
|
+
type MediaPart,
|
|
22
|
+
type ProviderMetadata,
|
|
23
|
+
type ProviderOptions,
|
|
24
|
+
type ToolCallPart,
|
|
25
|
+
type ToolDefinition,
|
|
26
|
+
type ToolChanges,
|
|
27
|
+
type ToolResultPart,
|
|
28
|
+
} from "../schema/index.js"
|
|
29
|
+
import { JsonObject, knownString, optionalArray, optionalNull, ProviderShared, withUntypedFrames } from "./shared.js"
|
|
30
|
+
import { classifyProviderFailure } from "../provider-error.js"
|
|
31
|
+
import { effortUpdate, resolveEffortUpdates } from "../effort-updates.js"
|
|
32
|
+
import { addsTools, toolsUpdate, type ToolUpdateEncoding } from "../tool-updates.js"
|
|
33
|
+
import * as Cache from "./utils/cache.js"
|
|
34
|
+
import { claudeVersion, supportsThinkingBlockBinding, THINKING_BINDING_BETA } from "./utils/claude-model.js"
|
|
35
|
+
import { Lifecycle } from "./utils/lifecycle.js"
|
|
36
|
+
import { ToolStream } from "./utils/tool-stream.js"
|
|
37
|
+
|
|
38
|
+
const ADAPTER = "anthropic-messages"
|
|
39
|
+
export const DEFAULT_BASE_URL = "https://api.anthropic.com/v1"
|
|
40
|
+
export const PATH = "/messages"
|
|
41
|
+
export const DEFAULT_MAX_TOKENS = 32_000
|
|
42
|
+
const MIN_THINKING_BUDGET = 1_024
|
|
43
|
+
const DEFAULT_EFFORT = "high"
|
|
44
|
+
|
|
45
|
+
const SSE_EVENTS = new Set([
|
|
46
|
+
"message",
|
|
47
|
+
"message_start",
|
|
48
|
+
"message_delta",
|
|
49
|
+
"message_stop",
|
|
50
|
+
"content_block_start",
|
|
51
|
+
"content_block_delta",
|
|
52
|
+
"content_block_stop",
|
|
53
|
+
"ping",
|
|
54
|
+
"error",
|
|
55
|
+
])
|
|
56
|
+
export const framing = Framing.sseEvents(SSE_EVENTS)
|
|
57
|
+
|
|
58
|
+
export type ThinkingInput = typeof Thinking.Encoded
|
|
59
|
+
/** Caller-facing provider options; unknown keys are accepted and ignored. `Options.Type` is the wire-ready form. */
|
|
60
|
+
export type OptionsInput = ProviderOptions & typeof Options.Encoded
|
|
61
|
+
export type ProviderOptionsInput = OptionsInput
|
|
62
|
+
|
|
63
|
+
export const ContextManagement = Schema.Struct({
|
|
64
|
+
edits: Schema.Array(
|
|
65
|
+
Schema.Struct({
|
|
66
|
+
type: Schema.Literal("compact_20260112"),
|
|
67
|
+
trigger: Schema.optional(
|
|
68
|
+
Schema.Struct({
|
|
69
|
+
type: Schema.Literal("input_tokens"),
|
|
70
|
+
value: Schema.Int.check(Schema.isGreaterThanOrEqualTo(50000)),
|
|
71
|
+
}),
|
|
72
|
+
),
|
|
73
|
+
pauseAfterCompaction: Schema.optional(Schema.Boolean),
|
|
74
|
+
instructions: Schema.optional(Schema.String),
|
|
75
|
+
}),
|
|
76
|
+
),
|
|
77
|
+
})
|
|
78
|
+
export type ContextManagement = typeof ContextManagement.Type
|
|
79
|
+
|
|
80
|
+
// =============================================================================
|
|
81
|
+
// Request Body Schema
|
|
82
|
+
// =============================================================================
|
|
83
|
+
const AnthropicCacheControl = Schema.Struct({
|
|
84
|
+
type: Schema.tag("ephemeral"),
|
|
85
|
+
ttl: Schema.optional(CacheTTL),
|
|
86
|
+
})
|
|
87
|
+
const AnthropicServiceTier = knownString<"auto" | "standard_only">()
|
|
88
|
+
const AnthropicSpeed = knownString<"fast" | "standard">()
|
|
89
|
+
|
|
90
|
+
const AnthropicTextBlock = Schema.Struct({
|
|
91
|
+
type: Schema.tag("text"),
|
|
92
|
+
text: Schema.String,
|
|
93
|
+
cache_control: Schema.optional(AnthropicCacheControl),
|
|
94
|
+
})
|
|
95
|
+
type AnthropicTextBlock = Schema.Schema.Type<typeof AnthropicTextBlock>
|
|
96
|
+
|
|
97
|
+
// SDK: Base64ImageSource:201 {type:"base64", media_type:"image/jpeg"|... , data}, URLImageSource:3817 {type:"url", url}, FileImageSource:2350 {type:"file", file_id}
|
|
98
|
+
// SDK: ImageBlockParam:2356 {source: Base64|URL|File, cache_control, transformations:2381 {oversized_image?}}
|
|
99
|
+
const AnthropicBase64ImageSource = Schema.Struct({
|
|
100
|
+
type: Schema.tag("base64"),
|
|
101
|
+
media_type: Schema.String,
|
|
102
|
+
data: Schema.String,
|
|
103
|
+
})
|
|
104
|
+
const AnthropicURLImageSource = Schema.Struct({ type: Schema.tag("url"), url: Schema.String })
|
|
105
|
+
const AnthropicFileImageSource = Schema.Struct({ type: Schema.tag("file"), file_id: Schema.String })
|
|
106
|
+
const AnthropicImageSource = Schema.Union([
|
|
107
|
+
AnthropicBase64ImageSource,
|
|
108
|
+
AnthropicURLImageSource,
|
|
109
|
+
AnthropicFileImageSource,
|
|
110
|
+
])
|
|
111
|
+
const AnthropicImageTransformations = Schema.Struct({
|
|
112
|
+
oversized_image: Schema.optional(Schema.Literals(["downsize", "error"])),
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
const AnthropicImageBlock = Schema.Struct({
|
|
116
|
+
type: Schema.tag("image"),
|
|
117
|
+
source: AnthropicImageSource,
|
|
118
|
+
cache_control: Schema.optional(AnthropicCacheControl),
|
|
119
|
+
transformations: Schema.optional(AnthropicImageTransformations),
|
|
120
|
+
})
|
|
121
|
+
type AnthropicImageBlock = Schema.Schema.Type<typeof AnthropicImageBlock>
|
|
122
|
+
|
|
123
|
+
const AnthropicVideoBlock = Schema.Struct({
|
|
124
|
+
type: Schema.tag("video"),
|
|
125
|
+
source: AnthropicImageSource,
|
|
126
|
+
cache_control: Schema.optional(AnthropicCacheControl),
|
|
127
|
+
})
|
|
128
|
+
type AnthropicVideoBlock = Schema.Schema.Type<typeof AnthropicVideoBlock>
|
|
129
|
+
|
|
130
|
+
// SDK: Base64PDFSource:209 {type:"base64", media_type:"application/pdf", data}, PlainTextSource:2716 {type:"text", media_type:"text/plain", data},
|
|
131
|
+
// SDK: URLPDFSource:3823 {type:"url", url}, FileDocumentSource:2344 {type:"file", file_id}, ContentBlockSource:2266 {type:"content", content}
|
|
132
|
+
// SDK: DocumentBlockParam:2297 {source: 5-way union, cache_control, citations, context, title}
|
|
133
|
+
const AnthropicBase64PDFSource = Schema.Struct({
|
|
134
|
+
type: Schema.tag("base64"),
|
|
135
|
+
media_type: Schema.Literal("application/pdf"),
|
|
136
|
+
data: Schema.String,
|
|
137
|
+
})
|
|
138
|
+
const AnthropicPlainTextSource = Schema.Struct({
|
|
139
|
+
type: Schema.tag("text"),
|
|
140
|
+
media_type: Schema.Literal("text/plain"),
|
|
141
|
+
data: Schema.String,
|
|
142
|
+
})
|
|
143
|
+
const AnthropicURLPDFSource = Schema.Struct({ type: Schema.tag("url"), url: Schema.String })
|
|
144
|
+
const AnthropicFileDocumentSource = Schema.Struct({ type: Schema.tag("file"), file_id: Schema.String })
|
|
145
|
+
const AnthropicDocumentSource = Schema.Union([
|
|
146
|
+
AnthropicBase64PDFSource,
|
|
147
|
+
AnthropicPlainTextSource,
|
|
148
|
+
AnthropicURLPDFSource,
|
|
149
|
+
AnthropicFileDocumentSource,
|
|
150
|
+
])
|
|
151
|
+
|
|
152
|
+
const AnthropicDocumentBlock = Schema.Struct({
|
|
153
|
+
type: Schema.tag("document"),
|
|
154
|
+
source: AnthropicDocumentSource,
|
|
155
|
+
cache_control: Schema.optional(AnthropicCacheControl),
|
|
156
|
+
title: Schema.optional(Schema.String),
|
|
157
|
+
context: Schema.optional(Schema.String),
|
|
158
|
+
citations: Schema.optional(Schema.Struct({ enabled: Schema.Boolean })),
|
|
159
|
+
})
|
|
160
|
+
type AnthropicDocumentBlock = Schema.Schema.Type<typeof AnthropicDocumentBlock>
|
|
161
|
+
|
|
162
|
+
const AnthropicThinkingBlock = Schema.Struct({
|
|
163
|
+
type: Schema.tag("thinking"),
|
|
164
|
+
thinking: Schema.String,
|
|
165
|
+
signature: Schema.String,
|
|
166
|
+
cache_control: Schema.optional(AnthropicCacheControl),
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
// Safety-filtered thinking arrives as an opaque encrypted `data` payload with
|
|
170
|
+
// no visible text. It must round-trip verbatim so multi-turn thinking + tool
|
|
171
|
+
// use conversations keep their reasoning continuity.
|
|
172
|
+
const AnthropicRedactedThinkingBlock = Schema.Struct({
|
|
173
|
+
type: Schema.tag("redacted_thinking"),
|
|
174
|
+
data: Schema.String,
|
|
175
|
+
cache_control: Schema.optional(AnthropicCacheControl),
|
|
176
|
+
})
|
|
177
|
+
|
|
178
|
+
const AnthropicToolUseBlock = Schema.Struct({
|
|
179
|
+
type: Schema.tag("tool_use"),
|
|
180
|
+
id: Schema.String,
|
|
181
|
+
name: Schema.String,
|
|
182
|
+
input: Schema.Unknown,
|
|
183
|
+
cache_control: Schema.optional(AnthropicCacheControl),
|
|
184
|
+
})
|
|
185
|
+
type AnthropicToolUseBlock = Schema.Schema.Type<typeof AnthropicToolUseBlock>
|
|
186
|
+
|
|
187
|
+
const AnthropicServerToolUseBlock = Schema.Struct({
|
|
188
|
+
type: Schema.tag("server_tool_use"),
|
|
189
|
+
id: Schema.String,
|
|
190
|
+
name: Schema.String,
|
|
191
|
+
input: Schema.Unknown,
|
|
192
|
+
cache_control: Schema.optional(AnthropicCacheControl),
|
|
193
|
+
})
|
|
194
|
+
type AnthropicServerToolUseBlock = Schema.Schema.Type<typeof AnthropicServerToolUseBlock>
|
|
195
|
+
|
|
196
|
+
// Server tool result blocks: web_search_tool_result, code_execution_tool_result,
|
|
197
|
+
// and web_fetch_tool_result. The provider executes the tool and inlines the
|
|
198
|
+
// structured result into the assistant turn — there is no client tool_result
|
|
199
|
+
// round-trip. We round-trip the structured `content` payload as opaque JSON so
|
|
200
|
+
// the next request can echo it back when continuing the conversation.
|
|
201
|
+
const AnthropicServerToolResultType = Schema.Literals([
|
|
202
|
+
"web_search_tool_result",
|
|
203
|
+
"code_execution_tool_result",
|
|
204
|
+
"web_fetch_tool_result",
|
|
205
|
+
])
|
|
206
|
+
type AnthropicServerToolResultType = Schema.Schema.Type<typeof AnthropicServerToolResultType>
|
|
207
|
+
|
|
208
|
+
const AnthropicServerToolResultBlock = Schema.Struct({
|
|
209
|
+
type: AnthropicServerToolResultType,
|
|
210
|
+
tool_use_id: Schema.String,
|
|
211
|
+
content: Schema.Unknown,
|
|
212
|
+
cache_control: Schema.optional(AnthropicCacheControl),
|
|
213
|
+
})
|
|
214
|
+
type AnthropicServerToolResultBlock = Schema.Schema.Type<typeof AnthropicServerToolResultBlock>
|
|
215
|
+
|
|
216
|
+
// Anthropic accepts either a plain string or an ordered array of text, image, and
|
|
217
|
+
// document blocks inside `tool_result.content`. The array form keeps media as native
|
|
218
|
+
// model input instead of JSON-stringifying base64 into prompt text.
|
|
219
|
+
const AnthropicToolResultContent = Schema.Union([
|
|
220
|
+
AnthropicTextBlock,
|
|
221
|
+
AnthropicImageBlock,
|
|
222
|
+
AnthropicDocumentBlock,
|
|
223
|
+
AnthropicVideoBlock,
|
|
224
|
+
])
|
|
225
|
+
|
|
226
|
+
const AnthropicToolResultBlock = Schema.Struct({
|
|
227
|
+
type: Schema.tag("tool_result"),
|
|
228
|
+
tool_use_id: Schema.String,
|
|
229
|
+
content: Schema.Union([Schema.String, Schema.Array(AnthropicToolResultContent)]),
|
|
230
|
+
is_error: Schema.optional(Schema.Boolean),
|
|
231
|
+
cache_control: Schema.optional(AnthropicCacheControl),
|
|
232
|
+
})
|
|
233
|
+
|
|
234
|
+
const AnthropicUserBlock = Schema.Union([
|
|
235
|
+
AnthropicTextBlock,
|
|
236
|
+
AnthropicImageBlock,
|
|
237
|
+
AnthropicDocumentBlock,
|
|
238
|
+
AnthropicVideoBlock,
|
|
239
|
+
AnthropicToolResultBlock,
|
|
240
|
+
])
|
|
241
|
+
type AnthropicUserBlock = Schema.Schema.Type<typeof AnthropicUserBlock>
|
|
242
|
+
const AnthropicCompactionBlock = Schema.Struct({
|
|
243
|
+
type: Schema.Literal("compaction"),
|
|
244
|
+
content: Schema.NullOr(Schema.String),
|
|
245
|
+
})
|
|
246
|
+
const AnthropicAssistantBlock = Schema.Union([
|
|
247
|
+
AnthropicCompactionBlock,
|
|
248
|
+
AnthropicTextBlock,
|
|
249
|
+
AnthropicThinkingBlock,
|
|
250
|
+
AnthropicRedactedThinkingBlock,
|
|
251
|
+
AnthropicToolUseBlock,
|
|
252
|
+
AnthropicServerToolUseBlock,
|
|
253
|
+
AnthropicServerToolResultBlock,
|
|
254
|
+
])
|
|
255
|
+
type AnthropicAssistantBlock = Schema.Schema.Type<typeof AnthropicAssistantBlock>
|
|
256
|
+
type AnthropicToolResultBlock = Schema.Schema.Type<typeof AnthropicToolResultBlock>
|
|
257
|
+
|
|
258
|
+
const AnthropicTool = Schema.Struct({
|
|
259
|
+
name: Schema.String,
|
|
260
|
+
description: Schema.String,
|
|
261
|
+
input_schema: JsonObject,
|
|
262
|
+
cache_control: Schema.optional(AnthropicCacheControl),
|
|
263
|
+
})
|
|
264
|
+
type AnthropicTool = Schema.Schema.Type<typeof AnthropicTool>
|
|
265
|
+
|
|
266
|
+
const AnthropicToolAdditionBlock = Schema.Struct({
|
|
267
|
+
type: Schema.tag("tool_addition"),
|
|
268
|
+
tool: Schema.Struct({ type: Schema.tag("tool_definition"), definition: AnthropicTool }),
|
|
269
|
+
})
|
|
270
|
+
const AnthropicToolRemovalBlock = Schema.Struct({
|
|
271
|
+
type: Schema.tag("tool_removal"),
|
|
272
|
+
tool: Schema.Struct({ type: Schema.tag("tool_reference"), name: Schema.String }),
|
|
273
|
+
})
|
|
274
|
+
|
|
275
|
+
const AnthropicMessage = Schema.Union([
|
|
276
|
+
Schema.Struct({ role: Schema.Literal("user"), content: Schema.Array(AnthropicUserBlock) }),
|
|
277
|
+
Schema.Struct({ role: Schema.Literal("assistant"), content: Schema.Array(AnthropicAssistantBlock) }),
|
|
278
|
+
Schema.Struct({
|
|
279
|
+
role: Schema.Literal("system"),
|
|
280
|
+
content: Schema.Array(Schema.Union([AnthropicTextBlock, AnthropicToolAdditionBlock, AnthropicToolRemovalBlock])),
|
|
281
|
+
output_config: Schema.optional(Schema.Struct({ effort: Schema.String })),
|
|
282
|
+
}),
|
|
283
|
+
]).pipe(Schema.toTaggedUnion("role"))
|
|
284
|
+
type AnthropicMessage = Schema.Schema.Type<typeof AnthropicMessage>
|
|
285
|
+
|
|
286
|
+
const AnthropicToolChoice = Schema.Union([
|
|
287
|
+
Schema.Struct({
|
|
288
|
+
type: Schema.Literals(["auto", "any", "none"]),
|
|
289
|
+
disable_parallel_tool_use: Schema.optional(Schema.Boolean),
|
|
290
|
+
}),
|
|
291
|
+
Schema.Struct({
|
|
292
|
+
type: Schema.tag("tool"),
|
|
293
|
+
name: Schema.String,
|
|
294
|
+
disable_parallel_tool_use: Schema.optional(Schema.Boolean),
|
|
295
|
+
}),
|
|
296
|
+
])
|
|
297
|
+
|
|
298
|
+
const AnthropicThinkingBlockBinding = Schema.Struct({
|
|
299
|
+
prefix_mismatch_behavior: Schema.optional(knownString<"error" | "drop_block">()),
|
|
300
|
+
})
|
|
301
|
+
|
|
302
|
+
const AnthropicThinkingFields = {
|
|
303
|
+
display: Schema.optional(knownString<"summarized" | "omitted">()),
|
|
304
|
+
block_binding: Schema.optional(AnthropicThinkingBlockBinding),
|
|
305
|
+
}
|
|
306
|
+
const AnthropicThinkingEnabled = Schema.Struct({
|
|
307
|
+
type: Schema.tag("enabled"),
|
|
308
|
+
budget_tokens: Schema.Number,
|
|
309
|
+
...AnthropicThinkingFields,
|
|
310
|
+
})
|
|
311
|
+
const AnthropicThinkingAdaptive = Schema.Struct({ type: Schema.tag("adaptive"), ...AnthropicThinkingFields })
|
|
312
|
+
const AnthropicThinkingDisabled = Schema.Struct({ type: Schema.Literals(["disabled", "between_tools"]) })
|
|
313
|
+
const AnthropicThinking = Schema.Union([AnthropicThinkingEnabled, AnthropicThinkingAdaptive, AnthropicThinkingDisabled])
|
|
314
|
+
type AnthropicThinking = typeof AnthropicThinking.Type
|
|
315
|
+
|
|
316
|
+
// SDK OutputConfig:2684 {effort?: "low"|"medium"|"high"|"xhigh"|"max"|null, format?: JSONOutputFormat:2399}
|
|
317
|
+
const AnthropicJsonOutputFormat = Schema.Struct({
|
|
318
|
+
type: Schema.Literal("json_schema"),
|
|
319
|
+
schema: JsonObject,
|
|
320
|
+
})
|
|
321
|
+
const AnthropicOutputConfig = Schema.Struct({
|
|
322
|
+
effort: Schema.optional(Schema.String),
|
|
323
|
+
format: Schema.optional(Schema.NullOr(AnthropicJsonOutputFormat)),
|
|
324
|
+
})
|
|
325
|
+
|
|
326
|
+
// SDK Metadata:2649 {user_id?: string|null}
|
|
327
|
+
const AnthropicMetadata = Schema.Struct({ user_id: optionalNull(Schema.String) })
|
|
328
|
+
|
|
329
|
+
// SDK MessageCreateParamsContainer:2596 ContainerParams|string; ContainerParams:2172 {id?, skills?}
|
|
330
|
+
const AnthropicContainer = Schema.Union([
|
|
331
|
+
Schema.String,
|
|
332
|
+
Schema.Struct({
|
|
333
|
+
id: optionalNull(Schema.String),
|
|
334
|
+
skills: optionalNull(Schema.Array(JsonObject)),
|
|
335
|
+
}),
|
|
336
|
+
])
|
|
337
|
+
|
|
338
|
+
// =============================================================================
|
|
339
|
+
// Provider Options
|
|
340
|
+
// =============================================================================
|
|
341
|
+
// Callers spell the budget as `budgetTokens` or the wire `budget_tokens`; the
|
|
342
|
+
// keys are disjoint per variant so the input type requires exactly one and the
|
|
343
|
+
// transform can narrow on it. Decoding straight to the wire block keeps the
|
|
344
|
+
// alias out of the rest of the file.
|
|
345
|
+
const ThinkingEnabledInput = Schema.Union([
|
|
346
|
+
Schema.Struct({ type: Schema.tag("enabled"), budgetTokens: Schema.Number, ...AnthropicThinkingFields }),
|
|
347
|
+
Schema.Struct({ type: Schema.tag("enabled"), budget_tokens: Schema.Number, ...AnthropicThinkingFields }),
|
|
348
|
+
]).pipe(
|
|
349
|
+
Schema.decodeTo(AnthropicThinkingEnabled, {
|
|
350
|
+
decode: SchemaGetter.transform((input) => ({
|
|
351
|
+
type: "enabled" as const,
|
|
352
|
+
budget_tokens: "budgetTokens" in input ? input.budgetTokens : input.budget_tokens,
|
|
353
|
+
display: input.display,
|
|
354
|
+
block_binding: input.block_binding,
|
|
355
|
+
})),
|
|
356
|
+
encode: SchemaGetter.passthrough({ strict: false }),
|
|
357
|
+
}),
|
|
358
|
+
)
|
|
359
|
+
const Thinking = Schema.Union([ThinkingEnabledInput, AnthropicThinkingAdaptive, AnthropicThinkingDisabled])
|
|
360
|
+
|
|
361
|
+
const OutputConfigInput = Schema.Struct({
|
|
362
|
+
effort: optionalNull(Schema.String),
|
|
363
|
+
format: optionalNull(AnthropicJsonOutputFormat),
|
|
364
|
+
})
|
|
365
|
+
|
|
366
|
+
// Both key spellings are accepted; `fromRequest` prefers the snake_case one.
|
|
367
|
+
const Options = Schema.Struct({
|
|
368
|
+
/** Advanced in-band compaction. The caller owns checkpoint persistence and recovery. */
|
|
369
|
+
contextManagement: Schema.optional(ContextManagement),
|
|
370
|
+
thinking: Schema.optional(Thinking),
|
|
371
|
+
effort: Schema.optional(Schema.String),
|
|
372
|
+
service_tier: Schema.optional(AnthropicServiceTier),
|
|
373
|
+
serviceTier: Schema.optional(AnthropicServiceTier),
|
|
374
|
+
speed: Schema.optional(AnthropicSpeed),
|
|
375
|
+
metadata: Schema.optional(AnthropicMetadata),
|
|
376
|
+
container: Schema.optional(AnthropicContainer),
|
|
377
|
+
inference_geo: optionalNull(Schema.String),
|
|
378
|
+
inferenceGeo: optionalNull(Schema.String),
|
|
379
|
+
cache_control: Schema.optional(AnthropicCacheControl),
|
|
380
|
+
cacheControl: Schema.optional(AnthropicCacheControl),
|
|
381
|
+
output_config: Schema.optional(OutputConfigInput),
|
|
382
|
+
outputConfig: Schema.optional(OutputConfigInput),
|
|
383
|
+
})
|
|
384
|
+
const decodeOptions = ProviderShared.validateWith(Schema.decodeUnknownEffect(Options))
|
|
385
|
+
|
|
386
|
+
const AnthropicBodyFields = {
|
|
387
|
+
context_management: Schema.optional(
|
|
388
|
+
Schema.Struct({
|
|
389
|
+
edits: Schema.Array(
|
|
390
|
+
Schema.Struct({
|
|
391
|
+
type: Schema.Literal("compact_20260112"),
|
|
392
|
+
trigger: ContextManagement.fields.edits.value.fields.trigger,
|
|
393
|
+
pause_after_compaction: Schema.optional(Schema.Boolean),
|
|
394
|
+
instructions: Schema.optional(Schema.String),
|
|
395
|
+
}),
|
|
396
|
+
),
|
|
397
|
+
}),
|
|
398
|
+
),
|
|
399
|
+
model: Schema.String,
|
|
400
|
+
system: optionalArray(AnthropicTextBlock),
|
|
401
|
+
messages: Schema.Array(AnthropicMessage),
|
|
402
|
+
tools: optionalArray(AnthropicTool),
|
|
403
|
+
tool_choice: Schema.optional(AnthropicToolChoice),
|
|
404
|
+
stream: Schema.Literal(true),
|
|
405
|
+
max_tokens: Schema.Number,
|
|
406
|
+
temperature: Schema.optional(Schema.Number),
|
|
407
|
+
top_p: Schema.optional(Schema.Number),
|
|
408
|
+
top_k: Schema.optional(Schema.Number),
|
|
409
|
+
stop_sequences: optionalArray(Schema.String),
|
|
410
|
+
thinking: Schema.optional(AnthropicThinking),
|
|
411
|
+
output_config: Schema.optional(AnthropicOutputConfig),
|
|
412
|
+
// SDK top-level passthrough: cache_control:4638, container:4643, inference_geo:4649, metadata:4654, service_tier:4670
|
|
413
|
+
cache_control: Schema.optional(AnthropicCacheControl),
|
|
414
|
+
container: Schema.optional(Schema.NullOr(AnthropicContainer)),
|
|
415
|
+
inference_geo: Schema.optional(Schema.NullOr(Schema.String)),
|
|
416
|
+
metadata: Schema.optional(AnthropicMetadata),
|
|
417
|
+
service_tier: Schema.optional(AnthropicServiceTier),
|
|
418
|
+
speed: Schema.optional(AnthropicSpeed),
|
|
419
|
+
}
|
|
420
|
+
export const AnthropicMessagesBody = Schema.Struct(AnthropicBodyFields)
|
|
421
|
+
export type AnthropicMessagesBody = Schema.Schema.Type<typeof AnthropicMessagesBody>
|
|
422
|
+
|
|
423
|
+
const AnthropicIterationUsage = Schema.StructWithRest(
|
|
424
|
+
Schema.Struct({
|
|
425
|
+
input_tokens: optionalNull(Schema.Number),
|
|
426
|
+
output_tokens: Schema.optional(Schema.Number),
|
|
427
|
+
cache_creation_input_tokens: optionalNull(Schema.Number),
|
|
428
|
+
cache_read_input_tokens: optionalNull(Schema.Number),
|
|
429
|
+
server_tool_use: optionalNull(
|
|
430
|
+
Schema.StructWithRest(Schema.Struct({ web_search_requests: Schema.optional(Schema.Number) }), [
|
|
431
|
+
Schema.Record(Schema.String, Schema.Unknown),
|
|
432
|
+
]),
|
|
433
|
+
),
|
|
434
|
+
output_tokens_details: optionalNull(
|
|
435
|
+
Schema.StructWithRest(Schema.Struct({ thinking_tokens: Schema.optional(Schema.Number) }), [
|
|
436
|
+
Schema.Record(Schema.String, Schema.Unknown),
|
|
437
|
+
]),
|
|
438
|
+
),
|
|
439
|
+
}),
|
|
440
|
+
[Schema.Record(Schema.String, Schema.Unknown)],
|
|
441
|
+
)
|
|
442
|
+
const AnthropicUsage = Schema.StructWithRest(
|
|
443
|
+
Schema.Struct({
|
|
444
|
+
...AnthropicIterationUsage.schema.fields,
|
|
445
|
+
iterations: Schema.optional(Schema.Array(AnthropicIterationUsage)),
|
|
446
|
+
}),
|
|
447
|
+
[JsonObject],
|
|
448
|
+
)
|
|
449
|
+
type AnthropicUsage = Schema.Schema.Type<typeof AnthropicUsage>
|
|
450
|
+
|
|
451
|
+
const AnthropicStreamBlock = Schema.StructWithRest(
|
|
452
|
+
Schema.Struct({
|
|
453
|
+
type: Schema.String,
|
|
454
|
+
id: Schema.optional(Schema.String),
|
|
455
|
+
name: Schema.optional(Schema.String),
|
|
456
|
+
text: Schema.optional(Schema.String),
|
|
457
|
+
thinking: Schema.optional(Schema.String),
|
|
458
|
+
signature: Schema.optional(Schema.String),
|
|
459
|
+
// redacted_thinking blocks arrive whole in content_block_start with the
|
|
460
|
+
// encrypted payload in `data`; there is no streaming delta sequence.
|
|
461
|
+
data: Schema.optional(Schema.String),
|
|
462
|
+
input: Schema.optional(Schema.Unknown),
|
|
463
|
+
// *_tool_result blocks arrive whole as content_block_start (no streaming
|
|
464
|
+
// delta) with the structured payload in `content` and the originating
|
|
465
|
+
// server_tool_use id in `tool_use_id`.
|
|
466
|
+
tool_use_id: Schema.optional(Schema.String),
|
|
467
|
+
content: Schema.optional(Schema.Unknown),
|
|
468
|
+
}),
|
|
469
|
+
[JsonObject],
|
|
470
|
+
)
|
|
471
|
+
type AnthropicStreamBlock = Schema.Schema.Type<typeof AnthropicStreamBlock>
|
|
472
|
+
const decodeAnthropicStreamBlock = Schema.decodeUnknownOption(AnthropicStreamBlock)
|
|
473
|
+
|
|
474
|
+
const AnthropicStreamDelta = Schema.StructWithRest(
|
|
475
|
+
Schema.Struct({
|
|
476
|
+
content: optionalNull(Schema.String),
|
|
477
|
+
type: Schema.optional(Schema.String),
|
|
478
|
+
text: Schema.optional(Schema.String),
|
|
479
|
+
thinking: Schema.optional(Schema.String),
|
|
480
|
+
partial_json: Schema.optional(Schema.String),
|
|
481
|
+
signature: Schema.optional(Schema.String),
|
|
482
|
+
stop_reason: optionalNull(Schema.String),
|
|
483
|
+
stop_sequence: optionalNull(Schema.String),
|
|
484
|
+
stop_details: optionalNull(
|
|
485
|
+
Schema.StructWithRest(
|
|
486
|
+
Schema.Struct({ category: optionalNull(Schema.String), explanation: optionalNull(Schema.String) }),
|
|
487
|
+
[JsonObject],
|
|
488
|
+
),
|
|
489
|
+
),
|
|
490
|
+
}),
|
|
491
|
+
[JsonObject],
|
|
492
|
+
)
|
|
493
|
+
type AnthropicStreamDelta = Schema.Schema.Type<typeof AnthropicStreamDelta>
|
|
494
|
+
const decodeAnthropicStreamDelta = Schema.decodeUnknownOption(AnthropicStreamDelta)
|
|
495
|
+
|
|
496
|
+
const TypedAnthropicEvent = Schema.StructWithRest(
|
|
497
|
+
Schema.Struct({
|
|
498
|
+
type: Schema.String,
|
|
499
|
+
index: Schema.optional(Schema.Number),
|
|
500
|
+
message: Schema.optional(
|
|
501
|
+
Schema.StructWithRest(Schema.Struct({ usage: Schema.optional(AnthropicUsage) }), [JsonObject]),
|
|
502
|
+
),
|
|
503
|
+
content_block: Schema.optional(Schema.Unknown),
|
|
504
|
+
delta: Schema.optional(Schema.Unknown),
|
|
505
|
+
usage: Schema.optional(AnthropicUsage),
|
|
506
|
+
// `type` and `message` are both required per Anthropic's spec, but
|
|
507
|
+
// OpenAI-compatible proxies and gateway translations occasionally drop one
|
|
508
|
+
// or the other; mark them optional so a partial payload still parses and
|
|
509
|
+
// the parser can fall back to whichever field is populated.
|
|
510
|
+
error: Schema.optional(
|
|
511
|
+
Schema.StructWithRest(
|
|
512
|
+
Schema.Struct({ type: Schema.optional(Schema.String), message: Schema.optional(Schema.String) }),
|
|
513
|
+
[JsonObject],
|
|
514
|
+
),
|
|
515
|
+
),
|
|
516
|
+
}),
|
|
517
|
+
[JsonObject],
|
|
518
|
+
)
|
|
519
|
+
const AnthropicEvent = withUntypedFrames(TypedAnthropicEvent)
|
|
520
|
+
type AnthropicEvent = Schema.Schema.Type<typeof AnthropicEvent>
|
|
521
|
+
|
|
522
|
+
interface ParserState {
|
|
523
|
+
readonly provider: LLMRequest["model"]["provider"]
|
|
524
|
+
readonly compactions: Readonly<Record<number, string | null>>
|
|
525
|
+
readonly providerMetadataKey: string
|
|
526
|
+
readonly tools: ToolStream.State<number>
|
|
527
|
+
readonly reasoningSignatures: Readonly<Record<number, string>>
|
|
528
|
+
readonly usage?: Usage
|
|
529
|
+
readonly pendingFinish?: {
|
|
530
|
+
readonly reason: FinishReasonDetails
|
|
531
|
+
readonly providerMetadata?: ProviderMetadata
|
|
532
|
+
}
|
|
533
|
+
readonly lifecycle: Lifecycle.State
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
const invalid = ProviderShared.invalidRequest
|
|
537
|
+
|
|
538
|
+
// =============================================================================
|
|
539
|
+
// Request Lowering
|
|
540
|
+
// =============================================================================
|
|
541
|
+
// Anthropic accepts at most 4 explicit cache_control breakpoints per request,
|
|
542
|
+
// across `tools`, `system`, and `messages`. Beyond the cap the API returns a
|
|
543
|
+
// 400 — so the lowering layer counts emitted markers and silently drops any
|
|
544
|
+
// that exceed it.
|
|
545
|
+
const ANTHROPIC_BREAKPOINT_CAP = 4
|
|
546
|
+
|
|
547
|
+
const cacheControl = (breakpoints: Cache.Breakpoints, cache: CacheHint | undefined) => {
|
|
548
|
+
if (cache?.type !== "ephemeral" && cache?.type !== "persistent") return undefined
|
|
549
|
+
if (!Cache.take(breakpoints)) return undefined
|
|
550
|
+
return { type: "ephemeral" as const, ...(cache.ttl === undefined ? {} : { ttl: cache.ttl }) }
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
const providerMetadata = (key: string, metadata: Record<string, unknown>): ProviderMetadata => ({ [key]: metadata })
|
|
554
|
+
|
|
555
|
+
const signatureFromMetadata = (metadata: ProviderMetadata | undefined, key: string): string | undefined => {
|
|
556
|
+
const provider = metadata?.[key]
|
|
557
|
+
if (!provider) return undefined
|
|
558
|
+
return typeof provider.signature === "string" ? provider.signature : undefined
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
const redactedDataFromMetadata = (metadata: ProviderMetadata | undefined, key: string): string | undefined => {
|
|
562
|
+
const provider = metadata?.[key]
|
|
563
|
+
if (!provider) return undefined
|
|
564
|
+
return typeof provider.redactedData === "string" ? provider.redactedData : undefined
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
const lowerTool = (breakpoints: Cache.Breakpoints, tool: ToolDefinition): AnthropicTool => ({
|
|
568
|
+
name: tool.name,
|
|
569
|
+
description: tool.description,
|
|
570
|
+
input_schema: tool.inputSchema,
|
|
571
|
+
cache_control: cacheControl(breakpoints, tool.cache),
|
|
572
|
+
})
|
|
573
|
+
|
|
574
|
+
const lowerToolChoice = (toolChoice: NonNullable<LLMRequest["toolChoice"]>) =>
|
|
575
|
+
ProviderShared.matchToolChoice("Anthropic Messages", toolChoice, {
|
|
576
|
+
auto: () => ({
|
|
577
|
+
type: "auto" as const,
|
|
578
|
+
...(toolChoice.disableParallelToolUse === undefined
|
|
579
|
+
? {}
|
|
580
|
+
: { disable_parallel_tool_use: toolChoice.disableParallelToolUse }),
|
|
581
|
+
}),
|
|
582
|
+
none: () => ({ type: "none" as const }),
|
|
583
|
+
required: () => ({
|
|
584
|
+
type: "any" as const,
|
|
585
|
+
...(toolChoice.disableParallelToolUse === undefined
|
|
586
|
+
? {}
|
|
587
|
+
: { disable_parallel_tool_use: toolChoice.disableParallelToolUse }),
|
|
588
|
+
}),
|
|
589
|
+
tool: (name) => ({
|
|
590
|
+
type: "tool" as const,
|
|
591
|
+
name,
|
|
592
|
+
...(toolChoice.disableParallelToolUse === undefined
|
|
593
|
+
? {}
|
|
594
|
+
: { disable_parallel_tool_use: toolChoice.disableParallelToolUse }),
|
|
595
|
+
}),
|
|
596
|
+
})
|
|
597
|
+
|
|
598
|
+
const scrubToolCallID = (id: string) => id.replace(/[^a-zA-Z0-9_-]/g, "_")
|
|
599
|
+
|
|
600
|
+
const lowerToolCall = (part: ToolCallPart): AnthropicToolUseBlock => ({
|
|
601
|
+
type: "tool_use",
|
|
602
|
+
id: scrubToolCallID(part.id),
|
|
603
|
+
name: part.name,
|
|
604
|
+
input: part.input,
|
|
605
|
+
})
|
|
606
|
+
|
|
607
|
+
const lowerServerToolCall = (part: ToolCallPart): AnthropicServerToolUseBlock => ({
|
|
608
|
+
type: "server_tool_use",
|
|
609
|
+
id: scrubToolCallID(part.id),
|
|
610
|
+
name: part.name,
|
|
611
|
+
input: part.input,
|
|
612
|
+
})
|
|
613
|
+
|
|
614
|
+
// Server tool result blocks are typed by name. Anthropic ships three today;
|
|
615
|
+
// extend this list when new server tools land. The block content is the
|
|
616
|
+
// structured payload returned by the provider, which we round-trip as-is.
|
|
617
|
+
const serverToolResultType = (name: string): AnthropicServerToolResultType | undefined => {
|
|
618
|
+
if (name === "web_search") return "web_search_tool_result"
|
|
619
|
+
if (name === "code_execution") return "code_execution_tool_result"
|
|
620
|
+
if (name === "web_fetch") return "web_fetch_tool_result"
|
|
621
|
+
return undefined
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
const lowerServerToolResult = Effect.fnUntraced(function* (part: ToolResultPart, providerMetadataKey: string) {
|
|
625
|
+
const wireType = serverToolResultType(part.name)
|
|
626
|
+
if (!wireType)
|
|
627
|
+
return yield* invalid(`Anthropic Messages does not know how to round-trip server tool result for ${part.name}`)
|
|
628
|
+
// Prefer the provider-owned replay payload; fall back to the result value for
|
|
629
|
+
// histories constructed directly from provider events.
|
|
630
|
+
const payload = part.providerMetadata?.[providerMetadataKey]?.["result"] ?? part.result.value
|
|
631
|
+
return {
|
|
632
|
+
type: wireType,
|
|
633
|
+
tool_use_id: scrubToolCallID(part.id),
|
|
634
|
+
content: payload,
|
|
635
|
+
} satisfies AnthropicServerToolResultBlock
|
|
636
|
+
})
|
|
637
|
+
|
|
638
|
+
// Per-part Anthropic block fields, read from `providerMetadata[providerMetadataKey]` with Anthropic's wire names.
|
|
639
|
+
const MediaOptions = Schema.Struct({
|
|
640
|
+
file_id: Schema.optional(Schema.String),
|
|
641
|
+
title: Schema.optional(Schema.String),
|
|
642
|
+
context: Schema.optional(Schema.String),
|
|
643
|
+
citations: Schema.optional(Schema.Struct({ enabled: Schema.Boolean })),
|
|
644
|
+
transformations: Schema.optional(AnthropicImageTransformations),
|
|
645
|
+
})
|
|
646
|
+
const decodeMediaOptions = ProviderShared.validateWith(Schema.decodeUnknownEffect(MediaOptions))
|
|
647
|
+
|
|
648
|
+
const isHttpUrl = (value: string) => /^https?:\/\//i.test(value.trim())
|
|
649
|
+
|
|
650
|
+
const lowerMedia = Effect.fnUntraced(function* (part: MediaPart, request: LLMRequest, breakpoints?: Cache.Breakpoints) {
|
|
651
|
+
const mime = part.media.mediaType.toLowerCase()
|
|
652
|
+
const cacheControlValue = breakpoints ? cacheControl(breakpoints, part.cache) : undefined
|
|
653
|
+
if (mime.startsWith("video/")) {
|
|
654
|
+
const inline = part.media.inline()
|
|
655
|
+
const source = inline
|
|
656
|
+
? { type: "base64" as const, media_type: mime, data: inline.base64 }
|
|
657
|
+
: yield* ProviderShared.mediaReference(part.media, request.model.provider, "Messages video").pipe(
|
|
658
|
+
Effect.map((reference) =>
|
|
659
|
+
reference.type === "ref" && !reference.value.includes("://")
|
|
660
|
+
? { type: "file" as const, file_id: reference.value }
|
|
661
|
+
: { type: "url" as const, url: reference.value },
|
|
662
|
+
),
|
|
663
|
+
)
|
|
664
|
+
return {
|
|
665
|
+
type: "video" as const,
|
|
666
|
+
source,
|
|
667
|
+
...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
|
|
668
|
+
} satisfies AnthropicVideoBlock
|
|
669
|
+
}
|
|
670
|
+
const options = yield* decodeMediaOptions(
|
|
671
|
+
part.providerMetadata?.[request.model.route.providerMetadataKey ?? request.model.provider] ?? {},
|
|
672
|
+
)
|
|
673
|
+
const image = (source: AnthropicImageBlock["source"]): AnthropicImageBlock => ({
|
|
674
|
+
type: "image",
|
|
675
|
+
source,
|
|
676
|
+
...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
|
|
677
|
+
...(options.transformations === undefined ? {} : { transformations: options.transformations }),
|
|
678
|
+
})
|
|
679
|
+
const document = (source: AnthropicDocumentBlock["source"]): AnthropicDocumentBlock => {
|
|
680
|
+
const title = options.title ?? (part.filename ? part.filename : undefined)
|
|
681
|
+
return {
|
|
682
|
+
type: "document",
|
|
683
|
+
source,
|
|
684
|
+
...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
|
|
685
|
+
...(title === undefined ? {} : { title }),
|
|
686
|
+
...(options.context === undefined ? {} : { context: options.context }),
|
|
687
|
+
...(options.citations === undefined ? {} : { citations: options.citations }),
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// SDK file sources: FileImageSource:2350 / FileDocumentSource:2344 {type:"file", file_id}
|
|
692
|
+
if (options.file_id) {
|
|
693
|
+
if (mime.startsWith("image/")) return image({ type: "file", file_id: options.file_id })
|
|
694
|
+
return document({ type: "file", file_id: options.file_id })
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
const rawString = ProviderShared.mediaUrl(part.media)?.trim()
|
|
698
|
+
// SDK URL sources: URLImageSource:3817 / URLPDFSource:3823 {type:"url", url}
|
|
699
|
+
if (rawString && isHttpUrl(rawString)) {
|
|
700
|
+
if (mime.startsWith("image/")) return image({ type: "url", url: rawString })
|
|
701
|
+
if (mime === "application/pdf") return document({ type: "url", url: rawString })
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
const media = yield* ProviderShared.requireInlineMedia("Anthropic Messages", part.media)
|
|
705
|
+
|
|
706
|
+
// SDK PlainTextSource:2716 {type:"text", media_type:"text/plain", data}
|
|
707
|
+
if (mime === "text/plain")
|
|
708
|
+
return document({
|
|
709
|
+
type: "text",
|
|
710
|
+
media_type: "text/plain",
|
|
711
|
+
data: Buffer.from(media.base64, "base64").toString("utf8"),
|
|
712
|
+
})
|
|
713
|
+
|
|
714
|
+
if (media.mime === "application/pdf")
|
|
715
|
+
return document({ type: "base64", media_type: "application/pdf", data: media.base64 })
|
|
716
|
+
if (!media.mime.startsWith("image/"))
|
|
717
|
+
return yield* invalid(`Anthropic Messages does not support media type ${part.media.mediaType}`)
|
|
718
|
+
return image({ type: "base64", media_type: media.mime, data: media.base64 })
|
|
719
|
+
})
|
|
720
|
+
|
|
721
|
+
// Tool results may carry structured text, images, and documents. Keep media as provider-native
|
|
722
|
+
// content instead of JSON-stringifying base64 into a prompt string.
|
|
723
|
+
const lowerToolResultContentItem = Effect.fnUntraced(function* (item: Tool.Content, request: LLMRequest) {
|
|
724
|
+
if (item.type === "text") return { type: "text" as const, text: item.text } satisfies AnthropicTextBlock
|
|
725
|
+
return yield* lowerMedia(ProviderShared.toolFileMedia(item), request)
|
|
726
|
+
})
|
|
727
|
+
|
|
728
|
+
const lowerToolResultContent = Effect.fnUntraced(function* (part: ToolResultPart, request: LLMRequest) {
|
|
729
|
+
// Text / json / error results stay as a string for backward compatibility
|
|
730
|
+
// with existing cassettes and provider expectations.
|
|
731
|
+
if (part.result.type !== "content") return ProviderShared.toolResultText(part)
|
|
732
|
+
// Preserve the narrowed array element type when compiled through a consumer package.
|
|
733
|
+
const content: ReadonlyArray<Tool.Content> = part.result.value
|
|
734
|
+
return yield* Effect.forEach(content, (item) => lowerToolResultContentItem(item, request))
|
|
735
|
+
})
|
|
736
|
+
|
|
737
|
+
const requireThinkingSignature = (request: LLMRequest) => {
|
|
738
|
+
if (request.model.compatibility?.requireSignature !== undefined) return request.model.compatibility.requireSignature
|
|
739
|
+
const provider = request.model.provider.toLowerCase()
|
|
740
|
+
const model = request.model.id.toLowerCase()
|
|
741
|
+
const baseURL = (request.model.route.endpoint.baseURL ?? "").toLowerCase()
|
|
742
|
+
if (
|
|
743
|
+
provider === "kimi-for-coding" ||
|
|
744
|
+
provider === "moonshotai" ||
|
|
745
|
+
provider === "moonshotai-cn" ||
|
|
746
|
+
model.startsWith("kimi-") ||
|
|
747
|
+
baseURL.includes("api.kimi.com/coding") ||
|
|
748
|
+
baseURL.includes("api.moonshot.ai/anthropic") ||
|
|
749
|
+
baseURL.includes("api.moonshot.cn/anthropic")
|
|
750
|
+
)
|
|
751
|
+
return false
|
|
752
|
+
if (provider.includes("xiaomi") || model.includes("mimo") || baseURL.includes("xiaomimimo.com")) return false
|
|
753
|
+
if (model.startsWith("qwen") || model.startsWith("minimax-")) return false
|
|
754
|
+
return true
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// Opus 4.8 and every Claude 5 model accept mid-conversation system messages; later versions inherit support.
|
|
758
|
+
const supportsNativeSystemUpdates = (request: LLMRequest) => {
|
|
759
|
+
const override = request.model.capabilities?.systemUpdates
|
|
760
|
+
if (override !== undefined) return override
|
|
761
|
+
const version = claudeVersion(request.model.id)
|
|
762
|
+
if (version === undefined) return false
|
|
763
|
+
if (version.family === "opus" && version.major === 4) return version.minor >= 8
|
|
764
|
+
return version.major >= 5
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
// Native system messages must follow a user turn (tool results count) or a paused server-tool turn.
|
|
768
|
+
const acceptsNativeSystemAfter = (message: AnthropicMessage | undefined) =>
|
|
769
|
+
message?.role === "user" || (message?.role === "assistant" && message.content.at(-1)?.type === "server_tool_use")
|
|
770
|
+
|
|
771
|
+
const splitsLocalToolResults = (messages: LLMRequest["messages"], index: number) => {
|
|
772
|
+
const pending = new Set<string>()
|
|
773
|
+
for (const message of messages.slice(0, index)) {
|
|
774
|
+
for (const part of message.content) {
|
|
775
|
+
if (message.role === "assistant" && part.type === "tool-call" && part.providerExecuted !== true)
|
|
776
|
+
pending.add(part.id)
|
|
777
|
+
if (message.role === "tool" && part.type === "tool-result") pending.delete(part.id)
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
return pending.size > 0
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
const lowerNativeSystemUpdate = Effect.fnUntraced(function* (
|
|
784
|
+
message: LLMRequest["messages"][number],
|
|
785
|
+
breakpoints: Cache.Breakpoints,
|
|
786
|
+
) {
|
|
787
|
+
const content = yield* ProviderShared.systemUpdateText("Anthropic Messages", message)
|
|
788
|
+
return {
|
|
789
|
+
role: "system" as const,
|
|
790
|
+
content: content.map((part) => ({
|
|
791
|
+
type: "text" as const,
|
|
792
|
+
text: part.text,
|
|
793
|
+
cache_control: cacheControl(breakpoints, part.cache),
|
|
794
|
+
})),
|
|
795
|
+
}
|
|
796
|
+
})
|
|
797
|
+
|
|
798
|
+
const lowerWrappedSystemUpdate = Effect.fnUntraced(function* (
|
|
799
|
+
message: LLMRequest["messages"][number],
|
|
800
|
+
breakpoints: Cache.Breakpoints,
|
|
801
|
+
) {
|
|
802
|
+
const part = yield* ProviderShared.wrappedSystemUpdate("Anthropic Messages", message)
|
|
803
|
+
return { type: "text" as const, text: part.text, cache_control: cacheControl(breakpoints, part.cache) }
|
|
804
|
+
})
|
|
805
|
+
|
|
806
|
+
const lowerToolsUpdate = Effect.fnUntraced(function* (
|
|
807
|
+
message: LLMRequest["messages"][number],
|
|
808
|
+
update: ToolChanges,
|
|
809
|
+
breakpoints: Cache.Breakpoints,
|
|
810
|
+
) {
|
|
811
|
+
const text = message.content.length === 0 ? [] : (yield* lowerNativeSystemUpdate(message, breakpoints)).content
|
|
812
|
+
return {
|
|
813
|
+
role: "system" as const,
|
|
814
|
+
content: [
|
|
815
|
+
...ProviderShared.flattenTools(update.add).map((tool) => ({
|
|
816
|
+
type: "tool_addition" as const,
|
|
817
|
+
tool: { type: "tool_definition" as const, definition: lowerTool(breakpoints, tool) },
|
|
818
|
+
})),
|
|
819
|
+
...update.remove.map((name) => ({
|
|
820
|
+
type: "tool_removal" as const,
|
|
821
|
+
tool: { type: "tool_reference" as const, name },
|
|
822
|
+
})),
|
|
823
|
+
...text,
|
|
824
|
+
],
|
|
825
|
+
}
|
|
826
|
+
})
|
|
827
|
+
|
|
828
|
+
const appendToUserTurn = (messages: AnthropicMessage[], block: AnthropicUserBlock) => {
|
|
829
|
+
const last = messages.at(-1)
|
|
830
|
+
if (last?.role === "user") messages[messages.length - 1] = { role: "user", content: [...last.content, block] }
|
|
831
|
+
else messages.push({ role: "user", content: [block] })
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, breakpoints: Cache.Breakpoints) {
|
|
835
|
+
const messages: AnthropicMessage[] = []
|
|
836
|
+
const providerMetadataKey = request.model.route.providerMetadataKey ?? request.model.provider
|
|
837
|
+
// Text updates stay where they are unless a user turn follows them; then they move after the latest
|
|
838
|
+
// user turn, the nearest spot where Anthropic accepts a native system message.
|
|
839
|
+
const holdUpdates = supportsNativeSystemUpdates(request)
|
|
840
|
+
const held: Array<LLMRequest["messages"][number]> = []
|
|
841
|
+
const releaseHeld = Effect.fnUntraced(function* () {
|
|
842
|
+
const native = acceptsNativeSystemAfter(messages.findLast((message) => message.role !== "system"))
|
|
843
|
+
for (const update of held.splice(0)) {
|
|
844
|
+
const tools = toolsUpdate(update)
|
|
845
|
+
if (tools !== undefined) {
|
|
846
|
+
if (!native) return yield* invalid("Anthropic Messages tool updates must follow a user message or tool result")
|
|
847
|
+
const lowered = yield* lowerToolsUpdate(update, tools, breakpoints)
|
|
848
|
+
if (lowered.content.length > 0) messages.push(lowered)
|
|
849
|
+
continue
|
|
850
|
+
}
|
|
851
|
+
if (native) messages.push(yield* lowerNativeSystemUpdate(update, breakpoints))
|
|
852
|
+
else appendToUserTurn(messages, yield* lowerWrappedSystemUpdate(update, breakpoints))
|
|
853
|
+
}
|
|
854
|
+
})
|
|
855
|
+
|
|
856
|
+
for (const [index, message] of request.messages.entries()) {
|
|
857
|
+
if (message.role === "system") {
|
|
858
|
+
const update = effortUpdate(message)
|
|
859
|
+
if (update) {
|
|
860
|
+
// Accepted at any position, so the text-update placement rules do not apply.
|
|
861
|
+
messages.push({ role: "system", content: [], output_config: { effort: update.effort ?? DEFAULT_EFFORT } })
|
|
862
|
+
continue
|
|
863
|
+
}
|
|
864
|
+
// Held like text updates, so one between a tool call and its result lands after the result. Planning keeps a
|
|
865
|
+
// marker in place only on models that take native system messages.
|
|
866
|
+
if (toolsUpdate(message) !== undefined) {
|
|
867
|
+
held.push(message)
|
|
868
|
+
continue
|
|
869
|
+
}
|
|
870
|
+
if (splitsLocalToolResults(request.messages, index))
|
|
871
|
+
return yield* invalid("Anthropic Messages system updates cannot split a local tool call from its tool result")
|
|
872
|
+
if (holdUpdates) held.push(message)
|
|
873
|
+
else appendToUserTurn(messages, yield* lowerWrappedSystemUpdate(message, breakpoints))
|
|
874
|
+
continue
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
if (message.role === "user") {
|
|
878
|
+
const content: AnthropicUserBlock[] = []
|
|
879
|
+
for (const part of message.content) {
|
|
880
|
+
if (part.type === "text") {
|
|
881
|
+
if (part.text.trim().length === 0) continue
|
|
882
|
+
content.push({ type: "text", text: part.text, cache_control: cacheControl(breakpoints, part.cache) })
|
|
883
|
+
continue
|
|
884
|
+
}
|
|
885
|
+
if (part.type === "media") {
|
|
886
|
+
content.push(yield* lowerMedia(part, request, breakpoints))
|
|
887
|
+
continue
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
if (content.length > 0) messages.push({ role: "user", content })
|
|
891
|
+
continue
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
if (message.role === "assistant") {
|
|
895
|
+
const content: AnthropicAssistantBlock[] = []
|
|
896
|
+
for (const part of message.content) {
|
|
897
|
+
if (part.type === "compaction") {
|
|
898
|
+
if (part.provider !== request.model.provider || part.text === undefined)
|
|
899
|
+
return yield* invalid("Compaction state must be replayed to its originating provider and API")
|
|
900
|
+
content.push({ type: "compaction", content: part.text })
|
|
901
|
+
continue
|
|
902
|
+
}
|
|
903
|
+
if (part.type === "text") {
|
|
904
|
+
if (part.text.trim().length === 0) continue
|
|
905
|
+
content.push({ type: "text", text: part.text, cache_control: cacheControl(breakpoints, part.cache) })
|
|
906
|
+
continue
|
|
907
|
+
}
|
|
908
|
+
if (part.type === "reasoning") {
|
|
909
|
+
// A signature marks visible thinking; only signature-less parts carrying
|
|
910
|
+
// redactedData round-trip as opaque redacted_thinking blocks.
|
|
911
|
+
const signature = part.encrypted ?? signatureFromMetadata(part.providerMetadata, providerMetadataKey)
|
|
912
|
+
const redactedData = redactedDataFromMetadata(part.providerMetadata, providerMetadataKey)
|
|
913
|
+
if (signature === undefined && redactedData !== undefined) {
|
|
914
|
+
content.push({ type: "redacted_thinking", data: redactedData })
|
|
915
|
+
continue
|
|
916
|
+
}
|
|
917
|
+
if (!signature || signature.trim().length === 0) {
|
|
918
|
+
if (part.text.trim().length > 0 && !requireThinkingSignature(request)) {
|
|
919
|
+
content.push({ type: "thinking", thinking: part.text, signature: "" })
|
|
920
|
+
}
|
|
921
|
+
continue
|
|
922
|
+
}
|
|
923
|
+
content.push({ type: "thinking", thinking: part.text, signature })
|
|
924
|
+
continue
|
|
925
|
+
}
|
|
926
|
+
if (part.type === "tool-call") {
|
|
927
|
+
content.push(part.providerExecuted ? lowerServerToolCall(part) : lowerToolCall(part))
|
|
928
|
+
continue
|
|
929
|
+
}
|
|
930
|
+
if (part.type === "tool-result" && part.providerExecuted) {
|
|
931
|
+
content.push(yield* lowerServerToolResult(part, providerMetadataKey))
|
|
932
|
+
continue
|
|
933
|
+
}
|
|
934
|
+
return yield* invalid(
|
|
935
|
+
`Anthropic Messages assistant messages only support text, reasoning, and tool-call content for now`,
|
|
936
|
+
)
|
|
937
|
+
}
|
|
938
|
+
if (content.length === 0) continue
|
|
939
|
+
yield* releaseHeld()
|
|
940
|
+
messages.push({ role: "assistant", content })
|
|
941
|
+
continue
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
const content: AnthropicToolResultBlock[] = []
|
|
945
|
+
for (const part of message.content) {
|
|
946
|
+
content.push({
|
|
947
|
+
type: "tool_result",
|
|
948
|
+
tool_use_id: scrubToolCallID(part.id),
|
|
949
|
+
content: yield* lowerToolResultContent(part, request),
|
|
950
|
+
is_error: part.result.type === "error" ? true : undefined,
|
|
951
|
+
cache_control: cacheControl(breakpoints, part.cache),
|
|
952
|
+
})
|
|
953
|
+
}
|
|
954
|
+
const previous = messages.at(-1)
|
|
955
|
+
if (previous?.role === "user" && previous.content.every((block) => block.type === "tool_result"))
|
|
956
|
+
messages[messages.length - 1] = { role: "user", content: [...previous.content, ...content] }
|
|
957
|
+
else messages.push({ role: "user", content })
|
|
958
|
+
}
|
|
959
|
+
yield* releaseHeld()
|
|
960
|
+
|
|
961
|
+
return messages
|
|
962
|
+
})
|
|
963
|
+
|
|
964
|
+
// The model-ID checks below are fallbacks for models that leave `capabilities.reasoning.updates`,
|
|
965
|
+
// `capabilities.systemUpdates` and `compatibility.supportsThinkingBlockBinding` unset.
|
|
966
|
+
const isThinkingOff = Schema.is(AnthropicThinkingDisabled)
|
|
967
|
+
|
|
968
|
+
// Per-turn effort started with Claude Opus 5 and every Claude 5.1 model; later versions of any family inherit it.
|
|
969
|
+
const supportsEffortUpdates = (request: LLMRequest) => {
|
|
970
|
+
if (isThinkingOff(request.providerOptions?.thinking)) return false
|
|
971
|
+
const override = request.model.capabilities?.reasoning?.updates
|
|
972
|
+
if (override !== undefined) return override
|
|
973
|
+
const version = claudeVersion(request.model.id)
|
|
974
|
+
if (version === undefined) return false
|
|
975
|
+
if (version.family === "opus" && version.major >= 5) return true
|
|
976
|
+
return version.major > 5 || (version.major === 5 && version.minor >= 1)
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
// `tool_addition` adds a tool, or redefines one with the same name; `tool_removal` removes one. A held marker is
|
|
980
|
+
// released just before the next assistant message, where Anthropic only accepts a native system message after a
|
|
981
|
+
// user message or tool result; a marker that would land elsewhere folds.
|
|
982
|
+
const toolUpdates = {
|
|
983
|
+
kinds: ["add", "remove", "replace"],
|
|
984
|
+
placeable: (request, index) => {
|
|
985
|
+
if (!supportsNativeSystemUpdates(request)) return false
|
|
986
|
+
const end = request.messages.findIndex((next, at) => at > index && next.role === "assistant")
|
|
987
|
+
const role = request.messages
|
|
988
|
+
.slice(0, end === -1 ? undefined : end)
|
|
989
|
+
.findLast((next) => next.role !== "system")?.role
|
|
990
|
+
return role === "user" || role === "tool"
|
|
991
|
+
},
|
|
992
|
+
} satisfies ToolUpdateEncoding
|
|
993
|
+
|
|
994
|
+
const applyThinkingBindingDefault = (model: LLMRequest["model"], thinking: AnthropicThinking | undefined) => {
|
|
995
|
+
if (isThinkingOff(thinking)) return thinking
|
|
996
|
+
if (!supportsThinkingBlockBinding(model)) return thinking
|
|
997
|
+
return {
|
|
998
|
+
...(thinking ?? { type: "adaptive" as const }),
|
|
999
|
+
block_binding: {
|
|
1000
|
+
prefix_mismatch_behavior: "drop_block",
|
|
1001
|
+
...thinking?.block_binding,
|
|
1002
|
+
},
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
// Anthropic also requires an explicit thinking budget below `max_tokens` and at or above its minimum.
|
|
1007
|
+
const fitThinking = (thinking: AnthropicThinking | undefined, maxTokens: number) =>
|
|
1008
|
+
thinking?.type === "enabled"
|
|
1009
|
+
? {
|
|
1010
|
+
...thinking,
|
|
1011
|
+
budget_tokens: ProviderShared.fitThinkingBudget(thinking.budget_tokens, maxTokens, MIN_THINKING_BUDGET),
|
|
1012
|
+
}
|
|
1013
|
+
: thinking
|
|
1014
|
+
|
|
1015
|
+
const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (request: LLMRequest) {
|
|
1016
|
+
const options = yield* decodeOptions(request.providerOptions ?? {})
|
|
1017
|
+
const management = options.contextManagement
|
|
1018
|
+
const outputConfig = options.output_config ?? options.outputConfig
|
|
1019
|
+
const format = outputConfig?.format ?? undefined
|
|
1020
|
+
const updates = resolveEffortUpdates(request, options.effort ?? outputConfig?.effort ?? undefined)
|
|
1021
|
+
// Allocate the 4-breakpoint budget in invalidation order: tools → system →
|
|
1022
|
+
// messages. Tools live highest in the cache hierarchy, so when callers
|
|
1023
|
+
// over-mark we keep their tool hints and shed the message-tail ones first.
|
|
1024
|
+
const breakpoints = Cache.newBreakpoints(ANTHROPIC_BREAKPOINT_CAP)
|
|
1025
|
+
const definitions = ProviderShared.flattenTools(updates.request.tools)
|
|
1026
|
+
const tools = definitions.length === 0 ? undefined : definitions.map((tool) => lowerTool(breakpoints, tool))
|
|
1027
|
+
// Anthropic rejects tool_choice when no tool is declared; "none" is only meaningful with tools present.
|
|
1028
|
+
const declared = tools !== undefined || addsTools(request)
|
|
1029
|
+
const toolChoice = !declared || !request.toolChoice ? undefined : yield* lowerToolChoice(request.toolChoice)
|
|
1030
|
+
const systemParts = request.system.filter((part) => part.text.length > 0)
|
|
1031
|
+
const system =
|
|
1032
|
+
systemParts.length === 0
|
|
1033
|
+
? undefined
|
|
1034
|
+
: systemParts.map((part) => ({
|
|
1035
|
+
type: "text" as const,
|
|
1036
|
+
text: part.text,
|
|
1037
|
+
cache_control: cacheControl(breakpoints, part.cache),
|
|
1038
|
+
}))
|
|
1039
|
+
const messages = yield* lowerMessages(updates.request, breakpoints)
|
|
1040
|
+
yield* Cache.warnDropped(breakpoints, "Anthropic Messages", ANTHROPIC_BREAKPOINT_CAP)
|
|
1041
|
+
const output_config =
|
|
1042
|
+
updates.effort === undefined && format === undefined ? undefined : { effort: updates.effort, format }
|
|
1043
|
+
const maxTokens = request.maxTokens ?? DEFAULT_MAX_TOKENS
|
|
1044
|
+
const body = {
|
|
1045
|
+
model: request.model.id,
|
|
1046
|
+
system,
|
|
1047
|
+
messages,
|
|
1048
|
+
tools,
|
|
1049
|
+
tool_choice: toolChoice,
|
|
1050
|
+
stream: true as const,
|
|
1051
|
+
max_tokens: maxTokens,
|
|
1052
|
+
temperature: request.temperature,
|
|
1053
|
+
top_p: request.topP,
|
|
1054
|
+
top_k: request.topK,
|
|
1055
|
+
stop_sequences: request.stop,
|
|
1056
|
+
thinking: applyThinkingBindingDefault(request.model, fitThinking(options.thinking, maxTokens)),
|
|
1057
|
+
output_config,
|
|
1058
|
+
// top-level passthrough per SDK MessageCreateParamsBase:4638,4643,4649,4654,4670
|
|
1059
|
+
cache_control: options.cache_control ?? options.cacheControl,
|
|
1060
|
+
container: options.container,
|
|
1061
|
+
inference_geo: options.inference_geo ?? options.inferenceGeo ?? undefined,
|
|
1062
|
+
metadata: options.metadata,
|
|
1063
|
+
service_tier: options.service_tier ?? options.serviceTier,
|
|
1064
|
+
speed: options.speed,
|
|
1065
|
+
}
|
|
1066
|
+
if (!management) return body
|
|
1067
|
+
return {
|
|
1068
|
+
...body,
|
|
1069
|
+
context_management: {
|
|
1070
|
+
edits: management.edits.map((edit) => ({
|
|
1071
|
+
type: edit.type,
|
|
1072
|
+
trigger: edit.trigger,
|
|
1073
|
+
pause_after_compaction: edit.pauseAfterCompaction,
|
|
1074
|
+
instructions: edit.instructions,
|
|
1075
|
+
})),
|
|
1076
|
+
},
|
|
1077
|
+
}
|
|
1078
|
+
})
|
|
1079
|
+
|
|
1080
|
+
// =============================================================================
|
|
1081
|
+
// Stream Parsing
|
|
1082
|
+
// =============================================================================
|
|
1083
|
+
const mapFinishReason = (reason: string | null | undefined): FinishReason => {
|
|
1084
|
+
if (reason === "end_turn" || reason === "stop_sequence" || reason === "pause_turn") return "stop"
|
|
1085
|
+
if (reason === "max_tokens" || reason === "model_context_window_exceeded") return "length"
|
|
1086
|
+
if (reason === "tool_use") return "tool-calls"
|
|
1087
|
+
if (reason === "refusal") return "content-filter"
|
|
1088
|
+
return "unknown"
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
// Anthropic reports the non-overlapping breakdown natively — its
|
|
1092
|
+
// `input_tokens` is the *non-cached* count per the Messages API docs, with
|
|
1093
|
+
// cache reads and writes as separate fields. We sum them to derive the
|
|
1094
|
+
// inclusive `inputTokens` the rest of the contract expects. Extended
|
|
1095
|
+
// thinking tokens are included in `output_tokens`; newer responses also
|
|
1096
|
+
// expose that subset through `output_tokens_details.thinking_tokens`.
|
|
1097
|
+
const mapUsage = (
|
|
1098
|
+
usage: AnthropicUsage | undefined,
|
|
1099
|
+
providerMetadataKey: string,
|
|
1100
|
+
frame?: AnthropicEvent,
|
|
1101
|
+
): Usage | undefined => {
|
|
1102
|
+
if (!usage) return undefined
|
|
1103
|
+
const iterations = usage.iterations?.length ? usage.iterations : [usage]
|
|
1104
|
+
const last = usage.iterations?.at(-1)
|
|
1105
|
+
const nonCached = ProviderShared.sumTokens(...iterations.map((item) => item.input_tokens ?? undefined))
|
|
1106
|
+
const cacheRead = ProviderShared.sumTokens(...iterations.map((item) => item.cache_read_input_tokens ?? undefined))
|
|
1107
|
+
const cacheWrite = ProviderShared.sumTokens(
|
|
1108
|
+
...iterations.map((item) => item.cache_creation_input_tokens ?? undefined),
|
|
1109
|
+
)
|
|
1110
|
+
const inputTokens = ProviderShared.sumTokens(nonCached, cacheRead, cacheWrite)
|
|
1111
|
+
const outputTokens = ProviderShared.sumTokens(...iterations.map((item) => item.output_tokens))
|
|
1112
|
+
return new Usage({
|
|
1113
|
+
inputTokens,
|
|
1114
|
+
outputTokens,
|
|
1115
|
+
contextTokens:
|
|
1116
|
+
last?.type === "message"
|
|
1117
|
+
? ProviderShared.sumTokens(
|
|
1118
|
+
last.input_tokens ?? undefined,
|
|
1119
|
+
last.cache_read_input_tokens ?? undefined,
|
|
1120
|
+
last.cache_creation_input_tokens ?? undefined,
|
|
1121
|
+
)
|
|
1122
|
+
: undefined,
|
|
1123
|
+
nonCachedInputTokens: nonCached,
|
|
1124
|
+
cacheReadInputTokens: cacheRead,
|
|
1125
|
+
cacheWriteInputTokens: cacheWrite,
|
|
1126
|
+
reasoningTokens: ProviderShared.sumTokens(...iterations.map((item) => item.output_tokens_details?.thinking_tokens)),
|
|
1127
|
+
totalTokens: ProviderShared.totalTokens(inputTokens, outputTokens, undefined),
|
|
1128
|
+
...ProviderShared.reportedBilling(usage, frame),
|
|
1129
|
+
providerMetadata: { [providerMetadataKey]: usage },
|
|
1130
|
+
})
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
// Anthropic emits usage on `message_start` and again on `message_delta` — the
|
|
1134
|
+
// final delta carries the authoritative totals. Right-biased merge: each
|
|
1135
|
+
// field prefers `right` when defined, falls back to `left`. `inputTokens` is
|
|
1136
|
+
// recomputed from the merged breakdown so the inclusive total stays
|
|
1137
|
+
// consistent with `nonCached + cacheRead + cacheWrite`.
|
|
1138
|
+
const mergeUsage = (left: Usage | undefined, right: Usage | undefined, providerMetadataKey: string) => {
|
|
1139
|
+
if (!left) return right
|
|
1140
|
+
if (!right) return left
|
|
1141
|
+
const nonCachedInputTokens = right.nonCachedInputTokens ?? left.nonCachedInputTokens
|
|
1142
|
+
const cacheReadInputTokens = right.cacheReadInputTokens ?? left.cacheReadInputTokens
|
|
1143
|
+
const cacheWriteInputTokens = right.cacheWriteInputTokens ?? left.cacheWriteInputTokens
|
|
1144
|
+
const inputTokens = ProviderShared.sumTokens(nonCachedInputTokens, cacheReadInputTokens, cacheWriteInputTokens)
|
|
1145
|
+
const outputTokens = right.outputTokens ?? left.outputTokens
|
|
1146
|
+
const reasoningTokens = right.reasoningTokens ?? left.reasoningTokens
|
|
1147
|
+
return new Usage({
|
|
1148
|
+
inputTokens,
|
|
1149
|
+
outputTokens,
|
|
1150
|
+
contextTokens: right.contextTokens ?? left.contextTokens,
|
|
1151
|
+
nonCachedInputTokens,
|
|
1152
|
+
cacheReadInputTokens,
|
|
1153
|
+
cacheWriteInputTokens,
|
|
1154
|
+
reasoningTokens,
|
|
1155
|
+
totalTokens: ProviderShared.totalTokens(inputTokens, outputTokens, undefined),
|
|
1156
|
+
cost: right.cost ?? left.cost,
|
|
1157
|
+
providerMetadata: {
|
|
1158
|
+
[providerMetadataKey]:
|
|
1159
|
+
mergeJsonRecords(left.providerMetadata?.[providerMetadataKey], right.providerMetadata?.[providerMetadataKey]) ??
|
|
1160
|
+
{},
|
|
1161
|
+
},
|
|
1162
|
+
})
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
// Server tool result blocks come whole in `content_block_start` (no streaming
|
|
1166
|
+
// delta sequence). We convert the payload to a `tool-result` event with
|
|
1167
|
+
// `providerExecuted: true`. The runtime appends it to the assistant message
|
|
1168
|
+
// for round-trip; downstream consumers can inspect `result.value` for the
|
|
1169
|
+
// structured payload.
|
|
1170
|
+
const SERVER_TOOL_RESULT_NAMES: Record<AnthropicServerToolResultType, string> = {
|
|
1171
|
+
web_search_tool_result: "web_search",
|
|
1172
|
+
code_execution_tool_result: "code_execution",
|
|
1173
|
+
web_fetch_tool_result: "web_fetch",
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
const isServerToolResultType = (type: string): type is AnthropicServerToolResultType => type in SERVER_TOOL_RESULT_NAMES
|
|
1177
|
+
|
|
1178
|
+
const serverToolResultEvent = (block: AnthropicStreamBlock, providerMetadataKey: string): LLMEvent | undefined => {
|
|
1179
|
+
if (!block.type || !isServerToolResultType(block.type)) return undefined
|
|
1180
|
+
const errorPayload =
|
|
1181
|
+
ProviderShared.isRecord(block.content) && "type" in block.content ? String(block.content.type) : ""
|
|
1182
|
+
const isError = errorPayload.endsWith("_tool_result_error")
|
|
1183
|
+
return LLMEvent.toolResult({
|
|
1184
|
+
id: block.tool_use_id ?? "",
|
|
1185
|
+
name: SERVER_TOOL_RESULT_NAMES[block.type],
|
|
1186
|
+
result: isError ? { type: "error", value: block.content } : { type: "json", value: block.content },
|
|
1187
|
+
providerExecuted: true,
|
|
1188
|
+
// The complete payload is irreducible provider replay state: subsequent
|
|
1189
|
+
// stateless requests must round-trip the typed result block verbatim.
|
|
1190
|
+
providerMetadata: providerMetadata(providerMetadataKey, { blockType: block.type, result: block.content }),
|
|
1191
|
+
})
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
type StepResult = readonly [ParserState, ReadonlyArray<LLMEvent>]
|
|
1195
|
+
|
|
1196
|
+
const NO_EVENTS: StepResult["1"] = []
|
|
1197
|
+
|
|
1198
|
+
const onMessageStart = (state: ParserState, event: AnthropicEvent): StepResult => {
|
|
1199
|
+
const usage = mapUsage(event.message?.usage, state.providerMetadataKey)
|
|
1200
|
+
return [usage ? { ...state, usage: mergeUsage(state.usage, usage, state.providerMetadataKey) } : state, NO_EVENTS]
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
const onContentBlockStart = (
|
|
1204
|
+
state: ParserState,
|
|
1205
|
+
event: AnthropicEvent & { readonly content_block: AnthropicStreamBlock },
|
|
1206
|
+
): StepResult => {
|
|
1207
|
+
const block = event.content_block
|
|
1208
|
+
|
|
1209
|
+
if (block.type === "tool_use" || block.type === "server_tool_use") {
|
|
1210
|
+
if (event.index === undefined || !block.id) return [state, NO_EVENTS]
|
|
1211
|
+
const events: LLMEvent[] = []
|
|
1212
|
+
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
|
1213
|
+
return [
|
|
1214
|
+
{
|
|
1215
|
+
...state,
|
|
1216
|
+
lifecycle,
|
|
1217
|
+
tools: ToolStream.start(state.tools, event.index, {
|
|
1218
|
+
id: block.id,
|
|
1219
|
+
name: block.name ?? "",
|
|
1220
|
+
input:
|
|
1221
|
+
block.input !== undefined && (!ProviderShared.isRecord(block.input) || Object.keys(block.input).length > 0)
|
|
1222
|
+
? ProviderShared.encodeJson(block.input)
|
|
1223
|
+
: undefined,
|
|
1224
|
+
providerExecuted: block.type === "server_tool_use",
|
|
1225
|
+
}),
|
|
1226
|
+
},
|
|
1227
|
+
[
|
|
1228
|
+
...events,
|
|
1229
|
+
LLMEvent.toolInputStart({
|
|
1230
|
+
id: block.id,
|
|
1231
|
+
name: block.name ?? "",
|
|
1232
|
+
providerExecuted: block.type === "server_tool_use" ? true : undefined,
|
|
1233
|
+
}),
|
|
1234
|
+
],
|
|
1235
|
+
]
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
if (block.type === "text" && block.text !== undefined) {
|
|
1239
|
+
const events: LLMEvent[] = []
|
|
1240
|
+
const id = `text-${event.index ?? 0}`
|
|
1241
|
+
const lifecycle = Lifecycle.textStart(state.lifecycle, events, id)
|
|
1242
|
+
return [
|
|
1243
|
+
{ ...state, lifecycle: block.text ? Lifecycle.textDelta(lifecycle, events, id, block.text) : lifecycle },
|
|
1244
|
+
events,
|
|
1245
|
+
]
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
if (block.type === "thinking" && block.thinking !== undefined) {
|
|
1249
|
+
const events: LLMEvent[] = []
|
|
1250
|
+
const id = `reasoning-${event.index ?? 0}`
|
|
1251
|
+
const metadata =
|
|
1252
|
+
block.signature === undefined
|
|
1253
|
+
? undefined
|
|
1254
|
+
: providerMetadata(state.providerMetadataKey, { signature: block.signature })
|
|
1255
|
+
const lifecycle = Lifecycle.reasoningStart(state.lifecycle, events, id, metadata)
|
|
1256
|
+
return [
|
|
1257
|
+
{
|
|
1258
|
+
...state,
|
|
1259
|
+
lifecycle: block.thinking
|
|
1260
|
+
? Lifecycle.reasoningDelta(lifecycle, events, id, block.thinking, metadata)
|
|
1261
|
+
: lifecycle,
|
|
1262
|
+
reasoningSignatures:
|
|
1263
|
+
event.index === undefined || block.signature === undefined
|
|
1264
|
+
? state.reasoningSignatures
|
|
1265
|
+
: { ...state.reasoningSignatures, [event.index]: block.signature },
|
|
1266
|
+
},
|
|
1267
|
+
events,
|
|
1268
|
+
]
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
// Redacted thinking surfaces as an empty reasoning part carrying the opaque
|
|
1272
|
+
// payload as `redactedData` metadata (same model as Vercel's
|
|
1273
|
+
// @ai-sdk/anthropic). The existing content_block_stop closes the part.
|
|
1274
|
+
if (block.type === "redacted_thinking" && block.data !== undefined) {
|
|
1275
|
+
const events: LLMEvent[] = []
|
|
1276
|
+
return [
|
|
1277
|
+
{
|
|
1278
|
+
...state,
|
|
1279
|
+
lifecycle: Lifecycle.reasoningStart(
|
|
1280
|
+
state.lifecycle,
|
|
1281
|
+
events,
|
|
1282
|
+
`reasoning-${event.index ?? 0}`,
|
|
1283
|
+
providerMetadata(state.providerMetadataKey, { redactedData: block.data }),
|
|
1284
|
+
),
|
|
1285
|
+
},
|
|
1286
|
+
events,
|
|
1287
|
+
]
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
const result = serverToolResultEvent(block, state.providerMetadataKey)
|
|
1291
|
+
if (!result) return [state, NO_EVENTS]
|
|
1292
|
+
const events: LLMEvent[] = []
|
|
1293
|
+
return [{ ...state, lifecycle: Lifecycle.stepStart(state.lifecycle, events) }, [...events, result]]
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
const onContentBlockDelta = Effect.fnUntraced(function* (
|
|
1297
|
+
state: ParserState,
|
|
1298
|
+
event: AnthropicEvent & { readonly delta: AnthropicStreamDelta },
|
|
1299
|
+
) {
|
|
1300
|
+
const delta = event.delta
|
|
1301
|
+
|
|
1302
|
+
if (delta.type === "compaction_delta") {
|
|
1303
|
+
if (event.index === undefined || !(event.index in state.compactions) || delta.content === undefined)
|
|
1304
|
+
return yield* ProviderShared.eventError(ADAPTER, "Compaction delta is missing its block or content")
|
|
1305
|
+
return [
|
|
1306
|
+
{ ...state, compactions: { ...state.compactions, [event.index]: delta.content } },
|
|
1307
|
+
NO_EVENTS,
|
|
1308
|
+
] satisfies StepResult
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
if (delta.type === "text_delta" && delta.text) {
|
|
1312
|
+
if (!state.lifecycle.text.has(`text-${event.index ?? 0}`)) return [state, NO_EVENTS] satisfies StepResult
|
|
1313
|
+
const events: LLMEvent[] = []
|
|
1314
|
+
return [
|
|
1315
|
+
{ ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events, `text-${event.index ?? 0}`, delta.text) },
|
|
1316
|
+
events,
|
|
1317
|
+
] satisfies StepResult
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
if (delta.type === "thinking_delta" && delta.thinking) {
|
|
1321
|
+
if (!state.lifecycle.reasoning.has(`reasoning-${event.index ?? 0}`)) return [state, NO_EVENTS] satisfies StepResult
|
|
1322
|
+
const events: LLMEvent[] = []
|
|
1323
|
+
return [
|
|
1324
|
+
{
|
|
1325
|
+
...state,
|
|
1326
|
+
lifecycle: Lifecycle.reasoningDelta(state.lifecycle, events, `reasoning-${event.index ?? 0}`, delta.thinking),
|
|
1327
|
+
},
|
|
1328
|
+
events,
|
|
1329
|
+
] satisfies StepResult
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
if (delta.type === "signature_delta" && delta.signature) {
|
|
1333
|
+
const index = event.index ?? 0
|
|
1334
|
+
if (!state.lifecycle.reasoning.has(`reasoning-${index}`)) return [state, NO_EVENTS] satisfies StepResult
|
|
1335
|
+
return [
|
|
1336
|
+
{
|
|
1337
|
+
...state,
|
|
1338
|
+
reasoningSignatures: { ...state.reasoningSignatures, [index]: delta.signature },
|
|
1339
|
+
},
|
|
1340
|
+
NO_EVENTS,
|
|
1341
|
+
] satisfies StepResult
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
if (delta.type === "input_json_delta" && event.index !== undefined) {
|
|
1345
|
+
if (!delta.partial_json) return [state, NO_EVENTS] satisfies StepResult
|
|
1346
|
+
if (!state.tools[event.index]) return [state, NO_EVENTS] satisfies StepResult
|
|
1347
|
+
const result = ToolStream.appendExisting(
|
|
1348
|
+
ADAPTER,
|
|
1349
|
+
state.tools,
|
|
1350
|
+
event.index,
|
|
1351
|
+
delta.partial_json,
|
|
1352
|
+
"Anthropic Messages tool argument delta is missing its tool call",
|
|
1353
|
+
)
|
|
1354
|
+
if (ToolStream.isError(result)) return yield* result
|
|
1355
|
+
const events: LLMEvent[] = []
|
|
1356
|
+
const lifecycle = result.events.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle
|
|
1357
|
+
events.push(...result.events)
|
|
1358
|
+
return [{ ...state, lifecycle, tools: result.tools }, events] satisfies StepResult
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
return [state, NO_EVENTS] satisfies StepResult
|
|
1362
|
+
})
|
|
1363
|
+
|
|
1364
|
+
const onContentBlockStop = Effect.fnUntraced(function* (state: ParserState, event: AnthropicEvent) {
|
|
1365
|
+
if (event.index === undefined) return [state, NO_EVENTS] satisfies StepResult
|
|
1366
|
+
if (event.index in state.compactions) {
|
|
1367
|
+
const { [event.index]: content, ...compactions } = state.compactions
|
|
1368
|
+
const events: LLMEvent[] = []
|
|
1369
|
+
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
|
1370
|
+
events.push(
|
|
1371
|
+
LLMEvent.compaction({
|
|
1372
|
+
provider: state.provider,
|
|
1373
|
+
text: content,
|
|
1374
|
+
}),
|
|
1375
|
+
)
|
|
1376
|
+
return [{ ...state, compactions, lifecycle }, events] satisfies StepResult
|
|
1377
|
+
}
|
|
1378
|
+
const result = yield* ToolStream.finish(ADAPTER, state.tools, event.index)
|
|
1379
|
+
const events: LLMEvent[] = []
|
|
1380
|
+
const resultEvents = result.events ?? []
|
|
1381
|
+
const signature = state.reasoningSignatures[event.index]
|
|
1382
|
+
const lifecycle = resultEvents.length
|
|
1383
|
+
? Lifecycle.stepStart(state.lifecycle, events)
|
|
1384
|
+
: Lifecycle.reasoningEnd(
|
|
1385
|
+
Lifecycle.textEnd(state.lifecycle, events, `text-${event.index}`),
|
|
1386
|
+
events,
|
|
1387
|
+
`reasoning-${event.index}`,
|
|
1388
|
+
signature === undefined ? undefined : providerMetadata(state.providerMetadataKey, { signature }),
|
|
1389
|
+
)
|
|
1390
|
+
events.push(...resultEvents)
|
|
1391
|
+
const reasoningSignatures = { ...state.reasoningSignatures }
|
|
1392
|
+
delete reasoningSignatures[event.index]
|
|
1393
|
+
return [{ ...state, lifecycle, tools: result.tools, reasoningSignatures }, events] satisfies StepResult
|
|
1394
|
+
})
|
|
1395
|
+
|
|
1396
|
+
const onMessageDelta = (
|
|
1397
|
+
state: ParserState,
|
|
1398
|
+
event: AnthropicEvent & { readonly delta?: AnthropicStreamDelta },
|
|
1399
|
+
): StepResult => {
|
|
1400
|
+
const usage = mergeUsage(
|
|
1401
|
+
state.usage,
|
|
1402
|
+
mapUsage(event.usage, state.providerMetadataKey, event),
|
|
1403
|
+
state.providerMetadataKey,
|
|
1404
|
+
)
|
|
1405
|
+
const pendingFinish = (() => {
|
|
1406
|
+
const stopReason = event.delta?.stop_reason
|
|
1407
|
+
if (stopReason === null || stopReason === undefined) return state.pendingFinish
|
|
1408
|
+
|
|
1409
|
+
const stopSequence = event.delta?.stop_sequence
|
|
1410
|
+
const finishMetadata =
|
|
1411
|
+
stopSequence === null || stopSequence === undefined
|
|
1412
|
+
? state.pendingFinish?.providerMetadata
|
|
1413
|
+
: providerMetadata(state.providerMetadataKey, { stopSequence })
|
|
1414
|
+
const category = event.delta?.stop_details?.category
|
|
1415
|
+
const explanation = event.delta?.stop_details?.explanation
|
|
1416
|
+
return {
|
|
1417
|
+
reason: {
|
|
1418
|
+
normalized: mapFinishReason(stopReason),
|
|
1419
|
+
raw: stopReason,
|
|
1420
|
+
...(category ? { category } : {}),
|
|
1421
|
+
...(explanation ? { explanation } : {}),
|
|
1422
|
+
},
|
|
1423
|
+
providerMetadata: finishMetadata,
|
|
1424
|
+
}
|
|
1425
|
+
})()
|
|
1426
|
+
return [
|
|
1427
|
+
{
|
|
1428
|
+
...state,
|
|
1429
|
+
usage,
|
|
1430
|
+
pendingFinish,
|
|
1431
|
+
},
|
|
1432
|
+
NO_EVENTS,
|
|
1433
|
+
]
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
const onMessageStop = Effect.fnUntraced(function* (state: ParserState) {
|
|
1437
|
+
if (Object.keys(state.compactions).length)
|
|
1438
|
+
return yield* ProviderShared.eventError(ADAPTER, "Response ended with an incomplete compaction block")
|
|
1439
|
+
const result = yield* ToolStream.finishAll(ADAPTER, state.tools)
|
|
1440
|
+
const events: LLMEvent[] = []
|
|
1441
|
+
const lifecycle = result.events.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle
|
|
1442
|
+
events.push(...result.events)
|
|
1443
|
+
const closed = Object.entries(state.reasoningSignatures).reduce(
|
|
1444
|
+
(current, [index, signature]) =>
|
|
1445
|
+
Lifecycle.reasoningEnd(
|
|
1446
|
+
current,
|
|
1447
|
+
events,
|
|
1448
|
+
`reasoning-${index}`,
|
|
1449
|
+
providerMetadata(state.providerMetadataKey, { signature }),
|
|
1450
|
+
),
|
|
1451
|
+
lifecycle,
|
|
1452
|
+
)
|
|
1453
|
+
const finished = Lifecycle.finish(closed, events, {
|
|
1454
|
+
reason: state.pendingFinish?.reason ?? {
|
|
1455
|
+
normalized: "unknown",
|
|
1456
|
+
raw: undefined,
|
|
1457
|
+
},
|
|
1458
|
+
usage: state.usage,
|
|
1459
|
+
providerMetadata: state.pendingFinish?.providerMetadata,
|
|
1460
|
+
})
|
|
1461
|
+
return [{ ...state, lifecycle: finished, tools: result.tools }, events] satisfies StepResult
|
|
1462
|
+
})
|
|
1463
|
+
|
|
1464
|
+
// Prefix `error.type` so overloads, rate limits, and quota errors are visible
|
|
1465
|
+
// even when the provider message is generic or empty.
|
|
1466
|
+
const providerErrorMessage = (event: AnthropicEvent): string => {
|
|
1467
|
+
const type = event.error?.type
|
|
1468
|
+
const message = event.error?.message
|
|
1469
|
+
if (type && message) return `${type}: ${message}`
|
|
1470
|
+
return message || type || "Anthropic Messages stream error"
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
const onError = (event: AnthropicEvent) => {
|
|
1474
|
+
const message = providerErrorMessage(event)
|
|
1475
|
+
const body = ProviderShared.encodeJson(event)
|
|
1476
|
+
return Effect.fail(
|
|
1477
|
+
new AIError({
|
|
1478
|
+
reason: classifyProviderFailure({ message, rawBody: body }),
|
|
1479
|
+
}),
|
|
1480
|
+
)
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
const STREAM_BLOCK_TYPES = new Set([
|
|
1484
|
+
"compaction",
|
|
1485
|
+
"text",
|
|
1486
|
+
"thinking",
|
|
1487
|
+
"redacted_thinking",
|
|
1488
|
+
"tool_use",
|
|
1489
|
+
"server_tool_use",
|
|
1490
|
+
])
|
|
1491
|
+
const STREAM_DELTA_TYPES = new Set([
|
|
1492
|
+
"compaction_delta",
|
|
1493
|
+
"text_delta",
|
|
1494
|
+
"thinking_delta",
|
|
1495
|
+
"signature_delta",
|
|
1496
|
+
"input_json_delta",
|
|
1497
|
+
])
|
|
1498
|
+
|
|
1499
|
+
const invalidStreamEvent = (event: AnthropicEvent) =>
|
|
1500
|
+
Effect.fail(
|
|
1501
|
+
ProviderShared.eventError(
|
|
1502
|
+
ADAPTER,
|
|
1503
|
+
"Invalid anthropic/anthropic-messages stream event",
|
|
1504
|
+
ProviderShared.encodeJson(event),
|
|
1505
|
+
),
|
|
1506
|
+
)
|
|
1507
|
+
|
|
1508
|
+
const step = (state: ParserState, event: AnthropicEvent) => {
|
|
1509
|
+
if (!SSE_EVENTS.has(event.type)) return Effect.succeed<StepResult>([state, NO_EVENTS])
|
|
1510
|
+
if (
|
|
1511
|
+
event.type !== "content_block_start" &&
|
|
1512
|
+
event.content_block !== undefined &&
|
|
1513
|
+
Option.isNone(decodeAnthropicStreamBlock(event.content_block))
|
|
1514
|
+
)
|
|
1515
|
+
return invalidStreamEvent(event)
|
|
1516
|
+
if (
|
|
1517
|
+
event.type !== "content_block_delta" &&
|
|
1518
|
+
event.delta !== undefined &&
|
|
1519
|
+
Option.isNone(decodeAnthropicStreamDelta(event.delta))
|
|
1520
|
+
)
|
|
1521
|
+
return invalidStreamEvent(event)
|
|
1522
|
+
if (event.type === "message_start") return Effect.succeed(onMessageStart(state, event))
|
|
1523
|
+
if (event.type === "content_block_start") {
|
|
1524
|
+
if (!ProviderShared.isRecord(event.content_block) || typeof event.content_block.type !== "string")
|
|
1525
|
+
return invalidStreamEvent(event)
|
|
1526
|
+
if (event.content_block.type === "compaction") {
|
|
1527
|
+
const decoded = Schema.decodeUnknownOption(AnthropicCompactionBlock)(event.content_block)
|
|
1528
|
+
if (event.index === undefined || Option.isNone(decoded)) return invalidStreamEvent(event)
|
|
1529
|
+
return Effect.succeed<StepResult>([
|
|
1530
|
+
{ ...state, compactions: { ...state.compactions, [event.index]: decoded.value.content } },
|
|
1531
|
+
NO_EVENTS,
|
|
1532
|
+
])
|
|
1533
|
+
}
|
|
1534
|
+
if (!STREAM_BLOCK_TYPES.has(event.content_block.type) && !isServerToolResultType(event.content_block.type))
|
|
1535
|
+
return Effect.succeed<StepResult>([state, NO_EVENTS])
|
|
1536
|
+
const decoded = decodeAnthropicStreamBlock(event.content_block)
|
|
1537
|
+
if (Option.isNone(decoded)) return invalidStreamEvent(event)
|
|
1538
|
+
const block = decoded.value
|
|
1539
|
+
if (block.type === "tool_use" || block.type === "server_tool_use") {
|
|
1540
|
+
if (event.index === undefined)
|
|
1541
|
+
return Effect.fail(ProviderShared.eventError(ADAPTER, `Anthropic ${block.type} missing index`))
|
|
1542
|
+
if (!block.id)
|
|
1543
|
+
return Effect.fail(ProviderShared.eventError(ADAPTER, `Anthropic tool_use missing id at index ${event.index}`))
|
|
1544
|
+
}
|
|
1545
|
+
return Effect.succeed(onContentBlockStart(state, { ...event, content_block: block }))
|
|
1546
|
+
}
|
|
1547
|
+
if (event.type === "content_block_delta") {
|
|
1548
|
+
if (!ProviderShared.isRecord(event.delta)) return invalidStreamEvent(event)
|
|
1549
|
+
if (typeof event.delta.type === "string" && !STREAM_DELTA_TYPES.has(event.delta.type))
|
|
1550
|
+
return Effect.succeed<StepResult>([state, NO_EVENTS])
|
|
1551
|
+
const decoded = decodeAnthropicStreamDelta(event.delta)
|
|
1552
|
+
if (Option.isNone(decoded)) return invalidStreamEvent(event)
|
|
1553
|
+
return onContentBlockDelta(state, { ...event, delta: decoded.value })
|
|
1554
|
+
}
|
|
1555
|
+
if (event.type === "content_block_stop") return onContentBlockStop(state, event)
|
|
1556
|
+
if (event.type === "message_delta") {
|
|
1557
|
+
const decoded = decodeAnthropicStreamDelta(event.delta)
|
|
1558
|
+
if (Option.isNone(decoded)) return invalidStreamEvent(event)
|
|
1559
|
+
return Effect.succeed(onMessageDelta(state, { ...event, delta: decoded.value }))
|
|
1560
|
+
}
|
|
1561
|
+
if (event.type === "message_stop") return onMessageStop(state)
|
|
1562
|
+
if (event.type === "error") return onError(event)
|
|
1563
|
+
return Effect.succeed<StepResult>([state, NO_EVENTS])
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
// =============================================================================
|
|
1567
|
+
// Protocol And Anthropic Route
|
|
1568
|
+
// =============================================================================
|
|
1569
|
+
/**
|
|
1570
|
+
* The Anthropic Messages protocol — request body construction, body schema,
|
|
1571
|
+
* and the streaming-event state machine shared by Anthropic-compatible and
|
|
1572
|
+
* Vertex-hosted Messages routes.
|
|
1573
|
+
*/
|
|
1574
|
+
export const protocol = Protocol.make({
|
|
1575
|
+
id: ADAPTER,
|
|
1576
|
+
body: {
|
|
1577
|
+
schema: AnthropicMessagesBody,
|
|
1578
|
+
from: fromRequest,
|
|
1579
|
+
},
|
|
1580
|
+
stream: {
|
|
1581
|
+
event: Protocol.jsonEvent(AnthropicEvent),
|
|
1582
|
+
initial: (request) => ({
|
|
1583
|
+
provider: request.model.provider,
|
|
1584
|
+
compactions: {},
|
|
1585
|
+
providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
|
|
1586
|
+
tools: ToolStream.empty<number>(),
|
|
1587
|
+
reasoningSignatures: {},
|
|
1588
|
+
lifecycle: Lifecycle.initial(),
|
|
1589
|
+
}),
|
|
1590
|
+
step,
|
|
1591
|
+
},
|
|
1592
|
+
supportsEffortUpdates,
|
|
1593
|
+
toolUpdates,
|
|
1594
|
+
})
|
|
1595
|
+
|
|
1596
|
+
export const transport = <
|
|
1597
|
+
Body extends Pick<AnthropicMessagesBody, "messages" | "context_management" | "thinking" | "speed">,
|
|
1598
|
+
>() => {
|
|
1599
|
+
const http = HttpTransport.httpJson<Body, string>({ framing })
|
|
1600
|
+
return {
|
|
1601
|
+
...http,
|
|
1602
|
+
prepare: (input: Parameters<typeof http.prepare>[0]) => {
|
|
1603
|
+
const requiredBetas = requiredBetaHeaders(input.body)
|
|
1604
|
+
if (requiredBetas.length === 0) return http.prepare(input)
|
|
1605
|
+
const headers = Headers.fromInput(input.request.headers)
|
|
1606
|
+
const existingBetas = (headers["anthropic-beta"] ?? "")
|
|
1607
|
+
.split(",")
|
|
1608
|
+
.map((item) => item.trim())
|
|
1609
|
+
.filter(Boolean)
|
|
1610
|
+
const betas = new Set([...existingBetas, ...requiredBetas])
|
|
1611
|
+
return http.prepare({
|
|
1612
|
+
...input,
|
|
1613
|
+
request: { ...input.request, headers: { ...headers, "anthropic-beta": [...betas].join(",") } },
|
|
1614
|
+
})
|
|
1615
|
+
},
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
function requiredBetaHeaders(
|
|
1620
|
+
body: Pick<AnthropicMessagesBody, "messages" | "context_management" | "thinking" | "speed">,
|
|
1621
|
+
) {
|
|
1622
|
+
// Always request interleaved thinking. The API accepts the header on any
|
|
1623
|
+
// model and ignores it where unsupported, while manual-thinking models need
|
|
1624
|
+
// it for thinking between tool calls.
|
|
1625
|
+
const betas: string[] = ["interleaved-thinking-2025-05-14"]
|
|
1626
|
+
const requestsCompaction = (body.context_management?.edits.length ?? 0) > 0
|
|
1627
|
+
const replaysCompaction = body.messages.some((message) =>
|
|
1628
|
+
message.content.some((block) => block.type === "compaction"),
|
|
1629
|
+
)
|
|
1630
|
+
if (requestsCompaction || replaysCompaction) betas.push("compact-2026-01-12")
|
|
1631
|
+
|
|
1632
|
+
if (body.messages.some((message) => message.role === "system" && message.output_config !== undefined))
|
|
1633
|
+
betas.push("mid-conversation-output-config-2026-07-01")
|
|
1634
|
+
if (
|
|
1635
|
+
body.messages.some(
|
|
1636
|
+
(message) =>
|
|
1637
|
+
message.role === "system" &&
|
|
1638
|
+
message.content.some((block) => block.type === "tool_addition" || block.type === "tool_removal"),
|
|
1639
|
+
)
|
|
1640
|
+
)
|
|
1641
|
+
betas.push("inline-tools-2026-09-15")
|
|
1642
|
+
|
|
1643
|
+
// Opus 5.5 accepts `speed` without this header; earlier fast-mode models reject `speed` without it.
|
|
1644
|
+
if (body.speed !== undefined) betas.push("fast-mode-2026-02-01")
|
|
1645
|
+
|
|
1646
|
+
const thinking = body.thinking
|
|
1647
|
+
if (thinking && !isThinkingOff(thinking) && thinking.block_binding) betas.push(THINKING_BINDING_BETA)
|
|
1648
|
+
return betas
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
export const route = Route.make({
|
|
1652
|
+
id: ADAPTER,
|
|
1653
|
+
provider: "anthropic",
|
|
1654
|
+
providerMetadataKey: "anthropic",
|
|
1655
|
+
protocol,
|
|
1656
|
+
endpoint: Endpoint.path((input) => (input.request.model.provider === "anthropic" ? `${PATH}?beta=true` : PATH), {
|
|
1657
|
+
baseURL: DEFAULT_BASE_URL,
|
|
1658
|
+
}),
|
|
1659
|
+
auth: Auth.none,
|
|
1660
|
+
transport: transport<AnthropicMessagesBody>(),
|
|
1661
|
+
headers: () => ({ "anthropic-version": "2023-06-01" }),
|
|
1662
|
+
})
|
|
1663
|
+
|
|
1664
|
+
export * as AnthropicMessages from "./anthropic-messages.js"
|