@opencode/ai 0.0.0-beta-19275

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) hide show
  1. package/README.md +682 -0
  2. package/dist/cache-policy.d.ts +2 -0
  3. package/dist/cache-policy.js +129 -0
  4. package/dist/image-client.d.ts +19 -0
  5. package/dist/image-client.js +28 -0
  6. package/dist/image.d.ts +110 -0
  7. package/dist/image.js +103 -0
  8. package/dist/index.d.ts +18 -0
  9. package/dist/index.js +12 -0
  10. package/dist/llm.d.ts +252 -0
  11. package/dist/llm.js +74 -0
  12. package/dist/protocols/anthropic-messages.d.ts +957 -0
  13. package/dist/protocols/anthropic-messages.js +1414 -0
  14. package/dist/protocols/bedrock-converse.d.ts +499 -0
  15. package/dist/protocols/bedrock-converse.js +643 -0
  16. package/dist/protocols/bedrock-event-stream.d.ts +9 -0
  17. package/dist/protocols/bedrock-event-stream.js +97 -0
  18. package/dist/protocols/gemini.d.ts +285 -0
  19. package/dist/protocols/gemini.js +671 -0
  20. package/dist/protocols/google-images.d.ts +30 -0
  21. package/dist/protocols/google-images.js +181 -0
  22. package/dist/protocols/index.d.ts +12 -0
  23. package/dist/protocols/index.js +12 -0
  24. package/dist/protocols/meta-images.d.ts +26 -0
  25. package/dist/protocols/meta-images.js +89 -0
  26. package/dist/protocols/meta-messages.d.ts +350 -0
  27. package/dist/protocols/meta-messages.js +41 -0
  28. package/dist/protocols/meta-responses.d.ts +473 -0
  29. package/dist/protocols/meta-responses.js +173 -0
  30. package/dist/protocols/mistral-chat.d.ts +540 -0
  31. package/dist/protocols/mistral-chat.js +624 -0
  32. package/dist/protocols/open-responses-channel.d.ts +23 -0
  33. package/dist/protocols/open-responses-channel.js +141 -0
  34. package/dist/protocols/open-responses-continuation.d.ts +12 -0
  35. package/dist/protocols/open-responses-continuation.js +161 -0
  36. package/dist/protocols/open-responses.d.ts +1583 -0
  37. package/dist/protocols/open-responses.js +1206 -0
  38. package/dist/protocols/openai-chat.d.ts +860 -0
  39. package/dist/protocols/openai-chat.js +966 -0
  40. package/dist/protocols/openai-compatible-chat.d.ts +109 -0
  41. package/dist/protocols/openai-compatible-chat.js +19 -0
  42. package/dist/protocols/openai-compatible-responses.d.ts +172 -0
  43. package/dist/protocols/openai-compatible-responses.js +18 -0
  44. package/dist/protocols/openai-images.d.ts +32 -0
  45. package/dist/protocols/openai-images.js +183 -0
  46. package/dist/protocols/openai-responses.d.ts +1389 -0
  47. package/dist/protocols/openai-responses.js +260 -0
  48. package/dist/protocols/shared.d.ts +193 -0
  49. package/dist/protocols/shared.js +290 -0
  50. package/dist/protocols/utils/bedrock-auth.d.ts +60 -0
  51. package/dist/protocols/utils/bedrock-auth.js +85 -0
  52. package/dist/protocols/utils/bedrock-cache.d.ts +19 -0
  53. package/dist/protocols/utils/bedrock-cache.js +49 -0
  54. package/dist/protocols/utils/bedrock-media.d.ts +55 -0
  55. package/dist/protocols/utils/bedrock-media.js +73 -0
  56. package/dist/protocols/utils/cache.d.ts +6 -0
  57. package/dist/protocols/utils/cache.js +5 -0
  58. package/dist/protocols/utils/gemini-tool-schema.d.ts +2 -0
  59. package/dist/protocols/utils/gemini-tool-schema.js +103 -0
  60. package/dist/protocols/utils/image-input.d.ts +21 -0
  61. package/dist/protocols/utils/image-input.js +20 -0
  62. package/dist/protocols/utils/lifecycle.d.ts +24 -0
  63. package/dist/protocols/utils/lifecycle.js +72 -0
  64. package/dist/protocols/utils/meta-image.d.ts +2 -0
  65. package/dist/protocols/utils/meta-image.js +13 -0
  66. package/dist/protocols/utils/open-responses-options.d.ts +56 -0
  67. package/dist/protocols/utils/open-responses-options.js +61 -0
  68. package/dist/protocols/utils/openai-image.d.ts +5 -0
  69. package/dist/protocols/utils/openai-image.js +18 -0
  70. package/dist/protocols/utils/openai-options.d.ts +16 -0
  71. package/dist/protocols/utils/openai-options.js +14 -0
  72. package/dist/protocols/utils/partial-json-options.d.ts +62 -0
  73. package/dist/protocols/utils/partial-json-options.js +52 -0
  74. package/dist/protocols/utils/partial-json.d.ts +8 -0
  75. package/dist/protocols/utils/partial-json.js +279 -0
  76. package/dist/protocols/utils/responses-checkpoint.d.ts +4 -0
  77. package/dist/protocols/utils/responses-checkpoint.js +107 -0
  78. package/dist/protocols/utils/responses-compaction.d.ts +4 -0
  79. package/dist/protocols/utils/responses-compaction.js +129 -0
  80. package/dist/protocols/utils/responses-hosted-tools.d.ts +26 -0
  81. package/dist/protocols/utils/responses-hosted-tools.js +32 -0
  82. package/dist/protocols/utils/tool-schema.d.ts +8 -0
  83. package/dist/protocols/utils/tool-schema.js +54 -0
  84. package/dist/protocols/utils/tool-stream.d.ts +710 -0
  85. package/dist/protocols/utils/tool-stream.js +155 -0
  86. package/dist/protocols/xai-images.d.ts +26 -0
  87. package/dist/protocols/xai-images.js +106 -0
  88. package/dist/protocols/xai-responses.d.ts +250 -0
  89. package/dist/protocols/xai-responses.js +81 -0
  90. package/dist/protocols/zai-images.d.ts +22 -0
  91. package/dist/protocols/zai-images.js +79 -0
  92. package/dist/protocols.d.ts +1 -0
  93. package/dist/protocols.js +1 -0
  94. package/dist/provider-error.d.ts +15 -0
  95. package/dist/provider-error.js +125 -0
  96. package/dist/provider-package.d.ts +11 -0
  97. package/dist/provider-package.js +1 -0
  98. package/dist/provider.d.ts +23 -0
  99. package/dist/provider.js +2 -0
  100. package/dist/providers/amazon-bedrock/mantle/chat.d.ts +2 -0
  101. package/dist/providers/amazon-bedrock/mantle/chat.js +1 -0
  102. package/dist/providers/amazon-bedrock/mantle/responses.d.ts +2 -0
  103. package/dist/providers/amazon-bedrock/mantle/responses.js +1 -0
  104. package/dist/providers/amazon-bedrock/mantle.d.ts +2 -0
  105. package/dist/providers/amazon-bedrock/mantle.js +1 -0
  106. package/dist/providers/amazon-bedrock-mantle.d.ts +371 -0
  107. package/dist/providers/amazon-bedrock-mantle.js +76 -0
  108. package/dist/providers/amazon-bedrock.d.ts +173 -0
  109. package/dist/providers/amazon-bedrock.js +41 -0
  110. package/dist/providers/anthropic-compatible.d.ts +304 -0
  111. package/dist/providers/anthropic-compatible.js +44 -0
  112. package/dist/providers/anthropic.d.ts +302 -0
  113. package/dist/providers/anthropic.js +39 -0
  114. package/dist/providers/azure/chat.d.ts +2 -0
  115. package/dist/providers/azure/chat.js +1 -0
  116. package/dist/providers/azure/responses.d.ts +2 -0
  117. package/dist/providers/azure/responses.js +1 -0
  118. package/dist/providers/azure.d.ts +599 -0
  119. package/dist/providers/azure.js +115 -0
  120. package/dist/providers/baseten.d.ts +229 -0
  121. package/dist/providers/baseten.js +38 -0
  122. package/dist/providers/cerebras.d.ts +228 -0
  123. package/dist/providers/cerebras.js +40 -0
  124. package/dist/providers/cloudflare-ai-gateway.d.ts +238 -0
  125. package/dist/providers/cloudflare-ai-gateway.js +59 -0
  126. package/dist/providers/cloudflare-workers-ai.d.ts +232 -0
  127. package/dist/providers/cloudflare-workers-ai.js +45 -0
  128. package/dist/providers/deepinfra.d.ts +228 -0
  129. package/dist/providers/deepinfra.js +43 -0
  130. package/dist/providers/deepseek.d.ts +229 -0
  131. package/dist/providers/deepseek.js +41 -0
  132. package/dist/providers/fireworks.d.ts +229 -0
  133. package/dist/providers/fireworks.js +38 -0
  134. package/dist/providers/google-vertex/chat.d.ts +2 -0
  135. package/dist/providers/google-vertex/chat.js +1 -0
  136. package/dist/providers/google-vertex/gemini.d.ts +2 -0
  137. package/dist/providers/google-vertex/gemini.js +1 -0
  138. package/dist/providers/google-vertex/messages.d.ts +2 -0
  139. package/dist/providers/google-vertex/messages.js +1 -0
  140. package/dist/providers/google-vertex/responses.d.ts +2 -0
  141. package/dist/providers/google-vertex/responses.js +1 -0
  142. package/dist/providers/google-vertex-chat.d.ts +133 -0
  143. package/dist/providers/google-vertex-chat.js +55 -0
  144. package/dist/providers/google-vertex-messages.d.ts +301 -0
  145. package/dist/providers/google-vertex-messages.js +75 -0
  146. package/dist/providers/google-vertex-responses.d.ts +198 -0
  147. package/dist/providers/google-vertex-responses.js +56 -0
  148. package/dist/providers/google-vertex-shared.d.ts +22 -0
  149. package/dist/providers/google-vertex-shared.js +61 -0
  150. package/dist/providers/google-vertex.d.ts +120 -0
  151. package/dist/providers/google-vertex.js +92 -0
  152. package/dist/providers/google.d.ts +115 -0
  153. package/dist/providers/google.js +42 -0
  154. package/dist/providers/groq.d.ts +315 -0
  155. package/dist/providers/groq.js +81 -0
  156. package/dist/providers/index.d.ts +28 -0
  157. package/dist/providers/index.js +28 -0
  158. package/dist/providers/meta/chat.d.ts +2 -0
  159. package/dist/providers/meta/chat.js +1 -0
  160. package/dist/providers/meta/messages.d.ts +2 -0
  161. package/dist/providers/meta/messages.js +1 -0
  162. package/dist/providers/meta/responses.d.ts +2 -0
  163. package/dist/providers/meta/responses.js +1 -0
  164. package/dist/providers/meta.d.ts +631 -0
  165. package/dist/providers/meta.js +113 -0
  166. package/dist/providers/minimax/chat.d.ts +4 -0
  167. package/dist/providers/minimax/chat.js +8 -0
  168. package/dist/providers/minimax/messages.d.ts +1 -0
  169. package/dist/providers/minimax/messages.js +1 -0
  170. package/dist/providers/minimax/responses.d.ts +4 -0
  171. package/dist/providers/minimax/responses.js +8 -0
  172. package/dist/providers/minimax.d.ts +593 -0
  173. package/dist/providers/minimax.js +89 -0
  174. package/dist/providers/mistral.d.ts +208 -0
  175. package/dist/providers/mistral.js +28 -0
  176. package/dist/providers/open-responses-options.d.ts +6 -0
  177. package/dist/providers/open-responses-options.js +1 -0
  178. package/dist/providers/openai/chat.d.ts +2 -0
  179. package/dist/providers/openai/chat.js +1 -0
  180. package/dist/providers/openai/responses.d.ts +2 -0
  181. package/dist/providers/openai/responses.js +1 -0
  182. package/dist/providers/openai-compatible/responses.d.ts +1 -0
  183. package/dist/providers/openai-compatible/responses.js +1 -0
  184. package/dist/providers/openai-compatible-responses.d.ts +196 -0
  185. package/dist/providers/openai-compatible-responses.js +32 -0
  186. package/dist/providers/openai-compatible.d.ts +131 -0
  187. package/dist/providers/openai-compatible.js +33 -0
  188. package/dist/providers/openai-options.d.ts +26 -0
  189. package/dist/providers/openai-options.js +41 -0
  190. package/dist/providers/openai.d.ts +405 -0
  191. package/dist/providers/openai.js +82 -0
  192. package/dist/providers/openrouter.d.ts +564 -0
  193. package/dist/providers/openrouter.js +114 -0
  194. package/dist/providers/togetherai.d.ts +228 -0
  195. package/dist/providers/togetherai.js +40 -0
  196. package/dist/providers/xai.d.ts +164 -0
  197. package/dist/providers/xai.js +84 -0
  198. package/dist/providers/zai.d.ts +24 -0
  199. package/dist/providers/zai.js +21 -0
  200. package/dist/providers.d.ts +1 -0
  201. package/dist/providers.js +1 -0
  202. package/dist/route/auth-options.d.ts +34 -0
  203. package/dist/route/auth-options.js +14 -0
  204. package/dist/route/auth.d.ts +51 -0
  205. package/dist/route/auth.js +87 -0
  206. package/dist/route/client.d.ts +430 -0
  207. package/dist/route/client.js +304 -0
  208. package/dist/route/endpoint.d.ts +28 -0
  209. package/dist/route/endpoint.js +21 -0
  210. package/dist/route/executor.d.ts +27 -0
  211. package/dist/route/executor.js +183 -0
  212. package/dist/route/framing.d.ts +29 -0
  213. package/dist/route/framing.js +14 -0
  214. package/dist/route/index.d.ts +16 -0
  215. package/dist/route/index.js +9 -0
  216. package/dist/route/protocol.d.ts +76 -0
  217. package/dist/route/protocol.js +16 -0
  218. package/dist/route/transport/http.d.ts +34 -0
  219. package/dist/route/transport/http.js +68 -0
  220. package/dist/route/transport/index.d.ts +41 -0
  221. package/dist/route/transport/index.js +4 -0
  222. package/dist/route/transport/websocket-channel.d.ts +57 -0
  223. package/dist/route/transport/websocket-channel.js +1 -0
  224. package/dist/route/transport/websocket.d.ts +56 -0
  225. package/dist/route/transport/websocket.js +366 -0
  226. package/dist/route.d.ts +1 -0
  227. package/dist/route.js +1 -0
  228. package/dist/schema/errors.d.ts +158 -0
  229. package/dist/schema/errors.js +120 -0
  230. package/dist/schema/events.d.ts +8123 -0
  231. package/dist/schema/events.js +550 -0
  232. package/dist/schema/ids.d.ts +17 -0
  233. package/dist/schema/ids.js +10 -0
  234. package/dist/schema/index.d.ts +5 -0
  235. package/dist/schema/index.js +5 -0
  236. package/dist/schema/messages.d.ts +646 -0
  237. package/dist/schema/messages.js +301 -0
  238. package/dist/schema/options.d.ts +157 -0
  239. package/dist/schema/options.js +187 -0
  240. package/dist/testing.d.ts +1693 -0
  241. package/dist/testing.js +129 -0
  242. package/dist/tool-history.d.ts +2 -0
  243. package/dist/tool-history.js +84 -0
  244. package/dist/tool-runtime.d.ts +15 -0
  245. package/dist/tool-runtime.js +62 -0
  246. package/dist/tool.d.ts +136 -0
  247. package/dist/tool.js +66 -0
  248. package/dist/utils/record.d.ts +2 -0
  249. package/dist/utils/record.js +2 -0
  250. package/dist/utils/sanitize.d.ts +1 -0
  251. package/dist/utils/sanitize.js +12 -0
  252. package/package.json +48 -0
package/README.md ADDED
@@ -0,0 +1,682 @@
1
+ # @opencode/ai
2
+
3
+ Schema-first language model and image-generation APIs built with Effect.
4
+
5
+ ```ts
6
+ import { Effect, Layer } from "effect"
7
+ import { LLM, LLMClient } from "@opencode/ai"
8
+ import { RequestExecutor } from "@opencode/ai/route"
9
+ import { OpenAI } from "@opencode/ai/providers"
10
+
11
+ const model = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY }).responses("gpt-4o-mini")
12
+
13
+ const request = LLM.request({
14
+ model,
15
+ system: "You are concise.",
16
+ prompt: "Say hello in one short sentence.",
17
+ generation: { maxTokens: 40 },
18
+ })
19
+
20
+ const program = Effect.gen(function* () {
21
+ const response = yield* LLMClient.generate(request)
22
+ console.log(response.text)
23
+ })
24
+
25
+ const llmLayer = LLMClient.layer.pipe(Layer.provide(RequestExecutor.fetchLayer))
26
+
27
+ await Effect.runPromise(program.pipe(Effect.provide(llmLayer)))
28
+ ```
29
+
30
+ Run `LLMClient.stream(request)` instead of `generate` when you want incremental `LLMEvent`s. The event stream is provider-neutral — same shape across OpenAI Chat, OpenAI Responses, Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployment.
31
+
32
+ ## MiniMax
33
+
34
+ MiniMax defaults to its Messages API and reads `MINIMAX_API_KEY` when `apiKey` is omitted:
35
+
36
+ ```ts
37
+ import { Effect, Layer } from "effect"
38
+ import { LLM, LLMClient } from "@opencode/ai"
39
+ import { MiniMax } from "@opencode/ai/providers"
40
+ import { RequestExecutor } from "@opencode/ai/route"
41
+
42
+ const minimax = MiniMax.configure({ apiKey: process.env.MINIMAX_API_KEY })
43
+ const request = LLM.request({
44
+ model: minimax.model("MiniMax-M3"), // also minimax.messages("MiniMax-M3")
45
+ prompt: "What is 173 multiplied by 219?",
46
+ providerOptions: { thinking: { type: "adaptive" } },
47
+ generation: { maxTokens: 1536 },
48
+ })
49
+
50
+ const layer = LLMClient.layer.pipe(Layer.provide(RequestExecutor.fetchLayer))
51
+ const response = await Effect.runPromise(LLMClient.generate(request).pipe(Effect.provide(layer)))
52
+ console.log(response.text)
53
+ ```
54
+
55
+ Select `minimax.chat("MiniMax-M3")` or `minimax.responses("MiniMax-M3")` for MiniMax's native Chat Completions
56
+ and Responses APIs. The matching package entrypoints are `@opencode/ai/providers/minimax/messages`,
57
+ `@opencode/ai/providers/minimax/chat`, and `@opencode/ai/providers/minimax/responses`.
58
+
59
+ - **Messages:** M3 thinking defaults off. Set `thinking: { type: "adaptive" }` to enable it or
60
+ `thinking: { type: "disabled" }` to disable it.
61
+ - **Chat:** M3 thinking defaults on and uses the same `thinking` control. The provider enables `reasoning_split`
62
+ by default so reasoning is separate from answer text; `reasoningSplit: false` selects native `<think>`-tagged text.
63
+ - **Responses:** M3 reasoning defaults off. `reasoningEffort: "none"` disables it; `"minimal"`, `"low"`,
64
+ `"medium"`, and `"high"` enable reasoning without changing its depth.
65
+
66
+ M2.x models always think, even when a disabling option is supplied. For tool continuations, retain the complete
67
+ `response.message` in history before adding `Message.tool(...)` results; this preserves reasoning and any signatures.
68
+
69
+ The default API bases are `https://api.minimax.io/anthropic/v1` for Messages and `https://api.minimax.io/v1` for
70
+ Chat and Responses. `configure({ baseURL })` replaces the selected API's base, including its version prefix.
71
+
72
+ ## Meta
73
+
74
+ Use Meta's direct [Model API](https://dev.meta.ai/docs/overview) with `META_API_KEY`:
75
+
76
+ ```ts
77
+ import { Meta } from "@opencode/ai/providers"
78
+
79
+ const meta = Meta.configure() // or Meta.configure({ apiKey })
80
+ const request = LLM.request({
81
+ model: meta.responses("muse-spark-1.3"), // meta.model(...) also selects Responses
82
+ prompt: "What is 173 multiplied by 219? Reply with the integer.",
83
+ providerOptions: { reasoningEffort: "low" },
84
+ generation: { maxTokens: 1024 },
85
+ })
86
+ ```
87
+
88
+ `meta.chat("muse-spark-1.3")` selects Chat Completions; `meta.messages("muse-spark-1.3")` selects
89
+ the Anthropic-compatible Messages API. All use `https://api.meta.ai/v1`. The package entrypoints
90
+ `@opencode/ai/providers/meta/responses`, `meta/chat`, and `meta/messages` expose `model(modelID, settings)`.
91
+
92
+ [Muse Spark](https://dev.meta.ai/docs/models) supports `minimal`, `low`, `medium`, `high`, and
93
+ `xhigh` reasoning effort; standard-tier 1.3 also supports `max`. Omitting effort uses the model's
94
+ default. Muse Spark always reasons and rejects `none`. The output-token budget includes private reasoning.
95
+
96
+ Responses defaults to `store: false` and `include: ["reasoning.encrypted_content"]`. Preserve
97
+ `response.message` along with matching `Message.tool(...)` results in subsequent requests to replay
98
+ reasoning through tool loops. Optional `reasoningSummary: "auto"` requests a readable summary.
99
+ For server-managed history, override `store: true, include: []` and send the response ID through
100
+ `http: { body: { previous_response_id: responseID } }` with only the new input.
101
+ Chat Completions redacts private reasoning and cannot carry it between calls.
102
+ Responses and Chat support only `toolChoice: "auto"` (the default). Messages also accepts `"none"`;
103
+ its documented forced `"any"` choice currently returns HTTP 400. Messages defaults to adaptive thinking
104
+ with `display: "omitted"`, preserving encrypted `redacted_thinking` in `response.message`. Use
105
+ `providerOptions: { effort: "low" }` for depth or `thinking: { type: "enabled", budgetTokens: 1024 }`
106
+ for budget compatibility (with `generation.maxTokens > 1024`).
107
+
108
+ Add `tools: [Meta.webSearch()]` to a Spark Responses or Messages request for hosted web search.
109
+ Responses exposes hosted results and URL citations in text-part `providerMetadata.meta.annotations`.
110
+ To include search result lists, set `include: ["reasoning.encrypted_content", "web_search_call.results"]`.
111
+ Messages exposes hosted search calls; the recorded Messages API stream does not supply structured
112
+ citations or separate result blocks. Retain `response.message` for either API's continuation.
113
+
114
+ Use `Image.generate` for one-off generation or editing:
115
+
116
+ ```ts
117
+ import { Image, ImageInput } from "@opencode/ai"
118
+
119
+ const generation = Image.generate({
120
+ model: meta.image("muse-image-1.0"),
121
+ prompt: "A flat black square on a white background.",
122
+ options: { n: 1, reasoningStrength: "low" },
123
+ })
124
+
125
+ const edit = Image.generate({
126
+ model: meta.image("muse-image-1.0"),
127
+ prompt: "Make the square purple.",
128
+ images: [ImageInput.bytes(imageBytes, "image/webp")],
129
+ options: { outputFormat: "png", reasoningStrength: "low" },
130
+ })
131
+ ```
132
+
133
+ The default image format is WEBP; `outputFormat` also accepts PNG/JPEG and `responseFormat: "url"`
134
+ returns a signed URL. `size` is an aspect-ratio hint. For conversational images, select
135
+ `meta.responses("muse-image-1.0")` with `tools: [Meta.imageGeneration({ reasoningStrength: "low" })]`.
136
+ Generated images are provider-executed tool results with file content. Retain `response.message` to
137
+ replay the signed image handle on the next request. Muse Image accepts only the `image_generation` tool.
138
+
139
+ Meta Responses is explicitly HTTP/SSE-only and does not use WebSockets, even when a caller supplies
140
+ `StreamOptions.webSocket`. The public `/v1/responses` endpoint rejects WebSocket upgrades with HTTP 405 (`Allow: POST`).
141
+
142
+ ## Image generation
143
+
144
+ Use `Image.generate` with an image model for direct asset generation:
145
+
146
+ ```ts
147
+ import { Image, ImageInput } from "@opencode/ai"
148
+ import { OpenAI } from "@opencode/ai/providers"
149
+
150
+ const program = Effect.gen(function* () {
151
+ const response = yield* Image.generate({
152
+ model: OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY }).image("gpt-image-2"),
153
+ prompt: "A robot tending a rooftop garden",
154
+ options: {
155
+ n: 2,
156
+ size: "1024x1024",
157
+ quality: "high", // inferred from the OpenAI image model
158
+ outputFormat: "webp",
159
+ future_option: true, // unknown native options pass through unchanged
160
+ },
161
+ })
162
+
163
+ return response.images // GeneratedImage[] with owned bytes or a provider URL
164
+ })
165
+ ```
166
+
167
+ Pass ordered image inputs to the same method for editing, composition, or image-conditioned generation:
168
+
169
+ ```ts
170
+ const response =
171
+ yield *
172
+ Image.generate({
173
+ model,
174
+ prompt: "Combine these product photos into one studio scene",
175
+ images: [
176
+ ImageInput.bytes(firstBytes, "image/png"),
177
+ ImageInput.url("https://example.com/second.webp"),
178
+ ImageInput.file("file_123"),
179
+ ],
180
+ options,
181
+ http,
182
+ })
183
+ ```
184
+
185
+ `ImageInput.fileUri(uri, mediaType)` represents provider file URIs such as Gemini Files. Raw strings are not
186
+ accepted as image inputs, avoiding ambiguity between base64, URLs, and provider IDs. Empty or omitted `images`
187
+ uses text-to-image generation; a non-empty array selects the provider's edit behavior without enforcing provider
188
+ image-count limits locally. `images` is the only common image-editing field. OpenAI uses multipart for byte/data-URL
189
+ edits and its JSON reference body for URL or file-ID edits. Its provider-specific `options.mask` accepts an
190
+ `ImageInput` for inpainting:
191
+
192
+ ```ts
193
+ yield *
194
+ Image.generate({
195
+ model: OpenAI.configure({ apiKey }).image("gpt-image-2"),
196
+ prompt,
197
+ images: [ImageInput.bytes(sourceBytes, "image/png")],
198
+ options: { mask: ImageInput.bytes(maskBytes, "image/png") },
199
+ })
200
+ ```
201
+
202
+ The OpenAI adapter extracts this helper value into the edit request's native `mask` field rather than passing the
203
+ tagged `ImageInput` object through as an ordinary option. On multipart requests, `http.body` can override option
204
+ fields but not structural `model`, `prompt`, `image[]`, or `mask` fields, and the transport owns the multipart
205
+ `Content-Type` boundary. For JSON requests, `http.body` remains the final raw-native overlay. Gemini does not fetch
206
+ public HTTP URLs, and hosted Z.ai image generation does not accept image inputs. These cases fail with
207
+ `InvalidRequest` before network I/O.
208
+
209
+ Provider-native image options belong to each request. Raw `http.body` fields have final precedence over them:
210
+
211
+ ```ts
212
+ const model = OpenAI.configure({ apiKey }).image("gpt-image-2")
213
+
214
+ yield *
215
+ Image.generate({
216
+ model,
217
+ prompt,
218
+ options: { quality: "medium" },
219
+ http,
220
+ })
221
+ ```
222
+
223
+ xAI image models use the same request API with xAI-native controls:
224
+
225
+ ```ts
226
+ yield *
227
+ Image.generate({
228
+ model: XAI.configure({ apiKey }).image("any-model-id"),
229
+ prompt,
230
+ options: {
231
+ n: 2,
232
+ aspectRatio: "16:9",
233
+ resolution: "1k",
234
+ responseFormat: "b64_json",
235
+ future_option: true,
236
+ },
237
+ http,
238
+ })
239
+ ```
240
+
241
+ Google's current Gemini image models use the same direct API:
242
+
243
+ ```ts
244
+ import { Google } from "@opencode/ai/providers"
245
+
246
+ const googleProgram = Effect.gen(function* () {
247
+ const response = yield* Image.generate({
248
+ model: Google.configure({ apiKey }).image("any-model-id"),
249
+ prompt: "A robot tending a rooftop garden",
250
+ options: {
251
+ aspectRatio: "16:9",
252
+ imageSize: "2K",
253
+ seed: 42,
254
+ thinkingLevel: "HIGH",
255
+ includeThoughts: true,
256
+ futureOption: true,
257
+ },
258
+ http,
259
+ })
260
+
261
+ return response.images
262
+ })
263
+ ```
264
+
265
+ Google image options are request-scoped and inferred from the selected model. Known fields autocomplete while
266
+ future string values and arbitrary native Gemini `generationConfig` fields remain available. Native fields override
267
+ their mapped aliases, and `http.body` is the final deep overlay. The selected model ID is sent to Gemini
268
+ `generateContent` without a local allowlist.
269
+
270
+ Z.ai image models infer open Z.ai-native options from the selected model:
271
+
272
+ ```ts
273
+ yield *
274
+ Image.generate({
275
+ model: ZAI.configure({ apiKey }).image("any-model-id"),
276
+ prompt,
277
+ options: {
278
+ quality: "hd",
279
+ userID: "user-123",
280
+ future_option: true,
281
+ },
282
+ http,
283
+ })
284
+ ```
285
+
286
+ Z.ai does not include trustworthy MIME metadata for output URLs, so generated images use
287
+ `application/octet-stream`. Output URLs expire after 30 days; download and persist them promptly if they must
288
+ remain available.
289
+
290
+ Conversational image generation remains part of the LLM interaction. OpenAI Responses exposes it through its hosted image tool:
291
+
292
+ ```ts
293
+ const program = Effect.gen(function* () {
294
+ const response = yield* LLM.generate(
295
+ LLM.request({
296
+ model: OpenAI.configure({ apiKey }).responses("gpt-5"),
297
+ prompt: "Design a solarpunk rooftop garden, then show me.",
298
+ tools: [OpenAI.imageGeneration({ quality: "high" })],
299
+ }),
300
+ )
301
+
302
+ return response.message
303
+ })
304
+ ```
305
+
306
+ The hosted result is represented as a provider-executed tool call and tool result. Its image is a `file` content item with a data URI, so retaining `response.message` preserves the generated image for continuation.
307
+
308
+ ## Public API
309
+
310
+ - **`LLM.request({...})`** — build a provider-neutral `LLMRequest`. Accepts ergonomic inputs (`system: string`, `prompt: string`) that normalize into the canonical Schema classes.
311
+ - **`LLM.generate` / `LLM.stream`** — re-exported from `LLMClient` for one-import use.
312
+ - **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model.
313
+ - **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
314
+ - **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
315
+ - **`Image.generate({...})`** — generate images through a provider-neutral image request and response model.
316
+ - **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`.
317
+
318
+ ## Testing
319
+
320
+ Use the deterministic test client from `@opencode/ai/testing` to script provider-neutral responses and inspect
321
+ the requests sent by code under test:
322
+
323
+ ```ts
324
+ import { Effect } from "effect"
325
+ import { TestLLM } from "@opencode/ai/testing"
326
+
327
+ const programWithTestClient = Effect.gen(function* () {
328
+ const test = yield* TestLLM.Test
329
+ yield* test.push(TestLLM.text("Hello from the test model", "text-1"))
330
+ const result = yield* program
331
+ console.log(yield* test.requests())
332
+ return result
333
+ }).pipe(Effect.provide(TestLLM.testLayer()))
334
+ ```
335
+
336
+ `testLayer()` provides the same object under `LLMClient.Service` and `TestLLM.Test`. Production consumes the
337
+ normal client; tests use the additional controls. Each layer build has fresh state.
338
+
339
+ - `test.push(...)` queues one-shot responses in execution order. Each argument is one response.
340
+ - `test.always(response)` installs a repeatable fallback. The layer's `fallback` option sets its initial value.
341
+ - `test.serve(request => response)` installs a request-dependent fallback. `always` and `serve` replace each
342
+ other without changing queued replies; queued replies take precedence.
343
+ - `test.requests()` returns an array snapshot. `transformRequest` changes only the recorded observation;
344
+ `serve` receives the original canonical request.
345
+ - `test.wait(count)` waits for request arrivals, not output or completion, and supports concurrent waiters.
346
+ - `test.gate()` returns a scoped gate with countable `started` notifications and a `release` Effect. Release
347
+ unblocks all requests captured by that gate; closing its scope also releases it. Effect-aware test runners
348
+ already provide Scope.
349
+
350
+ Constructing `stream()` or `generate()` does not record a request, invoke a responder, or consume a script.
351
+ Each execution does. An exhausted queue without a fallback defects immediately rather than waiting for a
352
+ future reply.
353
+
354
+ Generation responses remain canonical event arrays or arbitrary `Stream<LLMEvent, AIError>` values. The client consumes
355
+ supplied streams directly, preserving failure identity, finalizers, incomplete output, and post-finish tails;
356
+ it does not repair or truncate them.
357
+
358
+ For explicit compaction, script a `CompactionResponse` through `push`, `always`, or `serve`. Its `replacement` contains the next context window, including retained user messages. The client returns that result and usage directly, with the same lazy request recording and gates. Generation and compaction reject fixtures for the wrong operation instead of converting between response shapes.
359
+
360
+ 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.
361
+
362
+ The published legacy `Service`, `layer`, `clientLayer`, and module-level controls remain available as adapters
363
+ over the same implementation, including the legacy live `requests` array. New tests should use `Test` and
364
+ `testLayer`.
365
+
366
+ ## Provider compaction
367
+
368
+ Compaction is opt-in. The package supports automatic compaction in OpenAI/Azure Responses and Anthropic Messages (including Claude on Vertex), and explicit compaction calls in OpenAI/Azure/xAI Responses. Model and deployment support still depends on the provider.
369
+
370
+ This is different from prompt caching, server-side history storage, or truncation. Compaction returns provider-owned context that must be replayed to continue the conversation.
371
+
372
+ ### Explicit compaction
373
+
374
+ `LLMClient.compact(request)` (equivalently, `{ mechanism: "endpoint" }`) is the caller-controlled operation for OpenAI, Azure, and xAI Responses. It performs exactly one HTTP call to `/responses/compact`, using the selected route's endpoint, credentials, query, and HTTP middleware. It returns a `CompactionResponse` with `replacement: Message[]` and optional `usage`, not a normal generation response. This mechanism does not accept a WebSocket executor.
375
+
376
+ Prefer this operation, where supported, when the application owns compaction policy and durable context updates.
377
+
378
+ ```ts
379
+ const result = yield * LLMClient.compact(request)
380
+ const next = LLMRequest.update(request, {
381
+ messages: result.replacement,
382
+ })
383
+ const response = yield * LLMClient.generate(next)
384
+ ```
385
+
386
+ `replacement` replaces the complete input window. Do not append it to the original transcript or extract only the encrypted item: the provider may retain additional messages in its output. Retained user and assistant messages remain ordinary messages with typed text, media, or reasoning parts, in their original order. Provider-specific message IDs, status, and phase use `providerMetadata`, not a raw output array hidden in an assistant message. Unsupported returned item types fail explicitly.
387
+
388
+ The selected model carries explicit-compaction capability through request construction and updates. Calls using unsupported routes fail type checking. When the model is selected dynamically, narrow the request with `LLMClient.canCompact(request)` before calling `LLMClient.compact`; a model or route switch does not inherit the old capability. Runtime validation still rejects unsupported calls from untyped consumers. Capability describes the route's API, not whether every model or custom deployment supports the operation.
389
+
390
+ Generation-only body overlays such as `stream` and `store` are not sent to the compact endpoint. Supported compact controls such as service tier and prompt-cache settings preserve request defaults and HTTP-overlay precedence. Retained image and file detail settings survive serialization and replay.
391
+
392
+ The input must still fit the model's context window. Explicit compaction is not an overflow-recovery operation. Anthropic does not expose this operation in this package; its in-band compaction remains available below. Compatible routes do not inherit an explicit compact endpoint simply because they use a Responses protocol.
393
+
394
+ ### Streamed checkpoint compaction
395
+
396
+ OpenAI Responses also exposes a separate, explicitly selected mechanism:
397
+
398
+ ```ts
399
+ const result =
400
+ yield *
401
+ LLMClient.compact(request, {
402
+ mechanism: "trigger",
403
+ webSocket, // Optional: without it, the request uses HTTP/SSE.
404
+ })
405
+
406
+ result.checkpoint // Successful encrypted CompactionPart.
407
+ result.responseID
408
+ result.usage
409
+ ```
410
+
411
+ This appends a native `compaction_trigger` control item to the full input and sends a normal Responses request, with tools and instructions retained, `stream: true`, `store: false`, and parallel tool calls enabled. It removes normal-answer text/output-format controls, forced tool choices, output-token/tool-call limits, and automatic `context_management`. Body overlays cannot replace `input` or supply `previous_response_id`/`conversation`; the complete canonical history is required for safe stateless replay. Request metadata, auth, headers, query parameters, service tier, and supported prompt-cache settings are preserved.
412
+
413
+ Only a successful `response.completed` with a response ID and exactly one logical encrypted checkpoint succeeds. Repeated item events are correlated by ID/output slot, including ID-less checkpoints. Other output is ignored, not returned as assistant text or dispatched as tools. Failed, incomplete, malformed, and interrupted responses return errors rather than partial checkpoints.
414
+
415
+ The result is **not a replacement window**. The caller selects retained history, combines it with `result.checkpoint`, and durably installs it before continuing. The operation does not choose a retention budget, prune messages, or modify the original request.
416
+
417
+ The supplied WebSocket executor can reuse a compatible append baseline for the compaction request. On completion the protocol supplies no continuation checkpoint, clearing the old baseline so the next generation sends the newly installed window in full. Validation occurs before transport completion is acknowledged. There is no operation-level retry or fallback to `/responses/compact`; existing safe transport fallback may use SSE, with full history and no connection-local response ID.
418
+
419
+ Trigger support is separate from endpoint support. Only the OpenAI Responses route advertises it; Azure, xAI, Chat, and compatible Responses routes do not inherit it. Untyped calls still fail before sending: missing route capabilities return `UnsupportedOperation`, while unknown mechanism names and invalid inputs return `InvalidRequest`. Dynamic callers must narrow for the selected mechanism:
420
+
421
+ ```ts
422
+ if (LLMClient.canCompact(request, { mechanism: "trigger" })) {
423
+ const result = yield * LLMClient.compact(request, { mechanism: "trigger" })
424
+ }
425
+ ```
426
+
427
+ This capability describes protocol implementation, **not universal availability on OpenAI API deployments**. The host application owns subscription/deployment eligibility, OAuth, endpoint selection, and deployment-specific headers. Local protocol/socket tests do not establish live provider support.
428
+
429
+ ### Advanced: in-band compaction
430
+
431
+ `providerOptions.contextManagement` lets the provider decide when to compact during an ordinary `generate` or `stream` call. This is an advanced option for callers that own persistence and recovery: persist the complete assistant message, including its checkpoint, before continuing. Enabling the option does not provide durable checkpoint storage, interruption recovery, or model-switch policy. Keep the prior context until a successful checkpoint has been persisted.
432
+
433
+ Inside an `Effect.gen`, enable OpenAI compaction with typed provider options:
434
+
435
+ ```ts
436
+ import { LLM, LLMClient, LLMRequest, Message } from "@opencode/ai"
437
+ import { OpenAI } from "@opencode/ai/providers"
438
+
439
+ const request = LLM.request({
440
+ model: OpenAI.configure({ apiKey }).responses("gpt-5.3-codex"),
441
+ messages,
442
+ providerOptions: {
443
+ contextManagement: [{ type: "compaction", compactThreshold: 200_000 }],
444
+ },
445
+ })
446
+ const response = yield * LLMClient.generate(request)
447
+ const next = LLMRequest.update(request, {
448
+ messages: [...request.messages, response.message, Message.user("Continue")],
449
+ })
450
+ ```
451
+
452
+ `store: false` remains the default. Keep the entire `response.message`, not just `response.text`. Compaction events become ordered `CompactionPart`s alongside text and reasoning. The conversation contains everything needed to continue; there is no separate replay object or hidden provider transcript.
453
+
454
+ A compaction part has `provider` and exactly one representation: `encrypted` for Responses, or `text` for Anthropic. Responses also preserves the optional checkpoint `id`. These fields survive message serialization without becoming visible assistant text. Sending a checkpoint to another provider or an incompatible API fails rather than silently losing context.
455
+
456
+ ```ts
457
+ import { CompactionPart, ProviderID } from "@opencode/ai"
458
+
459
+ CompactionPart.make({ provider: ProviderID.make("openai"), id: "cmp_123", encrypted: "..." })
460
+ CompactionPart.make({ provider: ProviderID.make("anthropic"), text: "Summary of the conversation..." })
461
+ ```
462
+
463
+ For Anthropic, use:
464
+
465
+ ```ts
466
+ providerOptions: {
467
+ contextManagement: {
468
+ edits: [{
469
+ type: "compact_20260112",
470
+ trigger: { type: "input_tokens", value: 150_000 },
471
+ pauseAfterCompaction: true,
472
+ instructions: "Summarize the task and decisions. Do not call tools while summarizing.",
473
+ }],
474
+ },
475
+ }
476
+ ```
477
+
478
+ - The trigger is optional (provider default: 150,000 tokens), with a minimum of 50,000.
479
+ - Custom instructions replace Anthropic's default summarization instructions.
480
+ - The route adds `compact-2026-01-12` to existing beta headers, including when replaying a checkpoint without enabling new compactions.
481
+ - A pause is exposed as `response.finishReason.raw === "compaction"`. It occurs only if the threshold triggers compaction: `pauseAfterCompaction` does not mean "compact now". The caller explicitly issues the next request; the package never automatically resumes.
482
+ - Anthropic can return a compaction block with `content: null` when summarization fails. This becomes a compaction part with `text: null`, which is **not** a successful replacement for prior history. The package never prunes history automatically.
483
+ - `Usage` totals include all reported Anthropic `usage.iterations`, including compaction. `contextTokens` separately reports the final message iteration's inclusive input size, when available. A compaction-only pause does not report a post-compaction context size. Raw iteration usage remains in `providerMetadata`.
484
+
485
+ ### Recording tests
486
+
487
+ Tests cover serialized round trips, real local HTTP plus a tool loop, WebSocket recovery, provider errors, malformed blocks, and usage accounting. Live provider tests are gated by `RECORD=true` and the relevant API keys:
488
+
489
+ ```sh
490
+ # Run from packages/ai. Only records the selected new cassette group.
491
+ RECORD=true RECORDED_PREFIX=openai-compaction bun test test/provider/compaction.recorded.test.ts
492
+ RECORD=true RECORDED_PREFIX=xai-compaction bun test test/provider/compaction.recorded.test.ts
493
+ RECORD=true RECORDED_PREFIX=anthropic-compaction bun test test/provider/compaction.recorded.test.ts
494
+ ```
495
+
496
+ Provider references: [OpenAI](https://developers.openai.com/api/docs/guides/compaction), [Azure](https://learn.microsoft.com/en-us/azure/foundry/openai/how-to/responses#server-side-compaction), [Anthropic](https://platform.claude.com/docs/en/build-with-claude/compaction), [xAI](https://docs.x.ai/developers/advanced-api-usage/context-compaction).
497
+
498
+ ## Caching
499
+
500
+ Prompt caching is **on by default**. Every `LLMRequest` resolves to `cache: "auto"` unless the caller opts out with `cache: "none"`. Each protocol translates `CacheHint`s to its wire format (`cache_control` on Anthropic, `cachePoint` on Bedrock; OpenAI and Gemini do implicit caching server-side and don't need inline markers — auto is a no-op there).
501
+
502
+ ### Auto placement
503
+
504
+ `"auto"` places up to four breakpoints — the last tool definition, the first system part, the last system part when distinct, and the final message boundary. These expose successively larger reusable prefixes for tool definitions, system instructions, and the active conversation. The rolling final-message boundary advances on every request so recent conversation prefixes remain reusable during tool loops.
505
+
506
+ Tools precede every system and conversation block in the provider prefix, so tool definitions must remain byte-stable and deterministically ordered for downstream breakpoints to remain reusable.
507
+
508
+ Requests below a provider's minimum cacheable size simply do not produce a reusable cache entry.
509
+
510
+ ### Opting out
511
+
512
+ ```ts
513
+ LLM.request({
514
+ model,
515
+ system,
516
+ prompt: "one-off question",
517
+ cache: "none",
518
+ })
519
+ ```
520
+
521
+ ### Granular policy
522
+
523
+ ```ts
524
+ cache: {
525
+ tools?: boolean,
526
+ system?: boolean,
527
+ messages?: "latest-user-message" | "latest-assistant" | { tail: number },
528
+ ttlSeconds?: number, // ≥ 3600 → 1h on Anthropic/Bedrock; else 5m
529
+ }
530
+ ```
531
+
532
+ ### Manual hints
533
+
534
+ Inline `CacheHint` on any text / system / tool / tool-result part overrides automatic placement. The auto policy preserves manual hints, counts them against Anthropic and Bedrock's four-breakpoint limit, and only fills the remaining slots.
535
+
536
+ ```ts
537
+ LLM.request({
538
+ model,
539
+ system: [
540
+ { type: "text", text: "stable system prompt", cache: { type: "ephemeral" } },
541
+ ],
542
+ ...
543
+ })
544
+ ```
545
+
546
+ ### Provider behavior table
547
+
548
+ | Protocol | `cache: "auto"` |
549
+ | ----------------------- | ------------------------------------------------------------------------- |
550
+ | Anthropic Messages | emits up to 4 `cache_control` markers (4-breakpoint cap enforced) |
551
+ | Bedrock Converse | emits up to 4 `cachePoint` blocks (4-breakpoint cap enforced) |
552
+ | OpenRouter | emits up to 4 `cache_control` markers |
553
+ | OpenAI Chat / Responses | no-op (implicit caching above 1024 tokens) |
554
+ | Gemini | no-op (implicit caching on 2.5+; explicit `CachedContent` is out-of-band) |
555
+
556
+ Normalized cache usage is read back into `response.usage.cacheReadInputTokens` and `cacheWriteInputTokens` across every provider.
557
+
558
+ ## Providers
559
+
560
+ Provider facades configure endpoint/auth/deployment details first, then expose model selectors that take only a model or deployment id. The selected model carries the executable route value used at runtime.
561
+
562
+ ```ts
563
+ import { OpenAI, CloudflareAIGateway } from "@opencode/ai/providers"
564
+
565
+ const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY }).responses("gpt-4o-mini")
566
+ const gateway = CloudflareAIGateway.configure({
567
+ accountId: process.env.CLOUDFLARE_ACCOUNT_ID,
568
+ gatewayApiKey: process.env.CLOUDFLARE_API_TOKEN,
569
+ }).model("workers-ai/@cf/meta/llama-3.1-8b-instruct")
570
+ ```
571
+
572
+ Included LLM providers: OpenAI, Anthropic, Google (Gemini), Google Vertex, Amazon Bedrock, Azure OpenAI, Baseten, Cerebras, Cloudflare AI Gateway, Cloudflare Workers AI, DeepInfra, DeepSeek, Fireworks, Groq, Mistral, OpenRouter, TogetherAI, and xAI. Z.ai currently exposes image generation. Generic Chat Completions, Responses, and Anthropic Messages-compatible entrypoints support custom endpoints.
573
+
574
+ Each named provider owns its module, endpoint, authentication, and route setup. Providers with the same wire format compose the shared protocol directly:
575
+
576
+ ```ts
577
+ import { DeepSeek, Fireworks } from "@opencode/ai/providers"
578
+
579
+ const deepseek = DeepSeek.configure({ apiKey }).model("deepseek-chat")
580
+ const fireworks = Fireworks.configure({ apiKey }).model("accounts/fireworks/models/my-model")
581
+ ```
582
+
583
+ The former `OpenAICompatible.baseten`, `.cerebras`, `.deepinfra`, `.deepseek`, `.fireworks`, `.groq`, and `.togetherai` presets are replaced by the top-level `Baseten`, `Cerebras`, `DeepInfra`, `DeepSeek`, `Fireworks`, `Groq`, and `TogetherAI` exports. Use `CloudflareAIGateway` and `CloudflareWorkersAI` directly; each has its own module. `OpenAICompatible` configures generic endpoints with an explicit `baseURL`.
584
+
585
+ ### Provider entrypoints
586
+
587
+ Provider modules are available through dedicated exports from `@opencode/ai`. Each LLM entrypoint exports `model(modelID, settings)`, where `settings` contains provider configuration plus common `headers` and `body` overlays.
588
+
589
+ ```ts
590
+ import { model } from "@opencode/ai/providers/openai/responses"
591
+
592
+ const selected = model("gpt-5", {
593
+ apiKey: process.env.OPENAI_API_KEY,
594
+ headers: { "x-application": "example" },
595
+ })
596
+ ```
597
+
598
+ APIs have separate entrypoints:
599
+
600
+ - `@opencode/ai/providers/openai/chat`
601
+ - `@opencode/ai/providers/openai/responses`
602
+ - `@opencode/ai/providers/openai-compatible/responses`
603
+ - `@opencode/ai/providers/anthropic-compatible`
604
+ - `@opencode/ai/providers/google-vertex/gemini`
605
+ - `@opencode/ai/providers/google-vertex/chat`
606
+ - `@opencode/ai/providers/google-vertex/responses`
607
+ - `@opencode/ai/providers/google-vertex/messages`
608
+
609
+ OpenAI Responses has one semantic route and uses HTTP by default. Advanced callers may supply a per-call WebSocket channel executor through `StreamOptions`; transport policy does not change provider settings, model identity, or route identity. The provider-neutral Open Responses implementation owns the reusable WebSocket request and event contract, while each provider opts in with its own handshake and connection policy. Azure follows the same Chat/Responses split at `providers/azure/chat` and `providers/azure/responses`. Generic OpenAI-compatible Chat remains at `providers/openai-compatible`; the Responses adapter at `providers/openai-compatible/responses` uses the provider-neutral Open Responses protocol. OpenAI Responses extends that baseline with OpenAI tools, event variants, metadata, and defaults. Generic Anthropic Messages-compatible providers use `providers/anthropic-compatible`, which the named Anthropic provider composes. Google Gemini and Amazon Bedrock expose their single native API through their existing provider paths.
610
+
611
+ Vertex Gemini, Vertex Chat, Vertex Responses, and Vertex Messages are separate API entrypoints. All accept `project`, `location`, and an optional `accessToken`; when no explicit token or auth override is supplied they lazily use Google Application Default Credentials. Vertex Gemini instead selects express mode when `apiKey` or `GOOGLE_VERTEX_API_KEY` is present. Vertex Chat targets MaaS models through the OpenAI-compatible Chat Completions endpoint, while Vertex Responses targets Grok models and defaults `store` to `false` as required by Vertex. `providers/google-vertex` remains the default alias for `providers/google-vertex/gemini`.
612
+
613
+ Tuned Vertex Gemini deployments use model ids shaped like `endpoints/1234567890` and require OAuth or ADC; Vertex express-mode API keys support publisher models only.
614
+
615
+ ```ts
616
+ import { model } from "@opencode/ai/providers/google-vertex/gemini"
617
+
618
+ model("gemini-3.5-flash", { project: "my-project", location: "global" })
619
+ ```
620
+
621
+ ```ts
622
+ import { model } from "@opencode/ai/providers/google-vertex/chat"
623
+
624
+ model("deepseek-ai/deepseek-v3.2-maas", { project: "my-project", location: "global" })
625
+ ```
626
+
627
+ ```ts
628
+ import { model } from "@opencode/ai/providers/google-vertex/responses"
629
+
630
+ model("xai/grok-4.20-reasoning", { project: "my-project", location: "global" })
631
+ ```
632
+
633
+ ```ts
634
+ import { model } from "@opencode/ai/providers/google-vertex/messages"
635
+
636
+ model("claude-sonnet-4-6", { project: "my-project", location: "global" })
637
+ ```
638
+
639
+ Additional provider entrypoints include:
640
+
641
+ - `@opencode/ai/providers/baseten`
642
+ - `@opencode/ai/providers/deepseek`
643
+ - `@opencode/ai/providers/fireworks`
644
+ - `@opencode/ai/providers/cloudflare-ai-gateway`
645
+ - `@opencode/ai/providers/cloudflare-workers-ai`
646
+
647
+ ## Provider options & HTTP overlays
648
+
649
+ Request options in order of stability:
650
+
651
+ 1. **`generation`** — portable knobs (`maxTokens`, `temperature`, `topP`, `topK`, penalties, seed, stop).
652
+ 2. **`promptCacheKey`** — stable cache affinity lowered by every protocol that supports it.
653
+ 3. **`providerOptions: { ... }`** — flat options inferred from the selected model (OpenAI `store`, Anthropic `thinking`, Gemini `thinkingConfig`, OpenRouter routing).
654
+ 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.
655
+
656
+ Route/provider defaults are overridden by request-level values for each axis.
657
+
658
+ The selected model supplies the provider-specific option type, so per-request overrides stay flat while the canonical runtime request remains provider-neutral:
659
+
660
+ ```ts
661
+ LLM.request({
662
+ model,
663
+ prompt,
664
+ providerOptions: {
665
+ reasoningEffort: "low",
666
+ },
667
+ })
668
+ ```
669
+
670
+ ## Routes
671
+
672
+ Compose a route with `Route.make({ protocol, endpoint, auth, framing, ... })`. The route owns endpoint/auth/framing and the protocol owns body construction plus stream parsing. Transports receive the route's endpoint and auth when preparing requests. Unsupported request shapes fail during protocol lowering.
673
+
674
+ ## Effect
675
+
676
+ This package is built on Effect. Public methods return `Effect` or `Stream`; provide `LLMClient.layer` for LLM dispatch and `ImageClient.layer` for image dispatch, then import the provider/protocol modules for the routes you use. The example at `example/tutorial.ts` is a runnable walkthrough.
677
+
678
+ ## See also
679
+
680
+ - `AGENTS.md` — architecture, route construction, contributor guide
681
+ - `example/tutorial.ts` — runnable end-to-end walkthrough
682
+ - `test/provider/*.test.ts` — fixture-first protocol tests; `*.recorded.test.ts` files cover live cassettes