@opencode/ai 2.2.5 → 2.2.7

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 (306) hide show
  1. package/README.md +228 -72
  2. package/dist/ai-client.d.ts +2 -2
  3. package/dist/ai-client.js +2 -1
  4. package/dist/cache-policy.d.ts +1 -1
  5. package/dist/cache-policy.js +16 -4
  6. package/dist/decision-client.d.ts +3 -3
  7. package/dist/decision.d.ts +30 -125
  8. package/dist/decision.js +27 -15
  9. package/dist/effect.d.ts +10 -15
  10. package/dist/effect.js +6 -6
  11. package/dist/effort-updates.d.ts +3 -3
  12. package/dist/effort-updates.js +2 -2
  13. package/dist/embedding-client.d.ts +21 -0
  14. package/dist/embedding-client.js +30 -0
  15. package/dist/embedding.d.ts +111 -0
  16. package/dist/embedding.js +75 -0
  17. package/dist/experimental/cloudflare-run-extraction.d.ts +7 -3
  18. package/dist/experimental/cloudflare-run-extraction.js +4 -1
  19. package/dist/experimental/extraction.d.ts +10 -40
  20. package/dist/experimental/extraction.js +14 -13
  21. package/dist/experimental.d.ts +8 -8
  22. package/dist/experimental.js +4 -4
  23. package/dist/generation.d.ts +0 -2
  24. package/dist/generation.js +2 -2
  25. package/dist/image-client.d.ts +13 -7
  26. package/dist/image-client.js +1 -1
  27. package/dist/image.d.ts +357 -465
  28. package/dist/image.js +17 -18
  29. package/dist/index.d.ts +35 -467
  30. package/dist/index.js +23 -17
  31. package/dist/llm.d.ts +65 -266
  32. package/dist/llm.js +101 -92
  33. package/dist/loop.d.ts +38 -0
  34. package/dist/loop.js +136 -0
  35. package/dist/media-model.d.ts +1 -1
  36. package/dist/media-model.js +8 -6
  37. package/dist/media.d.ts +9 -0
  38. package/dist/media.js +37 -2
  39. package/dist/protocols/alibaba-chat.d.ts +9 -1
  40. package/dist/protocols/alibaba-chat.js +3 -3
  41. package/dist/protocols/alibaba-images.d.ts +2 -2
  42. package/dist/protocols/alibaba-messages.js +3 -3
  43. package/dist/protocols/alibaba-responses.js +8 -20
  44. package/dist/protocols/anthropic-messages.d.ts +1 -1
  45. package/dist/protocols/anthropic-messages.js +57 -176
  46. package/dist/protocols/assemblyai-transcription.d.ts +2 -2
  47. package/dist/protocols/bedrock-converse.js +10 -16
  48. package/dist/protocols/cartesia-speech.d.ts +2 -2
  49. package/dist/protocols/cloudflare-workers-ai-images.d.ts +2 -2
  50. package/dist/protocols/cohere-chat.js +9 -12
  51. package/dist/protocols/deepgram-speech.d.ts +2 -2
  52. package/dist/protocols/deepgram-transcription.d.ts +2 -2
  53. package/dist/protocols/elevenlabs-speech.d.ts +2 -2
  54. package/dist/protocols/elevenlabs-transcription.d.ts +2 -2
  55. package/dist/protocols/gemini.d.ts +3 -0
  56. package/dist/protocols/gemini.js +54 -72
  57. package/dist/protocols/google-embed-content.d.ts +34 -0
  58. package/dist/protocols/google-embed-content.js +110 -0
  59. package/dist/protocols/google-images.d.ts +2 -2
  60. package/dist/protocols/google-interactions.d.ts +3 -4
  61. package/dist/protocols/google-interactions.js +44 -30
  62. package/dist/protocols/google-speech.d.ts +2 -2
  63. package/dist/protocols/google-transcription.d.ts +2 -2
  64. package/dist/protocols/google-vertex-predict-embeddings.d.ts +18 -0
  65. package/dist/protocols/google-vertex-predict-embeddings.js +74 -0
  66. package/dist/protocols/google-video.d.ts +2 -2
  67. package/dist/protocols/index.d.ts +3 -0
  68. package/dist/protocols/index.js +3 -0
  69. package/dist/protocols/meta-images.d.ts +2 -2
  70. package/dist/protocols/meta-responses.js +26 -23
  71. package/dist/protocols/minimax-images.d.ts +2 -2
  72. package/dist/protocols/mistral-chat.js +7 -10
  73. package/dist/protocols/open-responses-channel.js +6 -19
  74. package/dist/protocols/open-responses-continuation.d.ts +1 -5
  75. package/dist/protocols/open-responses-continuation.js +1 -3
  76. package/dist/protocols/open-responses.d.ts +2 -22
  77. package/dist/protocols/open-responses.js +41 -23
  78. package/dist/protocols/openai-chat.d.ts +27 -23
  79. package/dist/protocols/openai-chat.js +62 -57
  80. package/dist/protocols/openai-compatible-chat.d.ts +2 -1
  81. package/dist/protocols/openai-compatible-responses.d.ts +2 -2
  82. package/dist/protocols/openai-compatible-responses.js +1 -1
  83. package/dist/protocols/openai-decisions.js +15 -2
  84. package/dist/protocols/openai-embeddings.d.ts +16 -0
  85. package/dist/protocols/openai-embeddings.js +76 -0
  86. package/dist/protocols/openai-images.d.ts +2 -2
  87. package/dist/protocols/openai-responses.js +10 -29
  88. package/dist/protocols/openai-speech.d.ts +2 -2
  89. package/dist/protocols/openai-transcription.d.ts +2 -2
  90. package/dist/protocols/runway-video.d.ts +2 -2
  91. package/dist/protocols/shared.d.ts +14 -7
  92. package/dist/protocols/shared.js +40 -15
  93. package/dist/protocols/system-one.d.ts +4 -4
  94. package/dist/protocols/system-one.js +8 -1
  95. package/dist/protocols/utils/bedrock-cache.js +2 -5
  96. package/dist/protocols/utils/bedrock-media.d.ts +0 -3
  97. package/dist/protocols/utils/cache.d.ts +3 -0
  98. package/dist/protocols/utils/cache.js +15 -2
  99. package/dist/protocols/utils/image-sizing.d.ts +1 -1
  100. package/dist/protocols/utils/responses-checkpoint.js +1 -1
  101. package/dist/protocols/utils/responses-compaction.d.ts +1 -1
  102. package/dist/protocols/utils/responses-compaction.js +6 -5
  103. package/dist/protocols/utils/responses-hosted-tools.d.ts +97 -1
  104. package/dist/protocols/utils/responses-hosted-tools.js +31 -0
  105. package/dist/protocols/utils/tool-stream.d.ts +5 -271
  106. package/dist/protocols/utils/tool-stream.js +3 -13
  107. package/dist/protocols/venice-chat.d.ts +7 -1
  108. package/dist/protocols/venice-chat.js +4 -4
  109. package/dist/protocols/xai-images.d.ts +2 -2
  110. package/dist/protocols/xai-responses.js +5 -25
  111. package/dist/protocols/xai-video.d.ts +2 -2
  112. package/dist/protocols/zai-chat.d.ts +9 -1
  113. package/dist/protocols/zai-chat.js +1 -1
  114. package/dist/protocols/zai-images.d.ts +2 -2
  115. package/dist/protocols/zai-messages.js +3 -3
  116. package/dist/provider-error.d.ts +0 -1
  117. package/dist/provider-error.js +7 -80
  118. package/dist/providers/alibaba/embeddings.d.ts +2 -0
  119. package/dist/providers/alibaba/embeddings.js +1 -0
  120. package/dist/providers/alibaba.d.ts +70 -4
  121. package/dist/providers/alibaba.js +20 -2
  122. package/dist/providers/amazon-bedrock-mantle.d.ts +7 -3
  123. package/dist/providers/amazon-bedrock-mantle.js +6 -3
  124. package/dist/providers/amazon-bedrock.d.ts +6 -7
  125. package/dist/providers/amazon-bedrock.js +1 -1
  126. package/dist/providers/anthropic-compatible.d.ts +7 -8
  127. package/dist/providers/anthropic-compatible.js +2 -5
  128. package/dist/providers/anthropic.d.ts +8 -9
  129. package/dist/providers/anthropic.js +2 -7
  130. package/dist/providers/assemblyai.d.ts +2 -2
  131. package/dist/providers/assemblyai.js +2 -7
  132. package/dist/providers/azure/embeddings.d.ts +2 -0
  133. package/dist/providers/azure/embeddings.js +1 -0
  134. package/dist/providers/azure/messages.d.ts +2 -0
  135. package/dist/providers/azure/messages.js +1 -0
  136. package/dist/providers/azure.d.ts +325 -7
  137. package/dist/providers/azure.js +40 -9
  138. package/dist/providers/baseten.d.ts +7 -5
  139. package/dist/providers/baseten.js +7 -21
  140. package/dist/providers/cartesia.d.ts +1 -1
  141. package/dist/providers/cerebras.d.ts +7 -5
  142. package/dist/providers/cerebras.js +4 -15
  143. package/dist/providers/cloudflare-ai-gateway.d.ts +23 -13
  144. package/dist/providers/cloudflare-ai-gateway.js +28 -40
  145. package/dist/providers/cloudflare-shared.d.ts +9 -0
  146. package/dist/providers/cloudflare-shared.js +25 -0
  147. package/dist/providers/cloudflare-workers-ai.d.ts +6 -4
  148. package/dist/providers/cloudflare-workers-ai.js +4 -20
  149. package/dist/providers/cohere/chat.js +2 -7
  150. package/dist/providers/cohere/embeddings.d.ts +2 -0
  151. package/dist/providers/cohere/embeddings.js +1 -0
  152. package/dist/providers/cohere.d.ts +14 -5
  153. package/dist/providers/cohere.js +23 -13
  154. package/dist/providers/deepgram.d.ts +2 -2
  155. package/dist/providers/deepgram.js +2 -7
  156. package/dist/providers/deepinfra/embeddings.d.ts +2 -0
  157. package/dist/providers/deepinfra/embeddings.js +1 -0
  158. package/dist/providers/deepinfra.d.ts +10 -5
  159. package/dist/providers/deepinfra.js +20 -14
  160. package/dist/providers/deepseek.d.ts +7 -5
  161. package/dist/providers/deepseek.js +3 -14
  162. package/dist/providers/digitalocean/embeddings.d.ts +2 -0
  163. package/dist/providers/digitalocean/embeddings.js +1 -0
  164. package/dist/providers/digitalocean.d.ts +18 -5
  165. package/dist/providers/digitalocean.js +28 -14
  166. package/dist/providers/elevenlabs.d.ts +2 -2
  167. package/dist/providers/elevenlabs.js +2 -7
  168. package/dist/providers/fireworks/embeddings.d.ts +2 -0
  169. package/dist/providers/fireworks/embeddings.js +1 -0
  170. package/dist/providers/fireworks.d.ts +10 -5
  171. package/dist/providers/fireworks.js +17 -14
  172. package/dist/providers/google/embeddings.d.ts +2 -0
  173. package/dist/providers/google/embeddings.js +1 -0
  174. package/dist/providers/google/interactions.d.ts +1 -1
  175. package/dist/providers/google/interactions.js +2 -7
  176. package/dist/providers/google-vertex/embeddings.d.ts +2 -0
  177. package/dist/providers/google-vertex/embeddings.js +1 -0
  178. package/dist/providers/google-vertex-chat.d.ts +4 -3
  179. package/dist/providers/google-vertex-chat.js +3 -29
  180. package/dist/providers/google-vertex-interactions.d.ts +3 -3
  181. package/dist/providers/google-vertex-messages.d.ts +3 -3
  182. package/dist/providers/google-vertex-messages.js +3 -29
  183. package/dist/providers/google-vertex-mistral.d.ts +3 -3
  184. package/dist/providers/google-vertex-mistral.js +3 -29
  185. package/dist/providers/google-vertex-responses.d.ts +3 -3
  186. package/dist/providers/google-vertex-responses.js +4 -30
  187. package/dist/providers/google-vertex-shared.d.ts +31 -0
  188. package/dist/providers/google-vertex-shared.js +25 -0
  189. package/dist/providers/google-vertex.d.ts +10 -3
  190. package/dist/providers/google-vertex.js +52 -0
  191. package/dist/providers/google.d.ts +21 -13
  192. package/dist/providers/google.js +23 -19
  193. package/dist/providers/groq.d.ts +10 -5
  194. package/dist/providers/groq.js +4 -15
  195. package/dist/providers/meta.d.ts +6 -5
  196. package/dist/providers/meta.js +10 -23
  197. package/dist/providers/minimax/chat.js +2 -7
  198. package/dist/providers/minimax/responses.js +2 -7
  199. package/dist/providers/minimax.d.ts +6 -5
  200. package/dist/providers/minimax.js +7 -22
  201. package/dist/providers/mistral.d.ts +10 -11
  202. package/dist/providers/mistral.js +3 -14
  203. package/dist/providers/moonshot/messages.js +2 -7
  204. package/dist/providers/moonshot/responses.js +2 -7
  205. package/dist/providers/moonshot.d.ts +6 -5
  206. package/dist/providers/moonshot.js +4 -16
  207. package/dist/providers/openai/embeddings.d.ts +2 -0
  208. package/dist/providers/openai/embeddings.js +1 -0
  209. package/dist/providers/openai-compatible/embeddings.d.ts +2 -0
  210. package/dist/providers/openai-compatible/embeddings.js +1 -0
  211. package/dist/providers/openai-compatible-responses.d.ts +6 -7
  212. package/dist/providers/openai-compatible-responses.js +2 -8
  213. package/dist/providers/openai-compatible.d.ts +10 -7
  214. package/dist/providers/openai-compatible.js +17 -10
  215. package/dist/providers/openai.d.ts +11 -4
  216. package/dist/providers/openai.js +17 -3
  217. package/dist/providers/opencode.d.ts +4 -4
  218. package/dist/providers/opencode.js +6 -2
  219. package/dist/providers/openrouter/embeddings.d.ts +2 -0
  220. package/dist/providers/openrouter/embeddings.js +1 -0
  221. package/dist/providers/openrouter.d.ts +24 -5
  222. package/dist/providers/openrouter.js +31 -24
  223. package/dist/providers/runway.d.ts +1 -1
  224. package/dist/providers/settings.d.ts +40 -0
  225. package/dist/providers/settings.js +19 -0
  226. package/dist/providers/togetherai.d.ts +7 -5
  227. package/dist/providers/togetherai.js +5 -15
  228. package/dist/providers/typesafe-ai.d.ts +4 -4
  229. package/dist/providers/typesafe-ai.js +6 -2
  230. package/dist/providers/venice.d.ts +5 -4
  231. package/dist/providers/venice.js +6 -2
  232. package/dist/providers/vercel-ai-gateway/embeddings.d.ts +2 -0
  233. package/dist/providers/vercel-ai-gateway/embeddings.js +1 -0
  234. package/dist/providers/vercel-ai-gateway.d.ts +9 -5
  235. package/dist/providers/vercel-ai-gateway.js +30 -29
  236. package/dist/providers/xai.d.ts +5 -4
  237. package/dist/providers/xai.js +4 -12
  238. package/dist/providers/zai-coding-plan/messages.js +2 -7
  239. package/dist/providers/zai-coding-plan/responses.js +2 -7
  240. package/dist/providers/zai-coding-plan.d.ts +6 -5
  241. package/dist/providers/zai-coding-plan.js +8 -15
  242. package/dist/providers/zai.d.ts +6 -5
  243. package/dist/providers/zai.js +10 -22
  244. package/dist/public.d.ts +14 -0
  245. package/dist/public.js +6 -0
  246. package/dist/route/auth-options.d.ts +9 -5
  247. package/dist/route/auth-options.js +10 -7
  248. package/dist/route/client.d.ts +50 -37
  249. package/dist/route/client.js +42 -53
  250. package/dist/route/decision.d.ts +8 -8
  251. package/dist/route/decision.js +3 -3
  252. package/dist/route/embedding.d.ts +61 -0
  253. package/dist/route/embedding.js +88 -0
  254. package/dist/route/executor.d.ts +5 -0
  255. package/dist/route/executor.js +10 -0
  256. package/dist/route/index.d.ts +5 -7
  257. package/dist/route/index.js +1 -1
  258. package/dist/route/media.d.ts +7 -11
  259. package/dist/route/media.js +22 -26
  260. package/dist/route/transport/http.js +6 -5
  261. package/dist/route/transport/websocket.js +7 -1
  262. package/dist/schema/errors.d.ts +16 -17
  263. package/dist/schema/errors.js +63 -12
  264. package/dist/schema/events.d.ts +2563 -2954
  265. package/dist/schema/events.js +54 -109
  266. package/dist/schema/messages.d.ts +194 -137
  267. package/dist/schema/messages.js +66 -83
  268. package/dist/schema/options.d.ts +112 -65
  269. package/dist/schema/options.js +52 -101
  270. package/dist/speech-client.d.ts +7 -7
  271. package/dist/speech.d.ts +306 -316
  272. package/dist/speech.js +16 -14
  273. package/dist/testing.d.ts +31 -175
  274. package/dist/testing.js +60 -5
  275. package/dist/tool-history.d.ts +1 -1
  276. package/dist/tool-history.js +3 -10
  277. package/dist/tool-runtime.d.ts +9 -2
  278. package/dist/tool-runtime.js +17 -31
  279. package/dist/tool.d.ts +39 -43
  280. package/dist/tool.js +16 -26
  281. package/dist/transcription-client.d.ts +7 -7
  282. package/dist/transcription.d.ts +314 -265
  283. package/dist/transcription.js +16 -14
  284. package/dist/utils/provider-codes.d.ts +3 -0
  285. package/dist/utils/provider-codes.js +41 -0
  286. package/dist/video-client.d.ts +7 -7
  287. package/dist/video-client.js +1 -1
  288. package/dist/video.d.ts +269 -287
  289. package/dist/video.js +16 -14
  290. package/package.json +309 -257
  291. package/dist/experimental/testing.d.ts +0 -3
  292. package/dist/experimental/testing.js +0 -3
  293. package/dist/testing/decision.d.ts +0 -16
  294. package/dist/testing/decision.js +0 -20
  295. package/dist/testing/image.d.ts +0 -14
  296. package/dist/testing/image.js +0 -12
  297. package/dist/testing/media.d.ts +0 -18
  298. package/dist/testing/media.js +0 -36
  299. package/dist/testing/script.d.ts +0 -28
  300. package/dist/testing/script.js +0 -60
  301. package/dist/testing/speech.d.ts +0 -14
  302. package/dist/testing/speech.js +0 -12
  303. package/dist/testing/transcription.d.ts +0 -14
  304. package/dist/testing/transcription.js +0 -12
  305. package/dist/testing/video.d.ts +0 -14
  306. package/dist/testing/video.js +0 -12
@@ -0,0 +1,61 @@
1
+ import { Effect } from "effect";
2
+ import type { HttpClientResponse } from "effect/http";
3
+ import { EmbeddingModel, EmbeddingResponse, type EmbeddingOptions, type EmbeddingRequest } from "../embedding.js";
4
+ import { ProviderID, type HttpOptions, type AIError, type ProviderOptions } from "../schema/index.js";
5
+ import { Auth } from "./auth.js";
6
+ import { Endpoint } from "./endpoint.js";
7
+ import { MediaProtocol } from "./media-protocol.js";
8
+ /** One embedding API: how a request becomes its JSON body and how its response becomes an `EmbeddingResponse`. */
9
+ export interface Protocol {
10
+ readonly id: string;
11
+ readonly name: string;
12
+ readonly body: {
13
+ readonly from: (request: EmbeddingRequest) => Effect.Effect<Record<string, unknown>, AIError>;
14
+ };
15
+ readonly response: {
16
+ readonly decode: (response: HttpClientResponse.HttpClientResponse, context: {
17
+ readonly request: EmbeddingRequest;
18
+ readonly providerMetadataKey: string;
19
+ }) => Effect.Effect<EmbeddingResponse, AIError>;
20
+ };
21
+ }
22
+ export declare const protocol: (input: Protocol) => Protocol;
23
+ export interface Patch {
24
+ readonly id?: string;
25
+ readonly provider?: string | ProviderID;
26
+ /** ProviderMetadata namespace for responses; defaults to the provider. */
27
+ readonly providerMetadataKey?: string;
28
+ readonly endpoint?: Endpoint.EndpointPatch<MediaProtocol.Body, EmbeddingRequest>;
29
+ readonly auth?: Auth.Definition;
30
+ readonly headers?: Record<string, string>;
31
+ readonly http?: HttpOptions;
32
+ /**
33
+ * Most values one HTTP request may carry. Longer requests are split into requests of this size, sent a few at a
34
+ * time, and joined back in value order.
35
+ */
36
+ readonly maxValues?: number;
37
+ }
38
+ export interface Route {
39
+ readonly id: string;
40
+ readonly provider: ProviderID;
41
+ readonly providerMetadataKey: string;
42
+ readonly protocol: Protocol;
43
+ readonly endpoint: Endpoint.Definition<MediaProtocol.Body, EmbeddingRequest>;
44
+ readonly auth: Auth.Definition;
45
+ readonly headers?: Record<string, string>;
46
+ readonly http?: HttpOptions;
47
+ readonly maxValues?: number;
48
+ readonly with: (patch: Patch) => Route;
49
+ readonly model: <Options extends EmbeddingOptions = EmbeddingOptions>(input: {
50
+ readonly id: string;
51
+ readonly providerOptions?: ProviderOptions;
52
+ }) => EmbeddingModel<Options>;
53
+ }
54
+ export interface MakeInput extends Omit<Patch, "endpoint"> {
55
+ readonly id: string;
56
+ readonly provider: string | ProviderID;
57
+ readonly protocol: Protocol;
58
+ readonly endpoint: Endpoint.Definition<MediaProtocol.Body, EmbeddingRequest>;
59
+ }
60
+ export declare const make: (input: MakeInput) => Route;
61
+ export * as EmbeddingRoute from "./embedding.js";
@@ -0,0 +1,88 @@
1
+ import { Effect } from "effect";
2
+ import { EmbeddingModel, EmbeddingResponse, EmbeddingUsage, } from "../embedding.js";
3
+ import { ProviderID } from "../schema/index.js";
4
+ import { Auth } from "./auth.js";
5
+ import { Endpoint } from "./endpoint.js";
6
+ import { MediaProtocol } from "./media-protocol.js";
7
+ import { MediaRoute } from "./media.js";
8
+ export const protocol = (input) => input;
9
+ export const make = (input) => {
10
+ const provider = ProviderID.make(input.provider);
11
+ const route = {
12
+ id: input.id,
13
+ provider,
14
+ providerMetadataKey: input.providerMetadataKey ?? provider,
15
+ protocol: input.protocol,
16
+ endpoint: input.endpoint,
17
+ auth: input.auth ?? Auth.none,
18
+ headers: input.headers,
19
+ http: input.http,
20
+ maxValues: input.maxValues,
21
+ };
22
+ return {
23
+ ...route,
24
+ with: (patch) => make({
25
+ ...route,
26
+ ...patch,
27
+ // A new provider gets its own metadata key unless the patch names one.
28
+ providerMetadataKey: patch.providerMetadataKey ?? (patch.provider === undefined ? route.providerMetadataKey : undefined),
29
+ endpoint: patch.endpoint === undefined ? route.endpoint : Endpoint.merge(route.endpoint, patch.endpoint),
30
+ headers: patch.headers === undefined ? route.headers : { ...route.headers, ...patch.headers },
31
+ http: patch.http ?? route.http,
32
+ maxValues: patch.maxValues ?? route.maxValues,
33
+ }),
34
+ model: (model) => EmbeddingModel.make({
35
+ id: model.id,
36
+ provider,
37
+ http: route.http,
38
+ providerOptions: model.providerOptions,
39
+ route: { id: route.id, generate: split(route.maxValues, transport(route).generate) },
40
+ }),
41
+ };
42
+ };
43
+ const CONCURRENCY = 4;
44
+ /**
45
+ * Splits a request whose values exceed `maxValues` and joins the parts: vectors in value order, `inputTokens` summed
46
+ * when every part reports it, and each part's metadata in order under `providerMetadata[key].responses`.
47
+ */
48
+ const split = (maxValues, generate) => (request, execute) => {
49
+ if (maxValues === undefined || request.values.length <= maxValues)
50
+ return generate(request, execute);
51
+ const chunks = Array.from({ length: Math.ceil(request.values.length / maxValues) }, (_, index) => request.values.slice(index * maxValues, (index + 1) * maxValues));
52
+ return Effect.forEach(chunks, (values) => generate({ ...request, values }, execute), {
53
+ concurrency: CONCURRENCY,
54
+ }).pipe(Effect.map((responses) => {
55
+ const tokens = responses.map((response) => response.usage?.inputTokens);
56
+ const keys = [...new Set(responses.flatMap((response) => Object.keys(response.providerMetadata ?? {})))];
57
+ return new EmbeddingResponse({
58
+ embeddings: responses.flatMap((response) => response.embeddings),
59
+ usage: tokens.every((count) => count !== undefined)
60
+ ? new EmbeddingUsage({ inputTokens: tokens.reduce((sum, count) => sum + count, 0) })
61
+ : undefined,
62
+ providerMetadata: keys.length === 0
63
+ ? undefined
64
+ : Object.fromEntries(keys.map((key) => [
65
+ key,
66
+ { responses: responses.map((response) => response.providerMetadata?.[key] ?? {}) },
67
+ ])),
68
+ });
69
+ }));
70
+ };
71
+ // The HTTP plumbing (URL, query, auth, headers, `http` overlays, surrogate sanitizing) is the one media routes use.
72
+ const transport = (route) => MediaRoute.inline({
73
+ protocol: MediaProtocol.inline(MediaProtocol.identity({ id: route.id, name: route.protocol.name, provider: route.provider }), {
74
+ body: {
75
+ from: (request) => route.protocol.body.from(request).pipe(Effect.map((body) => MediaProtocol.json(body))),
76
+ },
77
+ response: {
78
+ decode: (response, context) => route.protocol.response.decode(response, {
79
+ request: context.request,
80
+ providerMetadataKey: route.providerMetadataKey,
81
+ }),
82
+ },
83
+ }),
84
+ endpoint: route.endpoint,
85
+ auth: route.auth,
86
+ headers: route.headers,
87
+ });
88
+ export * as EmbeddingRoute from "./embedding.js";
@@ -18,6 +18,11 @@ export declare const responseStream: (response: HttpClientResponse.HttpClientRes
18
18
  export declare const stream: (executor: Interface, request: HttpClientRequest.HttpClientRequest, middleware?: HttpMiddleware) => Stream.Stream<Uint8Array, AIError>;
19
19
  export declare const layer: Layer.Layer<Service, never, HttpClient.HttpClient>;
20
20
  export declare const fetchLayer: Layer.Layer<import("./executor-service.js").RequestExecutorService, never, never>;
21
+ /**
22
+ * Per-call middleware that sends through `fetch` instead of the executor's HTTP client. Executor middleware and
23
+ * `middleware` still wrap the call, and status classification still applies.
24
+ */
25
+ export declare const withFetch: (fetch: typeof globalThis.fetch | undefined, middleware?: HttpMiddleware) => HttpMiddleware | undefined;
21
26
  /** Run `fn` on every request: it sees the raw response before status classification, inside middleware already on `executor`, and outside per-call middleware. */
22
27
  export declare const middleware: (fn: HttpMiddleware, executor?: Layer.Layer<Service>) => Layer.Layer<Service>;
23
28
  export * as RequestExecutor from "./executor.js";
@@ -186,6 +186,16 @@ export const layer = Layer.effect(Service, Effect.gen(function* () {
186
186
  });
187
187
  }));
188
188
  export const fetchLayer = layer.pipe(Layer.provide(FetchHttpClient.layer));
189
+ /**
190
+ * Per-call middleware that sends through `fetch` instead of the executor's HTTP client. Executor middleware and
191
+ * `middleware` still wrap the call, and status classification still applies.
192
+ */
193
+ export const withFetch = (fetch, middleware) => {
194
+ if (fetch === undefined)
195
+ return middleware;
196
+ const send = (request) => HttpClient.execute(request).pipe(Effect.provide(FetchHttpClient.layer), Effect.provideService(FetchHttpClient.Fetch, fetch));
197
+ return middleware === undefined ? send : (request) => middleware(request, send);
198
+ };
189
199
  /** Run `fn` on every request: it sees the raw response before status classification, inside middleware already on `executor`, and outside per-call middleware. */
190
200
  export const middleware = (fn, executor = fetchLayer) => Layer.effect(Service, Effect.gen(function* () {
191
201
  const inner = yield* Service;
@@ -1,5 +1,5 @@
1
1
  export { Route, LLMClient } from "./client.js";
2
- export type { Route as RouteShape, RouteLanguageModelInput, RouteRoutedLanguageModelInput, RouteDefaults, RouteDefaultsInput, AnyRoute, Interface as LLMClientShape, LLMClientService, StreamOptions, CompactMethod, CompactionOperations, CompactionRequest, CheckpointRequest, EndpointCompactOptions, TriggerCompactOptions, } from "./client.js";
2
+ export type { RouteLanguageModelInput, RouteRoutedLanguageModelInput, AnyRoute, LLMClientService, StreamOptions, CompactMethod, CompactionOperations, CompactionRequest, CheckpointRequest, EndpointCompactOptions, TriggerCompactOptions, } from "./client.js";
3
3
  export * from "./executor.js";
4
4
  export { Auth } from "./auth.js";
5
5
  export { AuthOptions } from "./auth-options.js";
@@ -12,10 +12,8 @@ export { HttpTransport, WebSocketTransport } from "./transport/index.js";
12
12
  export * as Transport from "./transport/index.js";
13
13
  export { ProviderShared } from "../protocols/shared.js";
14
14
  export { classifyProviderFailure } from "../provider-error.js";
15
- export { mergeHttpOptions } from "../schema/index.js";
16
- export type { Definition as AuthShape, AuthInput, Credential, CredentialError } from "./auth.js";
15
+ export { mergeTransport } from "../schema/index.js";
16
+ export type { AuthInput, Credential, CredentialError } from "./auth.js";
17
17
  export type { ApiKeyMode, AuthOverride, ProviderAuthOption } from "./auth-options.js";
18
- export type { Definition as EndpointFn, EndpointInput } from "./endpoint.js";
19
- export type { Definition as FramingDef } from "./framing.js";
20
- export type { Protocol as ProtocolDef } from "./protocol.js";
21
- export type { ChannelCheckpoint, ChannelCreate, ChannelObservation, HttpHandler, HttpMiddleware, Transport as TransportDef, TransportExecuteOptions, TransportExecution, TransportRuntime, WebSocketConnection, WebSocketChannelDriver, WebSocketChannelExchange, WebSocketChannelExecution, WebSocketChannelExecutor, WebSocketConnector, WebSocketRequest, } from "./transport/index.js";
18
+ export type { EndpointInput } from "./endpoint.js";
19
+ export type { ChannelCheckpoint, ChannelCreate, ChannelObservation, HttpHandler, HttpMiddleware, TransportExecuteOptions, TransportExecution, TransportRuntime, WebSocketConnection, WebSocketChannelDriver, WebSocketChannelExchange, WebSocketChannelExecution, WebSocketChannelExecutor, WebSocketConnector, WebSocketRequest, } from "./transport/index.js";
@@ -11,4 +11,4 @@ export { HttpTransport, WebSocketTransport } from "./transport/index.js";
11
11
  export * as Transport from "./transport/index.js";
12
12
  export { ProviderShared } from "../protocols/shared.js";
13
13
  export { classifyProviderFailure } from "../provider-error.js";
14
- export { mergeHttpOptions } from "../schema/index.js";
14
+ export { mergeTransport } from "../schema/index.js";
@@ -4,19 +4,15 @@ import { Endpoint } from "./endpoint.js";
4
4
  import type { Interface } from "./executor-service.js";
5
5
  import { MediaProtocol } from "./media-protocol.js";
6
6
  import { Generation } from "../generation.js";
7
- import { AIError, HttpOptions, ProviderID, type ProviderOptions } from "../schema/index.js";
7
+ import { AIError, ProviderID, type BaseRequest, type HttpOptions, type ProviderOptions } from "../schema/index.js";
8
8
  export type Execute = Interface["execute"];
9
9
  /** The minimum a media request must carry for the route to build a transport request. */
10
- export interface MediaRequest {
11
- readonly model: {
12
- readonly id: string;
13
- readonly provider: ProviderID;
14
- readonly http?: HttpOptions;
15
- readonly providerOptions?: ProviderOptions;
16
- };
17
- readonly providerOptions?: ProviderOptions;
10
+ export type MediaRequest = BaseRequest<{
11
+ readonly id: string;
12
+ readonly provider: ProviderID;
18
13
  readonly http?: HttpOptions;
19
- }
14
+ readonly providerOptions?: ProviderOptions;
15
+ }>;
20
16
  /** Deployment inputs every media model factory accepts; provider facades fill these from `configure(...)`. */
21
17
  export interface ModelInput {
22
18
  readonly id: string;
@@ -31,7 +27,7 @@ export interface ModelInput {
31
27
  export declare const deployment: (input: {
32
28
  readonly baseURL?: string;
33
29
  readonly headers?: Record<string, string>;
34
- readonly http?: HttpOptions.Input;
30
+ readonly http?: HttpOptions;
35
31
  }, auth: Auth.Definition) => Omit<ModelInput, "id">;
36
32
  /** One request, one response. */
37
33
  export interface InlineRoute<Request extends MediaRequest, Response> {
@@ -6,16 +6,11 @@ import { RequestExecutor } from "./executor.js";
6
6
  import { MediaProtocol } from "./media-protocol.js";
7
7
  import { Generation, isTerminal } from "../generation.js";
8
8
  import { isRetryable } from "../provider-error.js";
9
- import { AIError, AIErrorReason, HttpOptions, InvalidRequestError, ProviderID, UnsupportedOperationError, mergeHttpOptions, mergeProviderOptions, } from "../schema/index.js";
9
+ import { AIError, AIErrorReason, InvalidRequestError, ProviderID, UnsupportedOperationError, mergeProviderOptions, mergeTransport, } from "../schema/index.js";
10
10
  import { encodeJson } from "../utils/json.js";
11
11
  import { sanitizeSurrogates } from "../utils/sanitize.js";
12
12
  /** A provider facade's `configure(...)` input as the `ModelInput` every media selector shares, minus the model id. */
13
- export const deployment = (input, auth) => ({
14
- auth,
15
- baseURL: input.baseURL,
16
- headers: input.headers,
17
- http: HttpOptions.make(input.http),
18
- });
13
+ export const deployment = (input, auth) => ({ auth, baseURL: input.baseURL, headers: input.headers, http: input.http });
19
14
  /**
20
15
  * Compose an inline media protocol with an endpoint and auth into a runnable route. The route owns the transport
21
16
  * plumbing every media protocol would otherwise duplicate: option merging, surrogate sanitizing, unsupported-field
@@ -59,15 +54,15 @@ export const queued = (input) => {
59
54
  const decodeToken = Schema.decodeUnknownEffect(protocol.token);
60
55
  // A protocol producing a token its own codec rejects is a programmer defect, not a provider error.
61
56
  const encodeToken = Schema.encodeSync(protocol.token);
62
- const generationRoute = (token, http, execute) => {
57
+ const generationRoute = (token, exchange, execute) => {
63
58
  // Only the GET exchange retries: a decoded terminal failure (`output.ended`) can be a `ProviderInternal` too, and
64
59
  // re-reading it would spin until the caller's deadline.
65
- const poll = (operation) => transport.call("GET", operation.path(token), http, execute).pipe(Effect.retry({ schedule: READ_RETRY, while: isRetryable }), Effect.flatMap((sent) => operation.decode(sent.response, { token, auth: sent.auth })));
60
+ const poll = (operation) => transport.call("GET", operation.path(token), exchange, execute).pipe(Effect.retry({ schedule: READ_RETRY, while: isRetryable }), Effect.flatMap((sent) => operation.decode(sent.response, { token, auth: sent.auth })));
66
61
  const status = poll(protocol.status);
67
62
  const cancel = protocol.cancel;
68
63
  const send = cancel === undefined
69
64
  ? undefined
70
- : transport.call(cancel.method, cancel.path(token), http, execute).pipe(Effect.asVoid);
65
+ : transport.call(cancel.method, cancel.path(token), exchange, execute).pipe(Effect.asVoid);
71
66
  return {
72
67
  status,
73
68
  result: poll(protocol.result),
@@ -79,7 +74,7 @@ export const queued = (input) => {
79
74
  const start = Effect.fn("MediaRoute.start")(function* (request, execute) {
80
75
  const submitted = yield* transport.submit(request, { unsupported: protocol.unsupported, prepare: protocol.start.prepare, from: protocol.start.body.from }, execute);
81
76
  const started = yield* protocol.start.decode(submitted.response, submitted.context);
82
- const route = generationRoute(started.token, submitted.context.request.http, execute);
77
+ const route = generationRoute(started.token, submitted.exchange, execute);
83
78
  return new Generation(route, encodeToken(started.token), started.snapshot);
84
79
  });
85
80
  const resume = Effect.fn("MediaRoute.resume")(function* (model, raw, execute) {
@@ -89,7 +84,7 @@ export const queued = (input) => {
89
84
  cause,
90
85
  }),
91
86
  })));
92
- const route = generationRoute(token, transport.http(model), execute);
87
+ const route = generationRoute(token, transport.exchange(model), execute);
93
88
  return new Generation(route, encodeToken(token), yield* route.status);
94
89
  });
95
90
  return { kind: "queued", id: protocol.id, provider: protocol.provider, protocol: protocol.id, start, resume };
@@ -132,11 +127,10 @@ export const stream = (input) => {
132
127
  // Transport plumbing shared by every kind
133
128
  // ---------------------------------------------------------------------------
134
129
  const makeTransport = (input) => {
135
- const routeHttp = input.headers === undefined ? undefined : new HttpOptions({ headers: input.headers });
136
130
  const authorize = Auth.toEffect(input.auth);
137
131
  const baseURL = (path) => new URL(`${Endpoint.trimBaseUrl(input.endpoint.baseURL ?? "")}${path}`);
138
132
  /** `auth` is only what `Auth` added or changed, never untouched deployment headers. */
139
- const send = Effect.fn("MediaRoute.send")(function* (call, execute) {
133
+ const send = Effect.fn("MediaRoute.send")(function* (call, fetch, execute) {
140
134
  const encoded = encode(call.body, call.headers);
141
135
  const url = call.url.toString();
142
136
  const headers = yield* authorize({
@@ -146,41 +140,43 @@ const makeTransport = (input) => {
146
140
  body: encoded.text,
147
141
  headers: encoded.headers,
148
142
  });
149
- const response = yield* execute(encoded.apply(HttpClientRequest.make(call.method)(url).pipe(HttpClientRequest.setHeaders(headers))));
143
+ const response = yield* execute(encoded.apply(HttpClientRequest.make(call.method)(url).pipe(HttpClientRequest.setHeaders(headers))), RequestExecutor.withFetch(fetch));
150
144
  return {
151
145
  response,
152
146
  auth: Object.fromEntries(Object.entries(headers).filter(([key, value]) => encoded.headers[key] !== value)),
153
147
  };
154
148
  });
155
149
  return {
156
- /** Route and model overlays; `start` additionally merges the request's own `http`. */
157
- http: (model) => mergeHttpOptions(routeHttp, model.http),
150
+ /** Route and model overlays; `start` additionally merges the request's own. */
151
+ exchange: (model) => mergeTransport({ headers: input.headers, http: model.http }),
158
152
  /** POST the protocol body to the route endpoint. */
159
153
  submit: Effect.fn("MediaRoute.submit")(function* (request, protocol, execute) {
160
154
  yield* rejectUnsupported(input.protocol.id, input.protocol.provider, request, protocol.unsupported);
161
- const http = mergeHttpOptions(routeHttp, request.model.http, request.http);
155
+ const { headers: merged, http } = mergeTransport({ headers: input.headers, http: request.model.http }, request);
156
+ const exchange = { headers: merged, http, fetch: request.fetch };
162
157
  const providerOptions = mergeProviderOptions(request.model.providerOptions, request.providerOptions);
163
- const headers = Headers.fromInput(http?.headers);
158
+ const headers = Headers.fromInput(merged);
164
159
  const prepared = protocol.prepare === undefined
165
160
  ? request
166
- : yield* protocol.prepare(request, (path, body) => send({ method: "POST", url: baseURL(path), headers, request, body }, execute).pipe(Effect.map((sent) => sent.response)));
161
+ : yield* protocol.prepare(request, (path, body) => send({ method: "POST", url: baseURL(path), headers, request, body }, request.fetch, execute).pipe(Effect.map((sent) => sent.response)));
167
162
  // Sanitize after merging so model-level overlays are covered; the model value is restored, not sanitized.
168
163
  const resolved = {
169
- ...sanitizeSurrogates({ ...prepared, http, providerOptions }),
164
+ ...sanitizeSurrogates({ ...prepared, headers: merged, http, providerOptions }),
170
165
  model: request.model,
171
166
  };
172
167
  const body = yield* protocol.from(resolved);
173
168
  const url = withQuery(withQuery(Endpoint.render(input.endpoint, { request: resolved, body }), body.type === "multipart" ? undefined : body.query), http?.query);
174
- const sent = yield* send({ method: "POST", url, headers, request: resolved, body }, execute);
175
- return { response: sent.response, context: { request: resolved, body } };
169
+ const sent = yield* send({ method: "POST", url, headers, request: resolved, body }, request.fetch, execute);
170
+ return { response: sent.response, context: { request: resolved, body }, exchange };
176
171
  }),
177
172
  /** Bodiless follow-up call (status, result, cancel) with the same auth and headers as `submit`. */
178
- call: (method, path, http, execute) => {
173
+ call: (method, path, exchange, execute) => {
179
174
  // Provider-issued absolute URLs are used as-is; everything else resolves against the base.
180
- const url = withQuery(/^https?:\/\//.test(path) ? new URL(path) : baseURL(path), http?.query);
175
+ const url = withQuery(/^https?:\/\//.test(path) ? new URL(path) : baseURL(path), exchange.http?.query);
181
176
  for (const [key, value] of Object.entries(input.endpoint.query ?? {}))
182
177
  url.searchParams.set(key, value);
183
- return send({ method, url, headers: Headers.fromInput(http?.headers), request: { http } }, execute);
178
+ const headers = Headers.fromInput(exchange.headers);
179
+ return send({ method, url, headers, request: { http: exchange.http } }, exchange.fetch, execute);
184
180
  },
185
181
  };
186
182
  };
@@ -4,7 +4,7 @@ import { Auth } from "../auth.js";
4
4
  import { render as renderEndpoint } from "../endpoint.js";
5
5
  import { Framing } from "../framing.js";
6
6
  import * as ProviderShared from "../../protocols/shared.js";
7
- import { AIError, DEFAULT_CHUNK_TIMEOUT_MS, DEFAULT_HTTP_TIMEOUT_MS, mergeJsonRecords, TransportError, } from "../../schema/index.js";
7
+ import { AIError, DEFAULT_CHUNK_TIMEOUT_MS, DEFAULT_HTTP_TIMEOUT_MS, mergeJsonRecords, timeoutConfig, TransportError, } from "../../schema/index.js";
8
8
  import { RequestExecutor } from "../executor.js";
9
9
  const bodyWithOverlay = (body, request, encodeBody) => Effect.gen(function* () {
10
10
  if (request.http?.body === undefined)
@@ -29,7 +29,7 @@ export const jsonRequestParts = (input) => Effect.gen(function* () {
29
29
  body: body.bodyText,
30
30
  headers: Headers.fromInput({
31
31
  ...input.headers?.({ request: input.request }),
32
- ...input.request.http?.headers,
32
+ ...input.request.headers,
33
33
  }),
34
34
  });
35
35
  return { url, jsonBody: body.jsonBody, bodyText: body.bodyText, headers };
@@ -63,17 +63,18 @@ export const httpJson = (input) => ({
63
63
  }),
64
64
  });
65
65
  const started = yield* Clock.currentTimeMillis;
66
+ const limits = timeoutConfig(request.timeout);
66
67
  // Unlike the header and chunk limits, the whole-request budget has no default.
67
- const total = request.http?.timeout ? Duration.millis(request.http.timeout) : Duration.infinity;
68
+ const total = limits.total ? Duration.millis(limits.total) : Duration.infinity;
68
69
  const response = yield* runtime.http.execute(prepared.request, prepared.middleware).pipe(Effect.timeoutOrElse({
69
- duration: Duration.min(timeoutDuration(request.http?.headerTimeout), total),
70
+ duration: Duration.min(timeoutDuration(limits.headers), total),
70
71
  orElse: () => timeout("request", "Timed out waiting for response headers"),
71
72
  }));
72
73
  const http = RequestExecutor.responseHttp(response);
73
74
  const remaining = Duration.subtract(total, Duration.millis((yield* Clock.currentTimeMillis) - started));
74
75
  return {
75
76
  frames: prepared.framing.frame(RequestExecutor.responseStream(response).pipe(Stream.timeoutOrElse({
76
- duration: timeoutDuration(request.http?.chunkTimeout, DEFAULT_CHUNK_TIMEOUT_MS),
77
+ duration: timeoutDuration(limits.chunk, DEFAULT_CHUNK_TIMEOUT_MS),
77
78
  orElse: () => Stream.fail(timeout("read", "Timed out waiting for response data", http)),
78
79
  }), Stream.interruptWhen(Effect.sleep(remaining).pipe(Effect.andThen(Effect.fail(timeout("read", "Timed out waiting for the response to complete", http))))))),
79
80
  http,
@@ -32,6 +32,9 @@ const eventMessage = (event) => {
32
32
  return event.message;
33
33
  return event.type ?? "error";
34
34
  };
35
+ const systemCode = (cause) => typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string"
36
+ ? cause.code
37
+ : undefined;
35
38
  const binaryMessage = (data) => {
36
39
  if (data instanceof Uint8Array)
37
40
  return data;
@@ -75,10 +78,13 @@ const waitOpen = (ws, input) => {
75
78
  };
76
79
  const onError = (event) => {
77
80
  cleanup();
81
+ const cause = "error" in event ? (event.error ?? event) : event;
78
82
  resume(Effect.fail(transportError(`Failed to open WebSocket: ${eventMessage(event)}`, {
79
- cause: "error" in event ? (event.error ?? event) : event,
83
+ cause,
80
84
  url: input.url,
81
85
  operation: "request",
86
+ // Bun puts the system code (ENOTFOUND, ECONNREFUSED) on the event's error; lift it like HTTP failures do.
87
+ code: systemCode(cause),
82
88
  phase: "connect",
83
89
  delivery: "not-sent",
84
90
  })));
@@ -57,17 +57,6 @@ declare const ProviderConfigurationError_base: Schema.Class<ProviderConfiguratio
57
57
  */
58
58
  export declare class ProviderConfigurationError extends ProviderConfigurationError_base {
59
59
  }
60
- declare const NoRouteError_base: Schema.Class<NoRouteError, Schema.TaggedStruct<"NoRoute", {
61
- readonly message: Schema.String;
62
- readonly body: Schema.optional<Schema.String>;
63
- readonly http: Schema.optional<typeof HttpContext>;
64
- readonly cause: Schema.optional<Schema.Defect>;
65
- readonly route: Schema.String;
66
- readonly provider: Schema.brand<Schema.String, "AI.ProviderID">;
67
- readonly model: Schema.brand<Schema.String, "AI.ModelID">;
68
- }>, import("effect/Cause").YieldableError>;
69
- export declare class NoRouteError extends NoRouteError_base {
70
- }
71
60
  declare const AuthenticationError_base: Schema.Class<AuthenticationError, Schema.TaggedStruct<"Authentication", {
72
61
  message: Schema.String;
73
62
  body: Schema.optional<Schema.String>;
@@ -159,25 +148,35 @@ declare const TimeoutError_base: Schema.Class<TimeoutError, Schema.TaggedStruct<
159
148
  /** A caller-supplied deadline elapsed, such as `Generation.await` polling past its `Poll.timeout`. */
160
149
  export declare class TimeoutError extends TimeoutError_base {
161
150
  }
162
- export declare const AIErrorReason: Schema.toTaggedUnion<"_tag", readonly [typeof InvalidRequestError, typeof UnsupportedOperationError, typeof NoRouteError, typeof AuthenticationError, typeof RateLimitError, typeof QuotaExceededError, typeof ContentPolicyError, typeof ProviderInternalError, typeof TransportError, typeof InvalidProviderOutputError, typeof UnknownProviderError, typeof TimeoutError]>;
151
+ export declare const AIErrorReason: Schema.toTaggedUnion<"_tag", readonly [typeof InvalidRequestError, typeof UnsupportedOperationError, typeof AuthenticationError, typeof RateLimitError, typeof QuotaExceededError, typeof ContentPolicyError, typeof ProviderInternalError, typeof TransportError, typeof InvalidProviderOutputError, typeof UnknownProviderError, typeof TimeoutError]>;
163
152
  export type AIErrorReason = Schema.Schema.Type<typeof AIErrorReason>;
164
153
  declare const AIError_base: Schema.Class<AIError, Schema.TaggedStruct<"AI.Error", {
165
- readonly reason: Schema.toTaggedUnion<"_tag", readonly [typeof InvalidRequestError, typeof UnsupportedOperationError, typeof NoRouteError, typeof AuthenticationError, typeof RateLimitError, typeof QuotaExceededError, typeof ContentPolicyError, typeof ProviderInternalError, typeof TransportError, typeof InvalidProviderOutputError, typeof UnknownProviderError, typeof TimeoutError]>;
154
+ readonly reason: Schema.toTaggedUnion<"_tag", readonly [typeof InvalidRequestError, typeof UnsupportedOperationError, typeof AuthenticationError, typeof RateLimitError, typeof QuotaExceededError, typeof ContentPolicyError, typeof ProviderInternalError, typeof TransportError, typeof InvalidProviderOutputError, typeof UnknownProviderError, typeof TimeoutError]>;
166
155
  }>, import("effect/Cause").YieldableError>;
167
156
  export declare class AIError extends AIError_base {
168
- readonly cause: AuthenticationError | ContentPolicyError | InvalidProviderOutputError | InvalidRequestError | NoRouteError | ProviderInternalError | QuotaExceededError | RateLimitError | TimeoutError | TransportError | UnknownProviderError | UnsupportedOperationError;
169
- /** Output that arrived before `generate`, `generateObject` or a `loop` step failed. Not in the schema, so encoding omits it. */
157
+ readonly cause: AuthenticationError | ContentPolicyError | InvalidProviderOutputError | InvalidRequestError | ProviderInternalError | QuotaExceededError | RateLimitError | TimeoutError | TransportError | UnknownProviderError | UnsupportedOperationError;
158
+ /** Output that arrived before `generate` (including its `schema` decode) or a `loop` step failed. Not in the schema, so encoding omits it. */
170
159
  readonly partial?: LLMResponse;
171
160
  constructor(props: Pick<AIError, "reason" | "partial">);
172
161
  get message(): string;
162
+ /** HTTP status of the failed response, when the failure came from one. */
163
+ get status(): number | undefined;
164
+ /** The provider's error code from the response body or `x-amzn-errortype`, or the transport's system error code. */
165
+ get code(): string | undefined;
166
+ /** Delay the provider asked for before retrying, from `retry-after` style headers. */
167
+ get retryAfterMs(): number | undefined;
168
+ /**
169
+ * Whether a failed call may succeed when sent again: rate limits, provider-side failures, transport failures that did
170
+ * not deliver an accepted write, and unrecognized failures. Callers decide which calls are safe to repeat.
171
+ */
172
+ get isRetryable(): boolean;
173
173
  }
174
174
  /** Return `error` with `partial` attached, or unchanged when there is no partial output. */
175
175
  export declare const withPartial: (error: AIError, partial: LLMResponse | undefined) => AIError;
176
176
  /**
177
177
  * Failure type for tool execute handlers. Handlers must map their internal
178
178
  * errors to this shape; the runtime catches `ToolFailure`s and surfaces them
179
- * as `tool-error` events plus a `tool-result` of `type: "error"` so the model
180
- * can self-correct.
179
+ * as a `tool-result` of `type: "error"` so the model can self-correct.
181
180
  *
182
181
  * Anything thrown or yielded by a handler that is not a `ToolFailure` is
183
182
  * treated as a defect and fails the stream.
@@ -1,7 +1,8 @@
1
1
  import { Schema } from "effect";
2
2
  import { NonNegativeInt } from "@opencode/schema";
3
3
  import { Tool } from "@opencode/schema/tool";
4
- import { ModelID, ProviderID, RouteID } from "./ids.js";
4
+ import { ProviderID, RouteID } from "./ids.js";
5
+ import { awsErrorType, providerCodes } from "../utils/provider-codes.js";
5
6
  export const ProviderFailureClassification = Schema.Literals(["context-overflow", "payload-too-large"]);
6
7
  export class HttpContext extends Schema.Class("AI.HttpContext")({
7
8
  url: Schema.String,
@@ -53,13 +54,6 @@ export class ProviderConfigurationError extends Schema.TaggedError("AI.Error.Pro
53
54
  message: Schema.String,
54
55
  }) {
55
56
  }
56
- export class NoRouteError extends Schema.TaggedError("AI.Error.NoRoute")("NoRoute", {
57
- ...ReasonFields,
58
- route: RouteID,
59
- provider: ProviderID,
60
- model: ModelID,
61
- }) {
62
- }
63
57
  export class AuthenticationError extends Schema.TaggedError("AI.Error.Authentication")("Authentication", ReasonFields) {
64
58
  }
65
59
  export class RateLimitError extends Schema.TaggedError("AI.Error.RateLimit")("RateLimit", {
@@ -110,7 +104,6 @@ export class TimeoutError extends Schema.TaggedError("AI.Error.Timeout")("Timeou
110
104
  export const AIErrorReason = Schema.Union([
111
105
  InvalidRequestError,
112
106
  UnsupportedOperationError,
113
- NoRouteError,
114
107
  AuthenticationError,
115
108
  RateLimitError,
116
109
  QuotaExceededError,
@@ -125,7 +118,7 @@ export class AIError extends Schema.TaggedError()("AI.Error", {
125
118
  reason: AIErrorReason,
126
119
  }) {
127
120
  cause = this.reason;
128
- /** Output that arrived before `generate`, `generateObject` or a `loop` step failed. Not in the schema, so encoding omits it. */
121
+ /** Output that arrived before `generate` (including its `schema` decode) or a `loop` step failed. Not in the schema, so encoding omits it. */
129
122
  partial;
130
123
  constructor(props) {
131
124
  super({ reason: props.reason });
@@ -134,14 +127,72 @@ export class AIError extends Schema.TaggedError()("AI.Error", {
134
127
  get message() {
135
128
  return this.reason.message;
136
129
  }
130
+ /** HTTP status of the failed response, when the failure came from one. */
131
+ get status() {
132
+ return this.reason.http?.status;
133
+ }
134
+ /** The provider's error code from the response body or `x-amzn-errortype`, or the transport's system error code. */
135
+ get code() {
136
+ if (this.reason._tag === "Transport" && this.reason.code !== undefined)
137
+ return this.reason.code;
138
+ return [
139
+ ...(this.reason.body === undefined ? [] : providerCodes(this.reason.body)),
140
+ ...awsErrorType(this.reason.http?.headers["x-amzn-errortype"]),
141
+ ][0];
142
+ }
143
+ /** Delay the provider asked for before retrying, from `retry-after` style headers. */
144
+ get retryAfterMs() {
145
+ if (this.reason._tag === "RateLimit")
146
+ return this.reason.retryAfterMs ?? this.reason.rateLimit?.retryAfterMs;
147
+ if (this.reason._tag === "QuotaExceeded" || this.reason._tag === "ProviderInternal")
148
+ return this.reason.retryAfterMs;
149
+ return undefined;
150
+ }
151
+ /**
152
+ * Whether a failed call may succeed when sent again: rate limits, provider-side failures, transport failures that did
153
+ * not deliver an accepted write, and unrecognized failures. Callers decide which calls are safe to repeat.
154
+ */
155
+ get isRetryable() {
156
+ const override = this.reason.http?.headers["x-should-retry"];
157
+ if (override === "true")
158
+ return true;
159
+ if (override === "false")
160
+ return false;
161
+ switch (this.reason._tag) {
162
+ case "RateLimit":
163
+ case "ProviderInternal":
164
+ return true;
165
+ // A WebSocket acknowledgment marks delivery accepted before model output may exist.
166
+ // Read failures can still recover; the caller chooses retry versus continuation from durable output.
167
+ case "Transport":
168
+ return (this.reason.delivery !== "rejected" && (this.reason.delivery !== "accepted" || this.reason.operation === "read"));
169
+ case "InvalidProviderOutput":
170
+ return this.reason.classification === "incomplete-stream";
171
+ // Unrecognized failures retry: classification records affirmative
172
+ // deterministic evidence, and transient failures are exactly the ones
173
+ // that arrive in shapes no classifier anticipates.
174
+ case "UnknownProvider":
175
+ return true;
176
+ case "Authentication":
177
+ case "QuotaExceeded":
178
+ case "ContentPolicy":
179
+ case "InvalidRequest":
180
+ case "UnsupportedOperation":
181
+ case "Timeout":
182
+ return false;
183
+ default: {
184
+ const exhaustive = this.reason;
185
+ return exhaustive;
186
+ }
187
+ }
188
+ }
137
189
  }
138
190
  /** Return `error` with `partial` attached, or unchanged when there is no partial output. */
139
191
  export const withPartial = (error, partial) => partial === undefined ? error : new AIError({ reason: error.reason, partial });
140
192
  /**
141
193
  * Failure type for tool execute handlers. Handlers must map their internal
142
194
  * errors to this shape; the runtime catches `ToolFailure`s and surfaces them
143
- * as `tool-error` events plus a `tool-result` of `type: "error"` so the model
144
- * can self-correct.
195
+ * as a `tool-result` of `type: "error"` so the model can self-correct.
145
196
  *
146
197
  * Anything thrown or yielded by a handler that is not a `ToolFailure` is
147
198
  * treated as a defect and fails the stream.