@opencode/ai 2.2.5 → 2.2.6

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 (264) hide show
  1. package/README.md +133 -69
  2. package/dist/cache-policy.d.ts +1 -1
  3. package/dist/cache-policy.js +16 -4
  4. package/dist/decision-client.d.ts +3 -3
  5. package/dist/decision.d.ts +20 -125
  6. package/dist/decision.js +25 -15
  7. package/dist/effect.d.ts +4 -15
  8. package/dist/effect.js +2 -6
  9. package/dist/effort-updates.d.ts +3 -3
  10. package/dist/effort-updates.js +2 -2
  11. package/dist/experimental/cloudflare-run-extraction.d.ts +7 -3
  12. package/dist/experimental/cloudflare-run-extraction.js +4 -1
  13. package/dist/experimental/extraction.d.ts +10 -40
  14. package/dist/experimental/extraction.js +14 -13
  15. package/dist/experimental.d.ts +8 -8
  16. package/dist/experimental.js +4 -4
  17. package/dist/generation.d.ts +0 -2
  18. package/dist/generation.js +2 -2
  19. package/dist/image-client.d.ts +13 -7
  20. package/dist/image-client.js +1 -1
  21. package/dist/image.d.ts +357 -464
  22. package/dist/image.js +17 -15
  23. package/dist/index.d.ts +28 -465
  24. package/dist/index.js +18 -17
  25. package/dist/llm.d.ts +65 -266
  26. package/dist/llm.js +101 -92
  27. package/dist/loop.d.ts +38 -0
  28. package/dist/loop.js +136 -0
  29. package/dist/media-model.d.ts +1 -1
  30. package/dist/media-model.js +8 -6
  31. package/dist/media.d.ts +9 -0
  32. package/dist/media.js +37 -2
  33. package/dist/protocols/alibaba-chat.d.ts +5 -1
  34. package/dist/protocols/alibaba-chat.js +3 -3
  35. package/dist/protocols/alibaba-images.d.ts +2 -2
  36. package/dist/protocols/alibaba-messages.js +3 -3
  37. package/dist/protocols/alibaba-responses.js +8 -20
  38. package/dist/protocols/anthropic-messages.d.ts +1 -1
  39. package/dist/protocols/anthropic-messages.js +54 -173
  40. package/dist/protocols/assemblyai-transcription.d.ts +2 -2
  41. package/dist/protocols/bedrock-converse.js +10 -16
  42. package/dist/protocols/cartesia-speech.d.ts +2 -2
  43. package/dist/protocols/cloudflare-workers-ai-images.d.ts +2 -2
  44. package/dist/protocols/cohere-chat.js +9 -12
  45. package/dist/protocols/deepgram-speech.d.ts +2 -2
  46. package/dist/protocols/deepgram-transcription.d.ts +2 -2
  47. package/dist/protocols/elevenlabs-speech.d.ts +2 -2
  48. package/dist/protocols/elevenlabs-transcription.d.ts +2 -2
  49. package/dist/protocols/gemini.d.ts +3 -0
  50. package/dist/protocols/gemini.js +54 -72
  51. package/dist/protocols/google-images.d.ts +2 -2
  52. package/dist/protocols/google-interactions.d.ts +3 -4
  53. package/dist/protocols/google-interactions.js +44 -30
  54. package/dist/protocols/google-speech.d.ts +2 -2
  55. package/dist/protocols/google-transcription.d.ts +2 -2
  56. package/dist/protocols/google-video.d.ts +2 -2
  57. package/dist/protocols/meta-images.d.ts +2 -2
  58. package/dist/protocols/meta-responses.js +26 -23
  59. package/dist/protocols/minimax-images.d.ts +2 -2
  60. package/dist/protocols/mistral-chat.js +7 -10
  61. package/dist/protocols/open-responses-channel.js +6 -19
  62. package/dist/protocols/open-responses-continuation.d.ts +1 -5
  63. package/dist/protocols/open-responses-continuation.js +1 -3
  64. package/dist/protocols/open-responses.d.ts +1 -21
  65. package/dist/protocols/open-responses.js +10 -15
  66. package/dist/protocols/openai-chat.d.ts +3 -23
  67. package/dist/protocols/openai-chat.js +26 -47
  68. package/dist/protocols/openai-compatible-chat.d.ts +1 -1
  69. package/dist/protocols/openai-compatible-responses.d.ts +2 -2
  70. package/dist/protocols/openai-compatible-responses.js +1 -1
  71. package/dist/protocols/openai-decisions.js +1 -1
  72. package/dist/protocols/openai-images.d.ts +2 -2
  73. package/dist/protocols/openai-responses.js +10 -29
  74. package/dist/protocols/openai-speech.d.ts +2 -2
  75. package/dist/protocols/openai-transcription.d.ts +2 -2
  76. package/dist/protocols/runway-video.d.ts +2 -2
  77. package/dist/protocols/shared.d.ts +1 -4
  78. package/dist/protocols/shared.js +13 -11
  79. package/dist/protocols/system-one.d.ts +4 -4
  80. package/dist/protocols/utils/bedrock-cache.js +2 -5
  81. package/dist/protocols/utils/bedrock-media.d.ts +0 -3
  82. package/dist/protocols/utils/cache.d.ts +3 -0
  83. package/dist/protocols/utils/cache.js +15 -2
  84. package/dist/protocols/utils/image-sizing.d.ts +1 -1
  85. package/dist/protocols/utils/responses-checkpoint.js +1 -1
  86. package/dist/protocols/utils/responses-compaction.d.ts +1 -1
  87. package/dist/protocols/utils/responses-compaction.js +6 -5
  88. package/dist/protocols/utils/responses-hosted-tools.d.ts +97 -1
  89. package/dist/protocols/utils/responses-hosted-tools.js +31 -0
  90. package/dist/protocols/utils/tool-stream.d.ts +5 -271
  91. package/dist/protocols/utils/tool-stream.js +3 -13
  92. package/dist/protocols/venice-chat.d.ts +3 -1
  93. package/dist/protocols/venice-chat.js +4 -4
  94. package/dist/protocols/xai-images.d.ts +2 -2
  95. package/dist/protocols/xai-responses.js +5 -25
  96. package/dist/protocols/xai-video.d.ts +2 -2
  97. package/dist/protocols/zai-chat.d.ts +5 -1
  98. package/dist/protocols/zai-chat.js +1 -1
  99. package/dist/protocols/zai-images.d.ts +2 -2
  100. package/dist/protocols/zai-messages.js +3 -3
  101. package/dist/provider-error.d.ts +0 -1
  102. package/dist/provider-error.js +7 -80
  103. package/dist/providers/alibaba.d.ts +67 -4
  104. package/dist/providers/alibaba.js +6 -1
  105. package/dist/providers/amazon-bedrock-mantle.d.ts +6 -3
  106. package/dist/providers/amazon-bedrock-mantle.js +6 -3
  107. package/dist/providers/amazon-bedrock.d.ts +6 -7
  108. package/dist/providers/amazon-bedrock.js +1 -1
  109. package/dist/providers/anthropic-compatible.d.ts +7 -8
  110. package/dist/providers/anthropic-compatible.js +2 -5
  111. package/dist/providers/anthropic.d.ts +8 -9
  112. package/dist/providers/anthropic.js +2 -7
  113. package/dist/providers/assemblyai.d.ts +2 -2
  114. package/dist/providers/assemblyai.js +2 -7
  115. package/dist/providers/azure/messages.d.ts +2 -0
  116. package/dist/providers/azure/messages.js +1 -0
  117. package/dist/providers/azure.d.ts +322 -7
  118. package/dist/providers/azure.js +25 -9
  119. package/dist/providers/baseten.d.ts +5 -5
  120. package/dist/providers/baseten.js +7 -21
  121. package/dist/providers/cartesia.d.ts +1 -1
  122. package/dist/providers/cerebras.d.ts +5 -5
  123. package/dist/providers/cerebras.js +4 -15
  124. package/dist/providers/cloudflare-ai-gateway.d.ts +21 -13
  125. package/dist/providers/cloudflare-ai-gateway.js +28 -40
  126. package/dist/providers/cloudflare-shared.d.ts +9 -0
  127. package/dist/providers/cloudflare-shared.js +25 -0
  128. package/dist/providers/cloudflare-workers-ai.d.ts +4 -4
  129. package/dist/providers/cloudflare-workers-ai.js +4 -20
  130. package/dist/providers/cohere/chat.js +2 -7
  131. package/dist/providers/cohere.d.ts +6 -5
  132. package/dist/providers/cohere.js +7 -13
  133. package/dist/providers/deepgram.d.ts +2 -2
  134. package/dist/providers/deepgram.js +2 -7
  135. package/dist/providers/deepinfra.d.ts +5 -5
  136. package/dist/providers/deepinfra.js +5 -13
  137. package/dist/providers/deepseek.d.ts +5 -5
  138. package/dist/providers/deepseek.js +3 -14
  139. package/dist/providers/digitalocean.d.ts +8 -5
  140. package/dist/providers/digitalocean.js +13 -14
  141. package/dist/providers/elevenlabs.d.ts +2 -2
  142. package/dist/providers/elevenlabs.js +2 -7
  143. package/dist/providers/fireworks.d.ts +5 -5
  144. package/dist/providers/fireworks.js +4 -15
  145. package/dist/providers/google/interactions.d.ts +1 -1
  146. package/dist/providers/google/interactions.js +2 -7
  147. package/dist/providers/google-vertex-chat.d.ts +3 -3
  148. package/dist/providers/google-vertex-chat.js +3 -29
  149. package/dist/providers/google-vertex-interactions.d.ts +3 -3
  150. package/dist/providers/google-vertex-messages.d.ts +3 -3
  151. package/dist/providers/google-vertex-messages.js +3 -29
  152. package/dist/providers/google-vertex-mistral.d.ts +3 -3
  153. package/dist/providers/google-vertex-mistral.js +3 -29
  154. package/dist/providers/google-vertex-responses.d.ts +3 -3
  155. package/dist/providers/google-vertex-responses.js +4 -30
  156. package/dist/providers/google-vertex-shared.d.ts +31 -0
  157. package/dist/providers/google-vertex-shared.js +25 -0
  158. package/dist/providers/google-vertex.d.ts +3 -3
  159. package/dist/providers/google.d.ts +15 -13
  160. package/dist/providers/google.js +9 -19
  161. package/dist/providers/groq.d.ts +5 -5
  162. package/dist/providers/groq.js +4 -15
  163. package/dist/providers/meta.d.ts +5 -5
  164. package/dist/providers/meta.js +10 -23
  165. package/dist/providers/minimax/chat.js +2 -7
  166. package/dist/providers/minimax/responses.js +2 -7
  167. package/dist/providers/minimax.d.ts +5 -5
  168. package/dist/providers/minimax.js +7 -22
  169. package/dist/providers/mistral.d.ts +10 -11
  170. package/dist/providers/mistral.js +3 -14
  171. package/dist/providers/moonshot/messages.js +2 -7
  172. package/dist/providers/moonshot/responses.js +2 -7
  173. package/dist/providers/moonshot.d.ts +5 -5
  174. package/dist/providers/moonshot.js +4 -16
  175. package/dist/providers/openai-compatible-responses.d.ts +6 -7
  176. package/dist/providers/openai-compatible-responses.js +2 -8
  177. package/dist/providers/openai-compatible.d.ts +6 -7
  178. package/dist/providers/openai-compatible.js +4 -10
  179. package/dist/providers/openai.d.ts +4 -4
  180. package/dist/providers/openai.js +3 -3
  181. package/dist/providers/opencode.d.ts +4 -4
  182. package/dist/providers/opencode.js +6 -2
  183. package/dist/providers/openrouter.d.ts +8 -5
  184. package/dist/providers/openrouter.js +16 -24
  185. package/dist/providers/runway.d.ts +1 -1
  186. package/dist/providers/settings.d.ts +40 -0
  187. package/dist/providers/settings.js +19 -0
  188. package/dist/providers/togetherai.d.ts +5 -5
  189. package/dist/providers/togetherai.js +5 -15
  190. package/dist/providers/typesafe-ai.d.ts +4 -4
  191. package/dist/providers/typesafe-ai.js +6 -2
  192. package/dist/providers/venice.d.ts +4 -4
  193. package/dist/providers/venice.js +6 -2
  194. package/dist/providers/vercel-ai-gateway.d.ts +5 -5
  195. package/dist/providers/vercel-ai-gateway.js +15 -28
  196. package/dist/providers/xai.d.ts +4 -4
  197. package/dist/providers/xai.js +4 -12
  198. package/dist/providers/zai-coding-plan/messages.js +2 -7
  199. package/dist/providers/zai-coding-plan/responses.js +2 -7
  200. package/dist/providers/zai-coding-plan.d.ts +5 -5
  201. package/dist/providers/zai-coding-plan.js +8 -15
  202. package/dist/providers/zai.d.ts +5 -5
  203. package/dist/providers/zai.js +10 -22
  204. package/dist/public.d.ts +12 -0
  205. package/dist/public.js +5 -0
  206. package/dist/route/auth-options.d.ts +9 -5
  207. package/dist/route/auth-options.js +10 -7
  208. package/dist/route/client.d.ts +50 -37
  209. package/dist/route/client.js +42 -53
  210. package/dist/route/decision.d.ts +8 -8
  211. package/dist/route/decision.js +3 -3
  212. package/dist/route/executor.d.ts +5 -0
  213. package/dist/route/executor.js +10 -0
  214. package/dist/route/index.d.ts +5 -7
  215. package/dist/route/index.js +1 -1
  216. package/dist/route/media.d.ts +7 -11
  217. package/dist/route/media.js +22 -26
  218. package/dist/route/transport/http.js +6 -5
  219. package/dist/route/transport/websocket.js +7 -1
  220. package/dist/schema/errors.d.ts +16 -17
  221. package/dist/schema/errors.js +63 -12
  222. package/dist/schema/events.d.ts +2563 -2954
  223. package/dist/schema/events.js +54 -109
  224. package/dist/schema/messages.d.ts +194 -137
  225. package/dist/schema/messages.js +66 -83
  226. package/dist/schema/options.d.ts +112 -65
  227. package/dist/schema/options.js +52 -101
  228. package/dist/speech-client.d.ts +7 -7
  229. package/dist/speech.d.ts +306 -316
  230. package/dist/speech.js +16 -14
  231. package/dist/testing.d.ts +31 -175
  232. package/dist/testing.js +60 -5
  233. package/dist/tool-history.d.ts +1 -1
  234. package/dist/tool-history.js +3 -10
  235. package/dist/tool-runtime.d.ts +9 -2
  236. package/dist/tool-runtime.js +17 -31
  237. package/dist/tool.d.ts +39 -43
  238. package/dist/tool.js +16 -26
  239. package/dist/transcription-client.d.ts +7 -7
  240. package/dist/transcription.d.ts +314 -265
  241. package/dist/transcription.js +16 -14
  242. package/dist/utils/provider-codes.d.ts +3 -0
  243. package/dist/utils/provider-codes.js +41 -0
  244. package/dist/video-client.d.ts +7 -7
  245. package/dist/video-client.js +1 -1
  246. package/dist/video.d.ts +269 -287
  247. package/dist/video.js +16 -14
  248. package/package.json +9 -9
  249. package/dist/experimental/testing.d.ts +0 -3
  250. package/dist/experimental/testing.js +0 -3
  251. package/dist/testing/decision.d.ts +0 -16
  252. package/dist/testing/decision.js +0 -20
  253. package/dist/testing/image.d.ts +0 -14
  254. package/dist/testing/image.js +0 -12
  255. package/dist/testing/media.d.ts +0 -18
  256. package/dist/testing/media.js +0 -36
  257. package/dist/testing/script.d.ts +0 -28
  258. package/dist/testing/script.js +0 -60
  259. package/dist/testing/speech.d.ts +0 -14
  260. package/dist/testing/speech.js +0 -12
  261. package/dist/testing/transcription.d.ts +0 -14
  262. package/dist/testing/transcription.js +0 -12
  263. package/dist/testing/video.d.ts +0 -14
  264. package/dist/testing/video.js +0 -12
package/dist/loop.js ADDED
@@ -0,0 +1,136 @@
1
+ import { Effect, Stream } from "effect";
2
+ import { AIError, AssistantMessage, InvalidProviderOutputError, LLMResponse, ResponseFold, Message, Usage, LLMEvent, ToolCallPart, ToolChoice, } from "./schema/index.js";
3
+ /**
4
+ * Client calls to answer before the next step. A call whose input was not valid JSON carries the error the model
5
+ * gets back, so it can retry. A step is final when it calls `answerTool`, even alongside other tools, or when it hits
6
+ * the output token limit, which may have cut its calls off.
7
+ */
8
+ export const pendingCalls = (response, answerTool) => {
9
+ if (response.finishReason.normalized === "length")
10
+ return [];
11
+ if (answerTool !== undefined && response.toolCalls.some((call) => call.name === answerTool))
12
+ return [];
13
+ return [
14
+ ...response.toolCalls.filter((call) => call.providerExecuted !== true).map((call) => ({ call })),
15
+ ...response.events.filter(LLMEvent.is.toolInputError).map((event) => ({
16
+ call: invalidCall(event),
17
+ error: `Invalid tool arguments: the input is not valid JSON. Received: ${event.raw}`,
18
+ })),
19
+ ];
20
+ };
21
+ /** The call to replay for input that was not valid JSON. Providers require an object input, so it is empty. */
22
+ const invalidCall = (event) => ToolCallPart.make({ id: event.id, name: event.name, namespace: event.namespace, input: {} });
23
+ /** Add the replayed calls for invalid input to the assistant message, so each tool result has its call. */
24
+ const withInvalidCalls = (message, calls) => calls.length === 0 ? message : new AssistantMessage({ ...message, content: [...message.content, ...calls] });
25
+ /** The step's assistant message followed by one tool message per call, in call order. */
26
+ export const stepMessages = (response, calls, results) => [
27
+ withInvalidCalls(response.message, calls.flatMap((item) => (item.error === undefined ? [] : [item.call]))),
28
+ ...calls.map((item, i) => Message.tool({
29
+ id: item.call.id,
30
+ name: item.call.name,
31
+ namespace: item.call.namespace,
32
+ result: results[i].result,
33
+ providerMetadata: item.call.providerMetadata,
34
+ })),
35
+ ];
36
+ /**
37
+ * The request for the step after `response`, with its messages and tool results appended. A caller's forced
38
+ * `toolChoice` applies to the first step only; with `keepForcedChoice` (the answer tool's) it stays.
39
+ */
40
+ export const nextRequest = (request, response, calls, results, keepForcedChoice) => ({
41
+ ...request,
42
+ toolChoice: !keepForcedChoice && (request.toolChoice?.type === "required" || request.toolChoice?.type === "tool")
43
+ ? new ToolChoice({ type: "auto", disableParallelToolUse: request.toolChoice.disableParallelToolUse })
44
+ : request.toolChoice,
45
+ messages: [...request.messages, ...stepMessages(response, calls, results)],
46
+ });
47
+ /** Sum usage across steps. */
48
+ export const addUsage = (total, step) => {
49
+ if (total === undefined || step === undefined)
50
+ return total ?? step;
51
+ const sum = (key) => (total[key] === undefined && step[key] === undefined ? undefined : (total[key] ?? 0) + (step[key] ?? 0));
52
+ return new Usage({
53
+ // Context size describes the latest call, not a running total.
54
+ contextTokens: step.contextTokens ?? total.contextTokens,
55
+ inputTokens: sum("inputTokens"),
56
+ outputTokens: sum("outputTokens"),
57
+ nonCachedInputTokens: sum("nonCachedInputTokens"),
58
+ cacheReadInputTokens: sum("cacheReadInputTokens"),
59
+ cacheWriteInputTokens: sum("cacheWriteInputTokens"),
60
+ reasoningTokens: sum("reasoningTokens"),
61
+ totalTokens: sum("totalTokens"),
62
+ cost: sum("cost"),
63
+ });
64
+ };
65
+ export function collect(events) {
66
+ return Effect.suspend(() => {
67
+ const steps = [];
68
+ const messages = [];
69
+ let step = ResponseFold.empty();
70
+ // Between a `step-finish` and the next `step-start`, tool results come from the loop running tools.
71
+ let betweenSteps = false;
72
+ // The last step's assistant message, and its calls with invalid input that the loop may answer.
73
+ let assistant = -1;
74
+ let invalid = [];
75
+ let finish;
76
+ const close = (reason, usage) => {
77
+ if (step.events.length === 0)
78
+ return;
79
+ const response = new LLMResponse({
80
+ message: step.message,
81
+ events: step.events,
82
+ usage: usage ?? step.usage,
83
+ finishReason: reason,
84
+ });
85
+ steps.push(response);
86
+ assistant = messages.push(response.message) - 1;
87
+ invalid = step.events.filter(LLMEvent.is.toolInputError).map(invalidCall);
88
+ step = ResponseFold.empty();
89
+ };
90
+ return Stream.runForEach(events, (event) => Effect.sync(() => {
91
+ if (event.type === "finish") {
92
+ close(event.reason, event.usage);
93
+ finish = event;
94
+ return;
95
+ }
96
+ if (event.type === "tool-result" && betweenSteps) {
97
+ const call = invalid.find((item) => item.id === event.id);
98
+ const previous = messages[assistant];
99
+ if (call && previous.role === "assistant")
100
+ messages[assistant] = withInvalidCalls(previous, [call]);
101
+ messages.push(Message.tool({
102
+ id: event.id,
103
+ name: event.name,
104
+ namespace: event.namespace,
105
+ result: event.result,
106
+ providerMetadata: event.providerMetadata,
107
+ }));
108
+ return;
109
+ }
110
+ if (event.type === "step-start")
111
+ betweenSteps = false;
112
+ step = ResponseFold.reduce(step, event);
113
+ if (event.type !== "step-finish")
114
+ return;
115
+ close(event.reason, event.usage);
116
+ betweenSteps = true;
117
+ })).pipe(Effect.flatMap(() => {
118
+ if (finish === undefined)
119
+ return Effect.fail(new AIError({
120
+ reason: new InvalidProviderOutputError({
121
+ message: "The stream ended without a finish event.",
122
+ classification: "incomplete-stream",
123
+ }),
124
+ }));
125
+ const result = {
126
+ text: steps.at(-1)?.text ?? "",
127
+ steps,
128
+ messages,
129
+ usage: finish.usage,
130
+ finishReason: finish.reason,
131
+ ...("object" in finish ? { object: finish.object } : {}),
132
+ };
133
+ return Effect.succeed(result);
134
+ }));
135
+ });
136
+ }
@@ -2,7 +2,7 @@ import { Effect } from "effect";
2
2
  import { Endpoint } from "./route/endpoint.js";
3
3
  import { MediaRoute } from "./route/media.js";
4
4
  import type { MediaProtocol } from "./route/media-protocol.js";
5
- import { AIError, HttpOptions, ModelID, ProviderID, type ProviderOptions } from "./schema/index.js";
5
+ import { AIError, ModelID, ProviderID, type HttpOptions, type ProviderOptions } from "./schema/index.js";
6
6
  /**
7
7
  * What every media model carries: ids, the configured route, and deployment `http` overlays. Modality classes
8
8
  * (`ImageModel`, `VideoModel`, `SpeechModel`, `TranscriptionModel`) extend it with their route type and a nominal
@@ -1,7 +1,7 @@
1
1
  import { Effect } from "effect";
2
2
  import { Endpoint } from "./route/endpoint.js";
3
3
  import { MediaRoute } from "./route/media.js";
4
- import { AIError, HttpOptions, InvalidRequestError, ModelID, ProviderID } from "./schema/index.js";
4
+ import { AIError, InvalidRequestError, ModelID, ProviderID, } from "./schema/index.js";
5
5
  /**
6
6
  * What every media model carries: ids, the configured route, and deployment `http` overlays. Modality classes
7
7
  * (`ImageModel`, `VideoModel`, `SpeechModel`, `TranscriptionModel`) extend it with their route type and a nominal
@@ -41,10 +41,12 @@ const isQueuedInput = (route) => route.protocol.kind === "queued";
41
41
  /** Lift a synchronous Schema-class constructor into a typed `InvalidRequest` failure. */
42
42
  export const tryRequest = (make) => Effect.try({
43
43
  try: make,
44
- catch: (error) => new AIError({
45
- reason: new InvalidRequestError({
46
- message: error instanceof Error ? error.message : String(error),
47
- cause: error,
44
+ catch: (error) => error instanceof AIError
45
+ ? error
46
+ : new AIError({
47
+ reason: new InvalidRequestError({
48
+ message: error instanceof Error ? error.message : String(error),
49
+ cause: error,
50
+ }),
48
51
  }),
49
- }),
50
52
  });
package/dist/media.d.ts CHANGED
@@ -200,6 +200,15 @@ export declare const ref: (provider: string | ProviderID, id: string, mediaType?
200
200
  export declare const parseDataUrl: (value: string, options?: AssetOptions) => Asset | undefined;
201
201
  /** Parse a `data:<mime>;base64,<data>` URL. Malformed input throws a typed `AIError` because constructors are sync. */
202
202
  export declare const fromDataUrl: (dataUrl: string, options?: AssetOptions) => Asset;
203
+ /** Plain file data: bytes, a URL, or a string holding a data URL, an http(s) URL or base64. */
204
+ export type Data = Uint8Array | ArrayBuffer | URL | string;
205
+ /** What file inputs accept: an `Asset` or plain `Data`. */
206
+ export type Input = Asset | Data;
207
+ /**
208
+ * Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic
209
+ * bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged.
210
+ */
211
+ export declare const make: (input: Input, mediaType?: string) => Asset;
203
212
  /** Read a file through `FileSystem` and sniff its media type from magic bytes, then the extension. */
204
213
  export declare const file: (path: string, options?: AssetOptions) => Effect.Effect<Asset, AIError, FileSystem.FileSystem>;
205
214
  /** Materialize an asset and write its bytes through `FileSystem`. */
package/dist/media.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export * as Media from "./media.js";
2
- import { Effect, FileSystem, Schema, SchemaGetter } from "effect";
2
+ import { Effect, FileSystem, Result, Schema, SchemaGetter } from "effect";
3
3
  import { Base64 } from "effect/encoding";
4
4
  import { HttpClientRequest } from "effect/http";
5
5
  import { ProviderID } from "./schema/ids.js";
@@ -191,7 +191,7 @@ export const url = (value, options) => {
191
191
  return from({ type: "url", url: value, mediaType, expiresAt }, rest);
192
192
  };
193
193
  export const ref = (provider, id, mediaType, options) => from({ type: "ref", provider: ProviderID.make(provider), id, mediaType }, options);
194
- const DATA_URL = /^data:([^;,]+)(?:;[^,]*)*;base64,(.*)$/s;
194
+ const DATA_URL = /^data:([^;,]+)(?:;[^,]*)*;base64,(.*)$/is;
195
195
  /** Parse a `data:<mime>;base64,<data>` URL, or `undefined` when the value is not a base64 data URL. */
196
196
  export const parseDataUrl = (value, options) => {
197
197
  const match = DATA_URL.exec(value);
@@ -204,6 +204,41 @@ export const fromDataUrl = (dataUrl, options) => {
204
204
  throw invalid("Media data URLs must contain a MIME type and base64 data");
205
205
  return asset;
206
206
  };
207
+ /**
208
+ * Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic
209
+ * bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged.
210
+ */
211
+ export const make = (input, mediaType) => {
212
+ if (input instanceof Asset)
213
+ return input;
214
+ if (input instanceof ArrayBuffer)
215
+ return make(new Uint8Array(input), mediaType);
216
+ if (input instanceof Uint8Array)
217
+ return bytes(input, mediaType ?? requireMediaType(detectMediaType(input)));
218
+ const value = input instanceof URL ? input.href : input;
219
+ if (/^data:/i.test(value)) {
220
+ const match = DATA_URL.exec(value);
221
+ if (match === null)
222
+ throw invalid("Media data URLs must contain a MIME type and base64 data");
223
+ return base64(match[2], mediaType ?? match[1]);
224
+ }
225
+ if (input instanceof URL || /^https?:\/\//i.test(value))
226
+ return url(value, { mediaType });
227
+ if (!BASE64.test(value))
228
+ throw invalid("Media strings must be base64, a data URL or an http(s) URL; read files with Media.file");
229
+ return base64(value, mediaType ?? requireMediaType(sniffBase64(value)));
230
+ };
231
+ const BASE64 = /^[A-Za-z0-9+/\-_\s]*={0,2}\s*$/;
232
+ // 64 characters decode to 48 bytes, enough for every signature `detectMediaType` reads.
233
+ const sniffBase64 = (value) => {
234
+ const head = Result.getOrUndefined(Base64.decode(value.slice(0, 64)));
235
+ return head === undefined ? undefined : detectMediaType(head);
236
+ };
237
+ const requireMediaType = (detected) => {
238
+ if (detected === undefined)
239
+ throw invalid("Media data needs a mediaType because its type cannot be detected");
240
+ return detected;
241
+ };
207
242
  /** Read a file through `FileSystem` and sniff its media type from magic bytes, then the extension. */
208
243
  export const file = (path, options) => Effect.gen(function* () {
209
244
  const fs = yield* FileSystem.FileSystem;
@@ -29,10 +29,14 @@ declare const Options: Schema.Struct<{
29
29
  export type OptionsInput = typeof Options.Type;
30
30
  export declare const compatibility: {
31
31
  maxTokensField: "max_completion_tokens";
32
- supportsStrictMode: false;
33
32
  reasoningField: string;
34
33
  zaiToolStream: false;
35
34
  };
35
+ export declare const capabilities: {
36
+ tools: {
37
+ strict: false;
38
+ };
39
+ };
36
40
  export declare const protocol: Protocol<{
37
41
  readonly model: string;
38
42
  readonly messages: readonly ({
@@ -29,10 +29,10 @@ const Options = Schema.Struct({
29
29
  });
30
30
  export const compatibility = {
31
31
  maxTokensField: "max_completion_tokens",
32
- supportsStrictMode: false,
33
32
  reasoningField: "reasoning_content",
34
33
  zaiToolStream: false,
35
34
  };
35
+ export const capabilities = { tools: { strict: false } };
36
36
  export const protocol = Protocol.make({
37
37
  id: "alibaba-chat",
38
38
  body: {
@@ -58,7 +58,7 @@ export const protocol = Protocol.make({
58
58
  // Alibaba also rejects an explicit budget that is not below `max_completion_tokens`.
59
59
  thinking_budget: opts.thinkingBudget === undefined
60
60
  ? undefined
61
- : ProviderShared.fitThinkingBudget(opts.thinkingBudget, req.generation?.maxTokens),
61
+ : ProviderShared.fitThinkingBudget(opts.thinkingBudget, req.maxTokens),
62
62
  preserve_thinking: opts.preserveThinking,
63
63
  clear_thinking: opts.clearThinking,
64
64
  thinking: opts.thinking,
@@ -66,7 +66,7 @@ export const protocol = Protocol.make({
66
66
  parallel_tool_calls: opts.parallelToolCalls ??
67
67
  (req.toolChoice?.disableParallelToolUse === undefined ? undefined : !req.toolChoice.disableParallelToolUse),
68
68
  repetition_penalty: opts.repetitionPenalty,
69
- top_k: req.generation?.topK,
69
+ top_k: req.topK,
70
70
  response_format: opts.responseFormat,
71
71
  enable_search: opts.enableSearch,
72
72
  search_options: opts.searchOptions,
@@ -1,4 +1,4 @@
1
- import { ImageModel, ImageResponse, type ImageRequestFor } from "../image.js";
1
+ import { ImageModel, ImageResponse, type ImageRequest } from "../image.js";
2
2
  import { MediaProtocol } from "../route/media-protocol.js";
3
3
  import { MediaRoute } from "../route/media.js";
4
4
  export declare const PATH = "/services/aigc/multimodal-generation/generation";
@@ -13,7 +13,7 @@ export type AlibabaImageOptions = {
13
13
  readonly thinkingMode?: boolean;
14
14
  readonly enableSequential?: boolean;
15
15
  } & Record<string, unknown>;
16
- export type Request = ImageRequestFor<AlibabaImageOptions>;
16
+ export type Request = ImageRequest<ImageModel<AlibabaImageOptions>>;
17
17
  export declare const protocol: MediaProtocol.Inline<Request, ImageResponse>;
18
18
  export declare const model: (input: MediaRoute.ModelInput) => ImageModel<AlibabaImageOptions>;
19
19
  export declare const AlibabaImages: {
@@ -1,6 +1,5 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  import { Protocol } from "../route/protocol.js";
3
- import { LLMRequest } from "../schema/index.js";
4
3
  import { AnthropicMessages } from "./anthropic-messages.js";
5
4
  import { ProviderShared } from "./shared.js";
6
5
  import { OpenResponsesOptions } from "./utils/open-responses-options.js";
@@ -22,9 +21,10 @@ export const protocol = Protocol.make({
22
21
  from: Effect.fn("AlibabaMessages.fromRequest")(function* (req) {
23
22
  const opts = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(Options))(req.providerOptions ?? {});
24
23
  // Model Studio accepts enabled thinking without Anthropic's mandatory token budget.
25
- const body = yield* AnthropicMessages.protocol.body.from(LLMRequest.update(req, {
24
+ const body = yield* AnthropicMessages.protocol.body.from({
25
+ ...req,
26
26
  providerOptions: { ...req.providerOptions, thinking: undefined },
27
- }));
27
+ });
28
28
  const budget = opts.thinking?.budgetTokens ?? opts.thinking?.budget_tokens;
29
29
  return {
30
30
  ...body,
@@ -32,7 +32,7 @@ const adapter = {
32
32
  restoreHostedToolItem: (item) => (Schema.is(WebExtractorItem)(item) ? item : undefined),
33
33
  };
34
34
  const tools = {
35
- web_search_call: { name: "web_search", input: (item) => item.action ?? {} },
35
+ web_search_call: ResponsesHostedTools.common.web_search_call,
36
36
  code_interpreter_call: { name: "code_interpreter", input: (item) => ({ code: item.code }) },
37
37
  };
38
38
  export const protocol = Protocol.make({
@@ -55,24 +55,12 @@ export const protocol = Protocol.make({
55
55
  };
56
56
  }),
57
57
  },
58
- stream: {
59
- event: OpenResponses.protocol.stream.event,
60
- initial: (req) => OpenResponses.initial(req, adapter),
61
- step: (state, input) => Effect.gen(function* () {
62
- const event = OpenResponses.normalize(state, input);
63
- if (event.type !== "response.output_item.done" || !event.item)
64
- return yield* OpenResponses.step(state, event);
65
- if (event.item.type === "web_extractor_call") {
66
- const item = yield* Schema.decodeUnknownEffect(WebExtractorItem)(event.item).pipe(Effect.mapError((cause) => ProviderShared.eventError(adapter.id, "Alibaba returned an invalid web extraction item", ProviderShared.encodeJson(event), cause)));
67
- return yield* ResponsesHostedTools.onDone(state, item, {
68
- web_extractor_call: { name: "web_extractor", input: () => ({ urls: item.urls, goal: item.goal }) },
69
- });
70
- }
71
- if (ResponsesHostedTools.isItem(event.item, tools))
72
- return yield* ResponsesHostedTools.onDone(state, event.item, tools);
73
- return yield* OpenResponses.step(state, event);
74
- }),
75
- terminal: OpenResponses.terminal,
76
- },
58
+ stream: ResponsesHostedTools.stream(adapter, tools, (state, event) => {
59
+ if (event.type !== "response.output_item.done" || event.item?.type !== "web_extractor_call")
60
+ return undefined;
61
+ return Schema.decodeUnknownEffect(WebExtractorItem)(event.item).pipe(Effect.mapError((cause) => ProviderShared.eventError(adapter.id, "Alibaba returned an invalid web extraction item", ProviderShared.encodeJson(event), cause)), Effect.flatMap((item) => ResponsesHostedTools.onDone(state, item, {
62
+ web_extractor_call: { name: "web_extractor", input: () => ({ urls: item.urls, goal: item.goal }) },
63
+ })));
64
+ }),
77
65
  });
78
66
  export * as AlibabaResponses from "./alibaba-responses.js";
@@ -3,7 +3,7 @@ import { Route } from "../route/client.js";
3
3
  import { Framing } from "../route/framing.js";
4
4
  import { Protocol } from "../route/protocol.js";
5
5
  import { HttpTransport } from "../route/transport/index.js";
6
- import { AIError, LLMRequest, type ProviderOptions } from "../schema/index.js";
6
+ import { AIError, type LLMRequest, type ProviderOptions } from "../schema/index.js";
7
7
  import { Lifecycle } from "./utils/lifecycle.js";
8
8
  import { ToolStream } from "./utils/tool-stream.js";
9
9
  export declare const DEFAULT_BASE_URL = "https://api.anthropic.com/v1";