@opencode/ai 0.0.0-beta-19275

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.
Files changed (252) hide show
  1. package/README.md +682 -0
  2. package/dist/cache-policy.d.ts +2 -0
  3. package/dist/cache-policy.js +129 -0
  4. package/dist/image-client.d.ts +19 -0
  5. package/dist/image-client.js +28 -0
  6. package/dist/image.d.ts +110 -0
  7. package/dist/image.js +103 -0
  8. package/dist/index.d.ts +18 -0
  9. package/dist/index.js +12 -0
  10. package/dist/llm.d.ts +252 -0
  11. package/dist/llm.js +74 -0
  12. package/dist/protocols/anthropic-messages.d.ts +957 -0
  13. package/dist/protocols/anthropic-messages.js +1414 -0
  14. package/dist/protocols/bedrock-converse.d.ts +499 -0
  15. package/dist/protocols/bedrock-converse.js +643 -0
  16. package/dist/protocols/bedrock-event-stream.d.ts +9 -0
  17. package/dist/protocols/bedrock-event-stream.js +97 -0
  18. package/dist/protocols/gemini.d.ts +285 -0
  19. package/dist/protocols/gemini.js +671 -0
  20. package/dist/protocols/google-images.d.ts +30 -0
  21. package/dist/protocols/google-images.js +181 -0
  22. package/dist/protocols/index.d.ts +12 -0
  23. package/dist/protocols/index.js +12 -0
  24. package/dist/protocols/meta-images.d.ts +26 -0
  25. package/dist/protocols/meta-images.js +89 -0
  26. package/dist/protocols/meta-messages.d.ts +350 -0
  27. package/dist/protocols/meta-messages.js +41 -0
  28. package/dist/protocols/meta-responses.d.ts +473 -0
  29. package/dist/protocols/meta-responses.js +173 -0
  30. package/dist/protocols/mistral-chat.d.ts +540 -0
  31. package/dist/protocols/mistral-chat.js +624 -0
  32. package/dist/protocols/open-responses-channel.d.ts +23 -0
  33. package/dist/protocols/open-responses-channel.js +141 -0
  34. package/dist/protocols/open-responses-continuation.d.ts +12 -0
  35. package/dist/protocols/open-responses-continuation.js +161 -0
  36. package/dist/protocols/open-responses.d.ts +1583 -0
  37. package/dist/protocols/open-responses.js +1206 -0
  38. package/dist/protocols/openai-chat.d.ts +860 -0
  39. package/dist/protocols/openai-chat.js +966 -0
  40. package/dist/protocols/openai-compatible-chat.d.ts +109 -0
  41. package/dist/protocols/openai-compatible-chat.js +19 -0
  42. package/dist/protocols/openai-compatible-responses.d.ts +172 -0
  43. package/dist/protocols/openai-compatible-responses.js +18 -0
  44. package/dist/protocols/openai-images.d.ts +32 -0
  45. package/dist/protocols/openai-images.js +183 -0
  46. package/dist/protocols/openai-responses.d.ts +1389 -0
  47. package/dist/protocols/openai-responses.js +260 -0
  48. package/dist/protocols/shared.d.ts +193 -0
  49. package/dist/protocols/shared.js +290 -0
  50. package/dist/protocols/utils/bedrock-auth.d.ts +60 -0
  51. package/dist/protocols/utils/bedrock-auth.js +85 -0
  52. package/dist/protocols/utils/bedrock-cache.d.ts +19 -0
  53. package/dist/protocols/utils/bedrock-cache.js +49 -0
  54. package/dist/protocols/utils/bedrock-media.d.ts +55 -0
  55. package/dist/protocols/utils/bedrock-media.js +73 -0
  56. package/dist/protocols/utils/cache.d.ts +6 -0
  57. package/dist/protocols/utils/cache.js +5 -0
  58. package/dist/protocols/utils/gemini-tool-schema.d.ts +2 -0
  59. package/dist/protocols/utils/gemini-tool-schema.js +103 -0
  60. package/dist/protocols/utils/image-input.d.ts +21 -0
  61. package/dist/protocols/utils/image-input.js +20 -0
  62. package/dist/protocols/utils/lifecycle.d.ts +24 -0
  63. package/dist/protocols/utils/lifecycle.js +72 -0
  64. package/dist/protocols/utils/meta-image.d.ts +2 -0
  65. package/dist/protocols/utils/meta-image.js +13 -0
  66. package/dist/protocols/utils/open-responses-options.d.ts +56 -0
  67. package/dist/protocols/utils/open-responses-options.js +61 -0
  68. package/dist/protocols/utils/openai-image.d.ts +5 -0
  69. package/dist/protocols/utils/openai-image.js +18 -0
  70. package/dist/protocols/utils/openai-options.d.ts +16 -0
  71. package/dist/protocols/utils/openai-options.js +14 -0
  72. package/dist/protocols/utils/partial-json-options.d.ts +62 -0
  73. package/dist/protocols/utils/partial-json-options.js +52 -0
  74. package/dist/protocols/utils/partial-json.d.ts +8 -0
  75. package/dist/protocols/utils/partial-json.js +279 -0
  76. package/dist/protocols/utils/responses-checkpoint.d.ts +4 -0
  77. package/dist/protocols/utils/responses-checkpoint.js +107 -0
  78. package/dist/protocols/utils/responses-compaction.d.ts +4 -0
  79. package/dist/protocols/utils/responses-compaction.js +129 -0
  80. package/dist/protocols/utils/responses-hosted-tools.d.ts +26 -0
  81. package/dist/protocols/utils/responses-hosted-tools.js +32 -0
  82. package/dist/protocols/utils/tool-schema.d.ts +8 -0
  83. package/dist/protocols/utils/tool-schema.js +54 -0
  84. package/dist/protocols/utils/tool-stream.d.ts +710 -0
  85. package/dist/protocols/utils/tool-stream.js +155 -0
  86. package/dist/protocols/xai-images.d.ts +26 -0
  87. package/dist/protocols/xai-images.js +106 -0
  88. package/dist/protocols/xai-responses.d.ts +250 -0
  89. package/dist/protocols/xai-responses.js +81 -0
  90. package/dist/protocols/zai-images.d.ts +22 -0
  91. package/dist/protocols/zai-images.js +79 -0
  92. package/dist/protocols.d.ts +1 -0
  93. package/dist/protocols.js +1 -0
  94. package/dist/provider-error.d.ts +15 -0
  95. package/dist/provider-error.js +125 -0
  96. package/dist/provider-package.d.ts +11 -0
  97. package/dist/provider-package.js +1 -0
  98. package/dist/provider.d.ts +23 -0
  99. package/dist/provider.js +2 -0
  100. package/dist/providers/amazon-bedrock/mantle/chat.d.ts +2 -0
  101. package/dist/providers/amazon-bedrock/mantle/chat.js +1 -0
  102. package/dist/providers/amazon-bedrock/mantle/responses.d.ts +2 -0
  103. package/dist/providers/amazon-bedrock/mantle/responses.js +1 -0
  104. package/dist/providers/amazon-bedrock/mantle.d.ts +2 -0
  105. package/dist/providers/amazon-bedrock/mantle.js +1 -0
  106. package/dist/providers/amazon-bedrock-mantle.d.ts +371 -0
  107. package/dist/providers/amazon-bedrock-mantle.js +76 -0
  108. package/dist/providers/amazon-bedrock.d.ts +173 -0
  109. package/dist/providers/amazon-bedrock.js +41 -0
  110. package/dist/providers/anthropic-compatible.d.ts +304 -0
  111. package/dist/providers/anthropic-compatible.js +44 -0
  112. package/dist/providers/anthropic.d.ts +302 -0
  113. package/dist/providers/anthropic.js +39 -0
  114. package/dist/providers/azure/chat.d.ts +2 -0
  115. package/dist/providers/azure/chat.js +1 -0
  116. package/dist/providers/azure/responses.d.ts +2 -0
  117. package/dist/providers/azure/responses.js +1 -0
  118. package/dist/providers/azure.d.ts +599 -0
  119. package/dist/providers/azure.js +115 -0
  120. package/dist/providers/baseten.d.ts +229 -0
  121. package/dist/providers/baseten.js +38 -0
  122. package/dist/providers/cerebras.d.ts +228 -0
  123. package/dist/providers/cerebras.js +40 -0
  124. package/dist/providers/cloudflare-ai-gateway.d.ts +238 -0
  125. package/dist/providers/cloudflare-ai-gateway.js +59 -0
  126. package/dist/providers/cloudflare-workers-ai.d.ts +232 -0
  127. package/dist/providers/cloudflare-workers-ai.js +45 -0
  128. package/dist/providers/deepinfra.d.ts +228 -0
  129. package/dist/providers/deepinfra.js +43 -0
  130. package/dist/providers/deepseek.d.ts +229 -0
  131. package/dist/providers/deepseek.js +41 -0
  132. package/dist/providers/fireworks.d.ts +229 -0
  133. package/dist/providers/fireworks.js +38 -0
  134. package/dist/providers/google-vertex/chat.d.ts +2 -0
  135. package/dist/providers/google-vertex/chat.js +1 -0
  136. package/dist/providers/google-vertex/gemini.d.ts +2 -0
  137. package/dist/providers/google-vertex/gemini.js +1 -0
  138. package/dist/providers/google-vertex/messages.d.ts +2 -0
  139. package/dist/providers/google-vertex/messages.js +1 -0
  140. package/dist/providers/google-vertex/responses.d.ts +2 -0
  141. package/dist/providers/google-vertex/responses.js +1 -0
  142. package/dist/providers/google-vertex-chat.d.ts +133 -0
  143. package/dist/providers/google-vertex-chat.js +55 -0
  144. package/dist/providers/google-vertex-messages.d.ts +301 -0
  145. package/dist/providers/google-vertex-messages.js +75 -0
  146. package/dist/providers/google-vertex-responses.d.ts +198 -0
  147. package/dist/providers/google-vertex-responses.js +56 -0
  148. package/dist/providers/google-vertex-shared.d.ts +22 -0
  149. package/dist/providers/google-vertex-shared.js +61 -0
  150. package/dist/providers/google-vertex.d.ts +120 -0
  151. package/dist/providers/google-vertex.js +92 -0
  152. package/dist/providers/google.d.ts +115 -0
  153. package/dist/providers/google.js +42 -0
  154. package/dist/providers/groq.d.ts +315 -0
  155. package/dist/providers/groq.js +81 -0
  156. package/dist/providers/index.d.ts +28 -0
  157. package/dist/providers/index.js +28 -0
  158. package/dist/providers/meta/chat.d.ts +2 -0
  159. package/dist/providers/meta/chat.js +1 -0
  160. package/dist/providers/meta/messages.d.ts +2 -0
  161. package/dist/providers/meta/messages.js +1 -0
  162. package/dist/providers/meta/responses.d.ts +2 -0
  163. package/dist/providers/meta/responses.js +1 -0
  164. package/dist/providers/meta.d.ts +631 -0
  165. package/dist/providers/meta.js +113 -0
  166. package/dist/providers/minimax/chat.d.ts +4 -0
  167. package/dist/providers/minimax/chat.js +8 -0
  168. package/dist/providers/minimax/messages.d.ts +1 -0
  169. package/dist/providers/minimax/messages.js +1 -0
  170. package/dist/providers/minimax/responses.d.ts +4 -0
  171. package/dist/providers/minimax/responses.js +8 -0
  172. package/dist/providers/minimax.d.ts +593 -0
  173. package/dist/providers/minimax.js +89 -0
  174. package/dist/providers/mistral.d.ts +208 -0
  175. package/dist/providers/mistral.js +28 -0
  176. package/dist/providers/open-responses-options.d.ts +6 -0
  177. package/dist/providers/open-responses-options.js +1 -0
  178. package/dist/providers/openai/chat.d.ts +2 -0
  179. package/dist/providers/openai/chat.js +1 -0
  180. package/dist/providers/openai/responses.d.ts +2 -0
  181. package/dist/providers/openai/responses.js +1 -0
  182. package/dist/providers/openai-compatible/responses.d.ts +1 -0
  183. package/dist/providers/openai-compatible/responses.js +1 -0
  184. package/dist/providers/openai-compatible-responses.d.ts +196 -0
  185. package/dist/providers/openai-compatible-responses.js +32 -0
  186. package/dist/providers/openai-compatible.d.ts +131 -0
  187. package/dist/providers/openai-compatible.js +33 -0
  188. package/dist/providers/openai-options.d.ts +26 -0
  189. package/dist/providers/openai-options.js +41 -0
  190. package/dist/providers/openai.d.ts +405 -0
  191. package/dist/providers/openai.js +82 -0
  192. package/dist/providers/openrouter.d.ts +564 -0
  193. package/dist/providers/openrouter.js +114 -0
  194. package/dist/providers/togetherai.d.ts +228 -0
  195. package/dist/providers/togetherai.js +40 -0
  196. package/dist/providers/xai.d.ts +164 -0
  197. package/dist/providers/xai.js +84 -0
  198. package/dist/providers/zai.d.ts +24 -0
  199. package/dist/providers/zai.js +21 -0
  200. package/dist/providers.d.ts +1 -0
  201. package/dist/providers.js +1 -0
  202. package/dist/route/auth-options.d.ts +34 -0
  203. package/dist/route/auth-options.js +14 -0
  204. package/dist/route/auth.d.ts +51 -0
  205. package/dist/route/auth.js +87 -0
  206. package/dist/route/client.d.ts +430 -0
  207. package/dist/route/client.js +304 -0
  208. package/dist/route/endpoint.d.ts +28 -0
  209. package/dist/route/endpoint.js +21 -0
  210. package/dist/route/executor.d.ts +27 -0
  211. package/dist/route/executor.js +183 -0
  212. package/dist/route/framing.d.ts +29 -0
  213. package/dist/route/framing.js +14 -0
  214. package/dist/route/index.d.ts +16 -0
  215. package/dist/route/index.js +9 -0
  216. package/dist/route/protocol.d.ts +76 -0
  217. package/dist/route/protocol.js +16 -0
  218. package/dist/route/transport/http.d.ts +34 -0
  219. package/dist/route/transport/http.js +68 -0
  220. package/dist/route/transport/index.d.ts +41 -0
  221. package/dist/route/transport/index.js +4 -0
  222. package/dist/route/transport/websocket-channel.d.ts +57 -0
  223. package/dist/route/transport/websocket-channel.js +1 -0
  224. package/dist/route/transport/websocket.d.ts +56 -0
  225. package/dist/route/transport/websocket.js +366 -0
  226. package/dist/route.d.ts +1 -0
  227. package/dist/route.js +1 -0
  228. package/dist/schema/errors.d.ts +158 -0
  229. package/dist/schema/errors.js +120 -0
  230. package/dist/schema/events.d.ts +8123 -0
  231. package/dist/schema/events.js +550 -0
  232. package/dist/schema/ids.d.ts +17 -0
  233. package/dist/schema/ids.js +10 -0
  234. package/dist/schema/index.d.ts +5 -0
  235. package/dist/schema/index.js +5 -0
  236. package/dist/schema/messages.d.ts +646 -0
  237. package/dist/schema/messages.js +301 -0
  238. package/dist/schema/options.d.ts +157 -0
  239. package/dist/schema/options.js +187 -0
  240. package/dist/testing.d.ts +1693 -0
  241. package/dist/testing.js +129 -0
  242. package/dist/tool-history.d.ts +2 -0
  243. package/dist/tool-history.js +84 -0
  244. package/dist/tool-runtime.d.ts +15 -0
  245. package/dist/tool-runtime.js +62 -0
  246. package/dist/tool.d.ts +136 -0
  247. package/dist/tool.js +66 -0
  248. package/dist/utils/record.d.ts +2 -0
  249. package/dist/utils/record.js +2 -0
  250. package/dist/utils/sanitize.d.ts +1 -0
  251. package/dist/utils/sanitize.js +12 -0
  252. package/package.json +48 -0
@@ -0,0 +1,1414 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { Effect, Option, Schema } from "effect";
3
+ import { Tool } from "@opencode/schema/tool";
4
+ import { Route } from "../route/client.js";
5
+ import { Auth } from "../route/auth.js";
6
+ import { Endpoint } from "../route/endpoint.js";
7
+ import { Framing } from "../route/framing.js";
8
+ import { Protocol } from "../route/protocol.js";
9
+ import { Headers } from "effect/unstable/http";
10
+ import { HttpTransport } from "../route/transport/index.js";
11
+ import { AIError, HttpOptions, LLMRequest, LLMEvent, mergeJsonRecords, Usage, } from "../schema/index.js";
12
+ import { JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared.js";
13
+ import { classifyProviderFailure } from "../provider-error.js";
14
+ import * as Cache from "./utils/cache.js";
15
+ import { Lifecycle } from "./utils/lifecycle.js";
16
+ import { ToolSchemaProjection } from "./utils/tool-schema.js";
17
+ import { ToolStream } from "./utils/tool-stream.js";
18
+ const ADAPTER = "anthropic-messages";
19
+ export const DEFAULT_BASE_URL = "https://api.anthropic.com/v1";
20
+ export const PATH = "/messages";
21
+ export const DEFAULT_MAX_TOKENS = 32_000;
22
+ const SSE_EVENTS = new Set([
23
+ "message",
24
+ "message_start",
25
+ "message_delta",
26
+ "message_stop",
27
+ "content_block_start",
28
+ "content_block_delta",
29
+ "content_block_stop",
30
+ "ping",
31
+ "error",
32
+ ]);
33
+ export const framing = Framing.sseEvents(SSE_EVENTS);
34
+ export const ContextManagement = Schema.Struct({
35
+ edits: Schema.Array(Schema.Struct({
36
+ type: Schema.Literal("compact_20260112"),
37
+ trigger: Schema.optional(Schema.Struct({
38
+ type: Schema.Literal("input_tokens"),
39
+ value: Schema.Int.check(Schema.isGreaterThanOrEqualTo(50000)),
40
+ })),
41
+ pauseAfterCompaction: Schema.optional(Schema.Boolean),
42
+ instructions: Schema.optional(Schema.String),
43
+ })),
44
+ });
45
+ // =============================================================================
46
+ // Request Body Schema
47
+ // =============================================================================
48
+ const AnthropicCacheControl = Schema.Struct({
49
+ type: Schema.tag("ephemeral"),
50
+ ttl: Schema.optional(Schema.Literals(["5m", "1h"])),
51
+ });
52
+ const AnthropicTextBlock = Schema.Struct({
53
+ type: Schema.tag("text"),
54
+ text: Schema.String,
55
+ cache_control: Schema.optional(AnthropicCacheControl),
56
+ });
57
+ // SDK: Base64ImageSource:201 {type:"base64", media_type:"image/jpeg"|... , data}, URLImageSource:3817 {type:"url", url}, FileImageSource:2350 {type:"file", file_id}
58
+ // SDK: ImageBlockParam:2356 {source: Base64|URL|File, cache_control, transformations:2381 {oversized_image?}}
59
+ const AnthropicBase64ImageSource = Schema.Struct({
60
+ type: Schema.tag("base64"),
61
+ media_type: Schema.String,
62
+ data: Schema.String,
63
+ });
64
+ const AnthropicURLImageSource = Schema.Struct({ type: Schema.tag("url"), url: Schema.String });
65
+ const AnthropicFileImageSource = Schema.Struct({ type: Schema.tag("file"), file_id: Schema.String });
66
+ const AnthropicImageSource = Schema.Union([
67
+ AnthropicBase64ImageSource,
68
+ AnthropicURLImageSource,
69
+ AnthropicFileImageSource,
70
+ ]);
71
+ const AnthropicImageTransformations = Schema.Struct({
72
+ oversized_image: Schema.optional(Schema.Literals(["downsize", "error"])),
73
+ });
74
+ const AnthropicImageBlock = Schema.Struct({
75
+ type: Schema.tag("image"),
76
+ source: AnthropicImageSource,
77
+ cache_control: Schema.optional(AnthropicCacheControl),
78
+ transformations: Schema.optional(AnthropicImageTransformations),
79
+ });
80
+ // SDK: Base64PDFSource:209 {type:"base64", media_type:"application/pdf", data}, PlainTextSource:2716 {type:"text", media_type:"text/plain", data},
81
+ // SDK: URLPDFSource:3823 {type:"url", url}, FileDocumentSource:2344 {type:"file", file_id}, ContentBlockSource:2266 {type:"content", content}
82
+ // SDK: DocumentBlockParam:2297 {source: 5-way union, cache_control, citations, context, title}
83
+ const AnthropicBase64PDFSource = Schema.Struct({
84
+ type: Schema.tag("base64"),
85
+ media_type: Schema.Literal("application/pdf"),
86
+ data: Schema.String,
87
+ });
88
+ const AnthropicPlainTextSource = Schema.Struct({
89
+ type: Schema.tag("text"),
90
+ media_type: Schema.Literal("text/plain"),
91
+ data: Schema.String,
92
+ });
93
+ const AnthropicURLPDFSource = Schema.Struct({ type: Schema.tag("url"), url: Schema.String });
94
+ const AnthropicFileDocumentSource = Schema.Struct({ type: Schema.tag("file"), file_id: Schema.String });
95
+ const AnthropicDocumentSource = Schema.Union([
96
+ AnthropicBase64PDFSource,
97
+ AnthropicPlainTextSource,
98
+ AnthropicURLPDFSource,
99
+ AnthropicFileDocumentSource,
100
+ ]);
101
+ const AnthropicDocumentBlock = Schema.Struct({
102
+ type: Schema.tag("document"),
103
+ source: AnthropicDocumentSource,
104
+ cache_control: Schema.optional(AnthropicCacheControl),
105
+ title: Schema.optional(Schema.String),
106
+ context: Schema.optional(Schema.String),
107
+ citations: Schema.optional(Schema.Struct({ enabled: Schema.Boolean })),
108
+ });
109
+ const AnthropicThinkingBlock = Schema.Struct({
110
+ type: Schema.tag("thinking"),
111
+ thinking: Schema.String,
112
+ signature: Schema.String,
113
+ cache_control: Schema.optional(AnthropicCacheControl),
114
+ });
115
+ // Safety-filtered thinking arrives as an opaque encrypted `data` payload with
116
+ // no visible text. It must round-trip verbatim so multi-turn thinking + tool
117
+ // use conversations keep their reasoning continuity.
118
+ const AnthropicRedactedThinkingBlock = Schema.Struct({
119
+ type: Schema.tag("redacted_thinking"),
120
+ data: Schema.String,
121
+ cache_control: Schema.optional(AnthropicCacheControl),
122
+ });
123
+ const AnthropicToolUseBlock = Schema.Struct({
124
+ type: Schema.tag("tool_use"),
125
+ id: Schema.String,
126
+ name: Schema.String,
127
+ input: Schema.Unknown,
128
+ cache_control: Schema.optional(AnthropicCacheControl),
129
+ });
130
+ const AnthropicServerToolUseBlock = Schema.Struct({
131
+ type: Schema.tag("server_tool_use"),
132
+ id: Schema.String,
133
+ name: Schema.String,
134
+ input: Schema.Unknown,
135
+ cache_control: Schema.optional(AnthropicCacheControl),
136
+ });
137
+ // Server tool result blocks: web_search_tool_result, code_execution_tool_result,
138
+ // and web_fetch_tool_result. The provider executes the tool and inlines the
139
+ // structured result into the assistant turn — there is no client tool_result
140
+ // round-trip. We round-trip the structured `content` payload as opaque JSON so
141
+ // the next request can echo it back when continuing the conversation.
142
+ const AnthropicServerToolResultType = Schema.Literals([
143
+ "web_search_tool_result",
144
+ "code_execution_tool_result",
145
+ "web_fetch_tool_result",
146
+ ]);
147
+ const AnthropicServerToolResultBlock = Schema.Struct({
148
+ type: AnthropicServerToolResultType,
149
+ tool_use_id: Schema.String,
150
+ content: Schema.Unknown,
151
+ cache_control: Schema.optional(AnthropicCacheControl),
152
+ });
153
+ // Anthropic accepts either a plain string or an ordered array of text, image, and
154
+ // document blocks inside `tool_result.content`. The array form keeps media as native
155
+ // model input instead of JSON-stringifying base64 into prompt text.
156
+ const AnthropicToolResultContent = Schema.Union([AnthropicTextBlock, AnthropicImageBlock, AnthropicDocumentBlock]);
157
+ const AnthropicToolResultBlock = Schema.Struct({
158
+ type: Schema.tag("tool_result"),
159
+ tool_use_id: Schema.String,
160
+ content: Schema.Union([Schema.String, Schema.Array(AnthropicToolResultContent)]),
161
+ is_error: Schema.optional(Schema.Boolean),
162
+ cache_control: Schema.optional(AnthropicCacheControl),
163
+ });
164
+ const AnthropicUserBlock = Schema.Union([
165
+ AnthropicTextBlock,
166
+ AnthropicImageBlock,
167
+ AnthropicDocumentBlock,
168
+ AnthropicToolResultBlock,
169
+ ]);
170
+ const AnthropicCompactionBlock = Schema.Struct({
171
+ type: Schema.Literal("compaction"),
172
+ content: Schema.NullOr(Schema.String),
173
+ });
174
+ const AnthropicAssistantBlock = Schema.Union([
175
+ AnthropicCompactionBlock,
176
+ AnthropicTextBlock,
177
+ AnthropicThinkingBlock,
178
+ AnthropicRedactedThinkingBlock,
179
+ AnthropicToolUseBlock,
180
+ AnthropicServerToolUseBlock,
181
+ AnthropicServerToolResultBlock,
182
+ ]);
183
+ const AnthropicMessage = Schema.Union([
184
+ Schema.Struct({ role: Schema.Literal("user"), content: Schema.Array(AnthropicUserBlock) }),
185
+ Schema.Struct({ role: Schema.Literal("assistant"), content: Schema.Array(AnthropicAssistantBlock) }),
186
+ Schema.Struct({ role: Schema.Literal("system"), content: Schema.Array(AnthropicTextBlock) }),
187
+ ]).pipe(Schema.toTaggedUnion("role"));
188
+ const AnthropicTool = Schema.Struct({
189
+ name: Schema.String,
190
+ description: Schema.String,
191
+ input_schema: JsonObject,
192
+ cache_control: Schema.optional(AnthropicCacheControl),
193
+ });
194
+ const AnthropicToolChoice = Schema.Union([
195
+ Schema.Struct({
196
+ type: Schema.Literals(["auto", "any", "none"]),
197
+ disable_parallel_tool_use: Schema.optional(Schema.Boolean),
198
+ }),
199
+ Schema.Struct({
200
+ type: Schema.tag("tool"),
201
+ name: Schema.String,
202
+ disable_parallel_tool_use: Schema.optional(Schema.Boolean),
203
+ }),
204
+ ]);
205
+ const AnthropicThinking = Schema.Union([
206
+ Schema.Struct({
207
+ type: Schema.tag("enabled"),
208
+ budget_tokens: Schema.Number,
209
+ display: Schema.optional(Schema.Literals(["summarized", "omitted"])),
210
+ }),
211
+ Schema.Struct({
212
+ type: Schema.tag("adaptive"),
213
+ display: Schema.optional(Schema.Literals(["summarized", "omitted"])),
214
+ }),
215
+ Schema.Struct({
216
+ type: Schema.tag("disabled"),
217
+ }),
218
+ ]);
219
+ // SDK OutputConfig:2684 {effort?: "low"|"medium"|"high"|"xhigh"|"max"|null, format?: JSONOutputFormat:2399}
220
+ const AnthropicJsonOutputFormat = Schema.Struct({
221
+ type: Schema.Literal("json_schema"),
222
+ schema: JsonObject,
223
+ });
224
+ const AnthropicOutputConfig = Schema.Struct({
225
+ effort: Schema.optional(Schema.String),
226
+ format: Schema.optional(Schema.NullOr(AnthropicJsonOutputFormat)),
227
+ });
228
+ // SDK Metadata:2649 {user_id?: string|null}
229
+ const AnthropicMetadata = Schema.Struct({ user_id: optionalNull(Schema.String) });
230
+ // SDK MessageCreateParamsContainer:2596 ContainerParams|string; ContainerParams:2172 {id?, skills?}
231
+ const AnthropicContainer = Schema.Union([
232
+ Schema.String,
233
+ Schema.Struct({
234
+ id: optionalNull(Schema.String),
235
+ skills: optionalNull(Schema.Array(JsonObject)),
236
+ }),
237
+ ]);
238
+ const AnthropicBodyFields = {
239
+ context_management: Schema.optional(Schema.Struct({
240
+ edits: Schema.Array(Schema.Struct({
241
+ type: Schema.Literal("compact_20260112"),
242
+ trigger: ContextManagement.fields.edits.value.fields.trigger,
243
+ pause_after_compaction: Schema.optional(Schema.Boolean),
244
+ instructions: Schema.optional(Schema.String),
245
+ })),
246
+ })),
247
+ model: Schema.String,
248
+ system: optionalArray(AnthropicTextBlock),
249
+ messages: Schema.Array(AnthropicMessage),
250
+ tools: optionalArray(AnthropicTool),
251
+ tool_choice: Schema.optional(AnthropicToolChoice),
252
+ stream: Schema.Literal(true),
253
+ max_tokens: Schema.Number,
254
+ temperature: Schema.optional(Schema.Number),
255
+ top_p: Schema.optional(Schema.Number),
256
+ top_k: Schema.optional(Schema.Number),
257
+ stop_sequences: optionalArray(Schema.String),
258
+ thinking: Schema.optional(AnthropicThinking),
259
+ output_config: Schema.optional(AnthropicOutputConfig),
260
+ // SDK top-level passthrough: cache_control:4638, container:4643, inference_geo:4649, metadata:4654, service_tier:4670
261
+ cache_control: Schema.optional(AnthropicCacheControl),
262
+ container: Schema.optional(Schema.NullOr(AnthropicContainer)),
263
+ inference_geo: Schema.optional(Schema.NullOr(Schema.String)),
264
+ metadata: Schema.optional(AnthropicMetadata),
265
+ service_tier: Schema.optional(Schema.Literals(["auto", "standard_only"])),
266
+ };
267
+ export const AnthropicMessagesBody = Schema.Struct(AnthropicBodyFields);
268
+ const AnthropicIterationUsage = Schema.StructWithRest(Schema.Struct({
269
+ input_tokens: optionalNull(Schema.Number),
270
+ output_tokens: Schema.optional(Schema.Number),
271
+ cache_creation_input_tokens: optionalNull(Schema.Number),
272
+ cache_read_input_tokens: optionalNull(Schema.Number),
273
+ server_tool_use: optionalNull(Schema.StructWithRest(Schema.Struct({ web_search_requests: Schema.optional(Schema.Number) }), [
274
+ Schema.Record(Schema.String, Schema.Unknown),
275
+ ])),
276
+ output_tokens_details: optionalNull(Schema.StructWithRest(Schema.Struct({ thinking_tokens: Schema.optional(Schema.Number) }), [
277
+ Schema.Record(Schema.String, Schema.Unknown),
278
+ ])),
279
+ }), [Schema.Record(Schema.String, Schema.Unknown)]);
280
+ const AnthropicUsage = Schema.StructWithRest(Schema.Struct({
281
+ ...AnthropicIterationUsage.schema.fields,
282
+ iterations: Schema.optional(Schema.Array(AnthropicIterationUsage)),
283
+ }), [JsonObject]);
284
+ const AnthropicStreamBlock = Schema.Struct({
285
+ type: Schema.String,
286
+ id: Schema.optional(Schema.String),
287
+ name: Schema.optional(Schema.String),
288
+ text: Schema.optional(Schema.String),
289
+ thinking: Schema.optional(Schema.String),
290
+ signature: Schema.optional(Schema.String),
291
+ // redacted_thinking blocks arrive whole in content_block_start with the
292
+ // encrypted payload in `data`; there is no streaming delta sequence.
293
+ data: Schema.optional(Schema.String),
294
+ input: Schema.optional(Schema.Unknown),
295
+ // *_tool_result blocks arrive whole as content_block_start (no streaming
296
+ // delta) with the structured payload in `content` and the originating
297
+ // server_tool_use id in `tool_use_id`.
298
+ tool_use_id: Schema.optional(Schema.String),
299
+ content: Schema.optional(Schema.Unknown),
300
+ });
301
+ const decodeAnthropicStreamBlock = Schema.decodeUnknownOption(AnthropicStreamBlock);
302
+ const AnthropicStreamDelta = Schema.Struct({
303
+ content: optionalNull(Schema.String),
304
+ type: Schema.optional(Schema.String),
305
+ text: Schema.optional(Schema.String),
306
+ thinking: Schema.optional(Schema.String),
307
+ partial_json: Schema.optional(Schema.String),
308
+ signature: Schema.optional(Schema.String),
309
+ stop_reason: optionalNull(Schema.String),
310
+ stop_sequence: optionalNull(Schema.String),
311
+ });
312
+ const decodeAnthropicStreamDelta = Schema.decodeUnknownOption(AnthropicStreamDelta);
313
+ const AnthropicEvent = Schema.Struct({
314
+ type: Schema.String,
315
+ index: Schema.optional(Schema.Number),
316
+ message: Schema.optional(Schema.Struct({ usage: Schema.optional(AnthropicUsage) })),
317
+ content_block: Schema.optional(Schema.Unknown),
318
+ delta: Schema.optional(Schema.Unknown),
319
+ usage: Schema.optional(AnthropicUsage),
320
+ // `type` and `message` are both required per Anthropic's spec, but
321
+ // OpenAI-compatible proxies and gateway translations occasionally drop one
322
+ // or the other; mark them optional so a partial payload still parses and
323
+ // the parser can fall back to whichever field is populated.
324
+ error: Schema.optional(Schema.Struct({ type: Schema.optional(Schema.String), message: Schema.optional(Schema.String) })),
325
+ });
326
+ const invalid = ProviderShared.invalidRequest;
327
+ // =============================================================================
328
+ // Request Lowering
329
+ // =============================================================================
330
+ // Anthropic accepts at most 4 explicit cache_control breakpoints per request,
331
+ // across `tools`, `system`, and `messages`. Beyond the cap the API returns a
332
+ // 400 — so the lowering layer counts emitted markers and silently drops any
333
+ // that exceed it.
334
+ const ANTHROPIC_BREAKPOINT_CAP = 4;
335
+ const EPHEMERAL_5M = { type: "ephemeral" };
336
+ const EPHEMERAL_1H = { type: "ephemeral", ttl: "1h" };
337
+ const cacheControl = (breakpoints, cache) => {
338
+ if (cache?.type !== "ephemeral" && cache?.type !== "persistent")
339
+ return undefined;
340
+ if (breakpoints.remaining <= 0) {
341
+ breakpoints.dropped += 1;
342
+ return undefined;
343
+ }
344
+ breakpoints.remaining -= 1;
345
+ return Cache.ttlBucket(cache.ttlSeconds) === "1h" ? EPHEMERAL_1H : EPHEMERAL_5M;
346
+ };
347
+ const providerMetadata = (key, metadata) => ({ [key]: metadata });
348
+ const signatureFromMetadata = (metadata, key) => {
349
+ const provider = metadata?.[key];
350
+ if (!ProviderShared.isRecord(provider))
351
+ return undefined;
352
+ return typeof provider.signature === "string" ? provider.signature : undefined;
353
+ };
354
+ const redactedDataFromMetadata = (metadata, key) => {
355
+ const provider = metadata?.[key];
356
+ if (!ProviderShared.isRecord(provider))
357
+ return undefined;
358
+ return typeof provider.redactedData === "string" ? provider.redactedData : undefined;
359
+ };
360
+ const lowerTool = (breakpoints, tool, inputSchema) => ({
361
+ name: tool.name,
362
+ description: tool.description,
363
+ input_schema: inputSchema,
364
+ cache_control: cacheControl(breakpoints, tool.cache),
365
+ });
366
+ const lowerToolChoice = (toolChoice) => ProviderShared.matchToolChoice("Anthropic Messages", toolChoice, {
367
+ auto: () => ({
368
+ type: "auto",
369
+ ...(toolChoice.disableParallelToolUse === undefined
370
+ ? {}
371
+ : { disable_parallel_tool_use: toolChoice.disableParallelToolUse }),
372
+ }),
373
+ none: () => ({ type: "none" }),
374
+ required: () => ({
375
+ type: "any",
376
+ ...(toolChoice.disableParallelToolUse === undefined
377
+ ? {}
378
+ : { disable_parallel_tool_use: toolChoice.disableParallelToolUse }),
379
+ }),
380
+ tool: (name) => ({
381
+ type: "tool",
382
+ name,
383
+ ...(toolChoice.disableParallelToolUse === undefined
384
+ ? {}
385
+ : { disable_parallel_tool_use: toolChoice.disableParallelToolUse }),
386
+ }),
387
+ });
388
+ const scrubToolCallID = (id) => id.replace(/[^a-zA-Z0-9_-]/g, "_");
389
+ const lowerToolCall = (part) => ({
390
+ type: "tool_use",
391
+ id: scrubToolCallID(part.id),
392
+ name: part.name,
393
+ input: part.input,
394
+ });
395
+ const lowerServerToolCall = (part) => ({
396
+ type: "server_tool_use",
397
+ id: scrubToolCallID(part.id),
398
+ name: part.name,
399
+ input: part.input,
400
+ });
401
+ // Server tool result blocks are typed by name. Anthropic ships three today;
402
+ // extend this list when new server tools land. The block content is the
403
+ // structured payload returned by the provider, which we round-trip as-is.
404
+ const serverToolResultType = (name) => {
405
+ if (name === "web_search")
406
+ return "web_search_tool_result";
407
+ if (name === "code_execution")
408
+ return "code_execution_tool_result";
409
+ if (name === "web_fetch")
410
+ return "web_fetch_tool_result";
411
+ return undefined;
412
+ };
413
+ const lowerServerToolResult = Effect.fn("AnthropicMessages.lowerServerToolResult")(function* (part, providerMetadataKey) {
414
+ const wireType = serverToolResultType(part.name);
415
+ if (!wireType)
416
+ return yield* invalid(`Anthropic Messages does not know how to round-trip server tool result for ${part.name}`);
417
+ // Prefer the provider-owned replay payload; fall back to the result value for
418
+ // histories constructed directly from provider events.
419
+ const payload = part.providerMetadata?.[providerMetadataKey]?.["result"] ?? part.result.value;
420
+ return {
421
+ type: wireType,
422
+ tool_use_id: scrubToolCallID(part.id),
423
+ content: payload,
424
+ };
425
+ });
426
+ const fileIdFromMetadata = (metadata) => {
427
+ if (!ProviderShared.isRecord(metadata))
428
+ return undefined;
429
+ const anthropic = metadata.anthropic;
430
+ if (ProviderShared.isRecord(anthropic)) {
431
+ if (typeof anthropic.file_id === "string")
432
+ return anthropic.file_id;
433
+ if (typeof anthropic.fileId === "string")
434
+ return anthropic.fileId;
435
+ }
436
+ if (typeof metadata.file_id === "string")
437
+ return metadata.file_id;
438
+ if (typeof metadata.fileId === "string")
439
+ return metadata.fileId;
440
+ return undefined;
441
+ };
442
+ const transformationsFromMetadata = (metadata) => {
443
+ if (!ProviderShared.isRecord(metadata))
444
+ return undefined;
445
+ const anthropic = ProviderShared.isRecord(metadata.anthropic) ? metadata.anthropic : undefined;
446
+ const raw = anthropic?.transformations ?? metadata.transformations;
447
+ if (ProviderShared.isRecord(raw)) {
448
+ const value = raw.oversized_image;
449
+ if (value === "downsize" || value === "error")
450
+ return { oversized_image: value };
451
+ }
452
+ if (anthropic && (anthropic.oversized_image === "downsize" || anthropic.oversized_image === "error"))
453
+ return { oversized_image: anthropic.oversized_image };
454
+ return undefined;
455
+ };
456
+ const documentTitleFromPart = (part) => {
457
+ if (ProviderShared.isRecord(part.metadata)) {
458
+ const anthropic = part.metadata.anthropic;
459
+ if (ProviderShared.isRecord(anthropic) && typeof anthropic.title === "string")
460
+ return anthropic.title;
461
+ if (typeof part.metadata.title === "string")
462
+ return part.metadata.title;
463
+ }
464
+ if (typeof part.filename === "string" && part.filename.length > 0)
465
+ return part.filename;
466
+ return undefined;
467
+ };
468
+ const documentContextFromMetadata = (metadata) => {
469
+ if (!ProviderShared.isRecord(metadata))
470
+ return undefined;
471
+ const anthropic = ProviderShared.isRecord(metadata.anthropic) ? metadata.anthropic : undefined;
472
+ if (anthropic && typeof anthropic.context === "string")
473
+ return anthropic.context;
474
+ if (typeof metadata.context === "string")
475
+ return metadata.context;
476
+ return undefined;
477
+ };
478
+ const citationsFromMetadata = (metadata) => {
479
+ if (!ProviderShared.isRecord(metadata))
480
+ return undefined;
481
+ const raw = ProviderShared.isRecord(metadata.anthropic)
482
+ ? (metadata.anthropic.citations ?? metadata.citations)
483
+ : metadata.citations;
484
+ if (ProviderShared.isRecord(raw) && typeof raw.enabled === "boolean")
485
+ return { enabled: raw.enabled };
486
+ return undefined;
487
+ };
488
+ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());
489
+ const lowerMedia = Effect.fn("AnthropicMessages.lowerMedia")(function* (part, breakpoints) {
490
+ const mime = part.mediaType.toLowerCase();
491
+ const cacheControlValue = breakpoints ? cacheControl(breakpoints, part.cache) : undefined;
492
+ const fileId = fileIdFromMetadata(part.metadata);
493
+ // SDK file sources: FileImageSource:2350 / FileDocumentSource:2344 {type:"file", file_id}
494
+ if (fileId) {
495
+ if (mime.startsWith("image/"))
496
+ return {
497
+ type: "image",
498
+ source: { type: "file", file_id: fileId },
499
+ ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
500
+ ...(transformationsFromMetadata(part.metadata) === undefined
501
+ ? {}
502
+ : { transformations: transformationsFromMetadata(part.metadata) }),
503
+ };
504
+ return {
505
+ type: "document",
506
+ source: { type: "file", file_id: fileId },
507
+ ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
508
+ ...(documentTitleFromPart(part) === undefined ? {} : { title: documentTitleFromPart(part) }),
509
+ ...(documentContextFromMetadata(part.metadata) === undefined
510
+ ? {}
511
+ : { context: documentContextFromMetadata(part.metadata) }),
512
+ ...(citationsFromMetadata(part.metadata) === undefined
513
+ ? {}
514
+ : { citations: citationsFromMetadata(part.metadata) }),
515
+ };
516
+ }
517
+ const rawString = typeof part.data === "string" ? part.data.trim() : undefined;
518
+ // SDK URL sources: URLImageSource:3817 / URLPDFSource:3823 {type:"url", url}
519
+ if (rawString && isHttpUrl(rawString) && !rawString.startsWith("data:")) {
520
+ if (mime.startsWith("image/"))
521
+ return {
522
+ type: "image",
523
+ source: { type: "url", url: rawString },
524
+ ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
525
+ ...(transformationsFromMetadata(part.metadata) === undefined
526
+ ? {}
527
+ : { transformations: transformationsFromMetadata(part.metadata) }),
528
+ };
529
+ if (mime === "application/pdf")
530
+ return {
531
+ type: "document",
532
+ source: { type: "url", url: rawString },
533
+ ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
534
+ ...(documentTitleFromPart(part) === undefined ? {} : { title: documentTitleFromPart(part) }),
535
+ ...(documentContextFromMetadata(part.metadata) === undefined
536
+ ? {}
537
+ : { context: documentContextFromMetadata(part.metadata) }),
538
+ ...(citationsFromMetadata(part.metadata) === undefined
539
+ ? {}
540
+ : { citations: citationsFromMetadata(part.metadata) }),
541
+ };
542
+ }
543
+ // SDK PlainTextSource:2716 {type:"text", media_type:"text/plain", data}
544
+ if (mime === "text/plain") {
545
+ const textData = typeof part.data !== "string"
546
+ ? Buffer.from(part.data).toString("utf8")
547
+ : part.data.startsWith("data:")
548
+ ? (() => {
549
+ const comma = part.data.indexOf(",");
550
+ const payload = comma >= 0 ? part.data.slice(comma + 1) : part.data;
551
+ return part.data.includes(";base64")
552
+ ? Buffer.from(payload, "base64").toString("utf8")
553
+ : decodeURIComponent(payload);
554
+ })()
555
+ : part.data;
556
+ return {
557
+ type: "document",
558
+ source: { type: "text", media_type: "text/plain", data: textData },
559
+ ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
560
+ ...(documentTitleFromPart(part) === undefined ? {} : { title: documentTitleFromPart(part) }),
561
+ ...(documentContextFromMetadata(part.metadata) === undefined
562
+ ? {}
563
+ : { context: documentContextFromMetadata(part.metadata) }),
564
+ ...(citationsFromMetadata(part.metadata) === undefined
565
+ ? {}
566
+ : { citations: citationsFromMetadata(part.metadata) }),
567
+ };
568
+ }
569
+ const media = ProviderShared.normalizeMedia(part);
570
+ if (media.mime === "application/pdf")
571
+ return {
572
+ type: "document",
573
+ source: {
574
+ type: "base64",
575
+ media_type: "application/pdf",
576
+ data: media.base64,
577
+ },
578
+ ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
579
+ ...(documentTitleFromPart(part) === undefined ? {} : { title: documentTitleFromPart(part) }),
580
+ ...(documentContextFromMetadata(part.metadata) === undefined
581
+ ? {}
582
+ : { context: documentContextFromMetadata(part.metadata) }),
583
+ ...(citationsFromMetadata(part.metadata) === undefined
584
+ ? {}
585
+ : { citations: citationsFromMetadata(part.metadata) }),
586
+ };
587
+ if (!media.mime.startsWith("image/"))
588
+ return yield* invalid(`Anthropic Messages does not support media type ${part.mediaType}`);
589
+ return {
590
+ type: "image",
591
+ source: {
592
+ type: "base64",
593
+ media_type: media.mime,
594
+ data: media.base64,
595
+ },
596
+ ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
597
+ ...(transformationsFromMetadata(part.metadata) === undefined
598
+ ? {}
599
+ : { transformations: transformationsFromMetadata(part.metadata) }),
600
+ };
601
+ });
602
+ // Tool results may carry structured text, images, and documents. Keep media as provider-native
603
+ // content instead of JSON-stringifying base64 into a prompt string.
604
+ const lowerToolResultContentItem = Effect.fnUntraced(function* (item) {
605
+ if (item.type === "text")
606
+ return { type: "text", text: item.text };
607
+ return yield* lowerMedia({ type: "media", mediaType: item.mime, data: item.uri, filename: item.name });
608
+ });
609
+ const lowerToolResultContent = Effect.fnUntraced(function* (part) {
610
+ // Text / json / error results stay as a string for backward compatibility
611
+ // with existing cassettes and provider expectations.
612
+ if (part.result.type !== "content")
613
+ return ProviderShared.toolResultText(part);
614
+ // Preserve the narrowed array element type when compiled through a consumer package.
615
+ const content = part.result.value;
616
+ return yield* Effect.forEach(content, lowerToolResultContentItem);
617
+ });
618
+ const requireThinkingSignature = (request) => {
619
+ if (request.model.compatibility?.requireSignature !== undefined)
620
+ return request.model.compatibility.requireSignature;
621
+ const provider = request.model.provider.toLowerCase();
622
+ const model = request.model.id.toLowerCase();
623
+ const baseURL = (request.model.route.endpoint.baseURL ?? "").toLowerCase();
624
+ if (provider === "kimi-for-coding" ||
625
+ provider === "moonshotai" ||
626
+ provider === "moonshotai-cn" ||
627
+ model.startsWith("kimi-") ||
628
+ baseURL.includes("api.kimi.com/coding") ||
629
+ baseURL.includes("api.moonshot.ai/anthropic") ||
630
+ baseURL.includes("api.moonshot.cn/anthropic"))
631
+ return false;
632
+ if (provider.includes("xiaomi") || model.includes("mimo") || baseURL.includes("xiaomimimo.com"))
633
+ return false;
634
+ return true;
635
+ };
636
+ // Mid-conversation system messages became available with Opus 4.8 and version
637
+ // 5 of the other supported Claude families. Treat later family versions as
638
+ // compatible without assuming that every Anthropic Messages model is Claude.
639
+ const supportsNativeSystemUpdates = (request) => {
640
+ const match = /(?:^|[./])claude-(fable|haiku|mythos|opus|sonnet)-(\d+)(?:[.-](\d+))?/.exec(String(request.model.id).toLowerCase());
641
+ if (!match)
642
+ return false;
643
+ const major = Number(match[2]);
644
+ if (match[1] !== "opus")
645
+ return major >= 5;
646
+ if (major !== 4)
647
+ return major >= 5;
648
+ return match[3] !== undefined && match[3].length <= 2 && Number(match[3]) >= 8;
649
+ };
650
+ const endsInServerToolUse = (message) => {
651
+ const last = message.content.at(-1);
652
+ return message.role === "assistant" && last?.type === "tool-call" && last.providerExecuted === true;
653
+ };
654
+ const canUseNativeSystemUpdate = (request, index) => {
655
+ const previous = request.messages[index - 1];
656
+ const next = request.messages[index + 1];
657
+ // Vertex currently rejects/404s for a system message after local tool results,
658
+ // so fold it into the user tool-result turn across continuations and history.
659
+ if (request.model.route.id === "google-vertex-messages" && previous?.role === "tool")
660
+ return false;
661
+ return (previous !== undefined &&
662
+ previous.role !== "system" &&
663
+ (previous.role === "user" || previous.role === "tool" || endsInServerToolUse(previous)) &&
664
+ next?.role !== "system" &&
665
+ (next === undefined || next.role === "assistant"));
666
+ };
667
+ const splitsLocalToolResults = (messages, index) => {
668
+ const pending = new Set();
669
+ for (const message of messages.slice(0, index)) {
670
+ for (const part of message.content) {
671
+ if (message.role === "assistant" && part.type === "tool-call" && part.providerExecuted !== true)
672
+ pending.add(part.id);
673
+ if (message.role === "tool" && part.type === "tool-result")
674
+ pending.delete(part.id);
675
+ }
676
+ }
677
+ return pending.size > 0;
678
+ };
679
+ const lowerNativeSystemUpdate = Effect.fn("AnthropicMessages.lowerNativeSystemUpdate")(function* (message, breakpoints) {
680
+ const content = yield* ProviderShared.systemUpdateText("Anthropic Messages", message);
681
+ return {
682
+ role: "system",
683
+ content: content.map((part) => ({
684
+ type: "text",
685
+ text: part.text,
686
+ cache_control: cacheControl(breakpoints, part.cache),
687
+ })),
688
+ };
689
+ });
690
+ const lowerMessages = Effect.fn("AnthropicMessages.lowerMessages")(function* (request, breakpoints) {
691
+ const messages = [];
692
+ const providerMetadataKey = request.model.route.providerMetadataKey ?? String(request.model.provider);
693
+ for (const [index, message] of request.messages.entries()) {
694
+ if (message.role === "system") {
695
+ if (splitsLocalToolResults(request.messages, index))
696
+ return yield* invalid("Anthropic Messages system updates cannot split a local tool call from its tool result");
697
+ if (supportsNativeSystemUpdates(request) && canUseNativeSystemUpdate(request, index)) {
698
+ messages.push(yield* lowerNativeSystemUpdate(message, breakpoints));
699
+ continue;
700
+ }
701
+ const part = yield* ProviderShared.wrappedSystemUpdate("Anthropic Messages", message);
702
+ const block = { type: "text", text: part.text, cache_control: cacheControl(breakpoints, part.cache) };
703
+ const previous = messages.at(-1);
704
+ if (previous?.role === "user")
705
+ messages[messages.length - 1] = { role: "user", content: [...previous.content, block] };
706
+ else
707
+ messages.push({ role: "user", content: [block] });
708
+ continue;
709
+ }
710
+ if (message.role === "user") {
711
+ const content = [];
712
+ for (const part of message.content) {
713
+ if (part.type === "text") {
714
+ if (part.text.trim().length === 0)
715
+ continue;
716
+ content.push({ type: "text", text: part.text, cache_control: cacheControl(breakpoints, part.cache) });
717
+ continue;
718
+ }
719
+ if (part.type === "media") {
720
+ content.push(yield* lowerMedia(part, breakpoints));
721
+ continue;
722
+ }
723
+ return yield* ProviderShared.unsupportedContent("Anthropic Messages", "user", ["text", "media"]);
724
+ }
725
+ if (content.length > 0)
726
+ messages.push({ role: "user", content });
727
+ continue;
728
+ }
729
+ if (message.role === "assistant") {
730
+ const content = [];
731
+ for (const part of message.content) {
732
+ if (part.type === "compaction") {
733
+ if (part.provider !== request.model.provider || part.text === undefined)
734
+ return yield* invalid("Compaction state must be replayed to its originating provider and API");
735
+ content.push({ type: "compaction", content: part.text });
736
+ continue;
737
+ }
738
+ if (part.type === "text") {
739
+ if (part.text.trim().length === 0)
740
+ continue;
741
+ content.push({ type: "text", text: part.text, cache_control: cacheControl(breakpoints, part.cache) });
742
+ continue;
743
+ }
744
+ if (part.type === "reasoning") {
745
+ // A signature marks visible thinking; only signature-less parts carrying
746
+ // redactedData round-trip as opaque redacted_thinking blocks.
747
+ const signature = part.encrypted ?? signatureFromMetadata(part.providerMetadata, providerMetadataKey);
748
+ const redactedData = redactedDataFromMetadata(part.providerMetadata, providerMetadataKey);
749
+ if (signature === undefined && redactedData !== undefined) {
750
+ content.push({ type: "redacted_thinking", data: redactedData });
751
+ continue;
752
+ }
753
+ if (typeof signature !== "string" || signature.trim().length === 0) {
754
+ if (part.text.trim().length === 0)
755
+ continue;
756
+ if (!requireThinkingSignature(request)) {
757
+ content.push({ type: "thinking", thinking: part.text, signature: "" });
758
+ continue;
759
+ }
760
+ // Without a signature this cannot be a valid thinking block per
761
+ // the SDK ThinkingBlockParam:3217 — demote to text so the
762
+ // conversation remains sendable.
763
+ content.push({
764
+ type: "text",
765
+ text: part.text,
766
+ cache_control: cacheControl(breakpoints, part.cache),
767
+ });
768
+ continue;
769
+ }
770
+ content.push({ type: "thinking", thinking: part.text, signature });
771
+ continue;
772
+ }
773
+ if (part.type === "tool-call") {
774
+ content.push(part.providerExecuted ? lowerServerToolCall(part) : lowerToolCall(part));
775
+ continue;
776
+ }
777
+ if (part.type === "tool-result" && part.providerExecuted) {
778
+ content.push(yield* lowerServerToolResult(part, providerMetadataKey));
779
+ continue;
780
+ }
781
+ return yield* invalid(`Anthropic Messages assistant messages only support text, reasoning, and tool-call content for now`);
782
+ }
783
+ if (content.length > 0)
784
+ messages.push({ role: "assistant", content });
785
+ continue;
786
+ }
787
+ const content = [];
788
+ for (const part of message.content) {
789
+ if (!ProviderShared.supportsContent(part, ["tool-result"]))
790
+ return yield* ProviderShared.unsupportedContent("Anthropic Messages", "tool", ["tool-result"]);
791
+ content.push({
792
+ type: "tool_result",
793
+ tool_use_id: scrubToolCallID(part.id),
794
+ content: yield* lowerToolResultContent(part),
795
+ is_error: part.result.type === "error" ? true : undefined,
796
+ cache_control: cacheControl(breakpoints, part.cache),
797
+ });
798
+ }
799
+ const previous = messages.at(-1);
800
+ if (previous?.role === "user" && previous.content.every((block) => block.type === "tool_result"))
801
+ messages[messages.length - 1] = { role: "user", content: [...previous.content, ...content] };
802
+ else
803
+ messages.push({ role: "user", content });
804
+ }
805
+ return messages;
806
+ });
807
+ const resolveOptions = Effect.fn("AnthropicMessages.resolveOptions")(function* (request) {
808
+ const input = request.providerOptions;
809
+ const rawServiceTier = input?.service_tier ??
810
+ input?.serviceTier;
811
+ const service_tier = rawServiceTier === "auto" || rawServiceTier === "standard_only"
812
+ ? rawServiceTier
813
+ : undefined;
814
+ const rawMetadata = input?.metadata;
815
+ const metadata = ProviderShared.isRecord(rawMetadata) && (typeof rawMetadata.user_id === "string" || rawMetadata.user_id === null)
816
+ ? { user_id: rawMetadata.user_id }
817
+ : undefined;
818
+ const container = typeof input?.container === "string" ||
819
+ ProviderShared.isRecord(input?.container)
820
+ ? input.container
821
+ : undefined;
822
+ const rawInferenceGeo = input?.inference_geo ??
823
+ input?.inferenceGeo;
824
+ const inference_geo = typeof rawInferenceGeo === "string" ? rawInferenceGeo : undefined;
825
+ const rawCacheControl = input?.cache_control ??
826
+ input?.cacheControl;
827
+ const cache_control = ProviderShared.isRecord(rawCacheControl) && rawCacheControl.type === "ephemeral"
828
+ ? rawCacheControl
829
+ : undefined;
830
+ const rawOutputConfig = input?.output_config ??
831
+ input?.outputConfig;
832
+ const outputConfigEffort = typeof input?.effort === "string"
833
+ ? input.effort
834
+ : ProviderShared.isRecord(rawOutputConfig) && typeof rawOutputConfig.effort === "string"
835
+ ? rawOutputConfig.effort
836
+ : undefined;
837
+ const outputConfigFormat = ProviderShared.isRecord(rawOutputConfig) && ProviderShared.isRecord(rawOutputConfig.format)
838
+ ? rawOutputConfig.format
839
+ : undefined;
840
+ const output_config = outputConfigEffort === undefined && outputConfigFormat === undefined
841
+ ? undefined
842
+ : {
843
+ ...(outputConfigEffort === undefined ? {} : { effort: outputConfigEffort }),
844
+ ...(outputConfigFormat === undefined ? {} : { format: outputConfigFormat }),
845
+ };
846
+ return {
847
+ thinking: yield* resolveThinking(input?.thinking),
848
+ effort: outputConfigEffort,
849
+ output_config,
850
+ service_tier,
851
+ metadata,
852
+ container,
853
+ inference_geo,
854
+ cache_control,
855
+ };
856
+ });
857
+ const resolveThinking = Effect.fn("AnthropicMessages.resolveThinking")(function* (input) {
858
+ if (!ProviderShared.isRecord(input))
859
+ return undefined;
860
+ const display = input.display === "summarized" || input.display === "omitted"
861
+ ? input.display
862
+ : undefined;
863
+ if (input.type === "adaptive")
864
+ return { type: "adaptive", ...(display === undefined ? {} : { display }) };
865
+ if (input.type === "disabled")
866
+ return { type: "disabled" };
867
+ if (input.type !== "enabled")
868
+ return undefined;
869
+ const budget = typeof input.budgetTokens === "number"
870
+ ? input.budgetTokens
871
+ : typeof input.budget_tokens === "number"
872
+ ? input.budget_tokens
873
+ : undefined;
874
+ if (budget === undefined)
875
+ return yield* ProviderShared.invalidRequest("Anthropic thinking provider option requires budgetTokens");
876
+ return { type: "enabled", budget_tokens: budget, ...(display === undefined ? {} : { display }) };
877
+ });
878
+ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (request) {
879
+ const management = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(Schema.UndefinedOr(ContextManagement)))(request.providerOptions?.contextManagement);
880
+ const generation = request.generation;
881
+ const toolSchemaCompatibility = request.model.compatibility?.toolSchema;
882
+ // Allocate the 4-breakpoint budget in invalidation order: tools → system →
883
+ // messages. Tools live highest in the cache hierarchy, so when callers
884
+ // over-mark we keep their tool hints and shed the message-tail ones first.
885
+ const breakpoints = Cache.newBreakpoints(ANTHROPIC_BREAKPOINT_CAP);
886
+ const flattened = ProviderShared.flattenToolRequest(request);
887
+ const tools = flattened.tools.length === 0
888
+ ? undefined
889
+ : flattened.tools.map((tool) => lowerTool(breakpoints, tool, ToolSchemaProjection.modelCompatibility(tool.inputSchema, toolSchemaCompatibility)));
890
+ // Anthropic rejects tool_choice when tools are absent; "none" is only meaningful with tools present.
891
+ const toolChoice = tools === undefined || !request.toolChoice ? undefined : yield* lowerToolChoice(request.toolChoice);
892
+ const systemParts = request.system.filter((part) => part.text.length > 0);
893
+ const system = systemParts.length === 0
894
+ ? undefined
895
+ : systemParts.map((part) => ({
896
+ type: "text",
897
+ text: part.text,
898
+ cache_control: cacheControl(breakpoints, part.cache),
899
+ }));
900
+ const messages = yield* lowerMessages(flattened.request, breakpoints);
901
+ if (breakpoints.dropped > 0) {
902
+ yield* Effect.logWarning(`Anthropic Messages: dropped ${breakpoints.dropped} cache breakpoint(s); the API allows at most ${ANTHROPIC_BREAKPOINT_CAP} per request.`);
903
+ }
904
+ const options = yield* resolveOptions(request);
905
+ const body = {
906
+ model: request.model.id,
907
+ system,
908
+ messages,
909
+ tools,
910
+ tool_choice: toolChoice,
911
+ stream: true,
912
+ max_tokens: generation?.maxTokens ?? DEFAULT_MAX_TOKENS,
913
+ temperature: generation?.temperature,
914
+ top_p: generation?.topP,
915
+ top_k: generation?.topK,
916
+ stop_sequences: generation?.stop,
917
+ thinking: options.thinking,
918
+ output_config: options.output_config,
919
+ // top-level passthrough per SDK MessageCreateParamsBase:4638,4643,4649,4654,4670
920
+ cache_control: options.cache_control,
921
+ container: options.container,
922
+ inference_geo: options.inference_geo,
923
+ metadata: options.metadata,
924
+ service_tier: options.service_tier,
925
+ };
926
+ if (!management)
927
+ return body;
928
+ return {
929
+ ...body,
930
+ context_management: {
931
+ edits: management.edits.map((edit) => ({
932
+ type: edit.type,
933
+ trigger: edit.trigger,
934
+ pause_after_compaction: edit.pauseAfterCompaction,
935
+ instructions: edit.instructions,
936
+ })),
937
+ },
938
+ };
939
+ });
940
+ // =============================================================================
941
+ // Stream Parsing
942
+ // =============================================================================
943
+ const mapFinishReason = (reason) => {
944
+ if (reason === "end_turn" || reason === "stop_sequence" || reason === "pause_turn")
945
+ return "stop";
946
+ if (reason === "max_tokens" || reason === "model_context_window_exceeded")
947
+ return "length";
948
+ if (reason === "tool_use")
949
+ return "tool-calls";
950
+ if (reason === "refusal")
951
+ return "content-filter";
952
+ return "unknown";
953
+ };
954
+ // Anthropic reports the non-overlapping breakdown natively — its
955
+ // `input_tokens` is the *non-cached* count per the Messages API docs, with
956
+ // cache reads and writes as separate fields. We sum them to derive the
957
+ // inclusive `inputTokens` the rest of the contract expects. Extended
958
+ // thinking tokens are included in `output_tokens`; newer responses also
959
+ // expose that subset through `output_tokens_details.thinking_tokens`.
960
+ const mapUsage = (usage, providerMetadataKey) => {
961
+ if (!usage)
962
+ return undefined;
963
+ const iterations = usage.iterations?.length ? usage.iterations : [usage];
964
+ const last = usage.iterations?.at(-1);
965
+ const nonCached = ProviderShared.sumTokens(...iterations.map((item) => item.input_tokens ?? undefined));
966
+ const cacheRead = ProviderShared.sumTokens(...iterations.map((item) => item.cache_read_input_tokens ?? undefined));
967
+ const cacheWrite = ProviderShared.sumTokens(...iterations.map((item) => item.cache_creation_input_tokens ?? undefined));
968
+ const inputTokens = ProviderShared.sumTokens(nonCached, cacheRead, cacheWrite);
969
+ const outputTokens = ProviderShared.sumTokens(...iterations.map((item) => item.output_tokens));
970
+ return new Usage({
971
+ inputTokens,
972
+ outputTokens,
973
+ contextTokens: last?.type === "message"
974
+ ? ProviderShared.sumTokens(last.input_tokens ?? undefined, last.cache_read_input_tokens ?? undefined, last.cache_creation_input_tokens ?? undefined)
975
+ : undefined,
976
+ nonCachedInputTokens: nonCached,
977
+ cacheReadInputTokens: cacheRead,
978
+ cacheWriteInputTokens: cacheWrite,
979
+ reasoningTokens: ProviderShared.sumTokens(...iterations.map((item) => item.output_tokens_details?.thinking_tokens)),
980
+ totalTokens: ProviderShared.totalTokens(inputTokens, outputTokens, undefined),
981
+ providerMetadata: { [providerMetadataKey]: usage },
982
+ });
983
+ };
984
+ // Anthropic emits usage on `message_start` and again on `message_delta` — the
985
+ // final delta carries the authoritative totals. Right-biased merge: each
986
+ // field prefers `right` when defined, falls back to `left`. `inputTokens` is
987
+ // recomputed from the merged breakdown so the inclusive total stays
988
+ // consistent with `nonCached + cacheRead + cacheWrite`.
989
+ const mergeUsage = (left, right, providerMetadataKey) => {
990
+ if (!left)
991
+ return right;
992
+ if (!right)
993
+ return left;
994
+ const nonCachedInputTokens = right.nonCachedInputTokens ?? left.nonCachedInputTokens;
995
+ const cacheReadInputTokens = right.cacheReadInputTokens ?? left.cacheReadInputTokens;
996
+ const cacheWriteInputTokens = right.cacheWriteInputTokens ?? left.cacheWriteInputTokens;
997
+ const inputTokens = ProviderShared.sumTokens(nonCachedInputTokens, cacheReadInputTokens, cacheWriteInputTokens);
998
+ const outputTokens = right.outputTokens ?? left.outputTokens;
999
+ const reasoningTokens = right.reasoningTokens ?? left.reasoningTokens;
1000
+ return new Usage({
1001
+ inputTokens,
1002
+ outputTokens,
1003
+ contextTokens: right.contextTokens ?? left.contextTokens,
1004
+ nonCachedInputTokens,
1005
+ cacheReadInputTokens,
1006
+ cacheWriteInputTokens,
1007
+ reasoningTokens,
1008
+ totalTokens: ProviderShared.totalTokens(inputTokens, outputTokens, undefined),
1009
+ providerMetadata: {
1010
+ [providerMetadataKey]: mergeJsonRecords(left.providerMetadata?.[providerMetadataKey], right.providerMetadata?.[providerMetadataKey]) ??
1011
+ {},
1012
+ },
1013
+ });
1014
+ };
1015
+ // Server tool result blocks come whole in `content_block_start` (no streaming
1016
+ // delta sequence). We convert the payload to a `tool-result` event with
1017
+ // `providerExecuted: true`. The runtime appends it to the assistant message
1018
+ // for round-trip; downstream consumers can inspect `result.value` for the
1019
+ // structured payload.
1020
+ const SERVER_TOOL_RESULT_NAMES = {
1021
+ web_search_tool_result: "web_search",
1022
+ code_execution_tool_result: "code_execution",
1023
+ web_fetch_tool_result: "web_fetch",
1024
+ };
1025
+ const isServerToolResultType = (type) => type in SERVER_TOOL_RESULT_NAMES;
1026
+ const serverToolResultEvent = (block, providerMetadataKey) => {
1027
+ if (!block.type || !isServerToolResultType(block.type))
1028
+ return undefined;
1029
+ const errorPayload = typeof block.content === "object" && block.content !== null && "type" in block.content
1030
+ ? String(block.content.type)
1031
+ : "";
1032
+ const isError = errorPayload.endsWith("_tool_result_error");
1033
+ return LLMEvent.toolResult({
1034
+ id: block.tool_use_id ?? "",
1035
+ name: SERVER_TOOL_RESULT_NAMES[block.type],
1036
+ result: isError ? { type: "error", value: block.content } : { type: "json", value: block.content },
1037
+ providerExecuted: true,
1038
+ // The complete payload is irreducible provider replay state: subsequent
1039
+ // stateless requests must round-trip the typed result block verbatim.
1040
+ providerMetadata: providerMetadata(providerMetadataKey, { blockType: block.type, result: block.content }),
1041
+ });
1042
+ };
1043
+ const NO_EVENTS = [];
1044
+ const onMessageStart = (state, event) => {
1045
+ const usage = mapUsage(event.message?.usage, state.providerMetadataKey);
1046
+ return [usage ? { ...state, usage: mergeUsage(state.usage, usage, state.providerMetadataKey) } : state, NO_EVENTS];
1047
+ };
1048
+ const onContentBlockStart = (state, event) => {
1049
+ const block = event.content_block;
1050
+ if (block.type === "tool_use" || block.type === "server_tool_use") {
1051
+ if (event.index === undefined || !block.id)
1052
+ return [state, NO_EVENTS];
1053
+ const events = [];
1054
+ const lifecycle = Lifecycle.stepStart(state.lifecycle, events);
1055
+ return [
1056
+ {
1057
+ ...state,
1058
+ lifecycle,
1059
+ tools: ToolStream.start(state.tools, event.index, {
1060
+ id: block.id,
1061
+ name: block.name ?? "",
1062
+ input: block.input !== undefined && (!ProviderShared.isRecord(block.input) || Object.keys(block.input).length > 0)
1063
+ ? ProviderShared.encodeJson(block.input)
1064
+ : undefined,
1065
+ providerExecuted: block.type === "server_tool_use",
1066
+ }),
1067
+ },
1068
+ [
1069
+ ...events,
1070
+ LLMEvent.toolInputStart({
1071
+ id: block.id,
1072
+ name: block.name ?? "",
1073
+ providerExecuted: block.type === "server_tool_use" ? true : undefined,
1074
+ }),
1075
+ ],
1076
+ ];
1077
+ }
1078
+ if (block.type === "text" && block.text !== undefined) {
1079
+ const events = [];
1080
+ const id = `text-${event.index ?? 0}`;
1081
+ const lifecycle = Lifecycle.textStart(state.lifecycle, events, id);
1082
+ return [
1083
+ { ...state, lifecycle: block.text ? Lifecycle.textDelta(lifecycle, events, id, block.text) : lifecycle },
1084
+ events,
1085
+ ];
1086
+ }
1087
+ if (block.type === "thinking" && block.thinking !== undefined) {
1088
+ const events = [];
1089
+ const id = `reasoning-${event.index ?? 0}`;
1090
+ const metadata = block.signature === undefined
1091
+ ? undefined
1092
+ : providerMetadata(state.providerMetadataKey, { signature: block.signature });
1093
+ const lifecycle = Lifecycle.reasoningStart(state.lifecycle, events, id, metadata);
1094
+ return [
1095
+ {
1096
+ ...state,
1097
+ lifecycle: block.thinking
1098
+ ? Lifecycle.reasoningDelta(lifecycle, events, id, block.thinking, metadata)
1099
+ : lifecycle,
1100
+ reasoningSignatures: event.index === undefined || block.signature === undefined
1101
+ ? state.reasoningSignatures
1102
+ : { ...state.reasoningSignatures, [event.index]: block.signature },
1103
+ },
1104
+ events,
1105
+ ];
1106
+ }
1107
+ // Redacted thinking surfaces as an empty reasoning part carrying the opaque
1108
+ // payload as `redactedData` metadata (same model as Vercel's
1109
+ // @ai-sdk/anthropic). The existing content_block_stop closes the part.
1110
+ if (block.type === "redacted_thinking" && block.data !== undefined) {
1111
+ const events = [];
1112
+ return [
1113
+ {
1114
+ ...state,
1115
+ lifecycle: Lifecycle.reasoningStart(state.lifecycle, events, `reasoning-${event.index ?? 0}`, providerMetadata(state.providerMetadataKey, { redactedData: block.data })),
1116
+ },
1117
+ events,
1118
+ ];
1119
+ }
1120
+ const result = serverToolResultEvent(block, state.providerMetadataKey);
1121
+ if (!result)
1122
+ return [state, NO_EVENTS];
1123
+ const events = [];
1124
+ return [{ ...state, lifecycle: Lifecycle.stepStart(state.lifecycle, events) }, [...events, result]];
1125
+ };
1126
+ const onContentBlockDelta = Effect.fn("AnthropicMessages.onContentBlockDelta")(function* (state, event) {
1127
+ const delta = event.delta;
1128
+ if (delta.type === "compaction_delta") {
1129
+ if (event.index === undefined || !(event.index in state.compactions) || delta.content === undefined)
1130
+ return yield* ProviderShared.eventError(ADAPTER, "Compaction delta is missing its block or content");
1131
+ return [
1132
+ { ...state, compactions: { ...state.compactions, [event.index]: delta.content } },
1133
+ NO_EVENTS,
1134
+ ];
1135
+ }
1136
+ if (delta.type === "text_delta" && delta.text) {
1137
+ if (!state.lifecycle.text.has(`text-${event.index ?? 0}`))
1138
+ return [state, NO_EVENTS];
1139
+ const events = [];
1140
+ return [
1141
+ { ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events, `text-${event.index ?? 0}`, delta.text) },
1142
+ events,
1143
+ ];
1144
+ }
1145
+ if (delta.type === "thinking_delta" && delta.thinking) {
1146
+ if (!state.lifecycle.reasoning.has(`reasoning-${event.index ?? 0}`))
1147
+ return [state, NO_EVENTS];
1148
+ const events = [];
1149
+ return [
1150
+ {
1151
+ ...state,
1152
+ lifecycle: Lifecycle.reasoningDelta(state.lifecycle, events, `reasoning-${event.index ?? 0}`, delta.thinking),
1153
+ },
1154
+ events,
1155
+ ];
1156
+ }
1157
+ if (delta.type === "signature_delta" && delta.signature) {
1158
+ const index = event.index ?? 0;
1159
+ if (!state.lifecycle.reasoning.has(`reasoning-${index}`))
1160
+ return [state, NO_EVENTS];
1161
+ return [
1162
+ {
1163
+ ...state,
1164
+ reasoningSignatures: { ...state.reasoningSignatures, [index]: delta.signature },
1165
+ },
1166
+ NO_EVENTS,
1167
+ ];
1168
+ }
1169
+ if (delta.type === "input_json_delta" && event.index !== undefined) {
1170
+ if (!delta.partial_json)
1171
+ return [state, NO_EVENTS];
1172
+ if (!state.tools[event.index])
1173
+ return [state, NO_EVENTS];
1174
+ const result = ToolStream.appendExisting(ADAPTER, state.tools, event.index, delta.partial_json, "Anthropic Messages tool argument delta is missing its tool call");
1175
+ if (ToolStream.isError(result))
1176
+ return yield* result;
1177
+ const events = [];
1178
+ const lifecycle = result.events.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle;
1179
+ events.push(...result.events);
1180
+ return [{ ...state, lifecycle, tools: result.tools }, events];
1181
+ }
1182
+ return [state, NO_EVENTS];
1183
+ });
1184
+ const onContentBlockStop = Effect.fn("AnthropicMessages.onContentBlockStop")(function* (state, event) {
1185
+ if (event.index === undefined)
1186
+ return [state, NO_EVENTS];
1187
+ if (event.index in state.compactions) {
1188
+ const { [event.index]: content, ...compactions } = state.compactions;
1189
+ const events = [];
1190
+ const lifecycle = Lifecycle.stepStart(state.lifecycle, events);
1191
+ events.push(LLMEvent.compaction({
1192
+ provider: state.provider,
1193
+ text: content,
1194
+ }));
1195
+ return [{ ...state, compactions, lifecycle }, events];
1196
+ }
1197
+ const result = yield* ToolStream.finish(ADAPTER, state.tools, event.index);
1198
+ const events = [];
1199
+ const resultEvents = result.events ?? [];
1200
+ const signature = state.reasoningSignatures[event.index];
1201
+ const lifecycle = resultEvents.length
1202
+ ? Lifecycle.stepStart(state.lifecycle, events)
1203
+ : Lifecycle.reasoningEnd(Lifecycle.textEnd(state.lifecycle, events, `text-${event.index}`), events, `reasoning-${event.index}`, signature === undefined ? undefined : providerMetadata(state.providerMetadataKey, { signature }));
1204
+ events.push(...resultEvents);
1205
+ const reasoningSignatures = { ...state.reasoningSignatures };
1206
+ delete reasoningSignatures[event.index];
1207
+ return [{ ...state, lifecycle, tools: result.tools, reasoningSignatures }, events];
1208
+ });
1209
+ const onMessageDelta = (state, event) => {
1210
+ const usage = mergeUsage(state.usage, mapUsage(event.usage, state.providerMetadataKey), state.providerMetadataKey);
1211
+ const pendingFinish = (() => {
1212
+ const stopReason = event.delta?.stop_reason;
1213
+ if (stopReason === null || stopReason === undefined)
1214
+ return state.pendingFinish;
1215
+ const stopSequence = event.delta?.stop_sequence;
1216
+ const finishMetadata = stopSequence === null || stopSequence === undefined
1217
+ ? state.pendingFinish?.providerMetadata
1218
+ : providerMetadata(state.providerMetadataKey, { stopSequence });
1219
+ return {
1220
+ reason: {
1221
+ normalized: mapFinishReason(stopReason),
1222
+ raw: stopReason,
1223
+ },
1224
+ providerMetadata: finishMetadata,
1225
+ };
1226
+ })();
1227
+ return [
1228
+ {
1229
+ ...state,
1230
+ usage,
1231
+ pendingFinish,
1232
+ },
1233
+ NO_EVENTS,
1234
+ ];
1235
+ };
1236
+ const onMessageStop = Effect.fn("AnthropicMessages.onMessageStop")(function* (state) {
1237
+ if (Object.keys(state.compactions).length)
1238
+ return yield* ProviderShared.eventError(ADAPTER, "Response ended with an incomplete compaction block");
1239
+ const result = yield* ToolStream.finishAll(ADAPTER, state.tools);
1240
+ const events = [];
1241
+ const lifecycle = result.events.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle;
1242
+ events.push(...result.events);
1243
+ const closed = Object.entries(state.reasoningSignatures).reduce((current, [index, signature]) => Lifecycle.reasoningEnd(current, events, `reasoning-${index}`, providerMetadata(state.providerMetadataKey, { signature })), lifecycle);
1244
+ const finished = Lifecycle.finish(closed, events, {
1245
+ reason: state.pendingFinish?.reason ?? {
1246
+ normalized: "unknown",
1247
+ raw: undefined,
1248
+ },
1249
+ usage: state.usage,
1250
+ providerMetadata: state.pendingFinish?.providerMetadata,
1251
+ });
1252
+ return [{ ...state, lifecycle: finished, tools: result.tools }, events];
1253
+ });
1254
+ // Prefix `error.type` so overloads, rate limits, and quota errors are visible
1255
+ // even when the provider message is generic or empty.
1256
+ const providerErrorMessage = (event) => {
1257
+ const type = event.error?.type;
1258
+ const message = event.error?.message;
1259
+ if (type && message)
1260
+ return `${type}: ${message}`;
1261
+ return message || type || "Anthropic Messages stream error";
1262
+ };
1263
+ const onError = (event) => {
1264
+ const message = providerErrorMessage(event);
1265
+ const body = ProviderShared.encodeJson(event);
1266
+ return Effect.fail(new AIError({
1267
+ reason: classifyProviderFailure({ message, rawBody: body }),
1268
+ }));
1269
+ };
1270
+ const STREAM_BLOCK_TYPES = new Set([
1271
+ "compaction",
1272
+ "text",
1273
+ "thinking",
1274
+ "redacted_thinking",
1275
+ "tool_use",
1276
+ "server_tool_use",
1277
+ ]);
1278
+ const STREAM_DELTA_TYPES = new Set([
1279
+ "compaction_delta",
1280
+ "text_delta",
1281
+ "thinking_delta",
1282
+ "signature_delta",
1283
+ "input_json_delta",
1284
+ ]);
1285
+ const invalidStreamEvent = (event) => Effect.fail(ProviderShared.eventError(ADAPTER, "Invalid anthropic/anthropic-messages stream event", ProviderShared.encodeJson(event)));
1286
+ const step = (state, event) => {
1287
+ if (!SSE_EVENTS.has(event.type))
1288
+ return Effect.succeed([state, NO_EVENTS]);
1289
+ if (event.type !== "content_block_start" &&
1290
+ event.content_block !== undefined &&
1291
+ Option.isNone(decodeAnthropicStreamBlock(event.content_block)))
1292
+ return invalidStreamEvent(event);
1293
+ if (event.type !== "content_block_delta" &&
1294
+ event.delta !== undefined &&
1295
+ Option.isNone(decodeAnthropicStreamDelta(event.delta)))
1296
+ return invalidStreamEvent(event);
1297
+ if (event.type === "message_start")
1298
+ return Effect.succeed(onMessageStart(state, event));
1299
+ if (event.type === "content_block_start") {
1300
+ if (!ProviderShared.isRecord(event.content_block) || typeof event.content_block.type !== "string")
1301
+ return invalidStreamEvent(event);
1302
+ if (event.content_block.type === "compaction") {
1303
+ const decoded = Schema.decodeUnknownOption(AnthropicCompactionBlock)(event.content_block);
1304
+ if (event.index === undefined || Option.isNone(decoded))
1305
+ return invalidStreamEvent(event);
1306
+ return Effect.succeed([
1307
+ { ...state, compactions: { ...state.compactions, [event.index]: decoded.value.content } },
1308
+ NO_EVENTS,
1309
+ ]);
1310
+ }
1311
+ if (!STREAM_BLOCK_TYPES.has(event.content_block.type) && !isServerToolResultType(event.content_block.type))
1312
+ return Effect.succeed([state, NO_EVENTS]);
1313
+ const decoded = decodeAnthropicStreamBlock(event.content_block);
1314
+ if (Option.isNone(decoded))
1315
+ return invalidStreamEvent(event);
1316
+ const block = decoded.value;
1317
+ if (block.type === "tool_use" || block.type === "server_tool_use") {
1318
+ if (event.index === undefined)
1319
+ return Effect.fail(ProviderShared.eventError(ADAPTER, `Anthropic ${block.type} missing index`));
1320
+ if (!block.id)
1321
+ return Effect.fail(ProviderShared.eventError(ADAPTER, `Anthropic tool_use missing id at index ${event.index}`));
1322
+ }
1323
+ return Effect.succeed(onContentBlockStart(state, { ...event, content_block: block }));
1324
+ }
1325
+ if (event.type === "content_block_delta") {
1326
+ if (!ProviderShared.isRecord(event.delta))
1327
+ return invalidStreamEvent(event);
1328
+ if (typeof event.delta.type === "string" && !STREAM_DELTA_TYPES.has(event.delta.type))
1329
+ return Effect.succeed([state, NO_EVENTS]);
1330
+ const decoded = decodeAnthropicStreamDelta(event.delta);
1331
+ if (Option.isNone(decoded))
1332
+ return invalidStreamEvent(event);
1333
+ return onContentBlockDelta(state, { ...event, delta: decoded.value });
1334
+ }
1335
+ if (event.type === "content_block_stop")
1336
+ return onContentBlockStop(state, event);
1337
+ if (event.type === "message_delta") {
1338
+ const decoded = decodeAnthropicStreamDelta(event.delta);
1339
+ if (Option.isNone(decoded))
1340
+ return invalidStreamEvent(event);
1341
+ return Effect.succeed(onMessageDelta(state, { ...event, delta: decoded.value }));
1342
+ }
1343
+ if (event.type === "message_stop")
1344
+ return onMessageStop(state);
1345
+ if (event.type === "error")
1346
+ return onError(event);
1347
+ return Effect.succeed([state, NO_EVENTS]);
1348
+ };
1349
+ // =============================================================================
1350
+ // Protocol And Anthropic Route
1351
+ // =============================================================================
1352
+ /**
1353
+ * The Anthropic Messages protocol — request body construction, body schema,
1354
+ * and the streaming-event state machine shared by Anthropic-compatible and
1355
+ * Vertex-hosted Messages routes.
1356
+ */
1357
+ export const protocol = Protocol.make({
1358
+ id: ADAPTER,
1359
+ body: {
1360
+ schema: AnthropicMessagesBody,
1361
+ from: fromRequest,
1362
+ },
1363
+ stream: {
1364
+ event: Protocol.jsonEvent(AnthropicEvent),
1365
+ initial: (request) => ({
1366
+ provider: request.model.provider,
1367
+ compactions: {},
1368
+ providerMetadataKey: request.model.route.providerMetadataKey ?? String(request.model.provider),
1369
+ tools: ToolStream.empty(),
1370
+ reasoningSignatures: {},
1371
+ lifecycle: Lifecycle.initial(),
1372
+ }),
1373
+ step,
1374
+ },
1375
+ });
1376
+ export const transport = () => {
1377
+ const http = HttpTransport.httpJson({ framing });
1378
+ return {
1379
+ ...http,
1380
+ prepare: (input) => {
1381
+ if (!input.body.context_management?.edits.length &&
1382
+ !input.body.messages.some((message) => message.content.some((block) => block.type === "compaction")))
1383
+ return http.prepare(input);
1384
+ const headers = Headers.fromInput(input.request.http?.headers);
1385
+ const betas = new Set((headers["anthropic-beta"] ?? "")
1386
+ .split(",")
1387
+ .map((item) => item.trim())
1388
+ .filter(Boolean));
1389
+ betas.add("compact-2026-01-12");
1390
+ return http.prepare({
1391
+ ...input,
1392
+ request: LLMRequest.update(input.request, {
1393
+ http: new HttpOptions({
1394
+ ...input.request.http,
1395
+ headers: { ...headers, "anthropic-beta": [...betas].join(",") },
1396
+ }),
1397
+ }),
1398
+ });
1399
+ },
1400
+ };
1401
+ };
1402
+ export const route = Route.make({
1403
+ id: ADAPTER,
1404
+ provider: "anthropic",
1405
+ providerMetadataKey: "anthropic",
1406
+ protocol,
1407
+ endpoint: Endpoint.path((input) => (input.request.model.provider === "anthropic" ? `${PATH}?beta=true` : PATH), {
1408
+ baseURL: DEFAULT_BASE_URL,
1409
+ }),
1410
+ auth: Auth.none,
1411
+ transport: transport(),
1412
+ headers: () => ({ "anthropic-version": "2023-06-01" }),
1413
+ });
1414
+ export * as AnthropicMessages from "./anthropic-messages.js";