@zyro-sec/ai 1.0.0 → 1.0.2
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/example/tutorial.ts +284 -0
- package/package.json +11 -13
- 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,1636 @@
|
|
|
1
|
+
import { Effect, Option, Schema } from "effect"
|
|
2
|
+
import type { Content } from "@zyro-sec/schema/tool"
|
|
3
|
+
import { HttpTransport } from "../route/transport/index.js"
|
|
4
|
+
import { Protocol } from "../route/protocol.js"
|
|
5
|
+
import {
|
|
6
|
+
AIError,
|
|
7
|
+
LLMEvent,
|
|
8
|
+
ProviderInternalError,
|
|
9
|
+
Usage,
|
|
10
|
+
type FinishReason,
|
|
11
|
+
type LLMRequest,
|
|
12
|
+
type MediaPart,
|
|
13
|
+
type ProviderMetadata,
|
|
14
|
+
type ReasoningPart,
|
|
15
|
+
type TextPart,
|
|
16
|
+
type ToolCallPart,
|
|
17
|
+
type ToolChanges,
|
|
18
|
+
type ToolDefinition,
|
|
19
|
+
type ToolResultPart,
|
|
20
|
+
type UserMessage,
|
|
21
|
+
} from "../schema/index.js"
|
|
22
|
+
import type { Media } from "../media.js"
|
|
23
|
+
import {
|
|
24
|
+
JsonObject,
|
|
25
|
+
lenient,
|
|
26
|
+
optionalArray,
|
|
27
|
+
optionalNull,
|
|
28
|
+
optionalNullish,
|
|
29
|
+
ProviderShared,
|
|
30
|
+
withUntypedFrames,
|
|
31
|
+
} from "./shared.js"
|
|
32
|
+
import { classifyProviderFailure } from "../provider-error.js"
|
|
33
|
+
import { effortUpdate } from "../effort-updates.js"
|
|
34
|
+
import { toolsUpdate } from "../tool-updates.js"
|
|
35
|
+
import { OpenResponsesOptions } from "./utils/open-responses-options.js"
|
|
36
|
+
import { Lifecycle } from "./utils/lifecycle.js"
|
|
37
|
+
import { ToolStream } from "./utils/tool-stream.js"
|
|
38
|
+
import { OpenAIFreeform } from "./openai-freeform.js"
|
|
39
|
+
|
|
40
|
+
const ADAPTER = "open-responses"
|
|
41
|
+
const NAME = "Open Responses"
|
|
42
|
+
export const PATH = "/responses"
|
|
43
|
+
|
|
44
|
+
// =============================================================================
|
|
45
|
+
// Request Body Schema
|
|
46
|
+
// =============================================================================
|
|
47
|
+
export const OpenResponsesInputText = Schema.Struct({
|
|
48
|
+
type: Schema.tag("input_text"),
|
|
49
|
+
text: Schema.String,
|
|
50
|
+
})
|
|
51
|
+
export const OpenResponsesInputImage = Schema.Struct({
|
|
52
|
+
type: Schema.tag("input_image"),
|
|
53
|
+
image_url: Schema.String,
|
|
54
|
+
detail: Schema.optional(Schema.String),
|
|
55
|
+
})
|
|
56
|
+
export const OpenResponsesInputFile = Schema.Struct({
|
|
57
|
+
type: Schema.tag("input_file"),
|
|
58
|
+
filename: Schema.optional(Schema.String),
|
|
59
|
+
detail: Schema.optional(Schema.String),
|
|
60
|
+
file_data: Schema.optional(Schema.String),
|
|
61
|
+
file_url: Schema.optional(Schema.String),
|
|
62
|
+
})
|
|
63
|
+
const OpenResponsesInputVideo = Schema.Struct({
|
|
64
|
+
type: Schema.tag("input_video"),
|
|
65
|
+
video_url: Schema.String,
|
|
66
|
+
})
|
|
67
|
+
const MediaInput = Schema.Union([OpenResponsesInputImage, OpenResponsesInputFile, OpenResponsesInputVideo])
|
|
68
|
+
export type MediaInput = Schema.Schema.Type<typeof MediaInput>
|
|
69
|
+
const OpenResponsesInputContent = Schema.Union([OpenResponsesInputText, MediaInput])
|
|
70
|
+
|
|
71
|
+
export const OpenResponsesOutputText = Schema.Struct({
|
|
72
|
+
type: Schema.tag("output_text"),
|
|
73
|
+
text: Schema.String,
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
export const MessagePhase = Schema.NullOr(Schema.Literals(["commentary", "final_answer"]))
|
|
77
|
+
type MessagePhase = Schema.Schema.Type<typeof MessagePhase>
|
|
78
|
+
|
|
79
|
+
export const MessageMetadata = Schema.Struct({
|
|
80
|
+
itemId: Schema.optional(Schema.String),
|
|
81
|
+
status: Schema.optional(Schema.String),
|
|
82
|
+
phase: Schema.optional(MessagePhase),
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
const messagePhase = (value: unknown): MessagePhase | undefined => {
|
|
86
|
+
if (value === null || value === "commentary" || value === "final_answer") return value
|
|
87
|
+
return undefined
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const OpenResponsesReasoningSummaryText = Schema.Struct({
|
|
91
|
+
type: Schema.tag("summary_text"),
|
|
92
|
+
text: Schema.String,
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
export const OpenResponsesReasoningItem = Schema.Struct({
|
|
96
|
+
type: Schema.tag("reasoning"),
|
|
97
|
+
id: Schema.optionalKey(Schema.String),
|
|
98
|
+
summary: Schema.Array(OpenResponsesReasoningSummaryText),
|
|
99
|
+
encrypted_content: optionalNull(Schema.String),
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
const OpenResponsesWebSearchCall = Schema.StructWithRest(
|
|
103
|
+
Schema.Struct({
|
|
104
|
+
type: Schema.tag("web_search_call"),
|
|
105
|
+
id: Schema.String,
|
|
106
|
+
status: Schema.optional(Schema.String),
|
|
107
|
+
action: optionalNull(JsonObject),
|
|
108
|
+
}),
|
|
109
|
+
[JsonObject],
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
const OpenResponsesFileSearchCall = Schema.StructWithRest(
|
|
113
|
+
Schema.Struct({
|
|
114
|
+
type: Schema.tag("file_search_call"),
|
|
115
|
+
id: Schema.String,
|
|
116
|
+
status: Schema.optional(Schema.String),
|
|
117
|
+
queries: Schema.optional(Schema.Array(Schema.String)),
|
|
118
|
+
results: optionalNull(Schema.Array(JsonObject)),
|
|
119
|
+
}),
|
|
120
|
+
[JsonObject],
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
const OpenResponsesCodeInterpreterCall = Schema.StructWithRest(
|
|
124
|
+
Schema.Struct({
|
|
125
|
+
type: Schema.tag("code_interpreter_call"),
|
|
126
|
+
id: Schema.String,
|
|
127
|
+
status: Schema.optional(Schema.String),
|
|
128
|
+
code: optionalNull(Schema.String),
|
|
129
|
+
container_id: optionalNull(Schema.String),
|
|
130
|
+
outputs: optionalNull(Schema.Array(JsonObject)),
|
|
131
|
+
}),
|
|
132
|
+
[JsonObject],
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
const OpenResponsesMCPCall = Schema.StructWithRest(
|
|
136
|
+
Schema.Struct({
|
|
137
|
+
type: Schema.tag("mcp_call"),
|
|
138
|
+
id: Schema.String,
|
|
139
|
+
status: Schema.optional(Schema.String),
|
|
140
|
+
server_label: Schema.optional(Schema.String),
|
|
141
|
+
name: Schema.optional(Schema.String),
|
|
142
|
+
arguments: Schema.optional(Schema.String),
|
|
143
|
+
output: optionalNull(Schema.String),
|
|
144
|
+
error: Schema.optional(Schema.Unknown),
|
|
145
|
+
}),
|
|
146
|
+
[JsonObject],
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
export const HostedToolItem = Schema.Union([
|
|
150
|
+
OpenResponsesWebSearchCall,
|
|
151
|
+
OpenResponsesFileSearchCall,
|
|
152
|
+
OpenResponsesCodeInterpreterCall,
|
|
153
|
+
OpenResponsesMCPCall,
|
|
154
|
+
])
|
|
155
|
+
export type HostedToolItem = Schema.Schema.Type<typeof HostedToolItem>
|
|
156
|
+
|
|
157
|
+
// `function_call_output.output` accepts either a plain string or an ordered
|
|
158
|
+
// array of content items so tools can return images and files in addition to text.
|
|
159
|
+
// https://www.openresponses.org/reference
|
|
160
|
+
const OpenResponsesFunctionCallOutputContent = Schema.Union([
|
|
161
|
+
OpenResponsesInputText,
|
|
162
|
+
OpenResponsesInputImage,
|
|
163
|
+
OpenResponsesInputFile,
|
|
164
|
+
OpenResponsesInputVideo,
|
|
165
|
+
])
|
|
166
|
+
|
|
167
|
+
const OpenResponsesFunctionCallOutput = Schema.Union([
|
|
168
|
+
Schema.String,
|
|
169
|
+
Schema.Array(OpenResponsesFunctionCallOutputContent),
|
|
170
|
+
])
|
|
171
|
+
|
|
172
|
+
export const CompactionItem = Schema.Struct({
|
|
173
|
+
type: Schema.Literal("compaction"),
|
|
174
|
+
id: optionalNull(Schema.String),
|
|
175
|
+
encrypted_content: Schema.String,
|
|
176
|
+
})
|
|
177
|
+
|
|
178
|
+
// Kept out of the baseline `InputItem` union: only the OpenAI extension accepts it.
|
|
179
|
+
export const ConfigurationUpdate = Schema.Struct({
|
|
180
|
+
type: Schema.Literal("configuration_update"),
|
|
181
|
+
reasoning: Schema.Struct({ effort: OpenResponsesOptions.ReasoningEffort }),
|
|
182
|
+
})
|
|
183
|
+
export type ConfigurationUpdate = Schema.Schema.Type<typeof ConfigurationUpdate>
|
|
184
|
+
|
|
185
|
+
export const HostedToolReplay = Schema.StructWithRest(
|
|
186
|
+
Schema.Struct({
|
|
187
|
+
type: Schema.String,
|
|
188
|
+
id: Schema.String,
|
|
189
|
+
}),
|
|
190
|
+
[JsonObject],
|
|
191
|
+
)
|
|
192
|
+
export type HostedToolReplayItem = Schema.Schema.Type<typeof HostedToolReplay>
|
|
193
|
+
|
|
194
|
+
export const Tool = Schema.Struct({
|
|
195
|
+
type: Schema.tag("function"),
|
|
196
|
+
name: Schema.String,
|
|
197
|
+
description: Schema.String,
|
|
198
|
+
parameters: JsonObject,
|
|
199
|
+
strict: Schema.optional(Schema.Boolean),
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
export const CustomTool = Schema.Struct({
|
|
203
|
+
type: Schema.tag("custom"),
|
|
204
|
+
name: Schema.String,
|
|
205
|
+
description: Schema.String,
|
|
206
|
+
format: Schema.Union([
|
|
207
|
+
Schema.Struct({ type: Schema.tag("text") }),
|
|
208
|
+
Schema.Struct({
|
|
209
|
+
type: Schema.tag("grammar"),
|
|
210
|
+
syntax: Schema.Literals(["lark", "regex"]),
|
|
211
|
+
definition: Schema.String,
|
|
212
|
+
}),
|
|
213
|
+
]),
|
|
214
|
+
})
|
|
215
|
+
|
|
216
|
+
export const HostedTool = Schema.StructWithRest(
|
|
217
|
+
Schema.Struct({
|
|
218
|
+
type: Schema.String,
|
|
219
|
+
}),
|
|
220
|
+
[JsonObject],
|
|
221
|
+
)
|
|
222
|
+
export type HostedTool = Schema.Schema.Type<typeof HostedTool>
|
|
223
|
+
|
|
224
|
+
const NamedTool = Schema.Struct({ type: Schema.Literals(["function", "custom"]), name: Schema.String })
|
|
225
|
+
|
|
226
|
+
// Tools added mid-conversation. Only the OpenAI extension lowers it; other hosts fold tool updates.
|
|
227
|
+
export const AdditionalTools = Schema.Struct({
|
|
228
|
+
type: Schema.Literal("additional_tools"),
|
|
229
|
+
role: Schema.Literal("developer"),
|
|
230
|
+
tools: Schema.Array(Schema.Union([Tool, CustomTool, HostedTool])),
|
|
231
|
+
})
|
|
232
|
+
|
|
233
|
+
export const InputItem = Schema.Union([
|
|
234
|
+
CompactionItem,
|
|
235
|
+
ConfigurationUpdate,
|
|
236
|
+
AdditionalTools,
|
|
237
|
+
Schema.Struct({ type: Schema.tag("message"), role: Schema.tag("system"), content: Schema.String }),
|
|
238
|
+
Schema.Struct({ type: Schema.tag("message"), role: Schema.tag("developer"), content: Schema.String }),
|
|
239
|
+
Schema.Struct({
|
|
240
|
+
type: Schema.tag("message"),
|
|
241
|
+
role: Schema.tag("user"),
|
|
242
|
+
content: Schema.Array(OpenResponsesInputContent),
|
|
243
|
+
id: Schema.optional(Schema.String),
|
|
244
|
+
status: Schema.optional(Schema.String),
|
|
245
|
+
}),
|
|
246
|
+
Schema.Struct({
|
|
247
|
+
type: Schema.tag("message"),
|
|
248
|
+
id: Schema.optionalKey(Schema.String),
|
|
249
|
+
role: Schema.tag("assistant"),
|
|
250
|
+
content: Schema.Array(OpenResponsesOutputText),
|
|
251
|
+
phase: Schema.optionalKey(MessagePhase),
|
|
252
|
+
status: Schema.optional(Schema.String),
|
|
253
|
+
}),
|
|
254
|
+
OpenResponsesReasoningItem,
|
|
255
|
+
Schema.Struct({
|
|
256
|
+
type: Schema.tag("function_call"),
|
|
257
|
+
id: Schema.optionalKey(Schema.String),
|
|
258
|
+
call_id: Schema.String,
|
|
259
|
+
name: Schema.String,
|
|
260
|
+
namespace: Schema.optional(Schema.String),
|
|
261
|
+
arguments: Schema.String,
|
|
262
|
+
}),
|
|
263
|
+
Schema.Struct({
|
|
264
|
+
type: Schema.Literals(["function_call_output", "custom_tool_call_output"]),
|
|
265
|
+
call_id: Schema.String,
|
|
266
|
+
output: OpenResponsesFunctionCallOutput,
|
|
267
|
+
}),
|
|
268
|
+
Schema.Struct({
|
|
269
|
+
type: Schema.tag("custom_tool_call"),
|
|
270
|
+
id: Schema.optionalKey(Schema.String),
|
|
271
|
+
call_id: Schema.String,
|
|
272
|
+
name: Schema.String,
|
|
273
|
+
input: Schema.String,
|
|
274
|
+
}),
|
|
275
|
+
HostedToolItem,
|
|
276
|
+
HostedToolReplay,
|
|
277
|
+
])
|
|
278
|
+
type OpenResponsesInputItem = Schema.Schema.Type<typeof InputItem>
|
|
279
|
+
|
|
280
|
+
// Mutable counterpart of the schema reasoning item so `lowerMessages` can fold
|
|
281
|
+
// multiple streamed summary parts into the same item before flushing.
|
|
282
|
+
type OpenResponsesReasoningInput = {
|
|
283
|
+
type: "reasoning"
|
|
284
|
+
id?: string
|
|
285
|
+
summary: Array<{ type: "summary_text"; text: string }>
|
|
286
|
+
encrypted_content?: string | null
|
|
287
|
+
}
|
|
288
|
+
export const ToolChoice = Schema.Union([
|
|
289
|
+
Schema.Literals(["auto", "none", "required"]),
|
|
290
|
+
NamedTool,
|
|
291
|
+
Schema.Struct({
|
|
292
|
+
type: Schema.tag("allowed_tools"),
|
|
293
|
+
mode: Schema.Literals(["auto", "none", "required"]),
|
|
294
|
+
tools: Schema.Array(NamedTool),
|
|
295
|
+
}),
|
|
296
|
+
])
|
|
297
|
+
|
|
298
|
+
// Fields shared between the HTTP body and the WebSocket `response.create`
|
|
299
|
+
// message. The HTTP body adds `stream: true`; the WebSocket message adds
|
|
300
|
+
// `type: "response.create"`. Defining the shared shape once keeps the two
|
|
301
|
+
// transports in sync without a destructure-and-strip dance.
|
|
302
|
+
export const coreFields = {
|
|
303
|
+
model: Schema.String,
|
|
304
|
+
input: Schema.Array(InputItem),
|
|
305
|
+
instructions: Schema.optional(Schema.String),
|
|
306
|
+
tools: optionalArray(Schema.Union([Tool, CustomTool, HostedTool])),
|
|
307
|
+
tool_choice: Schema.optional(ToolChoice),
|
|
308
|
+
store: Schema.optional(Schema.Boolean),
|
|
309
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
310
|
+
safety_identifier: Schema.optional(Schema.String),
|
|
311
|
+
stream_options: Schema.optional(
|
|
312
|
+
Schema.Struct({
|
|
313
|
+
include_obfuscation: Schema.optional(Schema.Boolean),
|
|
314
|
+
}),
|
|
315
|
+
),
|
|
316
|
+
top_logprobs: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 20 }))),
|
|
317
|
+
truncation: Schema.optional(OpenResponsesOptions.TruncationSchema),
|
|
318
|
+
service_tier: Schema.optional(OpenResponsesOptions.ServiceTierSchema),
|
|
319
|
+
prompt_cache_key: Schema.optional(Schema.String),
|
|
320
|
+
include: optionalArray(OpenResponsesOptions.ResponseIncludableSchema),
|
|
321
|
+
reasoning: Schema.optional(
|
|
322
|
+
Schema.Struct({
|
|
323
|
+
effort: Schema.optional(OpenResponsesOptions.ReasoningEffort),
|
|
324
|
+
summary: Schema.optional(Schema.Literals(["auto", "concise", "detailed"])),
|
|
325
|
+
}),
|
|
326
|
+
),
|
|
327
|
+
text: Schema.optional(
|
|
328
|
+
Schema.Struct({
|
|
329
|
+
verbosity: Schema.optional(OpenResponsesOptions.TextVerbositySchema),
|
|
330
|
+
}),
|
|
331
|
+
),
|
|
332
|
+
max_output_tokens: Schema.optional(Schema.Number),
|
|
333
|
+
max_tool_calls: Schema.optional(Schema.Int),
|
|
334
|
+
parallel_tool_calls: Schema.optional(Schema.Boolean),
|
|
335
|
+
temperature: Schema.optional(Schema.Number),
|
|
336
|
+
top_p: Schema.optional(Schema.Number),
|
|
337
|
+
presence_penalty: Schema.optional(Schema.Number),
|
|
338
|
+
frequency_penalty: Schema.optional(Schema.Number),
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export const OpenResponsesBody = Schema.Struct({
|
|
342
|
+
...coreFields,
|
|
343
|
+
stream: Schema.Literal(true),
|
|
344
|
+
})
|
|
345
|
+
export type OpenResponsesBody = Schema.Schema.Type<typeof OpenResponsesBody>
|
|
346
|
+
|
|
347
|
+
export const OpenResponsesUsage = Schema.StructWithRest(
|
|
348
|
+
Schema.Struct({
|
|
349
|
+
input_tokens: lenient(Schema.Number),
|
|
350
|
+
input_tokens_details: optionalNull(
|
|
351
|
+
Schema.StructWithRest(
|
|
352
|
+
Schema.Struct({
|
|
353
|
+
cached_tokens: lenient(Schema.Number),
|
|
354
|
+
cache_write_tokens: lenient(Schema.Number),
|
|
355
|
+
}),
|
|
356
|
+
[JsonObject],
|
|
357
|
+
),
|
|
358
|
+
),
|
|
359
|
+
output_tokens: lenient(Schema.Number),
|
|
360
|
+
output_tokens_details: optionalNull(
|
|
361
|
+
Schema.StructWithRest(Schema.Struct({ reasoning_tokens: lenient(Schema.Number) }), [JsonObject]),
|
|
362
|
+
),
|
|
363
|
+
total_tokens: lenient(Schema.Number),
|
|
364
|
+
}),
|
|
365
|
+
[JsonObject],
|
|
366
|
+
)
|
|
367
|
+
type OpenResponsesUsage = Schema.Schema.Type<typeof OpenResponsesUsage>
|
|
368
|
+
|
|
369
|
+
// The spec requires `id` on every output item, but some gateways drop it from
|
|
370
|
+
// later item events (Bedrock Mantle renames it to `item_id` on
|
|
371
|
+
// `output_item.done` and `response.completed.output`). Decode it as optional
|
|
372
|
+
// and let `normalize` recover or mint it once before the parser runs.
|
|
373
|
+
// https://www.openresponses.org/specification#extending-items
|
|
374
|
+
export const StreamItem = Schema.StructWithRest(
|
|
375
|
+
Schema.Struct({
|
|
376
|
+
type: Schema.String,
|
|
377
|
+
id: optionalNullish(Schema.String),
|
|
378
|
+
call_id: optionalNullish(Schema.String),
|
|
379
|
+
name: optionalNullish(Schema.String),
|
|
380
|
+
namespace: optionalNullish(Schema.String),
|
|
381
|
+
arguments: optionalNullish(Schema.String),
|
|
382
|
+
encrypted_content: optionalNull(Schema.String),
|
|
383
|
+
}),
|
|
384
|
+
[Schema.Record(Schema.String, Schema.Unknown)],
|
|
385
|
+
)
|
|
386
|
+
export type StreamItem = Schema.Schema.Type<typeof StreamItem>
|
|
387
|
+
export type OutputItem = StreamItem & { readonly id: string }
|
|
388
|
+
|
|
389
|
+
// Responses-compatible providers put error details at the top level, under `error`, or under
|
|
390
|
+
// `response.error`, and gateways reshape them freely: strings, numeric codes, extra fields. Those
|
|
391
|
+
// fields decode as opaque values and `errorDetail` reads them defensively, so an error frame can
|
|
392
|
+
// only fail on invalid JSON and otherwise always classifies with the raw body as the fallback.
|
|
393
|
+
// https://www.openresponses.org/specification
|
|
394
|
+
const asText = (value: unknown) =>
|
|
395
|
+
typeof value === "string" && value.length > 0 ? value : typeof value === "number" ? String(value) : undefined
|
|
396
|
+
|
|
397
|
+
const TypedEvent = Schema.StructWithRest(
|
|
398
|
+
Schema.Struct({
|
|
399
|
+
type: Schema.String,
|
|
400
|
+
delta: optionalNullish(Schema.String),
|
|
401
|
+
arguments: optionalNullish(Schema.String),
|
|
402
|
+
text: optionalNullish(Schema.String),
|
|
403
|
+
// Kept strict: item-scoped events always carry an id, so null means a broken stream.
|
|
404
|
+
item_id: Schema.optional(Schema.String),
|
|
405
|
+
output_index: optionalNullish(Schema.Number),
|
|
406
|
+
summary_index: optionalNullish(Schema.Number),
|
|
407
|
+
// OutputItemAdded/Done permit a null item in the Open Responses OpenAPI schema.
|
|
408
|
+
item: optionalNull(StreamItem),
|
|
409
|
+
response: optionalNullish(
|
|
410
|
+
Schema.StructWithRest(
|
|
411
|
+
Schema.Struct({
|
|
412
|
+
id: optionalNullish(Schema.String),
|
|
413
|
+
service_tier: optionalNull(Schema.String),
|
|
414
|
+
incomplete_details: optionalNull(Schema.Struct({ reason: optionalNullish(Schema.String) })),
|
|
415
|
+
output: optionalNullish(Schema.Array(StreamItem)),
|
|
416
|
+
usage: optionalNull(OpenResponsesUsage),
|
|
417
|
+
error: Schema.optional(Schema.Unknown),
|
|
418
|
+
}),
|
|
419
|
+
[Schema.Record(Schema.String, Schema.Unknown)],
|
|
420
|
+
),
|
|
421
|
+
),
|
|
422
|
+
code: Schema.optional(Schema.Unknown),
|
|
423
|
+
message: Schema.optional(Schema.Unknown),
|
|
424
|
+
error: Schema.optional(Schema.Unknown),
|
|
425
|
+
status: Schema.optional(Schema.Unknown),
|
|
426
|
+
status_code: Schema.optional(Schema.Unknown),
|
|
427
|
+
}),
|
|
428
|
+
[Schema.Record(Schema.String, Schema.Unknown)],
|
|
429
|
+
)
|
|
430
|
+
export const Event = withUntypedFrames(TypedEvent)
|
|
431
|
+
export type Event = Schema.Schema.Type<typeof Event>
|
|
432
|
+
export type NormalizedEvent = Event & { readonly item?: OutputItem | null }
|
|
433
|
+
|
|
434
|
+
/** Decodes one WebSocket frame. */
|
|
435
|
+
export const decodeChannelEvent = Schema.decodeUnknownEffect(Protocol.jsonEvent(Event))
|
|
436
|
+
|
|
437
|
+
export interface ProviderAdapter {
|
|
438
|
+
readonly id: string
|
|
439
|
+
readonly name: string
|
|
440
|
+
readonly nativeTool?: (native: NonNullable<ToolDefinition["native"]>) => Effect.Effect<HostedTool, AIError>
|
|
441
|
+
readonly lowerMedia?: (input: {
|
|
442
|
+
readonly part: MediaPart
|
|
443
|
+
readonly media: Media.Inline | undefined
|
|
444
|
+
readonly request: LLMRequest
|
|
445
|
+
}) => MediaInput | undefined
|
|
446
|
+
readonly restoreHostedToolItem?: (item: unknown) => HostedToolReplayItem | undefined
|
|
447
|
+
/** Lowers a `Message.tools(...)` marker sent in place; routes without it must fold tool updates. */
|
|
448
|
+
readonly lowerToolChanges?: (changes: ToolChanges) => Effect.Effect<ReadonlyArray<OpenResponsesInputItem>, AIError>
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const BASE_ADAPTER: ProviderAdapter = { id: ADAPTER, name: NAME }
|
|
452
|
+
|
|
453
|
+
export interface ParserState {
|
|
454
|
+
readonly provider: LLMRequest["model"]["provider"]
|
|
455
|
+
readonly completedCompactions: ReadonlySet<string>
|
|
456
|
+
readonly id: string
|
|
457
|
+
readonly name: string
|
|
458
|
+
readonly providerMetadataKey: string
|
|
459
|
+
readonly tools: ToolStream.State<string>
|
|
460
|
+
readonly custom: ReadonlyMap<string, OpenAIFreeform.Custom>
|
|
461
|
+
readonly hasFunctionCall: boolean
|
|
462
|
+
readonly lifecycle: Lifecycle.State
|
|
463
|
+
readonly outputItems: Readonly<Record<number, string>>
|
|
464
|
+
readonly message: { readonly id: string; readonly phase: MessagePhase | null | undefined } | undefined
|
|
465
|
+
readonly reasoningItems: Readonly<Record<string, ReasoningStreamItem>>
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
type ReasoningSummaryStatus = "active" | "can-conclude" | "concluded"
|
|
469
|
+
|
|
470
|
+
interface ReasoningStreamItem {
|
|
471
|
+
readonly encryptedContent: string | null | undefined
|
|
472
|
+
// Keyed by the wire protocol's numeric `summary_index`. JS object keys coerce to
|
|
473
|
+
// strings, but typing the map as `Record<number, ...>` documents intent
|
|
474
|
+
// and matches the wire field.
|
|
475
|
+
readonly summaryParts: Readonly<Record<number, ReasoningSummaryStatus>>
|
|
476
|
+
// Summary indexes that received at least one streamed delta. The `:0` block
|
|
477
|
+
// is started eagerly when the item opens, so block existence cannot tell
|
|
478
|
+
// whether a `.done` final would duplicate streamed text.
|
|
479
|
+
readonly deltaIndexes: ReadonlySet<number>
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// =============================================================================
|
|
483
|
+
// Request Lowering
|
|
484
|
+
// =============================================================================
|
|
485
|
+
export const lowerTool = Effect.fnUntraced(function* (protocolName: string, tool: ToolDefinition) {
|
|
486
|
+
if (tool.native !== undefined)
|
|
487
|
+
return yield* ProviderShared.invalidRequest(`${protocolName} does not support provider-native tool ${tool.name}`)
|
|
488
|
+
return {
|
|
489
|
+
type: "function" as const,
|
|
490
|
+
name: tool.name,
|
|
491
|
+
description: tool.description,
|
|
492
|
+
parameters: tool.inputSchema,
|
|
493
|
+
// The common tool definition does not currently express Responses strict-schema policy.
|
|
494
|
+
strict: false,
|
|
495
|
+
}
|
|
496
|
+
})
|
|
497
|
+
|
|
498
|
+
export const lowerCustomTool = (tool: ToolDefinition, custom: OpenAIFreeform.Custom) => {
|
|
499
|
+
const grammar = OpenAIFreeform.grammar(custom)
|
|
500
|
+
return {
|
|
501
|
+
type: "custom" as const,
|
|
502
|
+
name: tool.name,
|
|
503
|
+
description: OpenAIFreeform.description(tool, custom),
|
|
504
|
+
format: grammar ? { type: "grammar" as const, ...grammar } : { type: "text" as const },
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
export const lowerTools = (
|
|
509
|
+
tools: ReadonlyArray<ToolDefinition>,
|
|
510
|
+
adapter: ProviderAdapter,
|
|
511
|
+
custom: ReadonlyMap<string, OpenAIFreeform.Custom>,
|
|
512
|
+
) =>
|
|
513
|
+
Effect.forEach(
|
|
514
|
+
tools,
|
|
515
|
+
(tool): Effect.Effect<Schema.Schema.Type<typeof Tool | typeof CustomTool> | HostedTool, AIError> => {
|
|
516
|
+
if (tool.native !== undefined && adapter.nativeTool) return adapter.nativeTool(tool.native)
|
|
517
|
+
const definition = custom.get(tool.name)
|
|
518
|
+
return definition ? Effect.succeed(lowerCustomTool(tool, definition)) : lowerTool(adapter.name, tool)
|
|
519
|
+
},
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
export const namedTool = (name: string, custom: ReadonlyMap<string, OpenAIFreeform.Custom>) => ({
|
|
523
|
+
type: custom.has(name) ? ("custom" as const) : ("function" as const),
|
|
524
|
+
name,
|
|
525
|
+
})
|
|
526
|
+
|
|
527
|
+
export const lowerToolChoice = (
|
|
528
|
+
protocolName: string,
|
|
529
|
+
toolChoice: NonNullable<LLMRequest["toolChoice"]>,
|
|
530
|
+
custom: ReadonlyMap<string, OpenAIFreeform.Custom>,
|
|
531
|
+
) =>
|
|
532
|
+
ProviderShared.matchToolChoice(protocolName, toolChoice, {
|
|
533
|
+
auto: () => "auto" as const,
|
|
534
|
+
none: () => "none" as const,
|
|
535
|
+
required: () => "required" as const,
|
|
536
|
+
tool: (toolName) => namedTool(toolName, custom),
|
|
537
|
+
})
|
|
538
|
+
|
|
539
|
+
// Server-issued item ids need a nonempty prefix and suffix, but the prefix is
|
|
540
|
+
// provider-defined and does not necessarily identify the item's semantic type.
|
|
541
|
+
const itemID = (providerMetadata: ProviderMetadata | undefined, providerMetadataKey: string) => {
|
|
542
|
+
const metadata = providerMetadata?.[providerMetadataKey]
|
|
543
|
+
if (!metadata || typeof metadata.itemId !== "string") return undefined
|
|
544
|
+
const separator = metadata.itemId.indexOf("_")
|
|
545
|
+
return separator > 0 && separator < metadata.itemId.length - 1 ? metadata.itemId : undefined
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// A call replays as the type its tool is declared with now; the item id only survives when that type is unchanged.
|
|
549
|
+
const lowerToolCall = (
|
|
550
|
+
part: ToolCallPart,
|
|
551
|
+
providerMetadataKey: string,
|
|
552
|
+
custom: OpenAIFreeform.Custom | undefined,
|
|
553
|
+
): OpenResponsesInputItem => {
|
|
554
|
+
const id = OpenAIFreeform.keepsItemID(part.providerMetadata, providerMetadataKey, custom !== undefined)
|
|
555
|
+
? itemID(part.providerMetadata, providerMetadataKey)
|
|
556
|
+
: undefined
|
|
557
|
+
if (custom)
|
|
558
|
+
return {
|
|
559
|
+
type: "custom_tool_call",
|
|
560
|
+
...(id === undefined ? {} : { id }),
|
|
561
|
+
call_id: part.id,
|
|
562
|
+
name: part.name,
|
|
563
|
+
input: OpenAIFreeform.toRaw(custom, part.input, part.providerMetadata?.[providerMetadataKey]?.header),
|
|
564
|
+
}
|
|
565
|
+
return {
|
|
566
|
+
type: "function_call",
|
|
567
|
+
...(id === undefined ? {} : { id }),
|
|
568
|
+
call_id: part.id,
|
|
569
|
+
name: part.name,
|
|
570
|
+
namespace: part.namespace,
|
|
571
|
+
arguments: ProviderShared.encodeJson(part.input === undefined ? {} : part.input),
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
const lowerReasoning = (part: ReasoningPart, providerMetadataKey: string): OpenResponsesReasoningInput | undefined => {
|
|
576
|
+
const metadata = part.providerMetadata?.[providerMetadataKey]
|
|
577
|
+
if (!metadata) return undefined
|
|
578
|
+
const id = itemID(part.providerMetadata, providerMetadataKey)
|
|
579
|
+
const encryptedContent =
|
|
580
|
+
typeof metadata.reasoningEncryptedContent === "string" || metadata.reasoningEncryptedContent === null
|
|
581
|
+
? metadata.reasoningEncryptedContent
|
|
582
|
+
: undefined
|
|
583
|
+
if (part.text.length === 0 && !encryptedContent) return undefined
|
|
584
|
+
return {
|
|
585
|
+
type: "reasoning",
|
|
586
|
+
...(id === undefined ? {} : { id }),
|
|
587
|
+
summary: part.text.length > 0 ? [{ type: "summary_text", text: part.text }] : [],
|
|
588
|
+
encrypted_content: encryptedContent,
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
const decodeImageDetail = ProviderShared.validateWith(Schema.decodeUnknownEffect(OpenResponsesInputImage.fields.detail))
|
|
593
|
+
const decodeMessageMetadata = ProviderShared.validateWith(Schema.decodeUnknownEffect(MessageMetadata))
|
|
594
|
+
|
|
595
|
+
const lowerMedia = Effect.fnUntraced(function* (part: MediaPart, request: LLMRequest, adapter: ProviderAdapter) {
|
|
596
|
+
const media = part.media.inline()
|
|
597
|
+
const providerMedia = adapter.lowerMedia?.({ part, media, request })
|
|
598
|
+
if (providerMedia) return providerMedia
|
|
599
|
+
const rawDetail = part.providerMetadata?.[metadataKey(request.model)]?.detail
|
|
600
|
+
const detail = rawDetail === undefined ? undefined : yield* decodeImageDetail(rawDetail)
|
|
601
|
+
const mime = part.media.mediaType.toLowerCase()
|
|
602
|
+
const url = ProviderShared.mediaUrl(part.media)
|
|
603
|
+
const location = url ?? (yield* ProviderShared.requireInlineMedia(adapter.name, part.media)).dataUrl
|
|
604
|
+
if (part.media.kind !== "image") {
|
|
605
|
+
if (part.media.kind === "video") return { type: "input_video" as const, video_url: location }
|
|
606
|
+
if (url) return { type: "input_file" as const, file_url: url, detail }
|
|
607
|
+
return {
|
|
608
|
+
type: "input_file" as const,
|
|
609
|
+
filename: part.filename ?? (mime === "application/pdf" ? "document.pdf" : "file"),
|
|
610
|
+
detail,
|
|
611
|
+
file_data: location,
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
return {
|
|
615
|
+
type: "input_image" as const,
|
|
616
|
+
image_url: location,
|
|
617
|
+
detail,
|
|
618
|
+
}
|
|
619
|
+
})
|
|
620
|
+
|
|
621
|
+
const lowerUserContent = Effect.fnUntraced(function* (
|
|
622
|
+
part: UserMessage["content"][number],
|
|
623
|
+
request: LLMRequest,
|
|
624
|
+
adapter: ProviderAdapter,
|
|
625
|
+
) {
|
|
626
|
+
if (part.type === "text") return { type: "input_text" as const, text: part.text }
|
|
627
|
+
return yield* lowerMedia(part, request, adapter)
|
|
628
|
+
})
|
|
629
|
+
|
|
630
|
+
// Tool results may carry structured text, images, and files. Keep media as provider-native
|
|
631
|
+
// content instead of JSON-stringifying base64 into a prompt string.
|
|
632
|
+
const lowerToolResultContentItem = Effect.fnUntraced(function* (
|
|
633
|
+
item: Content,
|
|
634
|
+
request: LLMRequest,
|
|
635
|
+
adapter: ProviderAdapter,
|
|
636
|
+
) {
|
|
637
|
+
if (item.type === "text") return { type: "input_text" as const, text: item.text }
|
|
638
|
+
return yield* lowerMedia(ProviderShared.toolFileMedia(item), request, adapter)
|
|
639
|
+
})
|
|
640
|
+
|
|
641
|
+
const lowerToolResultOutput = Effect.fnUntraced(function* (
|
|
642
|
+
part: ToolResultPart,
|
|
643
|
+
request: LLMRequest,
|
|
644
|
+
adapter: ProviderAdapter,
|
|
645
|
+
) {
|
|
646
|
+
// Text/json/error results are encoded as a plain string for backward
|
|
647
|
+
// compatibility with existing cassettes and provider expectations.
|
|
648
|
+
if (part.result.type !== "content") return ProviderShared.toolResultText(part)
|
|
649
|
+
// Preserve the narrowed array element type when compiled through a consumer package.
|
|
650
|
+
const content: ReadonlyArray<Content> = part.result.value
|
|
651
|
+
return yield* Effect.forEach(content, (item) => lowerToolResultContentItem(item, request, adapter))
|
|
652
|
+
})
|
|
653
|
+
|
|
654
|
+
const DEFAULT_EFFORT = "medium"
|
|
655
|
+
|
|
656
|
+
export const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, adapter: ProviderAdapter) {
|
|
657
|
+
const input: OpenResponsesInputItem[] = []
|
|
658
|
+
const providerMetadataKey = metadataKey(request.model)
|
|
659
|
+
const custom = OpenAIFreeform.tools(request)
|
|
660
|
+
const customTool = (part: ToolCallPart | ToolResultPart) =>
|
|
661
|
+
part.namespace === undefined ? custom.get(part.name) : undefined
|
|
662
|
+
|
|
663
|
+
for (const message of request.messages) {
|
|
664
|
+
const rawMetadata =
|
|
665
|
+
message.role === "user" || message.role === "assistant"
|
|
666
|
+
? message.providerMetadata?.[providerMetadataKey]
|
|
667
|
+
: undefined
|
|
668
|
+
const metadata = rawMetadata === undefined ? undefined : yield* decodeMessageMetadata(rawMetadata)
|
|
669
|
+
if (message.role === "system") {
|
|
670
|
+
const update = effortUpdate(message)
|
|
671
|
+
if (update) {
|
|
672
|
+
// Consecutive updates are rejected, so a newer one replaces its predecessor.
|
|
673
|
+
const last = input.at(-1)
|
|
674
|
+
if (last !== undefined && "type" in last && last.type === "configuration_update") input.pop()
|
|
675
|
+
input.push({ type: "configuration_update", reasoning: { effort: update.effort ?? DEFAULT_EFFORT } })
|
|
676
|
+
continue
|
|
677
|
+
}
|
|
678
|
+
// Planning folds every marker on routes whose protocol has no `toolUpdates`, so only adapters with
|
|
679
|
+
// `lowerToolChanges` see one.
|
|
680
|
+
const tools = toolsUpdate(message)
|
|
681
|
+
if (tools && adapter.lowerToolChanges) {
|
|
682
|
+
input.push(...(yield* adapter.lowerToolChanges(tools)))
|
|
683
|
+
if (message.content.length === 0) continue
|
|
684
|
+
}
|
|
685
|
+
input.push({
|
|
686
|
+
type: "message",
|
|
687
|
+
role: "developer",
|
|
688
|
+
content: ProviderShared.joinText(yield* ProviderShared.systemUpdateText(adapter.name, message)),
|
|
689
|
+
})
|
|
690
|
+
continue
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
if (message.role === "user") {
|
|
694
|
+
const content = yield* Effect.forEach(message.content, (part) => lowerUserContent(part, request, adapter))
|
|
695
|
+
if (content.length > 0)
|
|
696
|
+
input.push({ type: "message", role: "user", content, id: metadata?.itemId, status: metadata?.status })
|
|
697
|
+
continue
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
if (message.role === "assistant") {
|
|
701
|
+
const content: TextPart[] = []
|
|
702
|
+
const reasoningItems: Record<string, OpenResponsesReasoningInput> = {}
|
|
703
|
+
const hostedToolItems = new Set<string>()
|
|
704
|
+
const flushText = () => {
|
|
705
|
+
if (content.length === 0) return
|
|
706
|
+
const groups = content.reduce<
|
|
707
|
+
Array<{ id: string | undefined; phase: MessagePhase | null | undefined; parts: TextPart[] }>
|
|
708
|
+
>((groups, part) => {
|
|
709
|
+
const partMetadata = part.providerMetadata?.[providerMetadataKey]
|
|
710
|
+
const id = itemID(part.providerMetadata, providerMetadataKey) ?? metadata?.itemId
|
|
711
|
+
const partPhase = messagePhase(partMetadata?.phase)
|
|
712
|
+
const phase = partPhase === undefined ? metadata?.phase : partPhase
|
|
713
|
+
const group = groups.at(-1)
|
|
714
|
+
if (group && group.id === id && group.phase === phase) group.parts.push(part)
|
|
715
|
+
else groups.push({ id, phase, parts: [part] })
|
|
716
|
+
return groups
|
|
717
|
+
}, [])
|
|
718
|
+
input.push(
|
|
719
|
+
...groups.map((group) => ({
|
|
720
|
+
type: "message" as const,
|
|
721
|
+
...(group.id === undefined ? {} : { id: group.id }),
|
|
722
|
+
role: "assistant" as const,
|
|
723
|
+
// Replayed text is a finished input item, even if generation was cut short.
|
|
724
|
+
status: "completed",
|
|
725
|
+
content: group.parts.map((part) => ({ type: "output_text" as const, text: part.text })),
|
|
726
|
+
...(group.phase === undefined ? {} : { phase: group.phase }),
|
|
727
|
+
})),
|
|
728
|
+
)
|
|
729
|
+
content.splice(0, content.length)
|
|
730
|
+
}
|
|
731
|
+
for (const part of message.content) {
|
|
732
|
+
if (part.type === "compaction") {
|
|
733
|
+
flushText()
|
|
734
|
+
if (part.provider !== request.model.provider || part.encrypted === undefined)
|
|
735
|
+
return yield* ProviderShared.invalidRequest(
|
|
736
|
+
"Compaction state must be replayed to its originating provider and API",
|
|
737
|
+
)
|
|
738
|
+
input.push({ type: "compaction", id: part.id, encrypted_content: part.encrypted })
|
|
739
|
+
continue
|
|
740
|
+
}
|
|
741
|
+
if (part.type === "text") {
|
|
742
|
+
content.push(part)
|
|
743
|
+
continue
|
|
744
|
+
}
|
|
745
|
+
if (part.type === "reasoning") {
|
|
746
|
+
flushText()
|
|
747
|
+
const reasoning = lowerReasoning(part, providerMetadataKey)
|
|
748
|
+
if (!reasoning) continue
|
|
749
|
+
const existing = reasoning.id === undefined ? undefined : reasoningItems[reasoning.id]
|
|
750
|
+
if (existing) {
|
|
751
|
+
existing.summary.push(...reasoning.summary)
|
|
752
|
+
if (typeof reasoning.encrypted_content === "string")
|
|
753
|
+
existing.encrypted_content = reasoning.encrypted_content
|
|
754
|
+
continue
|
|
755
|
+
}
|
|
756
|
+
if (reasoning.id !== undefined) reasoningItems[reasoning.id] = reasoning
|
|
757
|
+
input.push(reasoning)
|
|
758
|
+
continue
|
|
759
|
+
}
|
|
760
|
+
if (part.type === "tool-call") {
|
|
761
|
+
flushText()
|
|
762
|
+
if (part.providerExecuted === true) continue
|
|
763
|
+
input.push(lowerToolCall(part, providerMetadataKey, customTool(part)))
|
|
764
|
+
continue
|
|
765
|
+
}
|
|
766
|
+
if (part.type === "tool-result" && part.providerExecuted === true) {
|
|
767
|
+
flushText()
|
|
768
|
+
const id = itemID(part.providerMetadata, providerMetadataKey)
|
|
769
|
+
const hosted =
|
|
770
|
+
part.result.type !== "json"
|
|
771
|
+
? undefined
|
|
772
|
+
: Schema.is(HostedToolItem)(part.result.value)
|
|
773
|
+
? part.result.value
|
|
774
|
+
: adapter.restoreHostedToolItem?.(part.result.value)
|
|
775
|
+
if (id !== undefined && hosted?.id === id) {
|
|
776
|
+
if (!hostedToolItems.has(id)) {
|
|
777
|
+
input.push(hosted)
|
|
778
|
+
hostedToolItems.add(id)
|
|
779
|
+
}
|
|
780
|
+
continue
|
|
781
|
+
}
|
|
782
|
+
const content: ReadonlyArray<Content> =
|
|
783
|
+
part.result.type === "content"
|
|
784
|
+
? part.result.value
|
|
785
|
+
: [{ type: "text", text: ProviderShared.toolResultText(part) }]
|
|
786
|
+
input.push({
|
|
787
|
+
type: "message",
|
|
788
|
+
role: "user",
|
|
789
|
+
content: yield* Effect.forEach(content, (item) => lowerToolResultContentItem(item, request, adapter)),
|
|
790
|
+
})
|
|
791
|
+
continue
|
|
792
|
+
}
|
|
793
|
+
if (part.type === "media") {
|
|
794
|
+
flushText()
|
|
795
|
+
// Responses has no assistant-authored image item; replay generated media (e.g. from Gemini) as user input.
|
|
796
|
+
input.push({
|
|
797
|
+
type: "message",
|
|
798
|
+
role: "user",
|
|
799
|
+
content: [yield* lowerMedia(part, request, adapter)],
|
|
800
|
+
})
|
|
801
|
+
continue
|
|
802
|
+
}
|
|
803
|
+
return yield* ProviderShared.unsupportedContent(adapter.name, "assistant", [
|
|
804
|
+
"text",
|
|
805
|
+
"reasoning",
|
|
806
|
+
"tool-call",
|
|
807
|
+
"tool-result",
|
|
808
|
+
"media",
|
|
809
|
+
])
|
|
810
|
+
}
|
|
811
|
+
flushText()
|
|
812
|
+
continue
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
for (const part of message.content) {
|
|
816
|
+
input.push({
|
|
817
|
+
type: customTool(part) ? "custom_tool_call_output" : "function_call_output",
|
|
818
|
+
call_id: part.id,
|
|
819
|
+
output: yield* lowerToolResultOutput(part, request, adapter),
|
|
820
|
+
})
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
return input
|
|
825
|
+
})
|
|
826
|
+
|
|
827
|
+
// The system prompt leads `input` as a developer message: GPT-6.2 models never cache top-level `instructions`.
|
|
828
|
+
export const lowerConversation = Effect.fnUntraced(function* (request: LLMRequest, adapter: ProviderAdapter) {
|
|
829
|
+
const system = ProviderShared.joinText(request.system)
|
|
830
|
+
return {
|
|
831
|
+
model: request.model.id,
|
|
832
|
+
input: [
|
|
833
|
+
...(system ? [{ type: "message" as const, role: "developer" as const, content: system }] : []),
|
|
834
|
+
...(yield* lowerMessages(request, adapter)),
|
|
835
|
+
],
|
|
836
|
+
}
|
|
837
|
+
})
|
|
838
|
+
|
|
839
|
+
export const lowerGeneration = (request: LLMRequest, options = OpenResponsesOptions.resolve(request)) => {
|
|
840
|
+
const cacheKey = ProviderShared.promptCacheKey(request)
|
|
841
|
+
const parallelToolCalls = resolveParallelToolCalls(request, options)
|
|
842
|
+
return {
|
|
843
|
+
stream: true as const,
|
|
844
|
+
max_output_tokens: request.maxTokens,
|
|
845
|
+
temperature: request.temperature,
|
|
846
|
+
top_p: request.topP,
|
|
847
|
+
presence_penalty: request.presencePenalty,
|
|
848
|
+
frequency_penalty: request.frequencyPenalty,
|
|
849
|
+
...(options.store !== undefined ? { store: options.store } : {}),
|
|
850
|
+
...(options.metadata ? { metadata: options.metadata } : {}),
|
|
851
|
+
...(options.safetyIdentifier ? { safety_identifier: options.safetyIdentifier } : {}),
|
|
852
|
+
...(options.streamOptions?.includeObfuscation !== undefined
|
|
853
|
+
? { stream_options: { include_obfuscation: options.streamOptions.includeObfuscation } }
|
|
854
|
+
: {}),
|
|
855
|
+
...(options.topLogprobs !== undefined ? { top_logprobs: options.topLogprobs } : {}),
|
|
856
|
+
...(cacheKey ? { prompt_cache_key: cacheKey } : {}),
|
|
857
|
+
...(options.include ? { include: options.include } : {}),
|
|
858
|
+
...(options.reasoningEffort || options.reasoningSummary
|
|
859
|
+
? { reasoning: { effort: options.reasoningEffort, summary: options.reasoningSummary } }
|
|
860
|
+
: {}),
|
|
861
|
+
...(options.textVerbosity ? { text: { verbosity: options.textVerbosity } } : {}),
|
|
862
|
+
...(options.serviceTier ? { service_tier: options.serviceTier } : {}),
|
|
863
|
+
...(options.maxToolCalls !== undefined ? { max_tool_calls: options.maxToolCalls } : {}),
|
|
864
|
+
...(parallelToolCalls !== undefined ? { parallel_tool_calls: parallelToolCalls } : {}),
|
|
865
|
+
...(options.truncation ? { truncation: options.truncation } : {}),
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
export const resolveParallelToolCalls = (request: LLMRequest, options = OpenResponsesOptions.resolve(request)) => {
|
|
870
|
+
const configured = options.parallelToolCalls
|
|
871
|
+
if (configured !== undefined) return configured
|
|
872
|
+
const disabled = request.toolChoice?.disableParallelToolUse
|
|
873
|
+
return disabled === undefined ? undefined : !disabled
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
export const allowedToolChoice = (
|
|
877
|
+
options: OpenResponsesOptions.Resolved,
|
|
878
|
+
custom: ReadonlyMap<string, OpenAIFreeform.Custom>,
|
|
879
|
+
) => {
|
|
880
|
+
const allowed = options.allowedTools
|
|
881
|
+
if (!allowed) return undefined
|
|
882
|
+
return {
|
|
883
|
+
type: "allowed_tools" as const,
|
|
884
|
+
mode: allowed.mode,
|
|
885
|
+
tools: allowed.toolNames.map((name) => namedTool(name, custom)),
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
|
|
890
|
+
export const fromRequestWithAdapter = Effect.fn("OpenResponses.fromRequestWithAdapter")(function* (
|
|
891
|
+
request: LLMRequest,
|
|
892
|
+
adapter: ProviderAdapter,
|
|
893
|
+
) {
|
|
894
|
+
const definitions = ProviderShared.flattenTools(request.tools)
|
|
895
|
+
const options = OpenResponsesOptions.resolve(request)
|
|
896
|
+
const custom = OpenAIFreeform.tools(request)
|
|
897
|
+
return {
|
|
898
|
+
...(yield* lowerConversation(request, adapter)),
|
|
899
|
+
...lowerGeneration(request, options),
|
|
900
|
+
tools: definitions.length === 0 ? undefined : yield* lowerTools(definitions, adapter, custom),
|
|
901
|
+
tool_choice:
|
|
902
|
+
allowedToolChoice(options, custom) ??
|
|
903
|
+
(request.toolChoice ? yield* lowerToolChoice(adapter.name, request.toolChoice, custom) : undefined),
|
|
904
|
+
}
|
|
905
|
+
})
|
|
906
|
+
|
|
907
|
+
/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
|
|
908
|
+
export const fromRequest = (request: LLMRequest) => fromRequestWithAdapter(request, BASE_ADAPTER)
|
|
909
|
+
|
|
910
|
+
// =============================================================================
|
|
911
|
+
// Stream Parsing
|
|
912
|
+
// =============================================================================
|
|
913
|
+
// Responses APIs report `input_tokens` (inclusive total) with a
|
|
914
|
+
// cached-read and cache-write subsets, and `output_tokens` (inclusive total)
|
|
915
|
+
// with a `reasoning_tokens` subset. Pass the totals through and derive the
|
|
916
|
+
// non-cached breakdown.
|
|
917
|
+
export const mapUsage = (
|
|
918
|
+
usage: OpenResponsesUsage | null | undefined,
|
|
919
|
+
providerMetadataKey: string,
|
|
920
|
+
...frames: ReadonlyArray<unknown>
|
|
921
|
+
) => {
|
|
922
|
+
if (!usage) return undefined
|
|
923
|
+
const cached = usage.input_tokens_details?.cached_tokens
|
|
924
|
+
const cacheWrite = usage.input_tokens_details?.cache_write_tokens
|
|
925
|
+
const reasoning = usage.output_tokens_details?.reasoning_tokens
|
|
926
|
+
const nonCached = ProviderShared.subtractTokens(usage.input_tokens, ProviderShared.sumTokens(cached, cacheWrite))
|
|
927
|
+
return new Usage({
|
|
928
|
+
inputTokens: usage.input_tokens,
|
|
929
|
+
outputTokens: usage.output_tokens,
|
|
930
|
+
nonCachedInputTokens: nonCached,
|
|
931
|
+
cacheReadInputTokens: cached,
|
|
932
|
+
cacheWriteInputTokens: cacheWrite,
|
|
933
|
+
reasoningTokens: reasoning,
|
|
934
|
+
totalTokens: ProviderShared.totalTokens(usage.input_tokens, usage.output_tokens, usage.total_tokens),
|
|
935
|
+
...ProviderShared.reportedBilling(usage, ...frames),
|
|
936
|
+
providerMetadata: { [providerMetadataKey]: usage },
|
|
937
|
+
})
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
// GitHub Copilot lists the filters that ran; the blocking one names its rule in `content_filter_raw`.
|
|
941
|
+
const decodeContentFilters = Schema.decodeUnknownOption(
|
|
942
|
+
Schema.Array(
|
|
943
|
+
Schema.Struct({
|
|
944
|
+
source_type: Schema.optional(Schema.String),
|
|
945
|
+
blocked: Schema.optional(Schema.Boolean),
|
|
946
|
+
content_filter_raw: Schema.optional(
|
|
947
|
+
Schema.Array(
|
|
948
|
+
Schema.Struct({
|
|
949
|
+
action: Schema.optional(Schema.String),
|
|
950
|
+
label: Schema.optional(Schema.String),
|
|
951
|
+
result: Schema.optional(Schema.Unknown),
|
|
952
|
+
}),
|
|
953
|
+
),
|
|
954
|
+
),
|
|
955
|
+
content_filter_results: Schema.optional(Schema.Unknown),
|
|
956
|
+
}),
|
|
957
|
+
),
|
|
958
|
+
)
|
|
959
|
+
|
|
960
|
+
const contentFilterCategory = (raw: unknown) => {
|
|
961
|
+
const blocked = Option.getOrElse(decodeContentFilters(raw), () => []).filter((filter) => filter.blocked)
|
|
962
|
+
const filter = blocked.find((item) => item.source_type === "completion") ?? blocked[0]
|
|
963
|
+
if (!filter) return undefined
|
|
964
|
+
return (
|
|
965
|
+
filter.content_filter_raw?.find((rule) => rule.action === "BLOCK" && rule.result === true)?.label ??
|
|
966
|
+
ProviderShared.contentFilterCategory(filter.content_filter_results)
|
|
967
|
+
)
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
const mapFinishReason = (event: Event, hasFunctionCall: boolean): FinishReason => {
|
|
971
|
+
const reason = event.response?.incomplete_details?.reason
|
|
972
|
+
if (reason === undefined) {
|
|
973
|
+
if (hasFunctionCall) return "tool-calls"
|
|
974
|
+
if (event.type === "response.incomplete") return "unknown"
|
|
975
|
+
return "stop"
|
|
976
|
+
}
|
|
977
|
+
if (reason === "max_output_tokens") return "length"
|
|
978
|
+
if (reason === "content_filter") return "content-filter"
|
|
979
|
+
return hasFunctionCall ? "tool-calls" : "unknown"
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
export const metadataKey = (model: LLMRequest["model"]) => model.route.providerMetadataKey ?? "openresponses"
|
|
983
|
+
|
|
984
|
+
export const providerMetadata = (state: ParserState, metadata: Record<string, unknown>): ProviderMetadata => ({
|
|
985
|
+
[state.providerMetadataKey]: metadata,
|
|
986
|
+
})
|
|
987
|
+
|
|
988
|
+
export type StepResult = readonly [ParserState, ReadonlyArray<LLMEvent>]
|
|
989
|
+
|
|
990
|
+
const NO_EVENTS: StepResult["1"] = []
|
|
991
|
+
|
|
992
|
+
// `response.completed` / `response.incomplete` are clean finishes that emit a
|
|
993
|
+
// `finish` event; `response.failed` and `error` are hard failures. All four end
|
|
994
|
+
// the stream, so keep this set aligned with `step` and the protocol's terminal predicate.
|
|
995
|
+
const TERMINAL_TYPES = new Set(["error", "response.completed", "response.incomplete", "response.failed"])
|
|
996
|
+
export const terminal = (event: Event) => TERMINAL_TYPES.has(event.type)
|
|
997
|
+
|
|
998
|
+
const onOutputTextDelta = (state: ParserState, event: Event, id: string): StepResult => {
|
|
999
|
+
if (!event.delta || state.message?.id !== id) return [state, NO_EVENTS]
|
|
1000
|
+
const events: LLMEvent[] = []
|
|
1001
|
+
const phase = state.message.phase
|
|
1002
|
+
const metadata = providerMetadata(state, { itemId: id, ...(phase === undefined ? {} : { phase }) })
|
|
1003
|
+
const lifecycle = Lifecycle.textStart(state.lifecycle, events, id, metadata)
|
|
1004
|
+
return [{ ...state, lifecycle: Lifecycle.textDelta(lifecycle, events, id, event.delta) }, events]
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
const onOutputTextDone = (state: ParserState, event: Event, id: string): StepResult => {
|
|
1008
|
+
if (state.message?.id === id) {
|
|
1009
|
+
if (state.lifecycle.text.has(id) || event.text === undefined) return [state, NO_EVENTS]
|
|
1010
|
+
return onOutputTextDelta(state, { ...event, delta: event.text }, id)
|
|
1011
|
+
}
|
|
1012
|
+
const events: LLMEvent[] = []
|
|
1013
|
+
return [{ ...state, lifecycle: Lifecycle.textEnd(state.lifecycle, events, id) }, events]
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
const decodeMessagePart = Schema.decodeUnknownOption(
|
|
1017
|
+
Schema.Union([OpenResponsesOutputText, Schema.Struct({ type: Schema.tag("refusal"), refusal: Schema.String })]),
|
|
1018
|
+
)
|
|
1019
|
+
|
|
1020
|
+
const decodeSummaryPart = Schema.decodeUnknownOption(OpenResponsesReasoningSummaryText)
|
|
1021
|
+
|
|
1022
|
+
const decodeReasoningPart = Schema.decodeUnknownOption(
|
|
1023
|
+
Schema.Struct({ type: Schema.tag("reasoning_text"), text: Schema.String }),
|
|
1024
|
+
)
|
|
1025
|
+
|
|
1026
|
+
const joinReasoningText = (parts: ReadonlyArray<string | undefined>) => {
|
|
1027
|
+
if (!parts.some((part) => part !== undefined && part.length > 0)) return undefined
|
|
1028
|
+
return parts.filter((part) => part !== undefined).join("\n\n")
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
const outputItemID = (state: Pick<ParserState, "outputItems">, event: Event) =>
|
|
1032
|
+
event.output_index === undefined ? event.item_id : (state.outputItems[event.output_index] ?? event.item_id)
|
|
1033
|
+
|
|
1034
|
+
const ITEM_ID_PREFIX: Readonly<Record<string, string>> = {
|
|
1035
|
+
message: "msg",
|
|
1036
|
+
reasoning: "rs",
|
|
1037
|
+
function_call: "fc",
|
|
1038
|
+
custom_tool_call: "ctc",
|
|
1039
|
+
compaction: "cmp",
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
// An item adopts the id already open in its output slot, since GitHub Copilot
|
|
1043
|
+
// sends a different id on every event, including the item's own done event.
|
|
1044
|
+
// Otherwise it keeps its id or gets a locally minted one.
|
|
1045
|
+
const resolveItem = (
|
|
1046
|
+
state: Pick<ParserState, "outputItems">,
|
|
1047
|
+
item: StreamItem,
|
|
1048
|
+
index: number | undefined,
|
|
1049
|
+
): OutputItem => ({
|
|
1050
|
+
...item,
|
|
1051
|
+
id:
|
|
1052
|
+
(index === undefined ? undefined : state.outputItems[index]) ??
|
|
1053
|
+
item.id ??
|
|
1054
|
+
`${ITEM_ID_PREFIX[item.type] ?? "item"}_${crypto.randomUUID().replaceAll("-", "")}`,
|
|
1055
|
+
})
|
|
1056
|
+
|
|
1057
|
+
// Registered output slots are authoritative for `item_id` routing, and items
|
|
1058
|
+
// are resolved here so everything downstream can rely on `item.id`.
|
|
1059
|
+
export const normalize = (state: Pick<ParserState, "outputItems">, input: Event): NormalizedEvent => ({
|
|
1060
|
+
...input,
|
|
1061
|
+
item_id: input.item_id === undefined ? undefined : outputItemID(state, input),
|
|
1062
|
+
item: input.item ? resolveItem(state, input.item, input.output_index) : input.item,
|
|
1063
|
+
})
|
|
1064
|
+
|
|
1065
|
+
const startReasoningSummaryPart = (state: ParserState, itemID: string, index: number): StepResult => {
|
|
1066
|
+
const item = state.reasoningItems[itemID]
|
|
1067
|
+
if (!item || index === 0 || item.summaryParts[index] !== undefined) return [state, NO_EVENTS]
|
|
1068
|
+
|
|
1069
|
+
const events: LLMEvent[] = []
|
|
1070
|
+
const lifecycle = Object.entries(item.summaryParts)
|
|
1071
|
+
.filter((entry) => entry[1] !== "concluded")
|
|
1072
|
+
.reduce(
|
|
1073
|
+
(lifecycle, entry) =>
|
|
1074
|
+
Lifecycle.reasoningEnd(lifecycle, events, `${itemID}:${entry[0]}`, providerMetadata(state, { itemId: itemID })),
|
|
1075
|
+
state.lifecycle,
|
|
1076
|
+
)
|
|
1077
|
+
return [
|
|
1078
|
+
{
|
|
1079
|
+
...state,
|
|
1080
|
+
lifecycle: Lifecycle.reasoningStart(
|
|
1081
|
+
lifecycle,
|
|
1082
|
+
events,
|
|
1083
|
+
`${itemID}:${index}`,
|
|
1084
|
+
providerMetadata(state, { itemId: itemID, reasoningEncryptedContent: item.encryptedContent ?? null }),
|
|
1085
|
+
),
|
|
1086
|
+
reasoningItems: {
|
|
1087
|
+
...state.reasoningItems,
|
|
1088
|
+
[itemID]: {
|
|
1089
|
+
...item,
|
|
1090
|
+
summaryParts: {
|
|
1091
|
+
...Object.fromEntries(
|
|
1092
|
+
Object.entries(item.summaryParts).map((entry) =>
|
|
1093
|
+
entry[1] === "concluded" ? entry : [entry[0], "concluded" as const],
|
|
1094
|
+
),
|
|
1095
|
+
),
|
|
1096
|
+
[index]: "active",
|
|
1097
|
+
},
|
|
1098
|
+
},
|
|
1099
|
+
},
|
|
1100
|
+
},
|
|
1101
|
+
events,
|
|
1102
|
+
]
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
export const onReasoningDelta = (state: ParserState, event: Event, itemID: string): StepResult => {
|
|
1106
|
+
const item = state.reasoningItems[itemID]
|
|
1107
|
+
if (!event.delta || !item) return [state, NO_EVENTS]
|
|
1108
|
+
const index = event.summary_index ?? 0
|
|
1109
|
+
if (item.summaryParts[index] === "concluded") return [state, NO_EVENTS]
|
|
1110
|
+
const [started, emitted] = startReasoningSummaryPart(state, itemID, index)
|
|
1111
|
+
const current = started.reasoningItems[itemID]
|
|
1112
|
+
if (!current) return [started, emitted]
|
|
1113
|
+
const events: LLMEvent[] = [...emitted]
|
|
1114
|
+
return [
|
|
1115
|
+
{
|
|
1116
|
+
...started,
|
|
1117
|
+
lifecycle: Lifecycle.reasoningDelta(started.lifecycle, events, `${itemID}:${index}`, event.delta),
|
|
1118
|
+
reasoningItems: {
|
|
1119
|
+
...started.reasoningItems,
|
|
1120
|
+
[itemID]: { ...current, deltaIndexes: new Set([...current.deltaIndexes, index]) },
|
|
1121
|
+
},
|
|
1122
|
+
},
|
|
1123
|
+
events,
|
|
1124
|
+
]
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
// Some compatible gateways emit a reasoning final without streaming any
|
|
1128
|
+
// deltas, mirroring `response.output_text.done`. Reconcile the complete text
|
|
1129
|
+
// as a single delta unless that summary index already streamed one.
|
|
1130
|
+
export const onReasoningDone = (state: ParserState, event: Event, itemID: string): StepResult => {
|
|
1131
|
+
const item = state.reasoningItems[itemID]
|
|
1132
|
+
if (!item || event.text === undefined) return [state, NO_EVENTS]
|
|
1133
|
+
const index = event.summary_index ?? 0
|
|
1134
|
+
if (item.deltaIndexes.has(index)) return [state, NO_EVENTS]
|
|
1135
|
+
return onReasoningDelta(state, { ...event, delta: event.text }, itemID)
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
const reasoningMetadata = (state: ParserState, item: OutputItem) =>
|
|
1139
|
+
providerMetadata(state, { itemId: item.id, reasoningEncryptedContent: item.encrypted_content ?? null })
|
|
1140
|
+
|
|
1141
|
+
// Responses APIs normally stream reasoning items in this order:
|
|
1142
|
+
// `output_item.added` (reasoning) →
|
|
1143
|
+
// `reasoning_summary_part.added` (index=0) →
|
|
1144
|
+
// `reasoning_summary_text.delta` →
|
|
1145
|
+
// `reasoning_summary_part.done` (index=0) →
|
|
1146
|
+
// (repeat for index>0) →
|
|
1147
|
+
// `output_item.done` (reasoning).
|
|
1148
|
+
// `onOutputItemAdded` seeds the per-item entry, while each later part start is
|
|
1149
|
+
// also an implicit boundary for the previous part. This keeps the common event
|
|
1150
|
+
// lifecycle ordered when a compatible provider omits or delays a part-done event.
|
|
1151
|
+
const onOutputItemAdded = (state: ParserState, event: NormalizedEvent): StepResult => {
|
|
1152
|
+
const item = event.item
|
|
1153
|
+
if (!item) return [state, NO_EVENTS]
|
|
1154
|
+
if (item.type === "message") {
|
|
1155
|
+
const phase = messagePhase(item.phase)
|
|
1156
|
+
// A new message closes earlier messages, including ones that never streamed.
|
|
1157
|
+
const events: LLMEvent[] = []
|
|
1158
|
+
const lifecycle = [...state.lifecycle.text]
|
|
1159
|
+
.filter((id) => id !== item.id)
|
|
1160
|
+
.reduce((lifecycle, id) => {
|
|
1161
|
+
const openPhase = state.message?.id === id ? state.message.phase : undefined
|
|
1162
|
+
return Lifecycle.textEnd(
|
|
1163
|
+
lifecycle,
|
|
1164
|
+
events,
|
|
1165
|
+
id,
|
|
1166
|
+
providerMetadata(state, { itemId: id, ...(openPhase === undefined ? {} : { phase: openPhase }) }),
|
|
1167
|
+
)
|
|
1168
|
+
}, state.lifecycle)
|
|
1169
|
+
return [
|
|
1170
|
+
{
|
|
1171
|
+
...state,
|
|
1172
|
+
lifecycle,
|
|
1173
|
+
message: {
|
|
1174
|
+
id: item.id,
|
|
1175
|
+
phase: phase === undefined && state.message?.id === item.id ? state.message.phase : phase,
|
|
1176
|
+
},
|
|
1177
|
+
},
|
|
1178
|
+
events,
|
|
1179
|
+
]
|
|
1180
|
+
}
|
|
1181
|
+
if (item.type === "reasoning") {
|
|
1182
|
+
if (state.reasoningItems[item.id] !== undefined) return [state, NO_EVENTS]
|
|
1183
|
+
const events: LLMEvent[] = []
|
|
1184
|
+
return [
|
|
1185
|
+
{
|
|
1186
|
+
...state,
|
|
1187
|
+
lifecycle: Lifecycle.reasoningStart(state.lifecycle, events, `${item.id}:0`, reasoningMetadata(state, item)),
|
|
1188
|
+
reasoningItems: {
|
|
1189
|
+
...state.reasoningItems,
|
|
1190
|
+
[item.id]: {
|
|
1191
|
+
encryptedContent: item.encrypted_content,
|
|
1192
|
+
summaryParts: { 0: "active" },
|
|
1193
|
+
deltaIndexes: new Set(),
|
|
1194
|
+
},
|
|
1195
|
+
},
|
|
1196
|
+
},
|
|
1197
|
+
events,
|
|
1198
|
+
]
|
|
1199
|
+
}
|
|
1200
|
+
if ((item.type !== "function_call" && item.type !== "custom_tool_call") || !item.call_id) return [state, NO_EVENTS]
|
|
1201
|
+
if (state.tools[item.id] !== undefined) return [state, NO_EVENTS]
|
|
1202
|
+
const custom = item.type === "custom_tool_call"
|
|
1203
|
+
const metadata = providerMetadata(state, OpenAIFreeform.metadata(item.id, custom))
|
|
1204
|
+
const events: LLMEvent[] = []
|
|
1205
|
+
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
|
1206
|
+
const tools = ToolStream.start(state.tools, item.id, {
|
|
1207
|
+
id: item.call_id,
|
|
1208
|
+
name: item.name ?? "",
|
|
1209
|
+
namespace: item.namespace,
|
|
1210
|
+
input: custom ? "" : (item.arguments ?? ""),
|
|
1211
|
+
providerMetadata: metadata,
|
|
1212
|
+
})
|
|
1213
|
+
const opened = custom
|
|
1214
|
+
? ToolStream.append(tools, item.id, OpenAIFreeform.streamStart(state.custom.get(item.name ?? ""), rawInput(item)))
|
|
1215
|
+
: undefined
|
|
1216
|
+
return [
|
|
1217
|
+
{ ...state, lifecycle, tools: opened?.tools ?? tools },
|
|
1218
|
+
[
|
|
1219
|
+
...events,
|
|
1220
|
+
LLMEvent.toolInputStart({
|
|
1221
|
+
id: item.call_id,
|
|
1222
|
+
name: item.name ?? "",
|
|
1223
|
+
namespace: item.namespace,
|
|
1224
|
+
providerMetadata: metadata,
|
|
1225
|
+
}),
|
|
1226
|
+
...(opened?.events ?? []),
|
|
1227
|
+
],
|
|
1228
|
+
]
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
const rawInput = (item: OutputItem) => (typeof item.input === "string" ? item.input : "")
|
|
1232
|
+
|
|
1233
|
+
const onReasoningSummaryPartAdded = (state: ParserState, event: Event): StepResult => {
|
|
1234
|
+
if (event.item_id === undefined || event.summary_index === undefined) return [state, NO_EVENTS]
|
|
1235
|
+
return startReasoningSummaryPart(state, event.item_id, event.summary_index)
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
const onReasoningSummaryPartDone = (state: ParserState, event: Event): StepResult => {
|
|
1239
|
+
if (event.item_id === undefined || event.summary_index === undefined) return [state, NO_EVENTS]
|
|
1240
|
+
const item = state.reasoningItems[event.item_id]
|
|
1241
|
+
if (!item) return [state, NO_EVENTS]
|
|
1242
|
+
if (item.summaryParts[event.summary_index] !== "active") return [state, NO_EVENTS]
|
|
1243
|
+
return [
|
|
1244
|
+
{
|
|
1245
|
+
...state,
|
|
1246
|
+
reasoningItems: {
|
|
1247
|
+
...state.reasoningItems,
|
|
1248
|
+
[event.item_id]: {
|
|
1249
|
+
...item,
|
|
1250
|
+
summaryParts: {
|
|
1251
|
+
...item.summaryParts,
|
|
1252
|
+
[event.summary_index]: "can-conclude",
|
|
1253
|
+
},
|
|
1254
|
+
},
|
|
1255
|
+
},
|
|
1256
|
+
},
|
|
1257
|
+
NO_EVENTS,
|
|
1258
|
+
]
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
const onFunctionCallArgumentsDelta = Effect.fnUntraced(function* (state: ParserState, event: Event) {
|
|
1262
|
+
if (event.item_id === undefined) return [state, NO_EVENTS] satisfies StepResult
|
|
1263
|
+
const tool = state.tools[event.item_id]
|
|
1264
|
+
if (!tool) return [state, NO_EVENTS] satisfies StepResult
|
|
1265
|
+
const final = event.type === "response.function_call_arguments.done" ? event.arguments : undefined
|
|
1266
|
+
if (event.type === "response.function_call_arguments.done" && final === undefined)
|
|
1267
|
+
return [state, NO_EVENTS] satisfies StepResult
|
|
1268
|
+
if (final !== undefined && !final.startsWith(tool.input))
|
|
1269
|
+
return [
|
|
1270
|
+
{ ...state, tools: ToolStream.start(state.tools, event.item_id, { ...tool, input: final }) },
|
|
1271
|
+
NO_EVENTS,
|
|
1272
|
+
] satisfies StepResult
|
|
1273
|
+
const delta = final === undefined ? event.delta : final.slice(tool.input.length)
|
|
1274
|
+
if (!delta) return [state, NO_EVENTS] satisfies StepResult
|
|
1275
|
+
const result = ToolStream.appendExisting(
|
|
1276
|
+
state.id,
|
|
1277
|
+
state.tools,
|
|
1278
|
+
event.item_id,
|
|
1279
|
+
delta,
|
|
1280
|
+
`${state.name} tool argument delta is missing its tool call`,
|
|
1281
|
+
)
|
|
1282
|
+
if (ToolStream.isError(result)) return yield* result
|
|
1283
|
+
const events: LLMEvent[] = []
|
|
1284
|
+
const lifecycle = result.events.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle
|
|
1285
|
+
events.push(...result.events)
|
|
1286
|
+
return [{ ...state, lifecycle, tools: result.tools }, events] satisfies StepResult
|
|
1287
|
+
})
|
|
1288
|
+
|
|
1289
|
+
const onOutputItemDone = Effect.fnUntraced(function* (state: ParserState, item: NormalizedEvent["item"]) {
|
|
1290
|
+
if (!item) return [state, NO_EVENTS] satisfies StepResult
|
|
1291
|
+
|
|
1292
|
+
if (item.type === "compaction") {
|
|
1293
|
+
if (typeof item.encrypted_content !== "string")
|
|
1294
|
+
return yield* ProviderShared.eventError(state.id, "Compaction output is missing its encrypted content")
|
|
1295
|
+
if (state.completedCompactions.has(item.id)) return [state, NO_EVENTS] satisfies StepResult
|
|
1296
|
+
const events: LLMEvent[] = []
|
|
1297
|
+
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
|
1298
|
+
events.push(
|
|
1299
|
+
LLMEvent.compaction({
|
|
1300
|
+
provider: state.provider,
|
|
1301
|
+
id: item.id,
|
|
1302
|
+
encrypted: item.encrypted_content,
|
|
1303
|
+
}),
|
|
1304
|
+
)
|
|
1305
|
+
return [
|
|
1306
|
+
{ ...state, lifecycle, completedCompactions: new Set([...state.completedCompactions, item.id]) },
|
|
1307
|
+
events,
|
|
1308
|
+
] satisfies StepResult
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
if (item.type === "message") {
|
|
1312
|
+
const active = state.message?.id === item.id
|
|
1313
|
+
const itemPhase = messagePhase(item.phase)
|
|
1314
|
+
const phase = itemPhase === undefined && active ? state.message?.phase : itemPhase
|
|
1315
|
+
const parts: ReadonlyArray<unknown> = Array.isArray(item.content) ? item.content : []
|
|
1316
|
+
const content: string[] = []
|
|
1317
|
+
for (const part of parts) {
|
|
1318
|
+
const decoded = Option.getOrUndefined(decodeMessagePart(part))
|
|
1319
|
+
if (!decoded) continue
|
|
1320
|
+
content.push(decoded.type === "output_text" ? decoded.text : decoded.refusal)
|
|
1321
|
+
}
|
|
1322
|
+
const text = content.length > 0 ? content.join("") : undefined
|
|
1323
|
+
const metadata = providerMetadata(state, { itemId: item.id, ...(phase === undefined ? {} : { phase }) })
|
|
1324
|
+
const events: LLMEvent[] = []
|
|
1325
|
+
const lifecycle = text ? Lifecycle.textStart(state.lifecycle, events, item.id, metadata) : state.lifecycle
|
|
1326
|
+
return [
|
|
1327
|
+
{
|
|
1328
|
+
...state,
|
|
1329
|
+
lifecycle: Lifecycle.textEnd(lifecycle, events, item.id, metadata, text),
|
|
1330
|
+
message: active ? undefined : state.message,
|
|
1331
|
+
},
|
|
1332
|
+
events,
|
|
1333
|
+
] satisfies StepResult
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
if (item.type === "function_call" || item.type === "custom_tool_call") {
|
|
1337
|
+
if (!item.call_id || !item.name) return [state, NO_EVENTS] satisfies StepResult
|
|
1338
|
+
const custom = item.type === "custom_tool_call"
|
|
1339
|
+
const metadata = providerMetadata(state, OpenAIFreeform.metadata(item.id, custom))
|
|
1340
|
+
const registered = state.tools[item.id] !== undefined
|
|
1341
|
+
const started = registered
|
|
1342
|
+
? state.tools
|
|
1343
|
+
: ToolStream.start(state.tools, item.id, {
|
|
1344
|
+
id: item.call_id,
|
|
1345
|
+
name: item.name,
|
|
1346
|
+
namespace: item.namespace,
|
|
1347
|
+
providerMetadata: metadata,
|
|
1348
|
+
})
|
|
1349
|
+
// A custom call's final raw text sets its input, so it finishes without an override.
|
|
1350
|
+
const closed = custom
|
|
1351
|
+
? OpenAIFreeform.close(started, [item.id], state.custom, state.providerMetadataKey, rawInput(item))
|
|
1352
|
+
: undefined
|
|
1353
|
+
const result = yield* ToolStream.finish(
|
|
1354
|
+
state.id,
|
|
1355
|
+
closed?.tools ?? started,
|
|
1356
|
+
item.id,
|
|
1357
|
+
custom ? undefined : item.arguments,
|
|
1358
|
+
)
|
|
1359
|
+
const events: LLMEvent[] = []
|
|
1360
|
+
const finished = [...(closed?.events ?? []), ...(result.events ?? [])]
|
|
1361
|
+
// A done-only call never streamed a start event, so open its lifecycle here.
|
|
1362
|
+
const resultEvents =
|
|
1363
|
+
registered || finished.length === 0
|
|
1364
|
+
? finished
|
|
1365
|
+
: [
|
|
1366
|
+
LLMEvent.toolInputStart({
|
|
1367
|
+
id: item.call_id,
|
|
1368
|
+
name: item.name,
|
|
1369
|
+
namespace: item.namespace,
|
|
1370
|
+
providerMetadata: metadata,
|
|
1371
|
+
}),
|
|
1372
|
+
...finished,
|
|
1373
|
+
]
|
|
1374
|
+
const lifecycle = resultEvents.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle
|
|
1375
|
+
events.push(...resultEvents)
|
|
1376
|
+
return [
|
|
1377
|
+
{
|
|
1378
|
+
...state,
|
|
1379
|
+
lifecycle,
|
|
1380
|
+
hasFunctionCall:
|
|
1381
|
+
resultEvents.some((event) => LLMEvent.is.toolCall(event) || LLMEvent.is.toolInputError(event)) ||
|
|
1382
|
+
state.hasFunctionCall,
|
|
1383
|
+
tools: result.tools,
|
|
1384
|
+
},
|
|
1385
|
+
events,
|
|
1386
|
+
] satisfies StepResult
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
if (item.type === "reasoning") {
|
|
1390
|
+
const metadata = reasoningMetadata(state, item)
|
|
1391
|
+
const summaryParts: ReadonlyArray<unknown> = Array.isArray(item.summary) ? item.summary : []
|
|
1392
|
+
const summary: Array<string | undefined> = []
|
|
1393
|
+
for (const part of summaryParts) {
|
|
1394
|
+
const decoded = Option.getOrUndefined(decodeSummaryPart(part))
|
|
1395
|
+
// Keep missing entries so the array still matches the provider's summary indexes.
|
|
1396
|
+
summary.push(decoded?.text)
|
|
1397
|
+
}
|
|
1398
|
+
const reasoningParts: ReadonlyArray<unknown> = Array.isArray(item.content) ? item.content : []
|
|
1399
|
+
const content: string[] = []
|
|
1400
|
+
for (const part of reasoningParts) {
|
|
1401
|
+
const decoded = Option.getOrUndefined(decodeReasoningPart(part))
|
|
1402
|
+
if (decoded) content.push(decoded.text)
|
|
1403
|
+
}
|
|
1404
|
+
const itemText = joinReasoningText(summary) ?? joinReasoningText(content)
|
|
1405
|
+
const events: LLMEvent[] = []
|
|
1406
|
+
const reasoningItem = state.reasoningItems[item.id]
|
|
1407
|
+
if (reasoningItem) {
|
|
1408
|
+
const fragments = Object.entries(reasoningItem.summaryParts)
|
|
1409
|
+
let lifecycle = state.lifecycle
|
|
1410
|
+
for (const [index, status] of fragments) {
|
|
1411
|
+
if (status === "concluded") continue
|
|
1412
|
+
// Do not repeat earlier summaries that were already emitted as separate fragments.
|
|
1413
|
+
const finalText = fragments.length === 1 ? itemText : summary[Number(index)]
|
|
1414
|
+
lifecycle = Lifecycle.reasoningEnd(lifecycle, events, `${item.id}:${index}`, metadata, finalText || undefined)
|
|
1415
|
+
}
|
|
1416
|
+
const reasoningItems = { ...state.reasoningItems }
|
|
1417
|
+
delete reasoningItems[item.id]
|
|
1418
|
+
return [{ ...state, lifecycle, reasoningItems }, events] satisfies StepResult
|
|
1419
|
+
}
|
|
1420
|
+
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
|
1421
|
+
events.push(LLMEvent.reasoningStart({ id: item.id, providerMetadata: metadata }))
|
|
1422
|
+
events.push(LLMEvent.reasoningEnd({ id: item.id, providerMetadata: metadata, text: itemText }))
|
|
1423
|
+
return [{ ...state, lifecycle }, events] satisfies StepResult
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
return [state, NO_EVENTS] satisfies StepResult
|
|
1427
|
+
})
|
|
1428
|
+
|
|
1429
|
+
const onResponseFinish = Effect.fnUntraced(function* (state: ParserState, event: Event) {
|
|
1430
|
+
let current = state
|
|
1431
|
+
const events: LLMEvent[] = []
|
|
1432
|
+
if (event.type === "response.completed") {
|
|
1433
|
+
// An output item's array position is its output index.
|
|
1434
|
+
for (const item of (event.response?.output ?? []).map((item, index) => resolveItem(state, item, index))) {
|
|
1435
|
+
// Terminal recovery cannot insert a checkpoint before already-emitted content.
|
|
1436
|
+
if (item.type === "compaction" && state.lifecycle.stepStarted && !state.completedCompactions.has(item.id))
|
|
1437
|
+
return yield* ProviderShared.eventError(
|
|
1438
|
+
state.id,
|
|
1439
|
+
"Cannot recover a compaction checkpoint after output has been emitted",
|
|
1440
|
+
)
|
|
1441
|
+
const recoverable =
|
|
1442
|
+
item.type === "compaction" ||
|
|
1443
|
+
((item.type === "function_call" || item.type === "custom_tool_call") && current.tools[item.id] !== undefined)
|
|
1444
|
+
if (!recoverable) continue
|
|
1445
|
+
const [next, emitted] = yield* onOutputItemDone(current, item)
|
|
1446
|
+
current = next
|
|
1447
|
+
events.push(...emitted)
|
|
1448
|
+
}
|
|
1449
|
+
// Some compatible providers omit output_item.done even after completing the response.
|
|
1450
|
+
const open = OpenAIFreeform.close(
|
|
1451
|
+
current.tools,
|
|
1452
|
+
Object.keys(current.tools).filter(
|
|
1453
|
+
(key) => current.tools[key]?.providerMetadata?.[current.providerMetadataKey]?.custom === true,
|
|
1454
|
+
),
|
|
1455
|
+
current.custom,
|
|
1456
|
+
current.providerMetadataKey,
|
|
1457
|
+
)
|
|
1458
|
+
events.push(...open.events)
|
|
1459
|
+
const pending = yield* ToolStream.finishAll(current.id, open.tools)
|
|
1460
|
+
current = {
|
|
1461
|
+
...current,
|
|
1462
|
+
tools: pending.tools,
|
|
1463
|
+
hasFunctionCall:
|
|
1464
|
+
current.hasFunctionCall ||
|
|
1465
|
+
pending.events.some((event) => LLMEvent.is.toolCall(event) || LLMEvent.is.toolInputError(event)),
|
|
1466
|
+
}
|
|
1467
|
+
events.push(...pending.events)
|
|
1468
|
+
}
|
|
1469
|
+
const normalized = mapFinishReason(event, current.hasFunctionCall)
|
|
1470
|
+
const lifecycle = Lifecycle.finish(current.lifecycle, events, {
|
|
1471
|
+
reason: {
|
|
1472
|
+
normalized,
|
|
1473
|
+
raw: event.response?.incomplete_details?.reason,
|
|
1474
|
+
...(normalized === "content-filter" ? { category: contentFilterCategory(event.response?.content_filters) } : {}),
|
|
1475
|
+
},
|
|
1476
|
+
// Copilot reports its billing on the terminal event, beside `response`.
|
|
1477
|
+
usage: mapUsage(event.response?.usage, current.providerMetadataKey, event, event.response),
|
|
1478
|
+
providerMetadata:
|
|
1479
|
+
event.response?.id || event.response?.service_tier
|
|
1480
|
+
? providerMetadata(current, {
|
|
1481
|
+
responseId: event.response.id,
|
|
1482
|
+
serviceTier: event.response.service_tier,
|
|
1483
|
+
})
|
|
1484
|
+
: undefined,
|
|
1485
|
+
})
|
|
1486
|
+
return [{ ...current, lifecycle }, events] satisfies StepResult
|
|
1487
|
+
})
|
|
1488
|
+
|
|
1489
|
+
/** Error code and message from wherever the frame put them; top-level fields win over nested ones. */
|
|
1490
|
+
export const errorDetail = (event: Event) => {
|
|
1491
|
+
const raw = event.error ?? event.response?.error
|
|
1492
|
+
const nested = typeof raw === "string" ? { message: raw } : ProviderShared.isRecord(raw) ? raw : undefined
|
|
1493
|
+
return {
|
|
1494
|
+
message: asText(event.message) ?? asText(nested?.message),
|
|
1495
|
+
code: asText(event.code) ?? asText(nested?.code),
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
// Prefix the code when both are present (`rate_limit_exceeded: Slow down`) so the failure mode is
|
|
1500
|
+
// visible; fall back to the raw frame rather than a generic message when neither decodes.
|
|
1501
|
+
export const providerFailure = (event: Event, fallback: string, body = ProviderShared.encodeJson(event)) => {
|
|
1502
|
+
const detail = errorDetail(event)
|
|
1503
|
+
const summary = detail.message && detail.code ? `${detail.code}: ${detail.message}` : (detail.message ?? detail.code)
|
|
1504
|
+
const message = summary ?? (body === "{}" ? fallback : body)
|
|
1505
|
+
const status =
|
|
1506
|
+
typeof event.status === "number"
|
|
1507
|
+
? event.status
|
|
1508
|
+
: typeof event.status_code === "number"
|
|
1509
|
+
? event.status_code
|
|
1510
|
+
: undefined
|
|
1511
|
+
const reason =
|
|
1512
|
+
event.type === "error" &&
|
|
1513
|
+
event.error === undefined &&
|
|
1514
|
+
event.response === undefined &&
|
|
1515
|
+
summary === undefined &&
|
|
1516
|
+
status === undefined
|
|
1517
|
+
? new ProviderInternalError({ message, body })
|
|
1518
|
+
: classifyProviderFailure({ message, status, rawBody: body })
|
|
1519
|
+
return new AIError({ reason })
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
// Callers must pass events through `normalize` first. The OpenAPI requires
|
|
1523
|
+
// string IDs but imposes no minLength; empty is not missing.
|
|
1524
|
+
export const step = (state: ParserState, event: NormalizedEvent) => {
|
|
1525
|
+
if (event.type === "response.output_text.delta" || event.type === "response.output_text.done") {
|
|
1526
|
+
if (event.item_id === undefined) return ProviderShared.eventError(state.id, `${event.type} is missing item_id`)
|
|
1527
|
+
return Effect.succeed(
|
|
1528
|
+
event.type === "response.output_text.delta"
|
|
1529
|
+
? onOutputTextDelta(state, event, event.item_id)
|
|
1530
|
+
: onOutputTextDone(state, event, event.item_id),
|
|
1531
|
+
)
|
|
1532
|
+
}
|
|
1533
|
+
if (event.type === "response.refusal.delta" || event.type === "response.refusal.done") {
|
|
1534
|
+
const value = event.type === "response.refusal.delta" ? event.delta : event.refusal
|
|
1535
|
+
if (event.item_id === undefined || typeof value !== "string")
|
|
1536
|
+
return ProviderShared.eventError(state.id, `${event.type} is malformed`)
|
|
1537
|
+
return Effect.succeed(
|
|
1538
|
+
event.type === "response.refusal.delta"
|
|
1539
|
+
? onOutputTextDelta(state, event, event.item_id)
|
|
1540
|
+
: onOutputTextDone(state, { ...event, text: value }, event.item_id),
|
|
1541
|
+
)
|
|
1542
|
+
}
|
|
1543
|
+
if (event.type === "response.reasoning.delta" || event.type === "response.reasoning_summary_text.delta") {
|
|
1544
|
+
if (event.item_id === undefined) return ProviderShared.eventError(state.id, `${event.type} is missing item_id`)
|
|
1545
|
+
return Effect.succeed(onReasoningDelta(state, event, event.item_id))
|
|
1546
|
+
}
|
|
1547
|
+
if (
|
|
1548
|
+
event.type === "response.reasoning.done" ||
|
|
1549
|
+
event.type === "response.reasoning_summary_text.done" ||
|
|
1550
|
+
event.type === "response.reasoning_text.done"
|
|
1551
|
+
) {
|
|
1552
|
+
if (event.item_id === undefined) return ProviderShared.eventError(state.id, `${event.type} is missing item_id`)
|
|
1553
|
+
return Effect.succeed(onReasoningDone(state, event, event.item_id))
|
|
1554
|
+
}
|
|
1555
|
+
if (event.type === "response.reasoning_summary_part.added")
|
|
1556
|
+
return event.item_id !== undefined
|
|
1557
|
+
? Effect.succeed(onReasoningSummaryPartAdded(state, event))
|
|
1558
|
+
: ProviderShared.eventError(state.id, `${event.type} is missing item_id`)
|
|
1559
|
+
if (event.type === "response.reasoning_summary_part.done")
|
|
1560
|
+
return event.item_id !== undefined
|
|
1561
|
+
? Effect.succeed(onReasoningSummaryPartDone(state, event))
|
|
1562
|
+
: ProviderShared.eventError(state.id, `${event.type} is missing item_id`)
|
|
1563
|
+
if (event.type === "response.output_item.added") {
|
|
1564
|
+
if (
|
|
1565
|
+
event.item?.type === "reasoning" &&
|
|
1566
|
+
state.reasoningItems[event.item.id] === undefined &&
|
|
1567
|
+
state.lifecycle.reasoning.size > 0
|
|
1568
|
+
)
|
|
1569
|
+
return ProviderShared.eventError(state.id, `${event.type} started reasoning before the previous item ended`)
|
|
1570
|
+
return Effect.succeed(
|
|
1571
|
+
onOutputItemAdded(
|
|
1572
|
+
event.output_index !== undefined && event.item
|
|
1573
|
+
? { ...state, outputItems: { ...state.outputItems, [event.output_index]: event.item.id } }
|
|
1574
|
+
: state,
|
|
1575
|
+
event,
|
|
1576
|
+
),
|
|
1577
|
+
)
|
|
1578
|
+
}
|
|
1579
|
+
if (event.type === "response.function_call_arguments.delta" || event.type === "response.function_call_arguments.done")
|
|
1580
|
+
return event.item_id !== undefined
|
|
1581
|
+
? onFunctionCallArgumentsDelta(state, event)
|
|
1582
|
+
: ProviderShared.eventError(state.id, `${event.type} is missing item_id`)
|
|
1583
|
+
if (event.type === "response.custom_tool_call_input.delta")
|
|
1584
|
+
return event.item_id !== undefined
|
|
1585
|
+
? onFunctionCallArgumentsDelta(state, {
|
|
1586
|
+
...event,
|
|
1587
|
+
type: "response.function_call_arguments.delta",
|
|
1588
|
+
delta: OpenAIFreeform.streamDelta(event.delta ?? ""),
|
|
1589
|
+
})
|
|
1590
|
+
: ProviderShared.eventError(state.id, `${event.type} is missing item_id`)
|
|
1591
|
+
if (event.type === "response.output_item.done") return onOutputItemDone(state, event.item)
|
|
1592
|
+
if (event.type === "response.completed" || event.type === "response.incomplete") return onResponseFinish(state, event)
|
|
1593
|
+
if (event.type === "response.failed") return providerFailure(event, `${state.name} response failed`)
|
|
1594
|
+
if (event.type === "error") return providerFailure(event, `${state.name} stream error`)
|
|
1595
|
+
return Effect.succeed<StepResult>([state, NO_EVENTS])
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
// =============================================================================
|
|
1599
|
+
// Protocol
|
|
1600
|
+
// =============================================================================
|
|
1601
|
+
/**
|
|
1602
|
+
* The provider-neutral Open Responses protocol. Provider-specific Responses
|
|
1603
|
+
* implementations compose this baseline with their own tools and event variants.
|
|
1604
|
+
*/
|
|
1605
|
+
export const initial = (request: LLMRequest, adapter: ProviderAdapter = BASE_ADAPTER): ParserState => ({
|
|
1606
|
+
provider: request.model.provider,
|
|
1607
|
+
completedCompactions: new Set<string>(),
|
|
1608
|
+
id: adapter.id,
|
|
1609
|
+
name: adapter.name,
|
|
1610
|
+
providerMetadataKey: metadataKey(request.model),
|
|
1611
|
+
hasFunctionCall: false,
|
|
1612
|
+
tools: ToolStream.empty<string>(),
|
|
1613
|
+
custom: OpenAIFreeform.tools(request),
|
|
1614
|
+
lifecycle: Lifecycle.initial(),
|
|
1615
|
+
outputItems: {},
|
|
1616
|
+
message: undefined,
|
|
1617
|
+
reasoningItems: {},
|
|
1618
|
+
})
|
|
1619
|
+
|
|
1620
|
+
export const protocol = Protocol.make({
|
|
1621
|
+
id: ADAPTER,
|
|
1622
|
+
body: {
|
|
1623
|
+
schema: OpenResponsesBody,
|
|
1624
|
+
from: fromRequest,
|
|
1625
|
+
},
|
|
1626
|
+
stream: {
|
|
1627
|
+
event: Protocol.jsonEvent(Event),
|
|
1628
|
+
initial,
|
|
1629
|
+
step: (state: ParserState, event: Event) => step(state, normalize(state, event)),
|
|
1630
|
+
terminal,
|
|
1631
|
+
},
|
|
1632
|
+
})
|
|
1633
|
+
|
|
1634
|
+
export const httpTransport = HttpTransport.sseJson.with<OpenResponsesBody>()
|
|
1635
|
+
|
|
1636
|
+
export * as OpenResponses from "./open-responses.js"
|