@opencode/ai 2.1.4 → 2.2.0

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 (269) hide show
  1. package/README.md +283 -114
  2. package/dist/ai-client.d.ts +2 -2
  3. package/dist/ai-client.js +2 -1
  4. package/dist/cache-policy.d.ts +4 -0
  5. package/dist/cache-policy.js +20 -6
  6. package/dist/decision-client.d.ts +21 -0
  7. package/dist/decision-client.js +55 -0
  8. package/dist/decision.d.ts +472 -0
  9. package/dist/decision.js +158 -0
  10. package/dist/effect.d.ts +38 -0
  11. package/dist/effect.js +27 -0
  12. package/dist/effort-updates.d.ts +2 -2
  13. package/dist/experimental/cloudflare-run-extraction.d.ts +13 -0
  14. package/dist/experimental/cloudflare-run-extraction.js +83 -0
  15. package/dist/experimental/extraction.d.ts +183 -0
  16. package/dist/experimental/extraction.js +102 -0
  17. package/dist/experimental/realtime.d.ts +7 -2
  18. package/dist/experimental/realtime.js +5 -5
  19. package/dist/experimental.d.ts +2 -3
  20. package/dist/experimental.js +1 -2
  21. package/dist/image-client.d.ts +5 -14
  22. package/dist/image-client.js +0 -1
  23. package/dist/image.d.ts +6 -176
  24. package/dist/image.js +4 -11
  25. package/dist/index.d.ts +1426 -34
  26. package/dist/index.js +127 -24
  27. package/dist/llm.d.ts +16 -1
  28. package/dist/llm.js +34 -0
  29. package/dist/media-client.d.ts +2 -1
  30. package/dist/media-model.d.ts +3 -0
  31. package/dist/media-model.js +4 -1
  32. package/dist/media.d.ts +0 -7
  33. package/dist/media.js +0 -6
  34. package/dist/protocols/alibaba-chat.d.ts +20 -0
  35. package/dist/protocols/alibaba-images.d.ts +22 -0
  36. package/dist/protocols/alibaba-images.js +77 -0
  37. package/dist/protocols/alibaba-messages.d.ts +52 -17
  38. package/dist/protocols/alibaba-responses.d.ts +6 -3
  39. package/dist/protocols/anthropic-messages.d.ts +160 -54
  40. package/dist/protocols/anthropic-messages.js +44 -13
  41. package/dist/protocols/bedrock-converse.d.ts +110 -15
  42. package/dist/protocols/bedrock-converse.js +112 -15
  43. package/dist/protocols/bedrock-event-stream.js +1 -0
  44. package/dist/protocols/bfl-images.d.ts +9 -0
  45. package/dist/protocols/bfl-images.js +17 -15
  46. package/dist/protocols/cartesia-speech.d.ts +0 -18
  47. package/dist/protocols/cloudflare-run-decisions.d.ts +9 -0
  48. package/dist/protocols/cloudflare-run-decisions.js +36 -0
  49. package/dist/protocols/cloudflare-workers-ai-images.d.ts +23 -0
  50. package/dist/protocols/cloudflare-workers-ai-images.js +80 -0
  51. package/dist/protocols/deepgram-speech.d.ts +0 -18
  52. package/dist/protocols/elevenlabs-speech.d.ts +0 -18
  53. package/dist/protocols/fal-images.d.ts +10 -1
  54. package/dist/protocols/fal-images.js +16 -25
  55. package/dist/protocols/fal-video.js +1 -1
  56. package/dist/protocols/gemini.d.ts +3 -0
  57. package/dist/protocols/gemini.js +11 -6
  58. package/dist/protocols/google-images.d.ts +2 -2
  59. package/dist/protocols/google-images.js +8 -37
  60. package/dist/protocols/google-interactions.d.ts +4 -0
  61. package/dist/protocols/google-interactions.js +12 -5
  62. package/dist/protocols/google-speech.d.ts +0 -18
  63. package/dist/protocols/google-speech.js +0 -1
  64. package/dist/protocols/google-transcription.d.ts +0 -18
  65. package/dist/protocols/google-transcription.js +0 -1
  66. package/dist/protocols/google-video.d.ts +1 -1
  67. package/dist/protocols/google-video.js +2 -7
  68. package/dist/protocols/index.d.ts +3 -0
  69. package/dist/protocols/index.js +3 -0
  70. package/dist/protocols/meta-images.d.ts +7 -1
  71. package/dist/protocols/meta-images.js +10 -8
  72. package/dist/protocols/meta-messages.d.ts +52 -17
  73. package/dist/protocols/meta-messages.js +14 -1
  74. package/dist/protocols/meta-responses.d.ts +6 -0
  75. package/dist/protocols/meta-responses.js +29 -1
  76. package/dist/protocols/open-responses.d.ts +30 -0
  77. package/dist/protocols/open-responses.js +8 -18
  78. package/dist/protocols/openai-chat.d.ts +713 -1
  79. package/dist/protocols/openai-chat.js +35 -22
  80. package/dist/protocols/openai-compatible-chat.d.ts +22 -1
  81. package/dist/protocols/openai-compatible-responses.d.ts +8 -5
  82. package/dist/protocols/openai-decisions.d.ts +22 -0
  83. package/dist/protocols/openai-decisions.js +128 -0
  84. package/dist/protocols/openai-images.d.ts +21 -24
  85. package/dist/protocols/openai-images.js +100 -34
  86. package/dist/protocols/openai-responses.d.ts +82 -24
  87. package/dist/protocols/openai-responses.js +32 -2
  88. package/dist/protocols/openai-speech.d.ts +0 -18
  89. package/dist/protocols/openai-speech.js +15 -5
  90. package/dist/protocols/openai-transcription.d.ts +0 -18
  91. package/dist/protocols/openai-transcription.js +3 -4
  92. package/dist/protocols/replicate-images.js +1 -1
  93. package/dist/protocols/runway-video.d.ts +1 -1
  94. package/dist/protocols/runway-video.js +1 -1
  95. package/dist/protocols/shared.d.ts +9 -1
  96. package/dist/protocols/shared.js +13 -2
  97. package/dist/protocols/stability-images.d.ts +5 -0
  98. package/dist/protocols/stability-images.js +4 -9
  99. package/dist/protocols/system-one.d.ts +101 -0
  100. package/dist/protocols/system-one.js +230 -0
  101. package/dist/protocols/utils/bedrock-cache.d.ts +2 -2
  102. package/dist/protocols/utils/bedrock-cache.js +7 -6
  103. package/dist/protocols/utils/cache.d.ts +14 -3
  104. package/dist/protocols/utils/cache.js +11 -4
  105. package/dist/protocols/utils/gemini-generate-content.d.ts +3 -3
  106. package/dist/protocols/utils/gemini-generate-content.js +10 -16
  107. package/dist/protocols/utils/gemini-json-schema.d.ts +5 -0
  108. package/dist/protocols/utils/gemini-json-schema.js +3 -3
  109. package/dist/protocols/utils/image-sizing.d.ts +31 -0
  110. package/dist/protocols/utils/image-sizing.js +73 -0
  111. package/dist/protocols/utils/media-input.d.ts +4 -5
  112. package/dist/protocols/utils/media-input.js +8 -5
  113. package/dist/protocols/utils/speech-stream.d.ts +0 -1
  114. package/dist/protocols/utils/speech-stream.js +0 -1
  115. package/dist/protocols/utils/tool-schema.js +15 -5
  116. package/dist/protocols/utils/tool-stream.d.ts +9 -0
  117. package/dist/protocols/venice-chat.d.ts +19 -0
  118. package/dist/protocols/venice-chat.js +1 -1
  119. package/dist/protocols/xai-images.d.ts +1 -2
  120. package/dist/protocols/xai-images.js +9 -2
  121. package/dist/protocols/xai-responses.d.ts +10 -0
  122. package/dist/protocols/xai-responses.js +28 -2
  123. package/dist/protocols/xai-video.d.ts +1 -1
  124. package/dist/protocols/xai-video.js +11 -8
  125. package/dist/protocols/zai-chat.d.ts +21 -0
  126. package/dist/protocols/zai-images.d.ts +3 -1
  127. package/dist/protocols/zai-images.js +12 -11
  128. package/dist/protocols/zai-messages.d.ts +52 -17
  129. package/dist/provider-error.js +19 -4
  130. package/dist/providers/alibaba/images.d.ts +2 -0
  131. package/dist/providers/alibaba/images.js +1 -0
  132. package/dist/providers/alibaba.d.ts +79 -18
  133. package/dist/providers/alibaba.js +16 -8
  134. package/dist/providers/amazon-bedrock-mantle.d.ts +197 -138
  135. package/dist/providers/amazon-bedrock.d.ts +34 -14
  136. package/dist/providers/amazon-bedrock.js +11 -11
  137. package/dist/providers/anthropic-compatible.d.ts +52 -17
  138. package/dist/providers/anthropic.d.ts +52 -17
  139. package/dist/providers/azure/images.d.ts +2 -0
  140. package/dist/providers/azure/images.js +1 -0
  141. package/dist/providers/azure.d.ts +50 -9
  142. package/dist/providers/azure.js +19 -1
  143. package/dist/providers/baseten/decisions.d.ts +2 -0
  144. package/dist/providers/baseten/decisions.js +1 -0
  145. package/dist/providers/baseten.d.ts +51 -1
  146. package/dist/providers/baseten.js +41 -8
  147. package/dist/providers/cerebras.d.ts +42 -0
  148. package/dist/providers/cloudflare-ai-gateway/decisions.d.ts +2 -0
  149. package/dist/providers/cloudflare-ai-gateway/decisions.js +1 -0
  150. package/dist/providers/cloudflare-ai-gateway.d.ts +177 -43
  151. package/dist/providers/cloudflare-ai-gateway.js +32 -4
  152. package/dist/providers/cloudflare-workers-ai/decisions.d.ts +2 -0
  153. package/dist/providers/cloudflare-workers-ai/decisions.js +1 -0
  154. package/dist/providers/cloudflare-workers-ai/images.d.ts +2 -0
  155. package/dist/providers/cloudflare-workers-ai/images.js +1 -0
  156. package/dist/providers/cloudflare-workers-ai.d.ts +55 -1
  157. package/dist/providers/cloudflare-workers-ai.js +45 -9
  158. package/dist/providers/cohere.d.ts +42 -0
  159. package/dist/providers/deepinfra.d.ts +42 -0
  160. package/dist/providers/deepseek.d.ts +42 -0
  161. package/dist/providers/digitalocean/decisions.d.ts +2 -0
  162. package/dist/providers/digitalocean/decisions.js +1 -0
  163. package/dist/providers/digitalocean/images.d.ts +2 -0
  164. package/dist/providers/digitalocean/images.js +1 -0
  165. package/dist/providers/digitalocean.d.ts +72 -1
  166. package/dist/providers/digitalocean.js +39 -8
  167. package/dist/providers/fireworks.d.ts +42 -0
  168. package/dist/providers/google/images.d.ts +2 -0
  169. package/dist/providers/google/images.js +1 -0
  170. package/dist/providers/google-vertex/images.d.ts +2 -0
  171. package/dist/providers/google-vertex/images.js +1 -0
  172. package/dist/providers/google-vertex-chat.d.ts +21 -0
  173. package/dist/providers/google-vertex-messages.d.ts +52 -17
  174. package/dist/providers/google-vertex-responses.d.ts +3 -0
  175. package/dist/providers/google-vertex.d.ts +3 -1
  176. package/dist/providers/google-vertex.js +30 -13
  177. package/dist/providers/google.d.ts +5 -4
  178. package/dist/providers/google.js +15 -8
  179. package/dist/providers/groq.d.ts +42 -4
  180. package/dist/providers/groq.js +0 -6
  181. package/dist/providers/meta.d.ts +197 -138
  182. package/dist/providers/minimax.d.ts +76 -17
  183. package/dist/providers/moonshot.d.ts +76 -17
  184. package/dist/providers/openai/images.d.ts +2 -0
  185. package/dist/providers/openai/images.js +1 -0
  186. package/dist/providers/openai-compatible/images.d.ts +2 -0
  187. package/dist/providers/openai-compatible/images.js +1 -0
  188. package/dist/providers/openai-compatible-responses.d.ts +3 -0
  189. package/dist/providers/openai-compatible.d.ts +24 -1
  190. package/dist/providers/openai-compatible.js +21 -9
  191. package/dist/providers/openai-options.d.ts +3 -1
  192. package/dist/providers/openai.d.ts +46 -9
  193. package/dist/providers/openai.js +20 -4
  194. package/dist/providers/opencode/decisions.d.ts +2 -0
  195. package/dist/providers/opencode/decisions.js +1 -0
  196. package/dist/providers/opencode.d.ts +9 -10
  197. package/dist/providers/opencode.js +10 -8
  198. package/dist/providers/openrouter/decisions.d.ts +2 -0
  199. package/dist/providers/openrouter/decisions.js +1 -0
  200. package/dist/providers/openrouter/images.d.ts +2 -0
  201. package/dist/providers/openrouter/images.js +1 -0
  202. package/dist/providers/openrouter.d.ts +92 -11
  203. package/dist/providers/openrouter.js +38 -16
  204. package/dist/providers/togetherai.d.ts +42 -0
  205. package/dist/providers/typesafe-ai/decisions.d.ts +2 -0
  206. package/dist/providers/typesafe-ai/decisions.js +1 -0
  207. package/dist/providers/typesafe-ai.d.ts +9 -10
  208. package/dist/providers/typesafe-ai.js +10 -8
  209. package/dist/providers/venice.d.ts +19 -0
  210. package/dist/providers/vercel-ai-gateway/decisions.d.ts +2 -0
  211. package/dist/providers/vercel-ai-gateway/decisions.js +1 -0
  212. package/dist/providers/vercel-ai-gateway/images.d.ts +2 -0
  213. package/dist/providers/vercel-ai-gateway/images.js +1 -0
  214. package/dist/providers/vercel-ai-gateway.d.ts +10 -16
  215. package/dist/providers/vercel-ai-gateway.js +31 -85
  216. package/dist/providers/xai/images.d.ts +2 -0
  217. package/dist/providers/xai/images.js +1 -0
  218. package/dist/providers/xai.d.ts +28 -5
  219. package/dist/providers/xai.js +15 -8
  220. package/dist/providers/zai/images.d.ts +2 -0
  221. package/dist/providers/zai/images.js +1 -0
  222. package/dist/providers/zai-coding-plan.d.ts +76 -17
  223. package/dist/providers/zai.d.ts +26 -4
  224. package/dist/providers/zai.js +15 -8
  225. package/dist/route/client.d.ts +2 -2
  226. package/dist/route/client.js +26 -4
  227. package/dist/route/decision.d.ts +58 -0
  228. package/dist/route/decision.js +75 -0
  229. package/dist/route/executor.d.ts +1 -1
  230. package/dist/route/framing.d.ts +2 -0
  231. package/dist/route/index.d.ts +3 -0
  232. package/dist/route/index.js +3 -0
  233. package/dist/route/media-protocol.d.ts +1 -0
  234. package/dist/route/media-protocol.js +12 -8
  235. package/dist/route/media.d.ts +5 -1
  236. package/dist/route/media.js +6 -2
  237. package/dist/route/transport/http.js +1 -0
  238. package/dist/route/transport/index.d.ts +1 -0
  239. package/dist/schema/events.d.ts +148 -6
  240. package/dist/schema/events.js +20 -0
  241. package/dist/schema/messages.d.ts +6 -2
  242. package/dist/schema/messages.js +3 -0
  243. package/dist/schema/options.d.ts +5 -3
  244. package/dist/schema/options.js +8 -3
  245. package/dist/speech-client.d.ts +5 -14
  246. package/dist/speech-client.js +0 -1
  247. package/dist/speech.d.ts +0 -135
  248. package/dist/speech.js +2 -4
  249. package/dist/testing.d.ts +25 -24
  250. package/dist/testing.js +3 -21
  251. package/dist/transcription-client.d.ts +5 -14
  252. package/dist/transcription.d.ts +0 -135
  253. package/dist/transcription.js +1 -1
  254. package/dist/utils/media-type.js +22 -1
  255. package/dist/video-client.d.ts +5 -14
  256. package/dist/video-client.js +0 -1
  257. package/dist/video.d.ts +1 -136
  258. package/dist/video.js +3 -5
  259. package/package.json +513 -11
  260. package/dist/experimental/evaluation-client.d.ts +0 -21
  261. package/dist/experimental/evaluation-client.js +0 -64
  262. package/dist/experimental/evaluation.d.ts +0 -242
  263. package/dist/experimental/evaluation.js +0 -108
  264. package/dist/experimental/system-one.d.ts +0 -16
  265. package/dist/experimental/system-one.js +0 -135
  266. package/dist/promise.d.ts +0 -1021
  267. package/dist/promise.js +0 -101
  268. package/dist/provider.d.ts +0 -23
  269. package/dist/provider.js +0 -2
package/dist/index.js CHANGED
@@ -1,24 +1,127 @@
1
- export { AIClient } from "./ai-client.js";
2
- export { LLMClient } from "./route/client.js";
3
- export { ImageClient } from "./image-client.js";
4
- export { Auth } from "./route/auth.js";
5
- export { Provider } from "./provider.js";
6
- export { ProviderPackage } from "./provider-package.js";
7
- export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./provider-error.js";
8
- export * from "./schema/index.js";
9
- export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageRequest, ImageResponse, ImageSize, } from "./image.js";
10
- export { Image } from "./image.js";
11
- export { VideoClient } from "./video-client.js";
12
- export { VideoAspectRatio, VideoEvent, VideoFrames, VideoModel, VideoModelSchema, VideoRequest, VideoResponse, } from "./video.js";
13
- export { Video } from "./video.js";
14
- export { SpeechClient } from "./speech-client.js";
15
- export { SpeechEvent, SpeechModel, SpeechModelSchema, SpeechRequest, SpeechResponse, SpeechTimestamp, SpeechVoice, } from "./speech.js";
16
- export { Speech } from "./speech.js";
17
- export { TranscriptionClient } from "./transcription-client.js";
18
- export { TranscriptionEvent, TranscriptionModel, TranscriptionModelSchema, TranscriptionRequest, TranscriptionResponse, TranscriptionSegment, TranscriptionTimestamps, TranscriptionWord, } from "./transcription.js";
19
- export { Transcription } from "./transcription.js";
20
- export { Media } from "./media.js";
21
- export { Generation } from "./generation.js";
22
- export { Tool, ToolFailure, toDefinitions } from "./tool.js";
23
- export { ToolRuntime } from "./tool-runtime.js";
24
- export * as LLM from "./llm.js";
1
+ import { Effect, Layer, ManagedRuntime, Schema, Stream } from "effect";
2
+ import { AIClient } from "./ai-client.js";
3
+ import { Decision } from "./decision.js";
4
+ import { Image } from "./image.js";
5
+ import { LLM } from "./effect.js";
6
+ import { Media } from "./media.js";
7
+ import { RequestExecutor } from "./route/executor.js";
8
+ import { AIError, InvalidRequestError, LanguageModel } from "./schema/index.js";
9
+ import { Speech } from "./speech.js";
10
+ import { Transcription, } from "./transcription.js";
11
+ import { Tool, ToolFailure } from "./tool.js";
12
+ import { fileMediaType } from "./utils/media-type.js";
13
+ import { Video } from "./video.js";
14
+ // Fails with `signal.reason` so aborted calls reject and aborted streams throw like `fetch`: an `AbortError` by default.
15
+ const abortEffect = (signal) => signal === undefined
16
+ ? Effect.never
17
+ : Effect.callback((resume) => {
18
+ if (signal.aborted) {
19
+ resume(Effect.fail(signal.reason));
20
+ return;
21
+ }
22
+ const onAbort = () => resume(Effect.fail(signal.reason));
23
+ signal.addEventListener("abort", onAbort, { once: true });
24
+ return Effect.sync(() => signal.removeEventListener("abort", onAbort));
25
+ });
26
+ export const make = (options = {}) => {
27
+ const runtime = ManagedRuntime.make(AIClient.layerWith(options.layer ?? RequestExecutor.fetchLayer));
28
+ /** Run any package Effect (for example `LLMClient.compact(...)`) inside this runtime. */
29
+ const run = (effect, options) => runtime.runPromise(Effect.raceFirst(effect, abortEffect(options?.signal)));
30
+ const iterate = (stream, options) => Stream.toAsyncIterable(Stream.unwrap(runtime.contextEffect.pipe(Effect.map((context) => stream.pipe(Stream.interruptWhen(abortEffect(options?.signal)), Stream.provideContext(context))))));
31
+ function generateObject(input, options) {
32
+ return run("schema" in input ? LLM.generateObject(input) : LLM.generateObject(input), options);
33
+ }
34
+ const handle = (generation) => ({
35
+ ...generation.snapshot,
36
+ token: generation.token,
37
+ await: (options) => run(generation.await({ poll: options?.poll }), options),
38
+ events: (options) => iterate(generation.events({ poll: options?.poll }), options),
39
+ result: (options) => run(generation.result(), options),
40
+ refresh: (options) => run(generation.refresh(), options).then(handle),
41
+ cancel: (options) => run(generation.cancel(), options),
42
+ });
43
+ return {
44
+ run,
45
+ /** Decoded asset bytes, downloading `url` sources through the executor. */
46
+ bytes: (asset, options) => run(asset.bytes(), options),
47
+ base64: (asset, options) => run(asset.base64(), options),
48
+ /** Pull a `url` asset into owned bytes before the provider URL expires. */
49
+ materialize: (asset, options) => run(asset.materialize(), options),
50
+ /** Read a file into an asset like `Media.file`: sniffed media type, then the extension's. */
51
+ file: async (path, options) => {
52
+ const { readFile } = await import("node:fs/promises");
53
+ return run(Effect.tryPromise({
54
+ try: (signal) => readFile(path, { signal }),
55
+ catch: (cause) => fileError(`Failed to read media file ${path}`, cause),
56
+ }).pipe(Effect.map((buffer) => {
57
+ const data = new Uint8Array(buffer);
58
+ return Media.bytes(data, fileMediaType(data, path), options);
59
+ })), options);
60
+ },
61
+ /** Write an asset's bytes like `Media.write`, downloading `url` sources through the executor. */
62
+ write: async (asset, path, options) => {
63
+ const { writeFile } = await import("node:fs/promises");
64
+ return run(asset.bytes().pipe(Effect.flatMap((data) => Effect.tryPromise({
65
+ try: (signal) => writeFile(path, data, { signal }),
66
+ catch: (cause) => fileError(`Failed to write media file ${path}`, cause),
67
+ }))), options);
68
+ },
69
+ llm: {
70
+ request: LLM.request,
71
+ generate: (input, options) => run(LLM.generate(input), options),
72
+ stream: (input, options) => iterate(LLM.stream(input), options),
73
+ /** Stream model calls, running their tool calls, until the model stops calling tools or `until` is true. */
74
+ loop: (input, options) => iterate(LLM.loop(input), options),
75
+ /** Decode the model's output against `schema` (or `jsonSchema`, unvalidated) like `LLM.generateObject`. */
76
+ generateObject,
77
+ },
78
+ image: {
79
+ request: Image.request,
80
+ generate: (input, options) => run(Image.generate(input, { poll: options?.poll }), options),
81
+ stream: (input, options) => iterate(Image.stream(input, { poll: options?.poll }), options),
82
+ start: (input, options) => run(Image.start(input), options).then(handle),
83
+ resume: (model, token, options) => run(Image.resume(model, token), options).then(handle),
84
+ },
85
+ video: {
86
+ request: Video.request,
87
+ start: (input, options) => run(Video.start(input), options).then(handle),
88
+ generate: (input, options) => run(Video.generate(input, { poll: options?.poll }), options),
89
+ resume: (model, token, options) => run(Video.resume(model, token), options).then(handle),
90
+ stream: (input, options) => iterate(Video.stream(input, { poll: options?.poll }), options),
91
+ },
92
+ speech: {
93
+ request: Speech.request,
94
+ generate: (input, options) => run(Speech.generate(input), options),
95
+ stream: (input, options) => iterate(Speech.stream(input), options),
96
+ },
97
+ transcription: {
98
+ request: Transcription.request,
99
+ generate: (input, options) => run(Transcription.generate(input, { poll: options?.poll }), options),
100
+ stream: (input, options) => iterate(Transcription.stream(input, { poll: options?.poll }), options),
101
+ start: (input, options) => run(Transcription.start(input), options).then(handle),
102
+ resume: (model, token, options) => run(Transcription.resume(model, token), options).then(handle),
103
+ },
104
+ decision: {
105
+ request: Decision.request,
106
+ generate: (input, options) => run(Decision.generate(input), options),
107
+ },
108
+ dispose: () => runtime.dispose(),
109
+ };
110
+ };
111
+ const fileError = (message, cause) => new AIError({ reason: new InvalidRequestError({ message, cause }) });
112
+ /**
113
+ * Promise counterpart of `Tool.make` for `ai.llm.loop`. A throw or rejection becomes the error result the model sees, the
114
+ * returned value is sent unvalidated (`undefined` as `null`), and `signal` aborts when the loop is interrupted.
115
+ */
116
+ export const tool = (config) => Tool.make({
117
+ description: config.description,
118
+ parameters: config.parameters,
119
+ success: Schema.Unknown,
120
+ execute: (params, context) => Effect.tryPromise({
121
+ try: async (signal) => (await config.execute(params, { ...context, signal })) ?? null,
122
+ catch: (error) => new ToolFailure({ message: error instanceof Error ? error.message : String(error), error }),
123
+ }),
124
+ });
125
+ /** Default client over `RequestExecutor.fetchLayer` for scripts; the runtime builds its layer on first use. */
126
+ export const ai = make();
127
+ export * as AI from "./index.js";
package/dist/llm.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Effect, JsonSchema, Schema, Stream } from "effect";
2
2
  import { Service, type StreamOptions } from "./route/client.js";
3
3
  import { GenerationOptions, HttpOptions, AIError, LLMEvent, LLMRequest, LLMResponse, Message, LanguageModel, SystemPart, ToolChoice, type ContentPart, type LanguageModelProviderOptions, type ToolEntryInput } from "./schema/index.js";
4
- import { type ToolSchema } from "./tool.js";
4
+ import { type ExecutableTools, type ToolSchema } from "./tool.js";
5
5
  /** Input accepted by `LLM.request`, normalized into the canonical `LLMRequest` class. */
6
6
  export type RequestInput<SelectedLanguageModel extends LanguageModel = LanguageModel> = Omit<ConstructorParameters<typeof LLMRequest>[0], "model" | "system" | "messages" | "tools" | "toolChoice" | "generation" | "http" | "providerOptions"> & {
7
7
  readonly model: SelectedLanguageModel;
@@ -16,6 +16,18 @@ export type RequestInput<SelectedLanguageModel extends LanguageModel = LanguageM
16
16
  };
17
17
  export declare function generate<const Model extends LanguageModel>(input: RequestInput<Model> | LLMRequest, options?: StreamOptions): Effect.Effect<LLMResponse, AIError, Service>;
18
18
  export declare function stream<const Model extends LanguageModel>(input: RequestInput<Model> | LLMRequest, options?: StreamOptions): Stream.Stream<LLMEvent, AIError, Service>;
19
+ export type LoopInput<SelectedLanguageModel extends LanguageModel = LanguageModel> = Omit<RequestInput<SelectedLanguageModel>, "tools"> & {
20
+ readonly tools: ExecutableTools;
21
+ /** Called after each step that has tool calls; returning `true` ends the loop without running them. */
22
+ readonly until?: (state: {
23
+ readonly steps: ReadonlyArray<LLMResponse>;
24
+ }) => boolean;
25
+ };
26
+ /**
27
+ * Stream model calls, running the model's tool calls between them, until a step has no client-executed tool calls,
28
+ * reports a provider error, or `until` returns `true`. Each step's `step-start` and `step-finish` carry its step index.
29
+ */
30
+ export declare function loop<const Model extends LanguageModel>(input: LoopInput<Model>, options?: StreamOptions): Stream.Stream<LLMEvent, AIError, Service>;
19
31
  export declare const request: <const SelectedLanguageModel extends LanguageModel>(input: RequestInput<SelectedLanguageModel>) => LLMRequest<SelectedLanguageModel>;
20
32
  type GenerateObjectBase<SelectedLanguageModel extends LanguageModel = LanguageModel> = Omit<RequestInput<SelectedLanguageModel>, "tools" | "toolChoice">;
21
33
  export declare class GenerateObjectResponse<T> {
@@ -25,6 +37,9 @@ export declare class GenerateObjectResponse<T> {
25
37
  get events(): readonly ({
26
38
  readonly type: "step-start";
27
39
  readonly index: number;
40
+ } | {
41
+ readonly type: "raw";
42
+ readonly data: unknown;
28
43
  } | {
29
44
  readonly type: "text-start";
30
45
  readonly id: string;
package/dist/llm.js CHANGED
@@ -3,12 +3,46 @@ import { tryRequest } from "./media-model.js";
3
3
  import { LLMClient, Service } from "./route/client.js";
4
4
  import { GenerationOptions, HttpOptions, InvalidProviderOutputError, AIError, LLMEvent, LLMRequest, LLMResponse, Message, LanguageModel, SystemPart, ToolChoice, ToolEntry, } from "./schema/index.js";
5
5
  import { make as makeTool, toDefinitions } from "./tool.js";
6
+ import { ToolRuntime } from "./tool-runtime.js";
6
7
  export function generate(input, options) {
7
8
  return requestEffect(input).pipe(Effect.flatMap((request) => LLMClient.generate(request, options)));
8
9
  }
9
10
  export function stream(input, options) {
10
11
  return Stream.unwrap(requestEffect(input).pipe(Effect.map((request) => LLMClient.stream(request, options))));
11
12
  }
13
+ export function loop(input, options) {
14
+ const { tools, until, ...rest } = input;
15
+ const step = (request, steps) => Stream.suspend(() => {
16
+ const events = [];
17
+ return LLMClient.stream(request, options).pipe(Stream.map((event) => event.type === "step-start" || event.type === "step-finish" ? { ...event, index: steps.length } : event), Stream.tap((event) => Effect.sync(() => events.push(event))), Stream.concat(Stream.unwrap(Effect.gen(function* () {
18
+ const response = LLMResponse.fromEvents(events);
19
+ const calls = response?.toolCalls.filter((call) => call.providerExecuted !== true) ?? [];
20
+ if (!response || calls.length === 0 || events.some(LLMEvent.is.providerError))
21
+ return Stream.empty;
22
+ const done = [...steps, response];
23
+ if (until?.({ steps: done }))
24
+ return Stream.empty;
25
+ const results = yield* Effect.forEach(calls, (call) => ToolRuntime.dispatch(tools, call), {
26
+ concurrency: "unbounded",
27
+ });
28
+ const next = LLMRequest.update(request, {
29
+ messages: [
30
+ ...request.messages,
31
+ response.message,
32
+ ...calls.map((call, i) => Message.tool({
33
+ id: call.id,
34
+ name: call.name,
35
+ namespace: call.namespace,
36
+ result: results[i].result,
37
+ providerMetadata: call.providerMetadata,
38
+ })),
39
+ ],
40
+ });
41
+ return Stream.fromIterable(results.flatMap((result) => result.events)).pipe(Stream.concat(step(next, done)));
42
+ }))));
43
+ });
44
+ return Stream.unwrap(requestEffect({ ...rest, tools: toDefinitions(tools) }).pipe(Effect.map((request) => step(request, []))));
45
+ }
12
46
  const requestEffect = (input) => input instanceof LLMRequest ? Effect.succeed(input) : tryRequest(() => request(input));
13
47
  export const request = (input) => {
14
48
  const { system: requestSystem, prompt, messages, tools, toolChoice: requestToolChoice, generation: requestGeneration, providerOptions: requestProviderOptions, http: requestHttp, ...rest } = input;
@@ -1,5 +1,6 @@
1
1
  import { type Context, Effect, Layer, Stream } from "effect";
2
2
  import { type AwaitOptions, type Generation, type Observation } from "./generation.js";
3
+ import { RequestExecutor } from "./route/executor.js";
3
4
  import type { MediaRoute } from "./route/media.js";
4
5
  import { AIError } from "./schema/index.js";
5
6
  /** A media request whose model carries the route that executes it. */
@@ -21,7 +22,7 @@ export declare const make: <Self, Req extends RoutedRequest<Req, Event, Response
21
22
  /** A completed response expanded into the streaming event shape. */
22
23
  readonly responseEvents: (response: Response) => ReadonlyArray<Event>;
23
24
  }) => {
24
- layer: Layer.Layer<Self, never, import("./route/executor-service.js").RequestExecutorService>;
25
+ layer: Layer.Layer<Self, never, RequestExecutor.RequestExecutorService>;
25
26
  generate: (request: Req, options?: AwaitOptions) => Effect.Effect<Response, AIError, Self>;
26
27
  stream: (request: Req, options?: AwaitOptions) => Stream.Stream<Event | Observation, AIError, Exclude<Self, import("effect/Scope").Scope>>;
27
28
  start: (request: Req) => Effect.Effect<Generation<Response>, AIError, Self>;
@@ -14,6 +14,8 @@ export declare class MediaModel<Route, Options> {
14
14
  readonly provider: ProviderID;
15
15
  readonly route: Route;
16
16
  readonly http?: HttpOptions;
17
+ /** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
18
+ readonly providerOptions?: ProviderOptions;
17
19
  constructor(input: MediaModel.Input<Route>);
18
20
  }
19
21
  export declare namespace MediaModel {
@@ -23,6 +25,7 @@ export declare namespace MediaModel {
23
25
  readonly provider: string | ProviderID;
24
26
  readonly route: Route;
25
27
  readonly http?: HttpOptions;
28
+ readonly providerOptions?: ProviderOptions;
26
29
  }
27
30
  /** A protocol plus its canonical start path; `ModelInput.baseURL` overrides `baseURL` per deployment. */
28
31
  interface RouteInput<Request extends MediaRoute.MediaRequest, Protocol> {
@@ -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, HttpOptions, 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
@@ -12,11 +12,14 @@ export class MediaModel {
12
12
  provider;
13
13
  route;
14
14
  http;
15
+ /** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
16
+ providerOptions;
15
17
  constructor(input) {
16
18
  this.id = ModelID.make(input.id);
17
19
  this.provider = ProviderID.make(input.provider);
18
20
  this.route = input.route;
19
21
  this.http = input.http;
22
+ this.providerOptions = input.providerOptions;
20
23
  }
21
24
  }
22
25
  /** Compose a protocol route input with one deployment through `MediaRoute.inline`, `queued`, or `stream`. */
package/dist/media.d.ts CHANGED
@@ -42,13 +42,6 @@ export declare const Info: Schema.Struct<{
42
42
  readonly format: Schema.optional<Schema.String>;
43
43
  }>;
44
44
  export type Info = Schema.Schema.Type<typeof Info>;
45
- /** A provider-side partial result such as stripped audio or a moderated sample; never a silent drop. */
46
- export declare const Notice: Schema.Struct<{
47
- readonly type: Schema.Literals<readonly ["moderated", "filtered", "other"]>;
48
- readonly message: Schema.String;
49
- readonly providerMetadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
50
- }>;
51
- export type Notice = Schema.Schema.Type<typeof Notice>;
52
45
  /** Synchronous view of an inline payload; `undefined` for `url` and `ref` sources, which carry no local bytes. */
53
46
  export interface Inline {
54
47
  readonly mime: string;
package/dist/media.js CHANGED
@@ -63,12 +63,6 @@ export const Info = Schema.Struct({
63
63
  encoding: Schema.optional(Schema.String),
64
64
  format: Schema.optional(Schema.String),
65
65
  }).annotate({ identifier: "Media.Info" });
66
- /** A provider-side partial result such as stripped audio or a moderated sample; never a silent drop. */
67
- export const Notice = Schema.Struct({
68
- type: Schema.Literals(["moderated", "filtered", "other"]),
69
- message: Schema.String,
70
- providerMetadata: Schema.optional(ProviderMetadata),
71
- }).annotate({ identifier: "Media.Notice" });
72
66
  // ---------------------------------------------------------------------------
73
67
  // Asset
74
68
  // ---------------------------------------------------------------------------
@@ -42,6 +42,11 @@ export declare const protocol: Protocol<{
42
42
  readonly image_url: {
43
43
  readonly url: string;
44
44
  };
45
+ } | {
46
+ readonly type: "video_url";
47
+ readonly video_url: {
48
+ readonly url: string;
49
+ };
45
50
  } | {
46
51
  readonly type: "file";
47
52
  readonly file: {
@@ -63,6 +68,11 @@ export declare const protocol: Protocol<{
63
68
  readonly image_url: {
64
69
  readonly url: string;
65
70
  };
71
+ } | {
72
+ readonly type: "video_url";
73
+ readonly video_url: {
74
+ readonly url: string;
75
+ };
66
76
  } | {
67
77
  readonly type: "file";
68
78
  readonly file: {
@@ -144,7 +154,17 @@ export declare const protocol: Protocol<{
144
154
  } | undefined;
145
155
  readonly store?: boolean | undefined;
146
156
  readonly prompt_cache_key?: string | undefined;
157
+ readonly prompt_cache_retention?: string | undefined;
158
+ readonly prompt_cache_options?: {
159
+ readonly ttl?: string | undefined;
160
+ } | undefined;
147
161
  readonly reasoning_effort?: OpenResponsesOptions.ReasoningEffort | undefined;
162
+ readonly verbosity?: import("../schema/options.js").OpenString<"high" | "low" | "medium"> | undefined;
163
+ readonly service_tier?: import("../schema/options.js").OpenString<"auto" | "default" | "flex" | "priority"> | undefined;
164
+ readonly metadata?: {
165
+ readonly [x: string]: string;
166
+ } | undefined;
167
+ readonly safety_identifier?: string | undefined;
148
168
  readonly tool_stream?: boolean | undefined;
149
169
  readonly max_completion_tokens?: number | undefined;
150
170
  readonly max_tokens?: number | undefined;
@@ -0,0 +1,22 @@
1
+ import { ImageModel, ImageResponse, type ImageRequestFor } from "../image.js";
2
+ import { MediaProtocol } from "../route/media-protocol.js";
3
+ import { MediaRoute } from "../route/media.js";
4
+ export declare const PATH = "/services/aigc/multimodal-generation/generation";
5
+ /** Provider-native `parameters`. Common fields (`n`, `aspect`, `resolution`, `images`) live on the request. */
6
+ export type AlibabaImageOptions = {
7
+ /** Exact `WIDTH*HEIGHT`; it wins over `aspect` and `resolution`. */
8
+ readonly size?: string;
9
+ readonly seed?: number;
10
+ readonly negativePrompt?: string;
11
+ readonly promptExtend?: boolean;
12
+ readonly watermark?: boolean;
13
+ readonly thinkingMode?: boolean;
14
+ readonly enableSequential?: boolean;
15
+ } & Record<string, unknown>;
16
+ export type Request = ImageRequestFor<AlibabaImageOptions>;
17
+ export declare const protocol: MediaProtocol.Inline<Request, ImageResponse>;
18
+ export declare const model: (input: MediaRoute.ModelInput) => ImageModel<AlibabaImageOptions>;
19
+ export declare const AlibabaImages: {
20
+ readonly protocol: MediaProtocol.Inline<Request, ImageResponse>;
21
+ readonly model: typeof model;
22
+ };
@@ -0,0 +1,77 @@
1
+ import { Duration, Effect, Schema } from "effect";
2
+ import { ImageModel, ImageResponse } from "../image.js";
3
+ import { MediaProtocol } from "../route/media-protocol.js";
4
+ import { MediaRoute } from "../route/media.js";
5
+ import { mergeJsonRecords } from "../schema/index.js";
6
+ import { JsonObject, ProviderShared, lenient } from "./shared.js";
7
+ import { ImageSizing } from "./utils/image-sizing.js";
8
+ const route = MediaProtocol.identity({ id: "alibaba-images", name: "Alibaba Images", provider: "alibaba" });
9
+ export const PATH = "/services/aigc/multimodal-generation/generation";
10
+ const OUTPUT_RETENTION = Duration.hours(24);
11
+ // ---------------------------------------------------------------------------
12
+ // 2. Response schema
13
+ // ---------------------------------------------------------------------------
14
+ const AlibabaImageResponse = Schema.Struct({
15
+ output: Schema.Struct({
16
+ choices: Schema.Array(Schema.Struct({
17
+ message: Schema.Struct({
18
+ content: Schema.Array(Schema.Struct({ image: Schema.optional(Schema.String) })),
19
+ }),
20
+ })),
21
+ }),
22
+ usage: lenient(JsonObject),
23
+ request_id: Schema.optional(Schema.String),
24
+ });
25
+ // ---------------------------------------------------------------------------
26
+ // 5. Request body construction
27
+ // ---------------------------------------------------------------------------
28
+ const nativeOptions = (options) => {
29
+ if (!options)
30
+ return undefined;
31
+ const { negativePrompt, promptExtend, thinkingMode, enableSequential, ...native } = options;
32
+ return {
33
+ negative_prompt: negativePrompt,
34
+ prompt_extend: promptExtend,
35
+ thinking_mode: thinkingMode,
36
+ enable_sequential: enableSequential,
37
+ ...native,
38
+ };
39
+ };
40
+ const fromRequest = Effect.fn("AlibabaImages.fromRequest")(function* (request) {
41
+ const images = yield* Effect.forEach(request.images ?? [], (image) => ProviderShared.mediaReference(image, undefined, `${route.name} input`).pipe(Effect.map((item) => ({ image: item.value }))));
42
+ const size = yield* ImageSizing.exact(route, request, { multiple: 16, minPixels: 512 * 512, maxPixels: 2048 * 2048 });
43
+ return MediaProtocol.json(mergeJsonRecords({
44
+ model: request.model.id,
45
+ input: { messages: [{ role: "user", content: [...images, { text: request.prompt }] }] },
46
+ parameters: mergeJsonRecords({ size: size === undefined ? undefined : `${size.width}*${size.height}`, n: request.n }, nativeOptions(request.providerOptions)),
47
+ }, request.http?.body) ?? {});
48
+ });
49
+ // ---------------------------------------------------------------------------
50
+ // 6. Response decoding
51
+ // ---------------------------------------------------------------------------
52
+ const decodeDocument = route.decodeJson(AlibabaImageResponse);
53
+ const decodeResponse = Effect.fn("AlibabaImages.decodeResponse")(function* (response) {
54
+ const output = yield* decodeDocument(response);
55
+ const decoded = output.value;
56
+ // Qwen-Image returns every image in one choice; Wan returns one choice per image.
57
+ const urls = decoded.output.choices.flatMap((choice) => choice.message.content.flatMap((item) => (item.image === undefined ? [] : [item.image])));
58
+ if (urls.length === 0)
59
+ return yield* output.invalid(`${route.name} returned no images`);
60
+ // Model Studio bills per image; its token counts are informational, so the raw record stays in provider metadata.
61
+ return new ImageResponse({
62
+ images: yield* Effect.forEach(urls, (url) => MediaProtocol.expiringUrl(url, OUTPUT_RETENTION)),
63
+ providerMetadata: { alibaba: { requestID: decoded.request_id, usage: decoded.usage } },
64
+ });
65
+ });
66
+ // ---------------------------------------------------------------------------
67
+ // 7. Protocol and route
68
+ // ---------------------------------------------------------------------------
69
+ export const protocol = MediaProtocol.inline(route, {
70
+ body: { from: fromRequest },
71
+ response: { decode: decodeResponse },
72
+ });
73
+ export const model = (input) => ImageModel.fromRoute({ protocol, path: PATH }, input);
74
+ export const AlibabaImages = {
75
+ protocol,
76
+ model,
77
+ };