@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
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @opencode/ai
2
2
 
3
- Schema-first APIs for text, images, and decisions, built with Effect. Video, speech, transcription, extraction, and
3
+ Schema-first APIs for text, images, decisions, and embeddings, built with Effect. Video, speech, transcription, extraction, and
4
4
  realtime voice are [experimental](#experimental).
5
5
 
6
6
  `@opencode/ai` is the Promise API: one managed runtime behind the LLM and media methods, plus asset helpers. `ai.file`
@@ -16,7 +16,7 @@ const input = { model: openai.responses("gpt-4o-mini"), prompt: "Say hello." }
16
16
  const response = await ai.generate(input)
17
17
  console.log(response.text)
18
18
  const generated = await ai.image.generate({ model: openai.image("gpt-image-2"), prompt: "A lighthouse" })
19
- await ai.write(generated.image, "./lighthouse.png") // also ai.file(path), ai.bytes(asset), ai.base64(asset), ai.materialize(asset)
19
+ await ai.write(generated.images[0], "./lighthouse.png") // also ai.file(path), ai.bytes(asset), ai.base64(asset), ai.materialize(asset)
20
20
  for await (const event of ai.stream(ai.request(input))) {
21
21
  // LLMEvent
22
22
  }
@@ -37,7 +37,7 @@ const program = Effect.gen(function* () {
37
37
  model: openai.responses("gpt-4o-mini"), // `.chat(...)` selects the Chat Completions API instead
38
38
  system: "You are concise.",
39
39
  prompt: "Say hello in one short sentence.",
40
- generation: { maxTokens: 40 },
40
+ maxTokens: 40,
41
41
  })
42
42
  console.log(response.text)
43
43
  })
@@ -47,17 +47,26 @@ await Effect.runPromise(program.pipe(Effect.provide(AIClient.layer)))
47
47
  ```
48
48
 
49
49
  Run `ai.stream(...)` instead of `generate` when you want incremental `LLMEvent`s. Both accept input or a prebuilt
50
- `ai.request(...)`. The event stream is provider-neutral — same shape across OpenAI Chat, OpenAI Responses,
50
+ `ai.request(...)`. Input takes either `prompt`, a single user message, or `messages`, the whole conversation, never
51
+ both; `system` goes with either. The event stream is provider-neutral — same shape across OpenAI Chat, OpenAI Responses,
51
52
  Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployment.
52
53
 
53
54
  ### Tool loop
54
55
 
55
56
  `stream` runs one model call; `loop` runs the model's tool calls and calls the model again until it stops calling
56
- tools. Events from every step arrive on one stream, with a `tool-result` after each tool runs. `until` is checked
57
+ tools. Events from every step arrive on one stream, with a `tool-result` after each tool runs (an error result when
58
+ it fails). Each step ends with its own `step-finish`; one `finish` ends the loop, carrying the final step's reason
59
+ and the usage summed across steps. `until` is checked
57
60
  after each step that has tool calls, with every step's `LLMResponse`; returning `true` ends the loop without running
58
- them. `tool` takes a plain `async` execute; a throw or rejection goes back to the model as an error result, and
59
- `signal` aborts when the loop is interrupted.
60
- `tool` from `@opencode/ai/effect` takes the same options (including an optional `success` schema) with an Effect execute:
61
+ them. Tools are an array, sent in the order given so the provider can reuse its cached prompt prefix. Each tool has a
62
+ `name`, and two tools with the same name fail the request. Tool arguments that are not valid JSON go back to the model
63
+ as an error result so it can retry. A step that hits the output token limit ends the loop without running its tool
64
+ calls, which may be cut off. A forced `toolChoice` applies to the first step only; later steps use `auto`. `tool` takes
65
+ a plain `async` execute; a throw or rejection goes back to the model as an error result, and `signal` aborts when the
66
+ loop is interrupted.
67
+ `input` is an Effect Schema that decodes and types the arguments, or a raw JSON Schema object, such as an MCP tool's,
68
+ whose arguments arrive as `unknown` (pair it with an optional JSON Schema `outputSchema`). `tool` from
69
+ `@opencode/ai/effect` takes the same options (including an optional `success` schema) with an Effect execute:
61
70
 
62
71
  ```ts
63
72
  import { readFile } from "node:fs/promises"
@@ -65,15 +74,16 @@ import { Schema } from "effect"
65
74
  import { ai, tool } from "@opencode/ai"
66
75
 
67
76
  const read_file = tool({
77
+ name: "read_file",
68
78
  description: "Read a UTF-8 file.",
69
- parameters: Schema.Struct({ path: Schema.String }),
79
+ input: Schema.Struct({ path: Schema.String }),
70
80
  execute: ({ path }, { signal }) => readFile(path, { encoding: "utf8", signal }),
71
81
  })
72
82
 
73
83
  const events = ai.loop({
74
84
  model,
75
85
  prompt: "Summarize package.json.",
76
- tools: { read_file },
86
+ tools: [read_file],
77
87
  until: ({ steps }) => steps.length >= 8,
78
88
  })
79
89
  for await (const event of events) {
@@ -81,6 +91,17 @@ for await (const event of events) {
81
91
  }
82
92
  ```
83
93
 
94
+ The terminal `finish` carries the final assistant `message` and `usage`. To skip the events, `ai.collect` folds a
95
+ stream from `stream` or `loop` into one result: `text` of the final step, `steps` (one `LLMResponse` per call),
96
+ `messages` (each step's assistant message and its tool results, ready to append to the next request), the total
97
+ `usage`, `finishReason`, and `object` with `schema`.
98
+
99
+ ```ts
100
+ const result = await ai.collect(ai.loop({ model, prompt: "Summarize package.json.", tools: { read_file } }))
101
+ // Effect: const result = yield* ai.collect(ai.loop({ ... }))
102
+ console.log(result.text, result.usage?.totalTokens)
103
+ ```
104
+
84
105
  ### Freeform tools
85
106
 
86
107
  A tool with exactly one required string parameter can set `freeform`, so the model writes that parameter as raw text
@@ -88,8 +109,9 @@ instead of JSON arguments: unconstrained `text`, or text matching a `regex` or `
88
109
 
89
110
  ```ts
90
111
  const run_code = tool({
112
+ name: "run_code",
91
113
  description: "Run JavaScript",
92
- parameters: Schema.Struct({ code: Schema.String }),
114
+ input: Schema.Struct({ code: Schema.String }),
93
115
  freeform: { type: "lark", grammar: JS_GRAMMAR },
94
116
  execute: ({ code }) => runCode(code),
95
117
  })
@@ -104,35 +126,57 @@ history works with or without `freeform`.
104
126
 
105
127
  ### Structured output
106
128
 
107
- `generateObject` forces a tool call and decodes its input against `schema`; pass `jsonSchema` instead for an
108
- unvalidated `unknown` object:
129
+ Pass `schema` to `generate`, `stream` or `loop`. The model must answer through a hidden tool call, decoded into
130
+ `object` (typed from an Effect Schema, or an unvalidated `unknown` for a raw JSON Schema object):
109
131
 
110
132
  ```ts
111
- const { object } = await ai.generateObject({
112
- model,
113
- prompt: "Pick a city.",
114
- schema: Schema.Struct({ city: Schema.String }),
115
- })
133
+ const res = await ai.generate({ model, prompt: "Pick a city.", schema: Schema.Struct({ city: Schema.String }) })
134
+ res.object.city
135
+ ```
136
+
137
+ `stream` puts `object` on its `finish` event; `loop` runs tools first and puts it on the loop's `finish`. A
138
+ decode failure is an `AIError` whose `partial` holds the response.
139
+
140
+ ### Errors
141
+
142
+ Every failure is an `AIError`. `reason._tag` names the kind (`RateLimit`, `InvalidRequest`, `Transport`, ...), and
143
+ getters read the common fields without digging into `reason` or the raw body:
144
+
145
+ ```ts
146
+ try {
147
+ await ai.generate({ model, prompt: "Hi" })
148
+ } catch (error) {
149
+ if (!(error instanceof AIError)) throw error
150
+ error.status // HTTP status, when the failure came from a response
151
+ error.code // provider error code such as "model_not_found", when known
152
+ error.isRetryable // whether sending the same request again may succeed
153
+ error.retryAfterMs // delay the provider asked for, when known
154
+ }
116
155
  ```
117
156
 
118
157
  ### Raw provider events
119
158
 
120
159
  Set `includeRaw: true` on a request to also receive every provider frame as `{ type: "raw", data }`, in order and
121
160
  before the events parsed from that frame. `data` is the parsed JSON frame, so frames this package doesn't handle yet
122
- are visible too. Raw events are off by default, and `generate` ignores them. Translate a frame with a stream map:
161
+ are visible too. Raw events are off by default, and `generate` ignores them. `RawEvent` is the event's type. Act on a
162
+ frame with a stream map:
123
163
 
124
164
  ```ts
125
- import { Stream } from "effect"
126
- import { ai, LLMEvent } from "@opencode/ai/effect"
165
+ import { Effect, Stream } from "effect"
166
+ import { ai, AIError, ContentPolicyError } from "@opencode/ai/effect"
127
167
 
128
168
  const flagged = (data: unknown) =>
129
169
  typeof data === "object" && data !== null && "type" in data && data.type === "moderation.flagged"
130
170
 
131
- const events = ai.stream({ model, prompt: "Say hello.", includeRaw: true }).pipe(
132
- Stream.map((event) =>
133
- event.type === "raw" && flagged(event.data) ? LLMEvent.providerError({ message: "Flagged by moderation" }) : event,
134
- ),
135
- )
171
+ const events = ai
172
+ .stream({ model, prompt: "Say hello.", includeRaw: true })
173
+ .pipe(
174
+ Stream.mapEffect((event) =>
175
+ event.type === "raw" && flagged(event.data)
176
+ ? Effect.fail(new AIError({ reason: new ContentPolicyError({ message: "Flagged by moderation" }) }))
177
+ : Effect.succeed(event),
178
+ ),
179
+ )
136
180
  ```
137
181
 
138
182
  ### Google Interactions
@@ -147,11 +191,13 @@ live under `providerMetadata.vertex`. The default is still full-history replay w
147
191
 
148
192
  ```ts
149
193
  const model = Google.configure({ apiKey }).interactions("gemini-3.8-flash")
150
- const response = yield* ai.generate({
151
- model,
152
- prompt: "Say hello.",
153
- providerOptions: { thinkingLevel: "low", thinkingSummaries: "auto", store: true },
154
- })
194
+ const response =
195
+ yield *
196
+ ai.generate({
197
+ model,
198
+ prompt: "Say hello.",
199
+ providerOptions: { thinkingLevel: "low", thinkingSummaries: "auto", store: true },
200
+ })
155
201
  ```
156
202
 
157
203
  Interactions supports text output, streamed function calls, native tool results, thought signatures, and multimodal
@@ -180,7 +226,7 @@ const image = Effect.gen(function* () {
180
226
  resolution: "1K",
181
227
  providerOptions: { quality: "high" }, // typed per image model
182
228
  })
183
- yield* Media.write(response.image, "./garden.png")
229
+ yield* Media.write(response.images[0], "./garden.png")
184
230
  })
185
231
 
186
232
  // `Media.file` / `Media.write` use the Effect `FileSystem` service; provide your platform's layer.
@@ -276,6 +322,8 @@ const [refund, department] = response.answers
276
322
  ```
277
323
 
278
324
  `input` is a JSON object or an ordered list of `text`, `json` and `media` parts. Answers come back in question order.
325
+ A `predicate` can say what counts as true and as false with `criteria: { true, false }`; hosts without a criteria field
326
+ read them appended to the instructions.
279
327
  A question the host declines is `{ name, type: "error", reason, message? }`, with `reason` such as `"refusal"`; the
280
328
  other answers still come back.
281
329
  `response.usage` has `inputTokens`, `outputTokens`, `totalTokens` and the host's reported `cost` when it sends one;
@@ -309,6 +357,95 @@ CloudflareAIGateway.configure({ accountId }).decision("typesafe/jev")
309
357
  OpenAI and Vercel AI Gateway use OpenAI's `/v1/decisions` API. TypeSafe, OpenCode, OpenRouter, Baseten and
310
358
  DigitalOcean use System One (`/systemone`), and Cloudflare sends the System One body through `/ai/run`.
311
359
 
360
+ ## Embeddings
361
+
362
+ Embedding models turn each value into a vector, returned in value order.
363
+
364
+ ```ts
365
+ import { ai } from "@opencode/ai"
366
+ import { OpenAI } from "@opencode/ai/providers"
367
+
368
+ const response = await ai.embedding.generate({
369
+ model: OpenAI.configure().embedding("text-embedding-3-small"),
370
+ values: ["I was charged twice.", "How do I reset my password?"],
371
+ dimensions: 256,
372
+ inputType: "document",
373
+ })
374
+ const [charge, password] = response.embeddings
375
+ ```
376
+
377
+ A string value is text; media values are an `Asset` (or bytes or a URL) for hosts that embed images or documents.
378
+ `dimensions` asks models that can shorten their vectors for that length. `inputType` says whether the values are
379
+ search queries or stored documents; hosts with no such field (OpenAI's `/embeddings` API) ignore it, and host-specific
380
+ task types go in `providerOptions` (NVIDIA's `input_type: "passage"`). `response.usage.inputTokens` is the host's
381
+ token count, and its raw usage stays in `providerMetadata`. Media values fail the call on hosts that only embed text.
382
+
383
+ ```ts
384
+ import {
385
+ Alibaba,
386
+ Azure,
387
+ Cohere,
388
+ DeepInfra,
389
+ DigitalOcean,
390
+ Fireworks,
391
+ OpenAICompatible,
392
+ OpenRouter,
393
+ VercelAIGateway,
394
+ } from "@opencode/ai/providers"
395
+
396
+ OpenRouter.configure().embedding("openai/text-embedding-3-small")
397
+ VercelAIGateway.configure().embedding("openai/text-embedding-3-small")
398
+ Cohere.configure().embedding("embed-v4.0")
399
+ DeepInfra.configure().embedding("BAAI/bge-m3")
400
+ Fireworks.configure().embedding("nomic-ai/nomic-embed-text-v1.5")
401
+ DigitalOcean.configure().embedding("bge-m3")
402
+ Alibaba.configure({ region: "ap-southeast-1" }).embedding("text-embedding-v4")
403
+ Azure.configure({ resourceName }).embedding("text-embedding-3-small")
404
+ OpenAICompatible.configure({ provider: "nvidia", baseURL: "https://integrate.api.nvidia.com/v1" }).embedding(
405
+ "nvidia/nemotron-3.5-embed-1b",
406
+ )
407
+ ```
408
+
409
+ Every host here uses OpenAI's `/embeddings` API; Cohere through its compatibility API
410
+ (`https://api.cohere.ai/compatibility/v1`). Package entry points are `@opencode/ai/providers/<provider>/embeddings`.
411
+
412
+ Google embeds through `embedContent`, which also takes images, audio, video and PDFs on `gemini-embedding-2`. Each
413
+ value is its own content and gets its own vector (several parts in one content would be averaged into one). `dimensions`
414
+ is `outputDimensionality`, `inputType` becomes `taskType` `RETRIEVAL_QUERY` or `RETRIEVAL_DOCUMENT`, and `taskType` or
415
+ `title` in `providerOptions` replace or add to it. `gemini-embedding-2` ignores task types; Google recommends writing the
416
+ task into the text instead (`task: search result | query: …`, `title: none | text: …`).
417
+
418
+ ```ts
419
+ import { Google, GoogleVertex } from "@opencode/ai/providers"
420
+
421
+ const response = await ai.embedding.generate({
422
+ model: Google.configure().embedding("gemini-embedding-2"),
423
+ values: [await ai.file("./receipt.png"), "A receipt for two coffees."],
424
+ dimensions: 768,
425
+ })
426
+
427
+ GoogleVertex.configure({ project, location: "global" }).embedding("gemini-embedding-2")
428
+ ```
429
+
430
+ `GoogleVertex.configure().embedding(id)` picks the API from the model id: `gemini-embedding-2*` uses `embedContent`,
431
+ and every other model (`gemini-embedding-001`, `text-embedding-005`, `text-multilingual-embedding-002`) uses the
432
+ text-only `:predict` API, which also works with Express Mode keys. On `:predict`, `inputType` and the `taskType` and
433
+ `title` options go on each instance (`task_type`, `title`), and `dimensions`, `autoTruncate` and other options go under
434
+ `parameters`.
435
+
436
+ ```ts
437
+ GoogleVertex.configure({ apiKey }).embedding("text-embedding-005")
438
+ GoogleVertex.configure({ apiKey }).embedding("gemini-embedding-001")
439
+ ```
440
+
441
+ The Gemini API sends up to 100 values per `batchEmbedContents` request, and Vertex `:predict` up to 250 per request
442
+ (one for `gemini-embedding-001`, as Google documents). Vertex `embedContent` takes one value per request, so a call
443
+ sends one request per value, four at a time, and needs project credentials: Vertex Express Mode API keys can't call
444
+ `embedContent`. `gemini-embedding-2` runs in the `global`, `us` and `eu` Vertex locations. When a call
445
+ is split into several requests, the vectors stay in value order, `usage.inputTokens` is their sum, and each request's
446
+ metadata is listed in order under `providerMetadata.<provider>.responses`. The package entry points are
447
+ `@opencode/ai/providers/google/embeddings` and `@opencode/ai/providers/google-vertex/embeddings`.
448
+
312
449
  ## Alibaba Cloud Model Studio
313
450
 
314
451
  `Alibaba` provides standard Model Studio inference. Configure a region explicitly, then select
@@ -363,7 +500,7 @@ shared host; the entry above follows the base URL table. Dedicated hosts can be
363
500
  Replay complete `response.message` values to retain `reasoning_content` separately from answer text.
364
501
  Qwen 3.8 defaults to preserving thinking; older models have different defaults.
365
502
  Additional options include `toolStream`, `parallelToolCalls`, `repetitionPenalty`, `responseFormat`,
366
- `enableSearch`, and native `searchOptions`. `generation.topK` lowers to `top_k`.
503
+ `enableSearch`, and native `searchOptions`. `topK` lowers to `top_k`.
367
504
  `clearThinking` is a hosted GLM control, and `thinking.type` is available for hosted MiniMax models.
368
505
  - **Messages:** `effort` → `output_config.effort`. `thinking.type` accepts enabled/disabled with an
369
506
  optional `budgetTokens` (or native `budget_tokens`). `outputConfig.format` accepts a JSON schema.
@@ -532,7 +669,7 @@ const request = ai.request({
532
669
  model: minimax.model("MiniMax-M3"), // also minimax.messages("MiniMax-M3")
533
670
  prompt: "What is 173 multiplied by 219?",
534
671
  providerOptions: { thinking: { type: "adaptive" } },
535
- generation: { maxTokens: 1536 },
672
+ maxTokens: 1536,
536
673
  })
537
674
 
538
675
  const response = await Effect.runPromise(ai.generate(request).pipe(Effect.provide(AIClient.layer)))
@@ -570,7 +707,7 @@ const request = ai.request({
570
707
  model: meta.responses("muse-spark-1.3"), // meta.model(...) also selects Responses
571
708
  prompt: "What is 173 multiplied by 219? Reply with the integer.",
572
709
  providerOptions: { reasoningEffort: "low" },
573
- generation: { maxTokens: 1024 },
710
+ maxTokens: 1024,
574
711
  })
575
712
  ```
576
713
 
@@ -592,7 +729,7 @@ Responses and Chat support only `toolChoice: "auto"` (the default). Messages als
592
729
  its documented forced `"any"` choice currently returns HTTP 400. Messages defaults to adaptive thinking
593
730
  with `display: "omitted"`, preserving encrypted `redacted_thinking` in `response.message`. Use
594
731
  `providerOptions: { effort: "low" }` for depth or `thinking: { type: "enabled", budgetTokens: 1024 }`
595
- for budget compatibility (with `generation.maxTokens > 1024`).
732
+ for budget compatibility (with `maxTokens > 1024`).
596
733
 
597
734
  Add `tools: [Meta.webSearch()]` to a Spark Responses or Messages request for hosted web search.
598
735
  Responses exposes hosted results and URL citations in text-part `providerMetadata.meta.annotations`.
@@ -666,18 +803,18 @@ Common fields are portable in shape, not in support. Some routes approximate `as
666
803
  size they offer; others fail with a typed `AIError` before any network call rather than dropping them, so check this
667
804
  table before swapping only the `model`:
668
805
 
669
- | Provider | `n` | `aspect` | `resolution` | `images` | Moved to `providerOptions` |
670
- | --------------------- | --- | -------------------- | --------------------- | -------------------------------- | -------------------------------------------------- |
671
- | OpenAI | ✓¹ | nearest size | nearest size | ✓ | `size`, `outputFormat`, `mask` |
672
- | Google (Gemini) | 1 | ✓ | ✓ (`0.5K` as `512`) | ✓ (no public URLs) | `seed` |
673
- | xAI | ✓ | ✓ | `1k`/`2k` | ✓ | none |
674
- | Meta | ✓ | ✓ (hint) | ignored | ✓ | `size`, `outputFormat` |
675
- | Z.ai | ✗ | width × height | width × height | ✗ | `size` |
676
- | Alibaba | ✓ | width × height | width × height | ✓ | `size`, `seed` |
677
- | MiniMax | ✓ | preset or w × h⁴ | preset or w × h⁴ | 1 (portrait subject) | `aspect_ratio`, `width`, `height`, `seed` |
678
- | Vercel AI Gateway | ✓ | as OpenAI³ | as OpenAI³ | per model | as OpenAI |
679
- | OpenRouter | ✓ | ✓ (`aspect_ratio`) | tier⁵ | per model⁵ | `size`, `outputFormat` (no `mask`) |
680
- | Cloudflare Workers AI | 1 | width × height² | width × height² | ✗ | `width`, `height`, `seed` |
806
+ | Provider | `n` | `aspect` | `resolution` | `images` | Moved to `providerOptions` |
807
+ | --------------------- | --- | ------------------ | ------------------- | -------------------- | ----------------------------------------- |
808
+ | OpenAI | ✓¹ | nearest size | nearest size | ✓ | `size`, `outputFormat`, `mask` |
809
+ | Google (Gemini) | 1 | ✓ | ✓ (`0.5K` as `512`) | ✓ (no public URLs) | `seed` |
810
+ | xAI | ✓ | ✓ | `1k`/`2k` | ✓ | none |
811
+ | Meta | ✓ | ✓ (hint) | ignored | ✓ | `size`, `outputFormat` |
812
+ | Z.ai | ✗ | width × height | width × height | ✗ | `size` |
813
+ | Alibaba | ✓ | width × height | width × height | ✓ | `size`, `seed` |
814
+ | MiniMax | ✓ | preset or w × h⁴ | preset or w × h⁴ | 1 (portrait subject) | `aspect_ratio`, `width`, `height`, `seed` |
815
+ | Vercel AI Gateway | ✓ | as OpenAI³ | as OpenAI³ | per model | as OpenAI |
816
+ | OpenRouter | ✓ | ✓ (`aspect_ratio`) | tier⁵ | per model⁵ | `size`, `outputFormat` (no `mask`) |
817
+ | Cloudflare Workers AI | 1 | width × height² | width × height² | ✗ | `width`, `height`, `seed` |
681
818
 
682
819
  ✓ lowers natively; ✗ fails whenever the field is set (including `n: 1`); `1` means `n > 1` fails. "width × height"
683
820
  computes a size the provider accepts and fails when the request falls outside its limits. ¹ `ai.image.stream` on OpenAI
@@ -698,6 +835,20 @@ edits endpoint, so input images go to `/images/generations` as `input_references
698
835
  asset into owned bytes before the provider URL expires. Construct assets with `Media.bytes`, `Media.base64`,
699
836
  `Media.url`, `Media.ref(provider, id)`, `Media.fromDataUrl`, or `Media.file(path)`.
700
837
 
838
+ File inputs (message `media` parts, image `images`, decision `media` parts) also take plain data: a `Uint8Array`,
839
+ `ArrayBuffer`, `URL`, or a string holding a data URL, an http(s) URL or base64. Bytes and base64 are sniffed from
840
+ magic bytes; pass `mediaType` when that fails:
841
+
842
+ ```ts
843
+ ai.request({
844
+ model,
845
+ prompt: [
846
+ { type: "text", text: "Summarize this report" },
847
+ { type: "media", media: pdfBase64, mediaType: "application/pdf" },
848
+ ],
849
+ })
850
+ ```
851
+
701
852
  Pass ordered image inputs to the same method for editing, composition, or image-conditioned generation:
702
853
 
703
854
  ```ts
@@ -719,8 +870,8 @@ const composed = Effect.gen(function* () {
719
870
 
720
871
  `Media.ref(provider, id)` represents provider file handles such as OpenAI file IDs or Gemini Files URIs; routes
721
872
  only forward refs that belong to their own provider (OpenAI, xAI, and Gemini images accept them). No shipped route
722
- returns a ref yet, and `asset.bytes()` / `materialize()` on a ref fail by design. Raw strings are not accepted as
723
- image inputs, avoiding ambiguity between base64, URLs, and provider IDs. Empty or omitted `images` uses text-to-image generation; a
873
+ returns a ref yet, and `asset.bytes()` / `materialize()` on a ref fail by design. Empty or omitted `images` uses
874
+ text-to-image generation; a
724
875
  non-empty array selects the provider's edit behavior (see the table above for routes that limit the count). OpenAI
725
876
  uses multipart for byte/data-URL edits and its JSON reference body for URL or file-ID edits. Inpainting is a
726
877
  provider option on the routes that support it (OpenAI):
@@ -848,11 +999,13 @@ and emits `image-partial` events before each final `image`; `ai.image.generate`
848
999
  import { Stream } from "effect"
849
1000
  import { ImageEvent } from "@opencode/ai/effect"
850
1001
 
851
- const previews = ai.image.stream({
852
- model: openai.image("gpt-image-2"),
853
- prompt: "A lighthouse at dusk",
854
- providerOptions: { partialImages: 2 },
855
- }).pipe(Stream.runForEach((event) => (ImageEvent.is.imagePartial(event) ? showPreview(event.image) : Effect.void)))
1002
+ const previews = ai.image
1003
+ .stream({
1004
+ model: openai.image("gpt-image-2"),
1005
+ prompt: "A lighthouse at dusk",
1006
+ providerOptions: { partialImages: 2 },
1007
+ })
1008
+ .pipe(Stream.runForEach((event) => (ImageEvent.is.imagePartial(event) ? showPreview(event.image) : Effect.void)))
856
1009
  ```
857
1010
 
858
1011
  The provider may send fewer previews than requested when the final image is ready first.
@@ -882,9 +1035,10 @@ The hosted result is represented as a provider-executed tool call and a tool res
882
1035
 
883
1036
  Everything below is exported from `@opencode/ai/effect` unless noted.
884
1037
 
885
- - **`ai.request({...})`** — build a provider-neutral `LLMRequest`. Accepts ergonomic inputs (`system: string`, `prompt: string`) that normalize into the canonical Schema classes.
1038
+ - **`ai.request({...})`** — build a provider-neutral `LLMRequest`, a plain object. Accepts ergonomic inputs (`system: string`, `prompt: string`) and normalizes them into `system`, `messages` and `tools` arrays. Edit it with a spread, or pass the edited object back to `ai.request`.
886
1039
  - **`ai.generate` / `ai.stream`** — run direct input or an `LLMRequest` through `LLMClient` for one-import use.
887
1040
  - **`ai.loop`** — stream model calls, running `tool(...)` tools between them until the model stops calling tools.
1041
+ - **`ai.collect`** — fold a stream from `ai.stream` or `ai.loop` into its final result (`text`, `steps`, `messages`, `usage`).
888
1042
  - **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model.
889
1043
  - **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
890
1044
  - **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
@@ -893,18 +1047,19 @@ Everything below is exported from `@opencode/ai/effect` unless noted.
893
1047
  - **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests.
894
1048
  - **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
895
1049
  - **`ai.decision.request` / `ai.decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer.
1050
+ - **`ai.embedding.request` / `ai.embedding.generate`** — one vector per text or media value, with optional `dimensions` and `inputType`; `EmbeddingClient` is its Effect service and layer.
896
1051
  - **`AIClient.layer` / `AIClient.layerWith(executor)`** — every modality client plus the request executor in one layer.
897
- - **`@opencode/ai`** (Promise root) — a default `ai` with the text calls (`request`, `generate`, `stream`, `loop`, `generateObject`, `compact`, `canCompact`) at the top level plus `image` and `decision` (plus `experimental.video`, `experimental.speech`, and `experimental.transcription`) as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets. `AI.make({ layer?, clients? })` builds a client over a custom executor or test layers. The same `ai` from `@opencode/ai/effect` returns `Effect` and `Stream`.
1052
+ - **`@opencode/ai`** (Promise root) — a default `ai` with the text calls (`request`, `generate`, `stream`, `loop`, `compact`, `canCompact`) at the top level plus `image`, `decision` and `embedding` (plus `experimental.video`, `experimental.speech`, and `experimental.transcription`) as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets. `AI.make({ layer? })` builds a client over a custom executor. The same `ai` from `@opencode/ai/effect` returns `Effect` and `Stream`.
898
1053
  - **`@opencode/ai/experimental`** — APIs that may change without compatibility guarantees: `Video`, `Speech`, `Transcription`, `Extraction`, and `Realtime`. See [Experimental](#experimental).
899
1054
 
900
1055
  ## Experimental
901
1056
 
902
1057
  These APIs may change without compatibility guarantees. The Effect API is exported from `@opencode/ai/experimental`,
903
- the Promise client exposes it under `ai.experimental`, and test layers come from `@opencode/ai/experimental/testing`.
1058
+ and the Promise client exposes it under `ai.experimental`.
904
1059
 
905
1060
  - **`Video`**, **`Speech`**, and **`Transcription`** — media generation and speech-to-text, with `VideoClient`,
906
1061
  `SpeechClient`, and `TranscriptionClient` as their Effect services. Promise: `ai.experimental.video`, `.speech`, and
907
- `.transcription`. Testing: `TestVideo`, `TestSpeech`, and `TestTranscription`.
1062
+ `.transcription`.
908
1063
  - **`Extraction`** — typed values read out of text.
909
1064
  - **`Realtime`** — `Realtime.connect` starts an OpenAI, xAI, or Gemini voice session and returns a WebRTC answer SDP or
910
1065
  a short-lived WebSocket URL and token.
@@ -1233,13 +1388,16 @@ For explicit compaction, script a `CompactionResponse` through `push`, `always`,
1233
1388
 
1234
1389
  For `compact(request, { mechanism: "trigger" })`, script a `CompactionCheckpointResponse` instead. It carries `checkpoint`, `responseID`, and optional `usage`. Endpoint and trigger calls reject each other's fixtures; both share the same queue, gates, lazy recording, and fallback controls.
1235
1390
 
1236
- `TestImage` and `TestDecision` (and `TestVideo`, `TestSpeech`, and `TestTranscription` from `@opencode/ai/experimental/testing`) follow the same pattern: `testLayer()` provides the modality's client and `Test`, with the same `push`, `always`, `serve`, `requests`, `wait`, and `gate` controls. Script an `ImageResponse` (or the modality's response) or an `AIError`. `stream` expands the response into its events, and `start` returns an already finished generation that `resume` accepts by token. Decision responses are returned as scripted, without checking the answers against the questions.
1391
+ Response helpers build common event arrays: `TestLLM.text(value, id)`, `textWithUsage(value, id, inputTokens)`,
1392
+ `toolCall(id, name, input)`, `stop(...events)`, `toolCalls(...events)`, and
1393
+ `complete({ reason, usage?, providerMetadata? }, ...events)`. `failAfter(error, ...events)` and `hangAfter(...events)`
1394
+ return streams that fail or never finish after the given events.
1237
1395
 
1238
- The Promise client accepts the same layers as `AI.make({ clients: TestImage.testLayer() })`; `ai.run(TestImage.Test.use(...))` reaches the controls.
1396
+ `compileRequest`, also from `@opencode/ai/testing`, compiles an `LLMRequest` through its route without sending it, so
1397
+ tests can assert the provider payload.
1239
1398
 
1240
- The published legacy `Service`, `layer`, `clientLayer`, and module-level controls remain available as adapters
1241
- over the same implementation, including the legacy live `requests` array. New tests should use `Test` and
1242
- `testLayer`.
1399
+ Other modalities and the Promise client have no test double. Test them over a custom executor layer, such as
1400
+ `AI.make({ layer })`, that answers the HTTP requests.
1243
1401
 
1244
1402
  ## Provider compaction
1245
1403
 
@@ -1256,9 +1414,7 @@ Prefer this operation, where supported, when the application owns compaction pol
1256
1414
  ```ts
1257
1415
  const compacted = Effect.gen(function* () {
1258
1416
  const result = yield* ai.compact(request)
1259
- const next = LLMRequest.update(request, {
1260
- messages: result.replacement,
1261
- })
1417
+ const next = { ...request, messages: result.replacement }
1262
1418
  return yield* ai.generate(next)
1263
1419
  })
1264
1420
  ```
@@ -1318,7 +1474,7 @@ Enable OpenAI compaction with typed provider options:
1318
1474
 
1319
1475
  ```ts
1320
1476
  import { Effect } from "effect"
1321
- import { ai, LLMClient, LLMRequest, Message } from "@opencode/ai/effect"
1477
+ import { ai, LLMClient, Message } from "@opencode/ai/effect"
1322
1478
  import { OpenAI } from "@opencode/ai/providers"
1323
1479
 
1324
1480
  const request = ai.request({
@@ -1330,9 +1486,7 @@ const request = ai.request({
1330
1486
  })
1331
1487
  const continued = Effect.gen(function* () {
1332
1488
  const response = yield* LLMClient.generate(request)
1333
- return LLMRequest.update(request, {
1334
- messages: [...request.messages, response.message, Message.user("Continue")],
1335
- })
1489
+ return { ...request, messages: [...request.messages, response.message, Message.user("Continue")] }
1336
1490
  })
1337
1491
  ```
1338
1492
 
@@ -1476,6 +1630,8 @@ const gateway = CloudflareAIGateway.configure({
1476
1630
  }).model("workers-ai/@cf/meta/llama-3.1-8b-instruct")
1477
1631
  ```
1478
1632
 
1633
+ For a provider that needs no key, such as a local server, pass `apiKey: false`: the package skips the environment lookup and sends no auth header (Amazon Bedrock and Google Vertex keep their own auth).
1634
+
1479
1635
  Included LLM providers: OpenAI, Anthropic, Google (Gemini), Google Vertex, Amazon Bedrock (Converse and Mantle), Azure OpenAI, Alibaba, Baseten, Cerebras, Cohere, Cloudflare AI Gateway, Cloudflare Workers AI, DeepInfra, DeepSeek, DigitalOcean, Fireworks, Groq, Meta, MiniMax, Mistral, Moonshot, OpenRouter, TogetherAI, Venice, Vercel AI Gateway, xAI, Z.ai, and Z.ai Coding Plan. TypeSafe AI and OpenCode expose decision models only. Generic Chat Completions, Responses, and Anthropic Messages-compatible entrypoints support custom endpoints.
1480
1636
 
1481
1637
  Each named provider owns its module, endpoint, authentication, and route setup. Providers with the same wire format compose the shared protocol directly:
@@ -1556,7 +1712,7 @@ Additional provider entrypoints include:
1556
1712
 
1557
1713
  Request options in order of stability:
1558
1714
 
1559
- 1. **`generation`** — portable knobs (`maxTokens`, `temperature`, `topP`, `topK`, penalties, seed, stop).
1715
+ 1. **Portable knobs** — `maxTokens`, `temperature`, `topP`, `topK`, `frequencyPenalty`, `presencePenalty`, `seed` and `stop`, at the top level of a text request. `GENERATION_KEYS` lists them.
1560
1716
  2. **`promptCacheKey`** — stable cache affinity lowered by every protocol that supports it.
1561
1717
  3. **`providerOptions: { ... }`** — flat options inferred from the selected model (OpenAI `store`, Anthropic `thinking`, Gemini `thinkingConfig`, OpenRouter routing).
1562
1718
  4. **`http: { body, headers, query }`** — last-resort serializable overlays merged into the final HTTP request. Reach for this only when a stable typed path doesn't yet exist.
@@ -1,8 +1,8 @@
1
1
  import { Layer } from "effect";
2
2
  import { RequestExecutor } from "./route/executor.js";
3
3
  /** Every modality client over `executor`, which stays in the output so `asset.bytes()` and `Media.write` resolve. */
4
- export declare const layerWith: <E, R>(executor: Layer.Layer<RequestExecutor.Service, E, R>) => Layer.Layer<import("./image-client.js").ImageClientService | import("./route/client.js").LLMClientService | RequestExecutor.RequestExecutorService | import("./decision-client.js").Service | import("./speech-client.js").SpeechClientService | import("./transcription-client.js").TranscriptionClientService | import("./video-client.js").VideoClientService, E, R>;
4
+ export declare const layerWith: <E, R>(executor: Layer.Layer<RequestExecutor.Service, E, R>) => Layer.Layer<import("./image-client.js").ImageClientService | import("./route/client.js").LLMClientService | RequestExecutor.RequestExecutorService | import("./decision-client.js").Service | import("./embedding-client.js").Service | import("./speech-client.js").SpeechClientService | import("./transcription-client.js").TranscriptionClientService | import("./video-client.js").VideoClientService, E, R>;
5
5
  /** Every modality client plus the executor over `RequestExecutor.fetchLayer`: the one layer most programs need. */
6
- export declare const layer: Layer.Layer<import("./image-client.js").ImageClientService | import("./route/client.js").LLMClientService | RequestExecutor.RequestExecutorService | import("./decision-client.js").Service | import("./speech-client.js").SpeechClientService | import("./transcription-client.js").TranscriptionClientService | import("./video-client.js").VideoClientService, never, never>;
6
+ export declare const layer: Layer.Layer<import("./image-client.js").ImageClientService | import("./route/client.js").LLMClientService | RequestExecutor.RequestExecutorService | import("./decision-client.js").Service | import("./embedding-client.js").Service | import("./speech-client.js").SpeechClientService | import("./transcription-client.js").TranscriptionClientService | import("./video-client.js").VideoClientService, never, never>;
7
7
  export type Services = Layer.Success<typeof layer>;
8
8
  export * as AIClient from "./ai-client.js";
package/dist/ai-client.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Layer } from "effect";
2
2
  import { DecisionClient } from "./decision-client.js";
3
+ import { EmbeddingClient } from "./embedding-client.js";
3
4
  import { ImageClient } from "./image-client.js";
4
5
  import { LLMClient } from "./route/client.js";
5
6
  import { RequestExecutor } from "./route/executor.js";
@@ -7,7 +8,7 @@ import { SpeechClient } from "./speech-client.js";
7
8
  import { TranscriptionClient } from "./transcription-client.js";
8
9
  import { VideoClient } from "./video-client.js";
9
10
  /** Every modality client over `executor`, which stays in the output so `asset.bytes()` and `Media.write` resolve. */
10
- export const layerWith = (executor) => Layer.mergeAll(LLMClient.layer, ImageClient.layer, VideoClient.layer, SpeechClient.layer, TranscriptionClient.layer, DecisionClient.layer).pipe(Layer.provideMerge(executor));
11
+ export const layerWith = (executor) => Layer.mergeAll(LLMClient.layer, ImageClient.layer, VideoClient.layer, SpeechClient.layer, TranscriptionClient.layer, DecisionClient.layer, EmbeddingClient.layer).pipe(Layer.provideMerge(executor));
11
12
  /** Every modality client plus the executor over `RequestExecutor.fetchLayer`: the one layer most programs need. */
12
13
  export const layer = layerWith(RequestExecutor.fetchLayer);
13
14
  export * as AIClient from "./ai-client.js";
@@ -1,4 +1,4 @@
1
- import { LLMRequest } from "./schema/messages.js";
1
+ import { type LLMRequest } from "./schema/messages.js";
2
2
  /** The requested cache lifetime, for routes that send it as a request-level option instead of on markers. */
3
3
  export declare const requestTTL: (request: LLMRequest) => `${number}d` | `${number}h` | `${number}m` | `${number}ms` | `${number}s` | undefined;
4
4
  export declare const applyCachePolicy: (request: LLMRequest) => LLMRequest;
@@ -11,7 +11,7 @@
11
11
  // Manual `cache: CacheHint` placements on individual parts are preserved and
12
12
  // count against the four-breakpoint budget; auto only fills remaining slots.
13
13
  import { CacheHint } from "./schema/options.js";
14
- import { LLMRequest, Message, ToolDefinition } from "./schema/messages.js";
14
+ import { AssistantMessage, SystemMessage, ToolDefinition, ToolMessage, UserMessage, } from "./schema/messages.js";
15
15
  import { effortUpdate } from "./effort-updates.js";
16
16
  const AUTO = {
17
17
  tools: true,
@@ -119,8 +119,7 @@ const markMessageAt = (messages, index, hint, budget) => {
119
119
  if (!existing || !isCacheablePart(existing) || existing.cache || budget.remaining === 0)
120
120
  return messages;
121
121
  budget.remaining -= 1;
122
- const nextContent = target.content.map((part, i) => (i === markAt ? { ...existing, cache: hint } : part));
123
- const next = new Message({ ...target, content: nextContent });
122
+ const next = cachePartAt(target, markAt, hint);
124
123
  // Single pass over `messages`, substituting the one updated entry. Long
125
124
  // conversations call this on every request, so avoid `.map()` here — its
126
125
  // closure dispatch and identity copies show up in profiling.
@@ -128,6 +127,19 @@ const markMessageAt = (messages, index, hint, budget) => {
128
127
  result[index] = next;
129
128
  return result;
130
129
  };
130
+ const cachePartAt = (message, index, hint) => {
131
+ switch (message.role) {
132
+ case "system":
133
+ return new SystemMessage({ ...message, content: cacheContentAt(message.content, index, hint) });
134
+ case "user":
135
+ return new UserMessage({ ...message, content: cacheContentAt(message.content, index, hint) });
136
+ case "assistant":
137
+ return new AssistantMessage({ ...message, content: cacheContentAt(message.content, index, hint) });
138
+ case "tool":
139
+ return new ToolMessage({ ...message, content: cacheContentAt(message.content, index, hint) });
140
+ }
141
+ };
142
+ const cacheContentAt = (content, index, hint) => content.map((part, i) => (i === index ? { ...part, cache: hint } : part));
131
143
  const markMessages = (messages, strategy, hint, budget) => {
132
144
  if (messages.length === 0)
133
145
  return messages;
@@ -163,7 +175,7 @@ export const applyCachePolicy = (request) => {
163
175
  const messages = policy.messages ? markMessages(request.messages, policy.messages, hint, budget) : request.messages;
164
176
  if (tools === request.tools && system === request.system && messages === request.messages)
165
177
  return request;
166
- return LLMRequest.update(request, { tools, system, messages });
178
+ return { ...request, tools, system, messages };
167
179
  };
168
180
  /** Whether the cache policy places inline markers, which then carry the requested lifetime. */
169
181
  export const placesMarkers = (request) => {