@opencode/ai 0.0.0-dev-21920 → 0.0.0-dev-44

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 (166) hide show
  1. package/README.md +61 -19
  2. package/dist/ai-client.d.ts +2 -2
  3. package/dist/cache-policy.d.ts +4 -0
  4. package/dist/cache-policy.js +20 -6
  5. package/dist/decision-client.d.ts +3 -3
  6. package/dist/decision.d.ts +4 -1
  7. package/dist/decision.js +3 -0
  8. package/dist/effect.d.ts +4 -5
  9. package/dist/effect.js +2 -3
  10. package/dist/experimental/realtime.d.ts +3 -2
  11. package/dist/image-client.d.ts +1 -1
  12. package/dist/image.js +1 -0
  13. package/dist/index.d.ts +6 -0
  14. package/dist/llm.d.ts +3 -0
  15. package/dist/media-client.d.ts +2 -1
  16. package/dist/media-model.d.ts +3 -0
  17. package/dist/media-model.js +4 -1
  18. package/dist/protocols/alibaba-chat.d.ts +4 -0
  19. package/dist/protocols/alibaba-messages.d.ts +19 -19
  20. package/dist/protocols/alibaba-responses.d.ts +3 -3
  21. package/dist/protocols/anthropic-messages.d.ts +59 -59
  22. package/dist/protocols/anthropic-messages.js +3 -5
  23. package/dist/protocols/bedrock-converse.d.ts +110 -15
  24. package/dist/protocols/bedrock-converse.js +112 -15
  25. package/dist/protocols/bedrock-event-stream.js +1 -0
  26. package/dist/protocols/meta-messages.d.ts +19 -19
  27. package/dist/protocols/meta-messages.js +2 -1
  28. package/dist/protocols/open-responses.d.ts +3 -0
  29. package/dist/protocols/openai-chat.d.ts +588 -1
  30. package/dist/protocols/openai-chat.js +7 -2
  31. package/dist/protocols/openai-compatible-chat.d.ts +6 -2
  32. package/dist/protocols/openai-compatible-responses.d.ts +3 -3
  33. package/dist/protocols/openai-responses.d.ts +24 -0
  34. package/dist/protocols/openai-responses.js +5 -0
  35. package/dist/protocols/utils/bedrock-cache.d.ts +2 -2
  36. package/dist/protocols/utils/bedrock-cache.js +7 -6
  37. package/dist/protocols/utils/cache.d.ts +14 -3
  38. package/dist/protocols/utils/cache.js +11 -4
  39. package/dist/protocols/utils/gemini-json-schema.d.ts +5 -0
  40. package/dist/protocols/utils/gemini-json-schema.js +3 -3
  41. package/dist/protocols/utils/tool-schema.js +15 -5
  42. package/dist/protocols/utils/tool-stream.d.ts +9 -0
  43. package/dist/protocols/venice-chat.d.ts +3 -0
  44. package/dist/protocols/venice-chat.js +1 -1
  45. package/dist/protocols/zai-chat.d.ts +4 -0
  46. package/dist/protocols/zai-messages.d.ts +19 -19
  47. package/dist/providers/alibaba/images.d.ts +2 -0
  48. package/dist/providers/alibaba/images.js +1 -0
  49. package/dist/providers/alibaba.d.ts +26 -21
  50. package/dist/providers/alibaba.js +12 -8
  51. package/dist/providers/amazon-bedrock-mantle.d.ts +23 -19
  52. package/dist/providers/amazon-bedrock.d.ts +34 -14
  53. package/dist/providers/amazon-bedrock.js +11 -11
  54. package/dist/providers/anthropic-compatible.d.ts +19 -19
  55. package/dist/providers/anthropic.d.ts +19 -19
  56. package/dist/providers/azure/images.d.ts +2 -0
  57. package/dist/providers/azure/images.js +1 -0
  58. package/dist/providers/azure.d.ts +15 -1
  59. package/dist/providers/azure.js +19 -1
  60. package/dist/providers/baseten/decisions.d.ts +2 -0
  61. package/dist/providers/baseten/decisions.js +1 -0
  62. package/dist/providers/baseten.d.ts +13 -4
  63. package/dist/providers/baseten.js +15 -8
  64. package/dist/providers/cerebras.d.ts +8 -0
  65. package/dist/providers/cloudflare-ai-gateway/decisions.d.ts +2 -0
  66. package/dist/providers/cloudflare-ai-gateway/decisions.js +1 -0
  67. package/dist/providers/cloudflare-ai-gateway.d.ts +57 -40
  68. package/dist/providers/cloudflare-ai-gateway.js +11 -6
  69. package/dist/providers/cloudflare-workers-ai/decisions.d.ts +2 -0
  70. package/dist/providers/cloudflare-workers-ai/decisions.js +1 -0
  71. package/dist/providers/cloudflare-workers-ai/images.d.ts +2 -0
  72. package/dist/providers/cloudflare-workers-ai/images.js +1 -0
  73. package/dist/providers/cloudflare-workers-ai.d.ts +13 -3
  74. package/dist/providers/cloudflare-workers-ai.js +16 -7
  75. package/dist/providers/cohere.d.ts +8 -0
  76. package/dist/providers/deepinfra.d.ts +8 -0
  77. package/dist/providers/deepseek.d.ts +8 -0
  78. package/dist/providers/digitalocean/decisions.d.ts +2 -0
  79. package/dist/providers/digitalocean/decisions.js +1 -0
  80. package/dist/providers/digitalocean/images.d.ts +2 -0
  81. package/dist/providers/digitalocean/images.js +1 -0
  82. package/dist/providers/digitalocean.d.ts +21 -4
  83. package/dist/providers/digitalocean.js +25 -8
  84. package/dist/providers/fireworks.d.ts +8 -0
  85. package/dist/providers/google/images.d.ts +2 -0
  86. package/dist/providers/google/images.js +1 -0
  87. package/dist/providers/google-vertex/images.d.ts +2 -0
  88. package/dist/providers/google-vertex/images.js +1 -0
  89. package/dist/providers/google-vertex-chat.d.ts +4 -0
  90. package/dist/providers/google-vertex-messages.d.ts +19 -19
  91. package/dist/providers/google-vertex.d.ts +3 -1
  92. package/dist/providers/google-vertex.js +30 -13
  93. package/dist/providers/google.d.ts +5 -4
  94. package/dist/providers/google.js +15 -8
  95. package/dist/providers/groq.d.ts +8 -0
  96. package/dist/providers/meta.d.ts +23 -19
  97. package/dist/providers/minimax.d.ts +23 -19
  98. package/dist/providers/moonshot.d.ts +23 -19
  99. package/dist/providers/openai/images.d.ts +2 -0
  100. package/dist/providers/openai/images.js +1 -0
  101. package/dist/providers/openai-compatible/images.d.ts +2 -0
  102. package/dist/providers/openai-compatible/images.js +1 -0
  103. package/dist/providers/openai-compatible.d.ts +7 -1
  104. package/dist/providers/openai-compatible.js +21 -9
  105. package/dist/providers/openai.d.ts +18 -8
  106. package/dist/providers/openai.js +10 -2
  107. package/dist/providers/opencode/decisions.d.ts +2 -0
  108. package/dist/providers/opencode/decisions.js +1 -0
  109. package/dist/providers/opencode.d.ts +9 -4
  110. package/dist/providers/opencode.js +2 -1
  111. package/dist/providers/openrouter/decisions.d.ts +2 -0
  112. package/dist/providers/openrouter/decisions.js +1 -0
  113. package/dist/providers/openrouter/images.d.ts +2 -0
  114. package/dist/providers/openrouter/images.js +1 -0
  115. package/dist/providers/openrouter.d.ts +25 -4
  116. package/dist/providers/openrouter.js +31 -9
  117. package/dist/providers/togetherai.d.ts +8 -0
  118. package/dist/providers/typesafe-ai/decisions.d.ts +2 -0
  119. package/dist/providers/typesafe-ai/decisions.js +1 -0
  120. package/dist/providers/typesafe-ai.d.ts +9 -4
  121. package/dist/providers/typesafe-ai.js +2 -1
  122. package/dist/providers/venice.d.ts +3 -0
  123. package/dist/providers/vercel-ai-gateway/decisions.d.ts +2 -0
  124. package/dist/providers/vercel-ai-gateway/decisions.js +1 -0
  125. package/dist/providers/vercel-ai-gateway/images.d.ts +2 -0
  126. package/dist/providers/vercel-ai-gateway/images.js +1 -0
  127. package/dist/providers/vercel-ai-gateway.d.ts +9 -7
  128. package/dist/providers/vercel-ai-gateway.js +18 -10
  129. package/dist/providers/xai/images.d.ts +2 -0
  130. package/dist/providers/xai/images.js +1 -0
  131. package/dist/providers/xai.d.ts +9 -4
  132. package/dist/providers/xai.js +15 -8
  133. package/dist/providers/zai/images.d.ts +2 -0
  134. package/dist/providers/zai/images.js +1 -0
  135. package/dist/providers/zai-coding-plan.d.ts +23 -19
  136. package/dist/providers/zai.d.ts +9 -4
  137. package/dist/providers/zai.js +15 -8
  138. package/dist/route/client.d.ts +2 -2
  139. package/dist/route/client.js +15 -4
  140. package/dist/route/decision.d.ts +2 -1
  141. package/dist/route/decision.js +1 -0
  142. package/dist/route/executor.d.ts +1 -1
  143. package/dist/route/framing.d.ts +2 -0
  144. package/dist/route/index.d.ts +3 -0
  145. package/dist/route/index.js +3 -0
  146. package/dist/route/media.d.ts +5 -1
  147. package/dist/route/media.js +6 -2
  148. package/dist/route/transport/http.js +1 -0
  149. package/dist/route/transport/index.d.ts +1 -0
  150. package/dist/schema/events.d.ts +135 -6
  151. package/dist/schema/events.js +10 -0
  152. package/dist/schema/messages.d.ts +6 -2
  153. package/dist/schema/messages.js +3 -0
  154. package/dist/schema/options.d.ts +5 -3
  155. package/dist/schema/options.js +8 -3
  156. package/dist/speech-client.d.ts +1 -1
  157. package/dist/speech.js +2 -1
  158. package/dist/testing.d.ts +25 -24
  159. package/dist/testing.js +3 -21
  160. package/dist/transcription-client.d.ts +1 -1
  161. package/dist/transcription.js +1 -0
  162. package/dist/video-client.d.ts +1 -1
  163. package/dist/video.js +1 -0
  164. package/package.json +510 -8
  165. package/dist/provider.d.ts +0 -23
  166. package/dist/provider.js +0 -2
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @opencode/ai
2
2
 
3
- Schema-first APIs for text, images, video, speech, and transcription, built with Effect.
3
+ Schema-first APIs for text, images, video, speech, transcription, and decisions, built with Effect.
4
4
 
5
5
  `@opencode/ai` is the Promise API: one managed runtime behind the LLM and media methods, plus asset helpers. `ai.file`
6
6
  and `ai.write` load `node:fs/promises` on first use, so no Effect `FileSystem` is needed:
@@ -50,6 +50,26 @@ Run `LLM.stream(...)` instead of `generate` when you want incremental `LLMEvent`
50
50
  `LLM.request(...)`. The event stream is provider-neutral — same shape across OpenAI Chat, OpenAI Responses,
51
51
  Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployment.
52
52
 
53
+ ### Raw provider events
54
+
55
+ Set `includeRaw: true` on a request to also receive every provider frame as `{ type: "raw", data }`, in order and
56
+ before the events parsed from that frame. `data` is the parsed JSON frame, so frames this package doesn't handle yet
57
+ are visible too. Raw events are off by default, and `generate` ignores them. Translate a frame with a stream map:
58
+
59
+ ```ts
60
+ import { Stream } from "effect"
61
+ import { LLM, LLMEvent } from "@opencode/ai/effect"
62
+
63
+ const flagged = (data: unknown) =>
64
+ typeof data === "object" && data !== null && "type" in data && data.type === "moderation.flagged"
65
+
66
+ const events = LLM.stream({ model, prompt: "Say hello.", includeRaw: true }).pipe(
67
+ Stream.map((event) =>
68
+ event.type === "raw" && flagged(event.data) ? LLMEvent.providerError({ message: "Flagged by moderation" }) : event,
69
+ ),
70
+ )
71
+ ```
72
+
53
73
  ### Google Interactions
54
74
 
55
75
  `Google.configure({ apiKey }).interactions(modelID)` selects the Interactions API; `.model(modelID)` still selects
@@ -62,13 +82,11 @@ live under `providerMetadata.vertex`. The default is still full-history replay w
62
82
 
63
83
  ```ts
64
84
  const model = Google.configure({ apiKey }).interactions("gemini-3.8-flash")
65
- const response =
66
- yield *
67
- LLM.generate({
68
- model,
69
- prompt: "Say hello.",
70
- providerOptions: { thinkingLevel: "low", thinkingSummaries: "auto", store: true },
71
- })
85
+ const response = yield* LLM.generate({
86
+ model,
87
+ prompt: "Say hello.",
88
+ providerOptions: { thinkingLevel: "low", thinkingSummaries: "auto", store: true },
89
+ })
72
90
  ```
73
91
 
74
92
  Interactions supports text output, streamed function calls, native tool results, thought signatures, and multimodal
@@ -93,7 +111,8 @@ const image = Effect.gen(function* () {
93
111
  const response = yield* Image.generate({
94
112
  model: openai.image("gpt-image-2"),
95
113
  prompt: "A robot tending a rooftop garden",
96
- size: "1024x1024",
114
+ aspect: "1:1",
115
+ resolution: "1K",
97
116
  providerOptions: { quality: "high" }, // typed per image model
98
117
  })
99
118
  yield* Media.write(response.image, "./garden.png")
@@ -329,10 +348,11 @@ is unit-tested for all six regions.
329
348
  ### Images
330
349
 
331
350
  `alibaba.image(...)` uses the native multimodal generation API (`/api/v1/services/aigc/multimodal-generation/generation`)
332
- for Qwen-Image (`qwen-image-2.0`, `qwen-image-2.0-pro`) and Wan (`wan2.7-image`, `wan2.7-image-pro`). `size` lowers to
333
- `W*H`, and `images` are sent as URLs or data URLs for editing. Native `parameters` include `negativePrompt`,
334
- `promptExtend`, `watermark`, `thinkingMode`, and `enableSequential`; raw keys such as `bbox_list` or `size: "2K"`
335
- pass through. Results are URLs that Model Studio keeps for 24 hours. A complete `baseURL` for images includes `/api/v1`.
351
+ for Qwen-Image (`qwen-image-2.0`, `qwen-image-2.0-pro`) and Wan (`wan2.7-image`, `wan2.7-image-pro`). `aspect` and
352
+ `resolution` lower to a `W*H` size, `providerOptions.size` sets it exactly, and `images` are sent as URLs or data URLs
353
+ for editing. Native `parameters` include `size`, `seed`, `negativePrompt`, `promptExtend`, `watermark`, `thinkingMode`,
354
+ and `enableSequential`; raw keys such as `bbox_list` pass through. Results are URLs that Model Studio keeps for 24
355
+ hours. A complete `baseURL` for images includes `/api/v1`.
336
356
 
337
357
  ## Z.AI
338
358
 
@@ -1102,8 +1122,10 @@ Everything below is exported from `@opencode/ai/effect` unless noted.
1102
1122
  - **`Video.request` / `generate` / `stream` / `start` / `resume`** — queued video generation through a provider-neutral request; `VideoClient` is its Effect service and layer.
1103
1123
  - **`Speech.request` / `Speech.generate` / `Speech.stream`** — text-to-speech through a provider-neutral request; `SpeechClient` is its Effect service and layer.
1104
1124
  - **`Transcription.request` / `generate` / `stream` / `start` / `resume`** — speech-to-text over inline, streaming, and queued routes; `TranscriptionClient` is its Effect service and layer.
1125
+ - **`Decision.request` / `Decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer.
1105
1126
  - **`AIClient.layer` / `AIClient.layerWith(executor)`** — every modality client plus the request executor in one layer.
1106
- - **`@opencode/ai`** (Promise root) — `AI.make({ layer? })` and a default `ai` client exposing `llm`, `image`, `video`, `speech`, and `transcription` as Promise / `AsyncIterable` APIs, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets.
1127
+ - **`@opencode/ai`** (Promise root) — `AI.make({ layer? })` and a default `ai` client exposing `llm`, `image`, `video`, `speech`, `transcription`, and `decision` as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets.
1128
+ - **`@opencode/ai/experimental`** — APIs that may still change: `Extraction` (typed values read out of text) and `Realtime` (`Realtime.connect` starts an OpenAI, xAI, or Gemini voice session and returns a WebRTC answer SDP or a short-lived WebSocket URL and token).
1107
1129
 
1108
1130
  ## Testing
1109
1131
 
@@ -1322,13 +1344,33 @@ cache: {
1322
1344
  tools?: boolean,
1323
1345
  system?: boolean,
1324
1346
  messages?: "latest-user-message" | "latest-assistant" | { tail: number },
1325
- ttlSeconds?: number, // ≥ 3600 → 1h on Anthropic/Bedrock; else 5m
1347
+ ttl?: CacheTTL, // "5m", "30m", "1h", "12h", "24h", ...
1326
1348
  }
1327
1349
  ```
1328
1350
 
1351
+ An object with placement fields places exactly those breakpoints. An object with only `ttl` keeps automatic placement.
1352
+
1353
+ ### Cache lifetime
1354
+
1355
+ `ttl` is a duration in models.dev's format (`<number>` followed by `ms`, `s`, `m`, `h` or `d`). It is sent to the provider as given, so use one the provider accepts. Leaving it unset keeps the provider default.
1356
+
1357
+ ```ts
1358
+ LLM.request({ model, system, prompt, cache: { ttl: "1h" } })
1359
+ ```
1360
+
1361
+ | Protocol | How `ttl` is sent |
1362
+ | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
1363
+ | Anthropic Messages family, Meta Messages | `ttl` on every `cache_control` marker |
1364
+ | Bedrock Converse | `ttl` on every `cachePoint`; older Claude releases that only cache for 5m drop `"1h"` |
1365
+ | OpenRouter, DigitalOcean, Alibaba Chat markers | `ttl` on every `cache_control` marker |
1366
+ | OpenAI Responses (OpenAI, Azure, Cloudflare AI Gateway) | `"24h"` → `prompt_cache_retention: "24h"`; anything else → `prompt_cache_options: { ttl }` |
1367
+ | Chat Completions without markers (OpenAI-compatible, Moonshot, DeepInfra) | same mapping as OpenAI Responses |
1368
+
1369
+ OpenAI's two fields cover different models: `prompt_cache_retention` (`"in_memory"` or `"24h"`) is the only control before GPT-5.6, and GPT-5.6+ reads `prompt_cache_options.ttl` (`"30m"` or `"12h"`). Sending `prompt_cache_options` to an older model returns a 400. `"in_memory"` is not a duration; send it with an HTTP body overlay.
1370
+
1329
1371
  ### Manual hints
1330
1372
 
1331
- 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.
1373
+ Inline `CacheHint` (`{ type: "ephemeral", ttl? }`) 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.
1332
1374
 
1333
1375
  ```ts
1334
1376
  LLM.request({
@@ -1361,12 +1403,12 @@ import { OpenAI, CloudflareAIGateway } from "@opencode/ai/providers"
1361
1403
 
1362
1404
  const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY }).responses("gpt-4o-mini")
1363
1405
  const gateway = CloudflareAIGateway.configure({
1364
- accountId: process.env.CLOUDFLARE_ACCOUNT_ID,
1406
+ accountId,
1365
1407
  gatewayApiKey: process.env.CLOUDFLARE_API_TOKEN,
1366
1408
  }).model("workers-ai/@cf/meta/llama-3.1-8b-instruct")
1367
1409
  ```
1368
1410
 
1369
- Included LLM providers: OpenAI, Anthropic, Google (Gemini), Google Vertex, Amazon Bedrock, Azure OpenAI, Baseten, Cerebras, Cohere, Cloudflare AI Gateway, Cloudflare Workers AI, DeepInfra, DeepSeek, Fireworks, Groq, Mistral, OpenRouter, TogetherAI, Vercel AI Gateway, and xAI. Z.ai currently exposes image generation. Generic Chat Completions, Responses, and Anthropic Messages-compatible entrypoints support custom endpoints.
1411
+ 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.
1370
1412
 
1371
1413
  Each named provider owns its module, endpoint, authentication, and route setup. Providers with the same wire format compose the shared protocol directly:
1372
1414
 
@@ -1476,5 +1518,5 @@ This package is built on Effect. Public methods in `@opencode/ai/effect` return
1476
1518
  ## See also
1477
1519
 
1478
1520
  - `AGENTS.md` — architecture, route construction, contributor guide
1479
- - `example/tutorial.ts` — runnable end-to-end walkthrough
1521
+ - `example/tutorial.ts` — runnable end-to-end walkthrough (`bun example/tutorial.ts <example>`)
1480
1522
  - `test/provider/*.test.ts` — fixture-first protocol tests; `*.recorded.test.ts` files cover live cassettes
@@ -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 | import("./route/executor-service.js").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("./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 | import("./route/executor-service.js").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("./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";
@@ -1,2 +1,6 @@
1
1
  import { LLMRequest } from "./schema/messages.js";
2
+ /** The requested cache lifetime, for routes that send it as a request-level option instead of on markers. */
3
+ export declare const requestTTL: (request: LLMRequest) => `${number}d` | `${number}h` | `${number}m` | `${number}ms` | `${number}s` | undefined;
2
4
  export declare const applyCachePolicy: (request: LLMRequest) => LLMRequest;
5
+ /** Whether the cache policy places inline markers, which then carry the requested lifetime. */
6
+ export declare const placesMarkers: (request: LLMRequest) => boolean;
@@ -24,14 +24,23 @@ const BREAKPOINT_CAP = 4;
24
24
  // - undefined → "auto" — caching is on by default.
25
25
  // - "auto" → tools + first/last system + final message boundary.
26
26
  // - "none" → no auto placement; manual `CacheHint`s still flow.
27
+ // - `{ ttl }` → "auto" with that lifetime.
27
28
  // - object form → exactly what the caller asked for.
28
29
  const resolve = (policy) => {
29
- if (policy === undefined || policy === "auto")
30
- return AUTO;
31
30
  if (policy === "none")
32
31
  return NONE;
33
- return policy;
32
+ if (typeof policy === "object" && !isAuto(policy))
33
+ return policy;
34
+ return AUTO;
34
35
  };
36
+ const isAuto = (policy) => policy === undefined ||
37
+ policy === "auto" ||
38
+ (typeof policy === "object" &&
39
+ policy.tools === undefined &&
40
+ policy.system === undefined &&
41
+ policy.messages === undefined);
42
+ /** The requested cache lifetime, for routes that send it as a request-level option instead of on markers. */
43
+ export const requestTTL = (request) => (typeof request.cache === "object" ? request.cache.ttl : undefined);
35
44
  // Protocols whose wire format ignores inline cache markers (OpenAI's implicit
36
45
  // prefix caching, Gemini's implicit + out-of-band CachedContent). Skip the
37
46
  // whole policy pass for these — emitting hints would be harmless but pointless.
@@ -65,7 +74,7 @@ const gatewayPolicy = (modelID) => {
65
74
  return QWEN;
66
75
  return NONE;
67
76
  };
68
- const makeHint = (ttlSeconds) => ttlSeconds !== undefined ? new CacheHint({ type: "ephemeral", ttlSeconds }) : new CacheHint({ type: "ephemeral" });
77
+ const makeHint = (ttl) => ttl !== undefined ? new CacheHint({ type: "ephemeral", ttl }) : new CacheHint({ type: "ephemeral" });
69
78
  const markLastTool = (tools, hint, budget) => {
70
79
  const target = tools.at(-1);
71
80
  if (target === undefined)
@@ -147,7 +156,7 @@ export const applyCachePolicy = (request) => {
147
156
  const policy = selectPolicy(request);
148
157
  if (!policy.tools && !policy.system && !policy.messages)
149
158
  return request;
150
- const hint = makeHint(policy.ttlSeconds);
159
+ const hint = makeHint(requestTTL(request));
151
160
  const budget = { remaining: Math.max(0, BREAKPOINT_CAP - countHints(request)) };
152
161
  const tools = policy.tools ? markLastTool(request.tools, hint, budget) : request.tools;
153
162
  const system = policy.system ? markSystemBoundaries(request.system, hint, budget) : request.system;
@@ -156,11 +165,16 @@ export const applyCachePolicy = (request) => {
156
165
  return request;
157
166
  return LLMRequest.update(request, { tools, system, messages });
158
167
  };
168
+ /** Whether the cache policy places inline markers, which then carry the requested lifetime. */
169
+ export const placesMarkers = (request) => {
170
+ const policy = selectPolicy(request);
171
+ return Boolean(policy.tools || policy.system || policy.messages);
172
+ };
159
173
  // A declared cache format overrides the route allowlist and its model-ID heuristics.
160
174
  const selectPolicy = (request) => {
161
175
  const format = request.model.compatibility?.cacheFormat;
162
176
  const route = request.model.route.id;
163
- const auto = request.cache === undefined || request.cache === "auto";
177
+ const auto = isAuto(request.cache);
164
178
  if (format === "alibaba")
165
179
  return auto ? QWEN : { ...resolve(request.cache), tools: false };
166
180
  if (format === "anthropic")
@@ -11,11 +11,11 @@ export declare class Service extends Service_base {
11
11
  }
12
12
  export declare const generate: <Options extends DecisionOptions, const Questions extends DecisionQuestions>(request: DecisionRequestFor<Options, Questions>) => Effect.Effect<DecisionResponseFor<Questions>, AIError, Service>;
13
13
  export declare const layer: Layer.Layer<Service, never, RequestExecutor.Service>;
14
- export declare const fetchLayer: Layer.Layer<import("./route/executor-service.js").RequestExecutorService | Service, never, never>;
14
+ export declare const fetchLayer: Layer.Layer<RequestExecutor.RequestExecutorService | Service, never, never>;
15
15
  export declare const DecisionClient: {
16
16
  readonly Service: typeof Service;
17
- readonly layer: Layer.Layer<Service, never, import("./route/executor-service.js").RequestExecutorService>;
18
- readonly fetchLayer: Layer.Layer<import("./route/executor-service.js").RequestExecutorService | Service, never, never>;
17
+ readonly layer: Layer.Layer<Service, never, RequestExecutor.RequestExecutorService>;
18
+ readonly fetchLayer: Layer.Layer<RequestExecutor.RequestExecutorService | Service, never, never>;
19
19
  readonly generate: typeof generate;
20
20
  };
21
21
  export {};
@@ -1,7 +1,7 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  import { Service, type Execute } from "./decision-client.js";
3
3
  import { Media } from "./media.js";
4
- import { AIError, HttpOptions, ModelID, ProviderID, Usage } from "./schema/index.js";
4
+ import { AIError, HttpOptions, ModelID, ProviderID, ProviderOptions, Usage } from "./schema/index.js";
5
5
  export declare const DecisionTextPart: Schema.Struct<{
6
6
  readonly type: Schema.Literal<"text">;
7
7
  readonly text: Schema.String;
@@ -264,6 +264,8 @@ export declare class DecisionModel<Options extends DecisionOptions = DecisionOpt
264
264
  readonly route: DecisionModelRoute<Options>;
265
265
  readonly http?: HttpOptions;
266
266
  readonly compatibility?: DecisionModelCompatibility;
267
+ /** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
268
+ readonly providerOptions?: ProviderOptions;
267
269
  constructor(input: DecisionModel.Input<Options>);
268
270
  static make<Options extends DecisionOptions = DecisionOptions>(input: DecisionModel.MakeInput<Options>): DecisionModel<Options>;
269
271
  }
@@ -274,6 +276,7 @@ export declare namespace DecisionModel {
274
276
  readonly route: DecisionModelRoute<Options>;
275
277
  readonly http?: HttpOptions;
276
278
  readonly compatibility?: DecisionModelCompatibility;
279
+ readonly providerOptions?: ProviderOptions;
277
280
  }
278
281
  interface MakeInput<Options extends DecisionOptions = DecisionOptions> extends Omit<Input<Options>, "id" | "provider"> {
279
282
  readonly id: string | ModelID;
package/dist/decision.js CHANGED
@@ -91,12 +91,15 @@ export class DecisionModel {
91
91
  route;
92
92
  http;
93
93
  compatibility;
94
+ /** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
95
+ providerOptions;
94
96
  constructor(input) {
95
97
  this.id = input.id;
96
98
  this.provider = input.provider;
97
99
  this.route = input.route;
98
100
  this.http = input.http;
99
101
  this.compatibility = input.compatibility;
102
+ this.providerOptions = input.providerOptions;
100
103
  }
101
104
  static make(input) {
102
105
  return new DecisionModel({
package/dist/effect.d.ts CHANGED
@@ -2,11 +2,11 @@ export { AIClient } from "./ai-client.js";
2
2
  export { LLMClient } from "./route/client.js";
3
3
  export { ImageClient } from "./image-client.js";
4
4
  export { Auth } from "./route/auth.js";
5
- export { Provider } from "./provider.js";
6
5
  export { ProviderPackage } from "./provider-package.js";
7
6
  export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./provider-error.js";
8
- export type { RouteLanguageModelInput, RouteRoutedLanguageModelInput, Interface as LLMClientShape, LLMClientService, } from "./route/client.js";
9
- export * from "./schema/index.js";
7
+ export type { Interface as LLMClientShape, LLMClientService } from "./route/client.js";
8
+ export { ProtocolID, RouteID, ModelID, ProviderID, ResponseID, ContentBlockID, ToolCallID, JsonSchema, ProviderOptions, ProviderMetadata, HttpTimeout, RequestEncoding, HttpOptions, GenerationOptions, LanguageModelDefaults, ReasoningEfforts, ReasoningEffort, LanguageModelCompatibility, LanguageModel, LanguageModelSchema, CacheTTL, CacheHint, CachePolicyObject, CachePolicy, MessageRole, SystemPart, TextPart, MediaPart, ToolResultValue, ToolOutput, ToolCallPart, ToolResultPart, ReasoningPart, CompactionPart, EffortPart, ContentPart, Message, ToolDefinition, ToolNamespace, ToolEntry, ToolChoice, LLMRequest, FinishReason, Usage, MediaUsage, CompactionResponse, CompactionCheckpointResponse, StepStart, TextStart, TextDelta, TextEnd, ReasoningStart, ReasoningDelta, ReasoningEnd, ToolInputStart, ToolInputDelta, ToolInputEnd, ToolInputError, ToolCall, ToolResult, ToolError, FinishReasonDetails, StepFinish, Finish, MediaEvent, ProviderErrorEvent, LLMEvent, LLMResponse, HttpContext, HttpRateLimitDetails, InvalidRequestError, UnsupportedOperationError, ProviderConfigurationError, NoRouteError, AuthenticationError, RateLimitError, QuotaExceededError, ContentPolicyError, ProviderInternalError, TransportType, TransportOperation, TransportError, InvalidProviderOutputError, UnknownProviderError, TimeoutError, AIErrorReason, AIError, } from "./schema/index.js";
9
+ export type { GenerationOptionsFields, GenerationOptionsInput, LanguageModelInput, LanguageModelProviderOptions, ToolDefinitionInput, ToolNamespaceInput, ToolNamespaceEntryInput, ToolEntryInput, UsageInput, } from "./schema/index.js";
10
10
  export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageRequest, ImageResponse } from "./image.js";
11
11
  export type { ImageModelOptions, ImageOptions, ImageRequestFor, ImageRequestInput, ImageResolution, ImageRoute, } from "./image.js";
12
12
  export { Image } from "./image.js";
@@ -30,10 +30,9 @@ export { DecisionRoute } from "./route/decision.js";
30
30
  export { Media } from "./media.js";
31
31
  export { Generation } from "./generation.js";
32
32
  export type { AwaitOptions as GenerationAwaitOptions, Event as GenerationEvent, Poll, Route as GenerationRoute, Snapshot as GenerationSnapshot, Status as GenerationStatus, } from "./generation.js";
33
- export { Tool, ToolFailure, toDefinitions } from "./tool.js";
33
+ export { Tool, ToolFailure, emptyInputJsonSchema, toDefinitions } from "./tool.js";
34
34
  export { ToolRuntime } from "./tool-runtime.js";
35
35
  export type { DispatchResult as ToolDispatchResult, ToolSettlement } from "./tool-runtime.js";
36
36
  export type { AnyExecutableTool, AnyTool, ExecutableTool, ExecutableTools, Definition as ToolShape, ToolExecute, ToolExecuteContext, ToolModelOutputInput, Tools, ToolSchema, ToolToModelOutput, } from "./tool.js";
37
37
  export * as LLM from "./llm.js";
38
- export type { Definition as ProviderDefinition, LanguageModelFactory as ProviderLanguageModelFactory, LanguageModelOptions as ProviderLanguageModelOptions, } from "./provider.js";
39
38
  export type { Definition as ProviderPackageDefinition, Settings as ProviderPackageSettings, } from "./provider-package.js";
package/dist/effect.js CHANGED
@@ -2,10 +2,9 @@ export { AIClient } from "./ai-client.js";
2
2
  export { LLMClient } from "./route/client.js";
3
3
  export { ImageClient } from "./image-client.js";
4
4
  export { Auth } from "./route/auth.js";
5
- export { Provider } from "./provider.js";
6
5
  export { ProviderPackage } from "./provider-package.js";
7
6
  export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./provider-error.js";
8
- export * from "./schema/index.js";
7
+ export { ProtocolID, RouteID, ModelID, ProviderID, ResponseID, ContentBlockID, ToolCallID, JsonSchema, ProviderOptions, ProviderMetadata, HttpTimeout, RequestEncoding, HttpOptions, GenerationOptions, LanguageModelDefaults, ReasoningEfforts, ReasoningEffort, LanguageModelCompatibility, LanguageModel, LanguageModelSchema, CacheTTL, CacheHint, CachePolicyObject, CachePolicy, MessageRole, SystemPart, TextPart, MediaPart, ToolResultValue, ToolOutput, ToolCallPart, ToolResultPart, ReasoningPart, CompactionPart, EffortPart, ContentPart, Message, ToolDefinition, ToolNamespace, ToolEntry, ToolChoice, LLMRequest, FinishReason, Usage, MediaUsage, CompactionResponse, CompactionCheckpointResponse, StepStart, TextStart, TextDelta, TextEnd, ReasoningStart, ReasoningDelta, ReasoningEnd, ToolInputStart, ToolInputDelta, ToolInputEnd, ToolInputError, ToolCall, ToolResult, ToolError, FinishReasonDetails, StepFinish, Finish, MediaEvent, ProviderErrorEvent, LLMEvent, LLMResponse, HttpContext, HttpRateLimitDetails, InvalidRequestError, UnsupportedOperationError, ProviderConfigurationError, NoRouteError, AuthenticationError, RateLimitError, QuotaExceededError, ContentPolicyError, ProviderInternalError, TransportType, TransportOperation, TransportError, InvalidProviderOutputError, UnknownProviderError, TimeoutError, AIErrorReason, AIError, } from "./schema/index.js";
9
8
  export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageRequest, ImageResponse } from "./image.js";
10
9
  export { Image } from "./image.js";
11
10
  export { VideoClient } from "./video-client.js";
@@ -23,6 +22,6 @@ export { Decision } from "./decision.js";
23
22
  export { DecisionRoute } from "./route/decision.js";
24
23
  export { Media } from "./media.js";
25
24
  export { Generation } from "./generation.js";
26
- export { Tool, ToolFailure, toDefinitions } from "./tool.js";
25
+ export { Tool, ToolFailure, emptyInputJsonSchema, toDefinitions } from "./tool.js";
27
26
  export { ToolRuntime } from "./tool-runtime.js";
28
27
  export * as LLM from "./llm.js";
@@ -1,4 +1,5 @@
1
1
  import { Effect, Redacted } from "effect";
2
+ import { RequestExecutor } from "../route/executor.js";
2
3
  import { AIError } from "../schema/index.js";
3
4
  export type RealtimeTransportInput = {
4
5
  readonly type: "webrtc";
@@ -78,7 +79,7 @@ export declare const engine: (model: string) => {
78
79
  readonly provider: "google";
79
80
  readonly transports: readonly ["websocket"];
80
81
  } | undefined;
81
- export declare const connect: (input: RealtimeConnectInput) => Effect.Effect<RealtimeTransport, AIError, import("../route/executor-service.js").RequestExecutorService>;
82
+ export declare const connect: (input: RealtimeConnectInput) => Effect.Effect<RealtimeTransport, AIError, RequestExecutor.RequestExecutorService>;
82
83
  export declare const Realtime: {
83
84
  readonly engines: readonly [{
84
85
  readonly family: "gpt-live";
@@ -106,5 +107,5 @@ export declare const Realtime: {
106
107
  readonly transports: readonly ["websocket"];
107
108
  }];
108
109
  readonly engine: typeof engine;
109
- readonly connect: (input: RealtimeConnectInput) => Effect.Effect<RealtimeTransport, AIError, import("../route/executor-service.js").RequestExecutorService>;
110
+ readonly connect: (input: RealtimeConnectInput) => Effect.Effect<RealtimeTransport, AIError, RequestExecutor.RequestExecutorService>;
110
111
  };
@@ -8,7 +8,7 @@ export declare class ImageClientService extends ImageClientService_base {
8
8
  export declare const Service: typeof ImageClientService;
9
9
  export type Service = ImageClientService;
10
10
  export declare const ImageClient: {
11
- readonly layer: import("effect/Layer").Layer<ImageClientService, never, import("./route/executor-service.js").RequestExecutorService>;
11
+ readonly layer: import("effect/Layer").Layer<ImageClientService, never, import("./route.js").RequestExecutorService>;
12
12
  readonly generate: (request: ImageRequestFor, options?: import("./generation.js").AwaitOptions) => import("effect/Effect").Effect<ImageResponse, import("./effect.js").AIError, ImageClientService>;
13
13
  readonly stream: (request: ImageRequestFor, options?: import("./generation.js").AwaitOptions) => import("effect/Stream").Stream<{
14
14
  readonly type: "image-partial";
package/dist/image.js CHANGED
@@ -11,6 +11,7 @@ export class ImageModel extends MediaModel {
11
11
  id: input.id,
12
12
  provider: route.protocol.provider,
13
13
  http: input.http,
14
+ providerOptions: input.providerOptions,
14
15
  route: composeRoute(route, input, collectResponse),
15
16
  });
16
17
  }
package/dist/index.d.ts CHANGED
@@ -56,6 +56,9 @@ export declare const make: (options?: Options) => {
56
56
  stream: <const Model extends LanguageModel>(input: RequestInput<Model> | LLMRequest, options?: RunOptions) => AsyncIterable<{
57
57
  readonly type: "step-start";
58
58
  readonly index: number;
59
+ } | {
60
+ readonly type: "raw";
61
+ readonly data: unknown;
59
62
  } | {
60
63
  readonly type: "text-start";
61
64
  readonly id: string;
@@ -551,6 +554,9 @@ export declare const ai: {
551
554
  stream: <const Model extends LanguageModel>(input: RequestInput<Model> | LLMRequest, options?: RunOptions) => AsyncIterable<{
552
555
  readonly type: "step-start";
553
556
  readonly index: number;
557
+ } | {
558
+ readonly type: "raw";
559
+ readonly data: unknown;
554
560
  } | {
555
561
  readonly type: "text-start";
556
562
  readonly id: string;
package/dist/llm.d.ts CHANGED
@@ -25,6 +25,9 @@ export declare class GenerateObjectResponse<T> {
25
25
  get events(): readonly ({
26
26
  readonly type: "step-start";
27
27
  readonly index: number;
28
+ } | {
29
+ readonly type: "raw";
30
+ readonly data: unknown;
28
31
  } | {
29
32
  readonly type: "text-start";
30
33
  readonly id: string;
@@ -1,5 +1,6 @@
1
1
  import { type Context, Effect, Layer, Stream } from "effect";
2
2
  import { type AwaitOptions, type Generation, type Observation } from "./generation.js";
3
+ import { RequestExecutor } from "./route/executor.js";
3
4
  import type { MediaRoute } from "./route/media.js";
4
5
  import { AIError } from "./schema/index.js";
5
6
  /** A media request whose model carries the route that executes it. */
@@ -21,7 +22,7 @@ export declare const make: <Self, Req extends RoutedRequest<Req, Event, Response
21
22
  /** A completed response expanded into the streaming event shape. */
22
23
  readonly responseEvents: (response: Response) => ReadonlyArray<Event>;
23
24
  }) => {
24
- layer: Layer.Layer<Self, never, import("./route/executor-service.js").RequestExecutorService>;
25
+ layer: Layer.Layer<Self, never, RequestExecutor.RequestExecutorService>;
25
26
  generate: (request: Req, options?: AwaitOptions) => Effect.Effect<Response, AIError, Self>;
26
27
  stream: (request: Req, options?: AwaitOptions) => Stream.Stream<Event | Observation, AIError, Exclude<Self, import("effect/Scope").Scope>>;
27
28
  start: (request: Req) => Effect.Effect<Generation<Response>, AIError, Self>;
@@ -14,6 +14,8 @@ export declare class MediaModel<Route, Options> {
14
14
  readonly provider: ProviderID;
15
15
  readonly route: Route;
16
16
  readonly http?: HttpOptions;
17
+ /** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
18
+ readonly providerOptions?: ProviderOptions;
17
19
  constructor(input: MediaModel.Input<Route>);
18
20
  }
19
21
  export declare namespace MediaModel {
@@ -23,6 +25,7 @@ export declare namespace MediaModel {
23
25
  readonly provider: string | ProviderID;
24
26
  readonly route: Route;
25
27
  readonly http?: HttpOptions;
28
+ readonly providerOptions?: ProviderOptions;
26
29
  }
27
30
  /** A protocol plus its canonical start path; `ModelInput.baseURL` overrides `baseURL` per deployment. */
28
31
  interface RouteInput<Request extends MediaRoute.MediaRequest, Protocol> {
@@ -1,7 +1,7 @@
1
1
  import { Effect } from "effect";
2
2
  import { Endpoint } from "./route/endpoint.js";
3
3
  import { MediaRoute } from "./route/media.js";
4
- import { AIError, HttpOptions, InvalidRequestError, ModelID, ProviderID, } from "./schema/index.js";
4
+ import { AIError, HttpOptions, InvalidRequestError, ModelID, ProviderID } from "./schema/index.js";
5
5
  /**
6
6
  * What every media model carries: ids, the configured route, and deployment `http` overlays. Modality classes
7
7
  * (`ImageModel`, `VideoModel`, `SpeechModel`, `TranscriptionModel`) extend it with their route type and a nominal
@@ -12,11 +12,14 @@ export class MediaModel {
12
12
  provider;
13
13
  route;
14
14
  http;
15
+ /** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
16
+ providerOptions;
15
17
  constructor(input) {
16
18
  this.id = ModelID.make(input.id);
17
19
  this.provider = ProviderID.make(input.provider);
18
20
  this.route = input.route;
19
21
  this.http = input.http;
22
+ this.providerOptions = input.providerOptions;
20
23
  }
21
24
  }
22
25
  /** Compose a protocol route input with one deployment through `MediaRoute.inline`, `queued`, or `stream`. */
@@ -154,6 +154,10 @@ export declare const protocol: Protocol<{
154
154
  } | undefined;
155
155
  readonly store?: boolean | undefined;
156
156
  readonly prompt_cache_key?: string | undefined;
157
+ readonly prompt_cache_retention?: string | undefined;
158
+ readonly prompt_cache_options?: {
159
+ readonly ttl?: string | undefined;
160
+ } | undefined;
157
161
  readonly reasoning_effort?: OpenResponsesOptions.ReasoningEffort | undefined;
158
162
  readonly verbosity?: import("../schema/options.js").OpenString<"high" | "low" | "medium"> | undefined;
159
163
  readonly service_tier?: import("../schema/options.js").OpenString<"auto" | "default" | "flex" | "priority"> | undefined;