@opencode/ai 2.2.7 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +114 -96
  2. package/dist/effect.d.ts +8 -7
  3. package/dist/effect.js +2 -1
  4. package/dist/experimental.d.ts +0 -4
  5. package/dist/experimental.js +0 -3
  6. package/dist/image-client.d.ts +1 -1
  7. package/dist/image-client.js +2 -6
  8. package/dist/index.d.ts +11 -48
  9. package/dist/index.js +30 -13
  10. package/dist/media-model.d.ts +2 -0
  11. package/dist/media-model.js +3 -1
  12. package/dist/media.d.ts +9 -3
  13. package/dist/media.js +27 -7
  14. package/dist/protocols/google-decisions.d.ts +13 -0
  15. package/dist/protocols/google-decisions.js +133 -0
  16. package/dist/protocols/google-interactions-video.d.ts +43 -0
  17. package/dist/protocols/google-interactions-video.js +186 -0
  18. package/dist/protocols/google-interactions.d.ts +14 -1
  19. package/dist/protocols/google-interactions.js +1 -1
  20. package/dist/protocols/index.d.ts +1 -0
  21. package/dist/protocols/index.js +1 -0
  22. package/dist/protocols/minimax-video.d.ts +54 -0
  23. package/dist/protocols/minimax-video.js +292 -0
  24. package/dist/protocols/openrouter-video.d.ts +41 -0
  25. package/dist/protocols/openrouter-video.js +138 -0
  26. package/dist/protocols/seedance-video.d.ts +50 -0
  27. package/dist/protocols/seedance-video.js +216 -0
  28. package/dist/protocols/system-one.d.ts +45 -1
  29. package/dist/protocols/system-one.js +42 -7
  30. package/dist/protocols/utils/responses-compaction.js +1 -1
  31. package/dist/protocols/xai-video.d.ts +8 -2
  32. package/dist/protocols/xai-video.js +20 -15
  33. package/dist/provider-error.js +7 -1
  34. package/dist/providers/byteplus/videos.d.ts +2 -0
  35. package/dist/providers/byteplus/videos.js +1 -0
  36. package/dist/providers/byteplus.d.ts +26 -0
  37. package/dist/providers/byteplus.js +21 -0
  38. package/dist/providers/google/decisions.d.ts +2 -0
  39. package/dist/providers/google/decisions.js +1 -0
  40. package/dist/providers/google/videos.d.ts +2 -0
  41. package/dist/providers/google/videos.js +1 -0
  42. package/dist/providers/google.d.ts +11 -4
  43. package/dist/providers/google.js +13 -3
  44. package/dist/providers/index.d.ts +2 -1
  45. package/dist/providers/index.js +2 -1
  46. package/dist/providers/minimax/videos.d.ts +3 -0
  47. package/dist/providers/minimax/videos.js +1 -0
  48. package/dist/providers/minimax.d.ts +6 -1
  49. package/dist/providers/minimax.js +10 -1
  50. package/dist/providers/openai-compatible/decisions.d.ts +2 -0
  51. package/dist/providers/openai-compatible/decisions.js +1 -0
  52. package/dist/providers/openai-compatible.d.ts +2 -0
  53. package/dist/providers/openai-compatible.js +14 -0
  54. package/dist/providers/openrouter/videos.d.ts +2 -0
  55. package/dist/providers/openrouter/videos.js +1 -0
  56. package/dist/providers/openrouter.d.ts +5 -0
  57. package/dist/providers/openrouter.js +8 -0
  58. package/dist/providers/volcengine/videos.d.ts +2 -0
  59. package/dist/providers/volcengine/videos.js +1 -0
  60. package/dist/providers/volcengine.d.ts +26 -0
  61. package/dist/providers/volcengine.js +21 -0
  62. package/dist/public.d.ts +2 -0
  63. package/dist/public.js +1 -0
  64. package/dist/route/executor-service.d.ts +6 -0
  65. package/dist/route/executor-service.js +7 -0
  66. package/dist/route/executor.d.ts +7 -1
  67. package/dist/route/executor.js +7 -2
  68. package/dist/route/media-protocol.d.ts +12 -11
  69. package/dist/route/media.d.ts +2 -0
  70. package/dist/route/media.js +31 -22
  71. package/dist/route/transport/http.js +1 -1
  72. package/dist/schema/messages.d.ts +1 -1
  73. package/dist/schema/messages.js +1 -5
  74. package/dist/schema/options.d.ts +8 -0
  75. package/dist/schema/options.js +1 -0
  76. package/dist/speech-client.d.ts +1 -1
  77. package/dist/speech-client.js +4 -4
  78. package/dist/transcription-client.d.ts +1 -1
  79. package/dist/transcription-client.js +1 -2
  80. package/dist/video-client.d.ts +16 -84
  81. package/dist/video-client.js +28 -13
  82. package/dist/video.d.ts +56 -1072
  83. package/dist/video.js +28 -65
  84. package/package.json +55 -7
  85. package/dist/protocols/google-video.d.ts +0 -26
  86. package/dist/protocols/google-video.js +0 -146
  87. package/dist/protocols/runway-video.d.ts +0 -38
  88. package/dist/protocols/runway-video.js +0 -141
  89. package/dist/providers/runway.d.ts +0 -20
  90. package/dist/providers/runway.js +0 -17
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @opencode/ai
2
2
 
3
- Schema-first APIs for text, images, decisions, and embeddings, built with Effect. Video, speech, transcription, extraction, and
4
- realtime voice are [experimental](#experimental).
3
+ Schema-first APIs for text, images, video, decisions, and embeddings, built with Effect. Speech, transcription,
4
+ extraction, and realtime voice are [experimental](#experimental).
5
5
 
6
6
  `@opencode/ai` is the Promise API: one managed runtime behind the LLM and media methods, plus asset helpers. `ai.file`
7
7
  and `ai.write` load `node:fs/promises` on first use, so no Effect `FileSystem` is needed:
@@ -211,7 +211,7 @@ Raw usage is preserved in `usage.providerMetadata.google`. `inputTokens` follows
211
211
  `contextTokens` uses its full `raw_prompt_token` count when supplied. These can differ substantially with server-side
212
212
  continuation. Explicit caches, hosted tools, and generated media are not supported by this initial protocol.
213
213
 
214
- The same configured facade names image models (and the experimental video, speech, and transcription models).
214
+ The same configured facade names image and video models (and the experimental speech and transcription models).
215
215
  `ai.image.generate` resolves the provider's image route from the model and returns `Media.Asset`s with lazily decoded bytes:
216
216
 
217
217
  ```ts
@@ -1031,6 +1031,111 @@ const program = Effect.gen(function* () {
1031
1031
 
1032
1032
  The hosted result is represented as a provider-executed tool call and a tool result whose content carries the generated image as a file. Gemini image-capable models instead emit a first-class `media` `LLMEvent` for inline image output (`response.message` then carries a `media` part). Retaining `response.message` preserves the generated image for continuation on both routes.
1033
1033
 
1034
+ ## Video generation
1035
+
1036
+ Video generation is a job: `start` submits it and returns at once, and the caller decides when to read its `status`,
1037
+ fetch its `result`, or `cancel` it. Nothing polls for you. Every call after `start` takes the model and the job's
1038
+ `token`, plain JSON you can store and read back from another process, so recovering after a restart is the same call
1039
+ as a normal status read. Models come from `.video(...)` selectors on the `XAI`, `OpenRouter`, `Volcengine`,
1040
+ `BytePlus`, `MiniMax` and `Google` facades.
1041
+
1042
+ ```ts
1043
+ import { Effect } from "effect"
1044
+ import { ai, Media } from "@opencode/ai/effect"
1045
+ import { XAI } from "@opencode/ai/providers"
1046
+
1047
+ const model = XAI.configure({ apiKey: process.env.XAI_API_KEY }).video("grok-imagine-video-1.5")
1048
+
1049
+ const program = Effect.gen(function* () {
1050
+ const job = yield* ai.video.start({
1051
+ model,
1052
+ prompt: "Panning wide shot of a calico kitten sleeping in the sunshine",
1053
+ start: "https://example.com/first-frame.png", // exact first frame; `end` pins the last one
1054
+ references: [], // images, videos or audio that guide subject or style
1055
+ duration: "8 seconds",
1056
+ aspect: "16:9", // or "auto" to follow the start image
1057
+ resolution: "720p", // 480p | 720p | 1080p | 4k, or any provider value
1058
+ sound: false,
1059
+ })
1060
+ job.token // `{ requestID }` for xAI: store it with the provider and model ID
1061
+
1062
+ const status = yield* ai.video.status(model, job.token)
1063
+ status.status // "queued" | "running" | "completed" | "failed" | "cancelled" | "expired"
1064
+ status.progress // 0..1, only when the provider reports it
1065
+
1066
+ const response = yield* ai.video.result(model, job.token)
1067
+ yield* Media.write(response.video, "./kitten.mp4") // streams the download to disk
1068
+ })
1069
+ ```
1070
+
1071
+ The shared fields are `prompt`, `start`, `end`, `references`, `duration`, `aspect`, `resolution` and `sound`;
1072
+ everything else is provider-specific and goes under `providerOptions`, typed from the selected model. A request only
1073
+ fails before sending when its protocol has no way to express it, such as a reference video on xAI. Values the provider
1074
+ may reject, like an unsupported duration or too many references, go to the provider, and its error comes back typed.
1075
+
1076
+ `status` is one read; `result` fails with an `InvalidRequest` reason when the job hasn't finished, and with the
1077
+ provider's reason (and terminal document on `reason.body`) when it failed, was cancelled or expired. Moderation
1078
+ outcomes (xAI `respect_moderation`) fail with a `ContentPolicy` reason when no video comes back. Status and result reads
1079
+ retry transient failures (rate limits, provider 5xx, network errors) with backoff that honors `retry-after`; `start`
1080
+ and `cancel` never retry. `cancel` fails with an `UnsupportedOperation` reason on providers without a cancel endpoint,
1081
+ such as xAI, where the job keeps running and billing. Finished videos are usually URLs that expire (`expiresAt` when the
1082
+ provider documents it): download them with `Media.write`, `asset.stream()` or `materialize()` before then.
1083
+
1084
+ Provider notes:
1085
+
1086
+ - **xAI** maps `start` to `image`, `end` to `last_frame`, image references to `reference_images`, audio references to
1087
+ `reference_audios`, and `sound` to `generate_audio`, and leaves `aspect: "auto"` out when a start frame sets the
1088
+ shape. It has no reference video input. `providerOptions.mode: "edit" | "extend"` sends a native `video: { url }`
1089
+ source to `/videos/edits` or `/videos/extensions`.
1090
+ - **OpenRouter** (`OpenRouter.configure(...).video("google/veo-3.1")`) maps `start` and `end` to `frame_images`,
1091
+ references to `input_references` by kind (`image_url`, `video_url`, `audio_url`), `sound` to `generate_audio`, and
1092
+ `resolution` to its spelling (`4k` → `4K`), and leaves `aspect: "auto"` out so models that can follow the input image do.
1093
+ Frames and references are both sent; when both are present OpenRouter keeps the frames and drops the references. It
1094
+ rejects reference videos or audio that aren't http(s) URLs (inline images work). Routing and upstream parameters go under `providerOptions.provider` (`only`, `order`,
1095
+ `options: { <slug>: {...} }`), and `providerOptions.previous_job_id` edits or extends a finished job. Results are
1096
+ OpenRouter content URLs that download with the API key, which the asset carries; there is no cancel endpoint.
1097
+ - **Seedance** (`Volcengine.configure(...).video(...)` with `ARK_API_KEY`, `BytePlus.configure(...).video(...)` with
1098
+ `BYTEPLUS_API_KEY`) builds Ark's `content[]`: the prompt as a `text` item, `start` and `end` as `image_url` items
1099
+ with roles `first_frame` and `last_frame`, and references as `reference_image`, `reference_video` or
1100
+ `reference_audio` by kind. Your own `Media.ref(...)` assets go as `asset://<id>`. `duration` goes to `duration`,
1101
+ `aspect` to `ratio` (`auto` becomes `adaptive`), `resolution` to `resolution` and `sound` to `generate_audio`. Ark
1102
+ doesn't allow frames and references in one task; that combination is sent and the provider's error comes back.
1103
+ `providerOptions.draft_task: { id }` adds a `draft_task` item; `frames`, `seed`, `watermark`, `output_format`,
1104
+ `omni_reference_task_type`, `return_last_frame` and the rest go into the body as-is. `cancel` sends `DELETE`, which
1105
+ only cancels a queued task: Ark refuses it for a running one and deletes the record of a finished one. Video URLs
1106
+ expire 24 hours after the task finished.
1107
+ - **MiniMax** (`MiniMax.configure(...).video(id)`, or `@opencode/ai/providers/minimax/videos`) serves two APIs and picks
1108
+ one by model family: Hailuo and `*-01` models use v1, everything else (H3) uses v2. Video builds its `/v1` and `/v2`
1109
+ paths on the API host, so a `baseURL` shared with images or chat (`https://api.minimax.cn/v1`) loses its trailing
1110
+ `/v1`, and a bare host (`https://api.minimax.io`) works as is. On H3, `start`, `end` and `references` become `content[]` items with `first_frame`, `last_frame` and `reference_image` /
1111
+ `reference_video` / `reference_audio` roles, MiniMax file refs become `mm_file://` URLs, `aspect: "auto"` becomes
1112
+ `ratio: "adaptive"`, and `resolution` is uppercased (`480P`, `2K`). H3 requires `resolution` and `duration`, plus a
1113
+ `ratio` for text-only prompts; nothing is filled in, so MiniMax rejects a request without them. H3 always has sound,
1114
+ so `sound: false` fails before sending. On Hailuo, `start` and `end` map to `first_frame_image` and
1115
+ `last_frame_image`, image references to `subject_reference`, and the result looks up the file's download URL, which
1116
+ expires after one hour. Hailuo is silent and has no aspect field, so `sound: true`, an explicit `aspect`, and video
1117
+ or audio references fail before sending. Cancel works on H3 (only while queued); Hailuo has no cancel. Native fields
1118
+ such as `extra.prompt_expansion_mode` (H3), `prompt_optimizer` (Hailuo) and `callback_url` go under `providerOptions`.
1119
+ - **Google** (`Google.video("gemini-omni-1.2-flash")`) starts a background Gemini Omni interaction. Omni has no
1120
+ role field for media, so `start`, `end` and `references` go into `input` in that order (images, plus video
1121
+ references), and `generation_config.video_config.task` is set to `image_to_video` for frames only or
1122
+ `reference_to_video` for references only; with both, the prompt decides. `duration` becomes
1123
+ `response_format.duration` (`"3s"`), and `aspect` and `resolution` go to `response_format` as is (resolution
1124
+ lowercased); `aspect: "auto"` leaves the ratio out. It rejects `end` without `start` (a lone image reads as the
1125
+ first frame) and `sound: false` (Omni always generates audio). Videos come back as inline bytes. `cancel` posts to
1126
+ `/interactions/{id}/cancel`. `providerOptions` takes native Interactions fields, such as `previous_interaction_id`
1127
+ to edit or extend a generated video, `generation_config.video_config.task`, `service_tier` and `webhook_config`.
1128
+
1129
+ The promise client has the same calls, each accepting `{ signal }`:
1130
+
1131
+ ```ts
1132
+ import { ai } from "@opencode/ai"
1133
+
1134
+ const job = await ai.video.start({ model, prompt })
1135
+ const status = await ai.video.status(model, job.token)
1136
+ if (status.status === "completed") await ai.write((await ai.video.result(model, job.token)).video, "./kite.mp4")
1137
+ ```
1138
+
1034
1139
  ## Public API
1035
1140
 
1036
1141
  Everything below is exported from `@opencode/ai/effect` unless noted.
@@ -1044,117 +1149,30 @@ Everything below is exported from `@opencode/ai/effect` unless noted.
1044
1149
  - **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
1045
1150
  - **`ai.image.request` / `generate` / `stream` / `start` / `resume`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model.
1046
1151
  - **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`.
1152
+ - **`ai.video.request` / `start` / `status` / `result` / `cancel`** — video generation as a job addressed by a stored token; see [Video generation](#video-generation). `VideoClient` is its Effect service and layer.
1047
1153
  - **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests.
1048
1154
  - **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
1049
1155
  - **`ai.decision.request` / `ai.decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer.
1050
1156
  - **`ai.embedding.request` / `ai.embedding.generate`** — one vector per text or media value, with optional `dimensions` and `inputType`; `EmbeddingClient` is its Effect service and layer.
1051
1157
  - **`AIClient.layer` / `AIClient.layerWith(executor)`** — every modality client plus the request executor in one layer.
1052
- - **`@opencode/ai`** (Promise root) — a default `ai` with the text calls (`request`, `generate`, `stream`, `loop`, `compact`, `canCompact`) at the top level plus `image`, `decision` and `embedding` (plus `experimental.video`, `experimental.speech`, and `experimental.transcription`) as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets. `AI.make({ layer? })` builds a client over a custom executor. The same `ai` from `@opencode/ai/effect` returns `Effect` and `Stream`.
1053
- - **`@opencode/ai/experimental`** — APIs that may change without compatibility guarantees: `Video`, `Speech`, `Transcription`, `Extraction`, and `Realtime`. See [Experimental](#experimental).
1158
+ - **`@opencode/ai`** (Promise root) — a default `ai` with the text calls (`request`, `generate`, `stream`, `loop`, `compact`, `canCompact`) at the top level plus `image`, `decision`, `embedding` and `video` (plus `experimental.speech` and `experimental.transcription`) as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets. `AI.make({ layer? })` builds a client over a custom executor. The same `ai` from `@opencode/ai/effect` returns `Effect` and `Stream`.
1159
+ - **`@opencode/ai/experimental`** — APIs that may change without compatibility guarantees: `Speech`, `Transcription`, `Extraction`, and `Realtime`. See [Experimental](#experimental).
1054
1160
 
1055
1161
  ## Experimental
1056
1162
 
1057
1163
  These APIs may change without compatibility guarantees. The Effect API is exported from `@opencode/ai/experimental`,
1058
1164
  and the Promise client exposes it under `ai.experimental`.
1059
1165
 
1060
- - **`Video`**, **`Speech`**, and **`Transcription`** — media generation and speech-to-text, with `VideoClient`,
1061
- `SpeechClient`, and `TranscriptionClient` as their Effect services. Promise: `ai.experimental.video`, `.speech`, and
1062
- `.transcription`.
1166
+ - **`Speech`** and **`Transcription`** — speech generation and speech-to-text, with `SpeechClient` and
1167
+ `TranscriptionClient` as their Effect services. Promise: `ai.experimental.speech` and `.transcription`.
1063
1168
  - **`Extraction`** — typed values read out of text.
1064
1169
  - **`Realtime`** — `Realtime.connect` starts an OpenAI, xAI, or Gemini voice session and returns a WebRTC answer SDP or
1065
1170
  a short-lived WebSocket URL and token.
1066
1171
 
1067
- The provider selectors for these modalities (`.video(...)`, `.speech(...)`, `.transcription(...)`,
1172
+ The provider selectors for these modalities (`.speech(...)`, `.transcription(...)`,
1068
1173
  `.experimental.extraction(...)`) and their protocol entrypoints (such as `@opencode/ai/protocols/openai-speech`) are
1069
1174
  part of the same experimental surface.
1070
1175
 
1071
- ### Video generation
1072
-
1073
- Video mirrors `Image` with one difference: every provider is asynchronous, so the route is a submit-then-poll
1074
- `Generation`. Models come from `.video(...)` selectors on the `Google` (Veo), `XAI`, and `Runway` facades.
1075
- Common fields (`frames`, `references`, `video`, `durationSeconds`, `aspect`, `resolution`, `audio`, `n`, `seed`,
1076
- `negativePrompt`) lower natively or fail with a typed `AIError` before any network call; provider-native controls live
1077
- under `providerOptions`, inferred from the selected model.
1078
-
1079
- ```ts
1080
- import { Video } from "@opencode/ai/experimental"
1081
- import { Google, Runway } from "@opencode/ai/providers"
1082
-
1083
- const google = Google.configure({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY })
1084
-
1085
- // Simple: submit and wait.
1086
- const program = Effect.gen(function* () {
1087
- const response = yield* Video.generate(
1088
- {
1089
- model: google.video("veo-3.1-generate-preview"),
1090
- prompt: "Panning wide shot of a calico kitten sleeping in the sunshine",
1091
- aspect: "16:9",
1092
- resolution: "1080p",
1093
- durationSeconds: 8,
1094
- providerOptions: { personGeneration: "allow_adult" },
1095
- },
1096
- { poll: { interval: "10 seconds", timeout: "10 minutes" } },
1097
- )
1098
- // Veo serves files for two days behind the API key. The asset knows the deadline (`expiresAt`) and carries the
1099
- // download credentials only on the live instance (`asset.headers`), never in `source` or JSON: materialize
1100
- // before persisting, or the persisted URL cannot be fetched again.
1101
- return yield* response.video.materialize()
1102
- })
1103
-
1104
- // Explicit control: keep the handle, persist the token, resume elsewhere.
1105
- const controlled = Effect.gen(function* () {
1106
- const generation = yield* Video.start({ model: google.video("veo-3.1-generate-preview"), prompt })
1107
- generation.id // provider operation / task / request id
1108
- generation.status // "queued" | "running" | "completed" | "failed" | "cancelled" | "expired"
1109
- generation.token // route-owned JSON: `{ operation }`, `{ requestID }`, or `{ taskID }`
1110
- // The token carries no route identity: persist the provider and model ID alongside it, since `resume` needs the model.
1111
- const saved = JSON.stringify(generation.token)
1112
-
1113
- const resumed = yield* Video.resume(google.video("veo-3.1-generate-preview"), JSON.parse(saved))
1114
- return yield* resumed.await({ poll: { interval: "10 seconds" } })
1115
- })
1116
-
1117
- // Progress as a stream: generation-queued | generation-progress | video | finish.
1118
- const events = Video.stream({ model: Runway.configure({ apiKey }).video("gen4.5"), prompt }, { poll })
1119
- ```
1120
-
1121
- Status polls, result fetches, cancels, and asset downloads all run through the same request executor with the route's
1122
- auth. `Generation.await` and `Generation.events` fail with a
1123
- `Timeout` reason when `poll.timeout` (default 10 minutes) elapses. Status polls and result fetches retry transient
1124
- failures (rate limits, provider 5xx, network errors) with backoff that honors `retry-after`, always within
1125
- `poll.timeout`; submits and cancels never retry. Interrupting a wait (or aborting its `signal`) does not cancel the
1126
- provider job, which keeps running and billing: call `cancel()` to stop it. Failed,
1127
- cancelled, and expired generations fail typed with the provider's terminal document on `reason.body`; moderation
1128
- outcomes (Veo `raiMediaFilteredReasons`, xAI `respect_moderation`, Runway `SAFETY.*` codes) fail with a
1129
- `ContentPolicy` reason when no video comes back; when one still does, Veo and xAI keep the raw outcome in
1130
- `providerMetadata`.
1131
-
1132
- Provider notes:
1133
-
1134
- - **Google Veo** takes inline bytes only (materialize `url` assets first); `frames.last` requires `frames.first`;
1135
- audio is always on, so `audio: false` fails typed; one video per request. Output URLs need the API key to
1136
- download, which the returned asset holds transiently (see above).
1137
- - **xAI** sends a `video` input to `/videos/edits`, or `/videos/extensions` with `providerOptions.mode: "extend"`.
1138
- `seed` and `negativePrompt` are not supported.
1139
- - **Runway** expects pixel ratios in `aspect` for most models (`"1280:720"`), pins `X-Runway-Version`, reports
1140
- `usage: { type: "credits" }`, and its output URLs expire after 24–48 hours.
1141
-
1142
- The promise client exposes the same surface: `ai.experimental.video.start(...)` resolves to a handle with `await`, `events`,
1143
- `result`, `refresh`, `cancel`, and `token`; `ai.experimental.video.generate`, `ai.experimental.video.resume(model, token)`, and
1144
- `ai.experimental.video.stream` mirror the Effect API. The handle's `status` and `progress` are a snapshot from when it was
1145
- created; `refresh()` resolves to a new handle. Every promise method and stream accepts `{ signal }`: like `fetch`,
1146
- aborting rejects the Promise or throws from the `for await` loop with `signal.reason` (an `AbortError` `DOMException`
1147
- unless `abort(reason)` passed one), while `break` stops a stream without throwing.
1148
-
1149
- ```ts
1150
- import { ai } from "@opencode/ai"
1151
-
1152
- const generation = await ai.experimental.video.start({ model, prompt })
1153
- for await (const event of generation.events({ poll: { interval: 10_000 } })) console.log(event.type)
1154
- const video = await generation.result({ signal })
1155
- await ai.write(video.video, "./kite.mp4")
1156
- ```
1157
-
1158
1176
  ### Speech generation
1159
1177
 
1160
1178
  Speech (text-to-speech) is one request whose response is parsed incrementally, so every route supports both
package/dist/effect.d.ts CHANGED
@@ -23,6 +23,13 @@ export declare const ai: {
23
23
  readonly request: typeof import("./embedding.js").request;
24
24
  readonly generate: typeof import("./embedding.js").generate;
25
25
  };
26
+ readonly video: {
27
+ readonly request: typeof import("./video.js").request;
28
+ readonly start: typeof import("./video.js").start;
29
+ readonly status: typeof import("./video.js").status;
30
+ readonly result: typeof import("./video.js").result;
31
+ readonly cancel: typeof import("./video.js").cancel;
32
+ };
26
33
  /** Experimental: may change without compatibility guarantees. */
27
34
  readonly experimental: {
28
35
  readonly speech: {
@@ -37,18 +44,12 @@ export declare const ai: {
37
44
  readonly start: typeof import("./transcription.js").start;
38
45
  readonly resume: typeof import("./transcription.js").resume;
39
46
  };
40
- readonly video: {
41
- readonly request: typeof import("./video.js").request;
42
- readonly start: typeof import("./video.js").start;
43
- readonly generate: typeof import("./video.js").generate;
44
- readonly resume: typeof import("./video.js").resume;
45
- readonly stream: typeof import("./video.js").stream;
46
- };
47
47
  };
48
48
  };
49
49
  export { AIClient } from "./ai-client.js";
50
50
  export { LLMClient } from "./route/client.js";
51
51
  export { ImageClient } from "./image-client.js";
52
+ export { VideoClient } from "./video-client.js";
52
53
  export { Auth } from "./route/auth.js";
53
54
  export { ProviderPackage } from "./provider-package.js";
54
55
  export type { LLMClientService } from "./route/client.js";
package/dist/effect.js CHANGED
@@ -17,16 +17,17 @@ export const ai = {
17
17
  image: Image,
18
18
  decision: Decision,
19
19
  embedding: Embedding,
20
+ video: Video,
20
21
  /** Experimental: may change without compatibility guarantees. */
21
22
  experimental: {
22
23
  speech: Speech,
23
24
  transcription: Transcription,
24
- video: Video,
25
25
  },
26
26
  };
27
27
  export { AIClient } from "./ai-client.js";
28
28
  export { LLMClient } from "./route/client.js";
29
29
  export { ImageClient } from "./image-client.js";
30
+ export { VideoClient } from "./video-client.js";
30
31
  export { Auth } from "./route/auth.js";
31
32
  export { ProviderPackage } from "./provider-package.js";
32
33
  export { DecisionClient } from "./decision-client.js";
@@ -1,7 +1,3 @@
1
- export { VideoClient } from "./video-client.js";
2
- export { VideoAspectRatio, VideoEvent, VideoFrames, VideoModel, VideoModelSchema, VideoResponse } from "./video.js";
3
- export type { VideoModelOptions, VideoOptions, VideoRequest, VideoRequestInput, VideoResolution, VideoRoute, } from "./video.js";
4
- export { Video } from "./video.js";
5
1
  export { SpeechClient } from "./speech-client.js";
6
2
  export { SpeechEvent, SpeechModel, SpeechModelSchema, SpeechResponse, SpeechTimestamp, SpeechVoice } from "./speech.js";
7
3
  export type { SpeechFormat, SpeechModelOptions, SpeechOptions, SpeechRequest, SpeechRequestInput, SpeechRoute, } from "./speech.js";
@@ -1,6 +1,3 @@
1
- export { VideoClient } from "./video-client.js";
2
- export { VideoAspectRatio, VideoEvent, VideoFrames, VideoModel, VideoModelSchema, VideoResponse } from "./video.js";
3
- export { Video } from "./video.js";
4
1
  export { SpeechClient } from "./speech-client.js";
5
2
  export { SpeechEvent, SpeechModel, SpeechModelSchema, SpeechResponse, SpeechTimestamp, SpeechVoice } from "./speech.js";
6
3
  export { Speech } from "./speech.js";
@@ -1,6 +1,6 @@
1
1
  import { Context } from "effect";
2
2
  import { MediaClient } from "./media-client.js";
3
- import { type ImageEvent, type ImageRequest, type ImageResponse } from "./image.js";
3
+ import type { ImageEvent, ImageRequest, ImageResponse } from "./image.js";
4
4
  export type Interface = MediaClient.Interface<ImageRequest, ImageEvent, ImageResponse>;
5
5
  declare const ImageClientService_base: Context.ServiceClass<ImageClientService, "@opencode/ImageClient", Interface>;
6
6
  export declare class ImageClientService extends ImageClientService_base {
@@ -1,6 +1,5 @@
1
1
  import { Context } from "effect";
2
2
  import { MediaClient } from "./media-client.js";
3
- import { ImageOutputEvent, ImageFinishEvent } from "./image.js";
4
3
  export class ImageClientService extends Context.Service()("@opencode/ImageClient") {
5
4
  }
6
5
  export const Service = ImageClientService;
@@ -9,11 +8,8 @@ export const ImageClient = {
9
8
  ...MediaClient.make(Service, {
10
9
  modality: "image",
11
10
  responseEvents: (response) => [
12
- ...response.images.map((image, index) => ImageOutputEvent.make({ index, image })),
13
- ImageFinishEvent.make({
14
- usage: response.usage,
15
- providerMetadata: response.providerMetadata,
16
- }),
11
+ ...response.images.map((image, index) => ({ type: "image", index, image })),
12
+ { type: "finish", usage: response.usage, providerMetadata: response.providerMetadata },
17
13
  ],
18
14
  }),
19
15
  };
package/dist/index.d.ts CHANGED
@@ -53,7 +53,7 @@ export declare const make: (options?: Options) => {
53
53
  materialize: (asset: Media.Asset, options?: RunOptions) => Promise<Media.Asset>;
54
54
  /** Read a file into an asset like `Media.file`: sniffed media type, then the extension's. */
55
55
  file: (path: string, options?: Media.AssetOptions & RunOptions) => Promise<Media.Asset>;
56
- /** Write an asset's bytes like `Media.write`, downloading `url` sources through the executor. */
56
+ /** Write an asset's bytes like `Media.write`: streamed through a temporary file that replaces `path` on success. */
57
57
  write: (asset: Media.Asset, path: string, options?: RunOptions) => Promise<void>;
58
58
  request: typeof LLM.request;
59
59
  generate: {
@@ -141,6 +141,16 @@ export declare const make: (options?: Options) => {
141
141
  request: typeof import("./embedding.js").request;
142
142
  generate: <const Model extends EmbeddingModel>(input: EmbeddingRequestInput<Model>, options?: RunOptions) => Promise<import("./embedding.js").EmbeddingResponse>;
143
143
  };
144
+ video: {
145
+ request: typeof import("./video.js").request;
146
+ /** Submit a generation and return its `{ id, token }` at once; nothing polls. */
147
+ start: <const Model extends VideoModel>(input: VideoRequestInput<Model> | VideoRequest, options?: RunOptions) => Promise<import("./video.js").VideoJob>;
148
+ /** One status read for a stored token. */
149
+ status: (model: VideoModel, token: unknown, options?: RunOptions) => Promise<import("./video.js").VideoStatus>;
150
+ /** The finished videos; fails while the job is still running. */
151
+ result: (model: VideoModel, token: unknown, options?: RunOptions) => Promise<import("./video.js").VideoResponse>;
152
+ cancel: (model: VideoModel, token: unknown, options?: RunOptions) => Promise<void>;
153
+ };
144
154
  /** Experimental: may change without compatibility guarantees. */
145
155
  experimental: {
146
156
  speech: {
@@ -265,53 +275,6 @@ export declare const make: (options?: Options) => {
265
275
  start: <const Model extends TranscriptionModel>(input: TranscriptionRequestInput<Model> | TranscriptionRequest, options?: RunOptions) => Promise<GenerationHandle<import("./transcription.js").TranscriptionResponse>>;
266
276
  resume: (model: TranscriptionModel, token: unknown, options?: RunOptions) => Promise<GenerationHandle<import("./transcription.js").TranscriptionResponse>>;
267
277
  };
268
- video: {
269
- request: typeof import("./video.js").request;
270
- start: <const Model extends VideoModel>(input: VideoRequestInput<Model> | VideoRequest, options?: RunOptions) => Promise<GenerationHandle<import("./video.js").VideoResponse>>;
271
- generate: <const Model extends VideoModel>(input: VideoRequestInput<Model> | VideoRequest, options?: AwaitOptions & RunOptions) => Promise<import("./video.js").VideoResponse>;
272
- resume: (model: VideoModel, token: unknown, options?: RunOptions) => Promise<GenerationHandle<import("./video.js").VideoResponse>>;
273
- stream: <const Model extends VideoModel>(input: VideoRequestInput<Model> | VideoRequest, options?: AwaitOptions & RunOptions) => AsyncIterable<{
274
- readonly type: "video";
275
- readonly index: number;
276
- readonly video: Media.Asset;
277
- } | {
278
- readonly type: "generation-queued";
279
- readonly id: string;
280
- readonly position?: number | undefined;
281
- } | {
282
- readonly type: "generation-progress";
283
- readonly id: string;
284
- readonly progress?: number | undefined;
285
- } | {
286
- readonly type: "finish";
287
- readonly usage?: {
288
- readonly type: "seconds";
289
- readonly seconds: number;
290
- } | {
291
- readonly type: "characters";
292
- readonly characters: number;
293
- } | {
294
- readonly type: "credits";
295
- readonly credits: number;
296
- } | {
297
- readonly type: "compute";
298
- readonly seconds: number;
299
- } | {
300
- readonly type: "tokens";
301
- readonly input?: number | undefined;
302
- readonly output?: number | undefined;
303
- readonly total?: number | undefined;
304
- readonly details?: {
305
- readonly [x: string]: unknown;
306
- } | undefined;
307
- } | undefined;
308
- readonly providerMetadata?: {
309
- readonly [x: string]: {
310
- readonly [x: string]: unknown;
311
- };
312
- } | undefined;
313
- }>;
314
- };
315
278
  };
316
279
  dispose: () => Promise<void>;
317
280
  };
package/dist/index.js CHANGED
@@ -76,13 +76,27 @@ export const make = (options = {}) => {
76
76
  return Media.bytes(data, fileMediaType(data, path), options);
77
77
  })), options);
78
78
  },
79
- /** Write an asset's bytes like `Media.write`, downloading `url` sources through the executor. */
79
+ /** Write an asset's bytes like `Media.write`: streamed through a temporary file that replaces `path` on success. */
80
80
  write: async (asset, path, options) => {
81
- const { writeFile } = await import("node:fs/promises");
82
- return run(asset.bytes().pipe(Effect.flatMap((data) => Effect.tryPromise({
83
- try: (signal) => writeFile(path, data, { signal }),
84
- catch: (cause) => fileError(`Failed to write media file ${path}`, cause),
85
- }))), options);
81
+ const { open, rename, rm } = await import("node:fs/promises");
82
+ const temporary = `${path}.${crypto.randomUUID()}.tmp`;
83
+ try {
84
+ const file = await open(temporary, "w");
85
+ try {
86
+ for await (const chunk of iterate(asset.stream(), options))
87
+ await file.write(chunk);
88
+ }
89
+ finally {
90
+ await file.close();
91
+ }
92
+ await rename(temporary, path);
93
+ }
94
+ catch (cause) {
95
+ await rm(temporary, { force: true });
96
+ if (cause instanceof AIError || cause === options?.signal?.reason)
97
+ throw cause;
98
+ throw fileError(`Failed to write media file ${path}`, cause);
99
+ }
86
100
  },
87
101
  request: LLM.request,
88
102
  generate,
@@ -108,6 +122,16 @@ export const make = (options = {}) => {
108
122
  request: Embedding.request,
109
123
  generate: (input, options) => run(Embedding.generate(input), options),
110
124
  },
125
+ video: {
126
+ request: Video.request,
127
+ /** Submit a generation and return its `{ id, token }` at once; nothing polls. */
128
+ start: (input, options) => run(Video.start(input), options),
129
+ /** One status read for a stored token. */
130
+ status: (model, token, options) => run(Video.status(model, token), options),
131
+ /** The finished videos; fails while the job is still running. */
132
+ result: (model, token, options) => run(Video.result(model, token), options),
133
+ cancel: (model, token, options) => run(Video.cancel(model, token), options),
134
+ },
111
135
  /** Experimental: may change without compatibility guarantees. */
112
136
  experimental: {
113
137
  speech: {
@@ -122,13 +146,6 @@ export const make = (options = {}) => {
122
146
  start: (input, options) => run(Transcription.start(input), options).then(handle),
123
147
  resume: (model, token, options) => run(Transcription.resume(model, token), options).then(handle),
124
148
  },
125
- video: {
126
- request: Video.request,
127
- start: (input, options) => run(Video.start(input), options).then(handle),
128
- generate: (input, options) => run(Video.generate(input, { poll: options?.poll }), options),
129
- resume: (model, token, options) => run(Video.resume(model, token), options).then(handle),
130
- stream: (input, options) => iterate(Video.stream(input, { poll: options?.poll }), options),
131
- },
132
149
  },
133
150
  dispose: () => runtime.dispose(),
134
151
  };
@@ -42,5 +42,7 @@ export declare namespace MediaModel {
42
42
  }
43
43
  /** Compose a protocol route input with one deployment through `MediaRoute.inline`, `queued`, or `stream`. */
44
44
  export declare const composeRoute: <Request extends MediaRoute.MediaRequest, Event, Response, Frame, State, Token>(route: MediaModel.AnyRouteInput<Request, Event, Response, Frame, State, Token>, input: MediaRoute.ModelInput, collect: (events: ReadonlyArray<Event>) => Effect.Effect<Response, AIError>) => MediaRoute.AnyRoute<Request, Event, Response>;
45
+ /** Compose a queued protocol route input with one deployment through `MediaRoute.queued`. */
46
+ export declare const composeQueuedRoute: <Request extends MediaRoute.MediaRequest, Response, Token>(route: MediaModel.QueuedRouteInput<Request, Response, Token>, input: MediaRoute.ModelInput) => MediaRoute.QueuedRoute<Request, Response>;
45
47
  /** Lift a synchronous Schema-class constructor into a typed `InvalidRequest` failure. */
46
48
  export declare const tryRequest: <A>(make: () => A) => Effect.Effect<A, AIError>;
@@ -27,9 +27,11 @@ export const composeRoute = (route, input, collect) => {
27
27
  if (isStreamInput(route))
28
28
  return MediaRoute.stream({ ...composition(route, input), collect });
29
29
  if (isQueuedInput(route))
30
- return MediaRoute.queued(composition(route, input));
30
+ return composeQueuedRoute(route, input);
31
31
  return MediaRoute.inline(composition(route, input));
32
32
  };
33
+ /** Compose a queued protocol route input with one deployment through `MediaRoute.queued`. */
34
+ export const composeQueuedRoute = (route, input) => MediaRoute.queued(composition(route, input));
33
35
  const composition = (route, input) => ({
34
36
  protocol: route.protocol,
35
37
  endpoint: Endpoint.path(route.path, { baseURL: input.baseURL ?? route.baseURL }),
package/dist/media.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export * as Media from "./media.js";
2
- import { Effect, FileSystem, Schema } from "effect";
2
+ import { Effect, FileSystem, Schema, Stream } from "effect";
3
3
  import { ProviderID } from "./schema/ids.js";
4
4
  import { AIError } from "./schema/errors.js";
5
5
  import { ProviderMetadata } from "./schema/options.js";
@@ -65,6 +65,8 @@ export declare class Asset {
65
65
  inline(): Inline | undefined;
66
66
  /** Decoded payload; downloads `url` sources through the request executor and caches the result. */
67
67
  bytes(): Effect.Effect<Uint8Array, AIError, Service>;
68
+ /** The payload as a byte stream; `url` sources stream from the network without being buffered or cached. */
69
+ stream(): Stream.Stream<Uint8Array, AIError, Service>;
68
70
  base64(): Effect.Effect<string, AIError, Service>;
69
71
  dataUrl(): Effect.Effect<string, AIError, Service>;
70
72
  /**
@@ -115,7 +117,7 @@ export declare namespace Asset {
115
117
  readonly info?: Info;
116
118
  readonly providerMetadata?: ProviderMetadata;
117
119
  /**
118
- * Headers required to download a `url` source, such as the provider API key Veo demands for its file URIs.
120
+ * Headers required to download a `url` source, such as a provider API key.
119
121
  * They are runtime-only: never part of `source`, `toJSON()`, or `AssetSchema`, so a persisted asset cannot leak
120
122
  * credentials and cannot be downloaded again after a round-trip. Call `materialize()` before persisting.
121
123
  */
@@ -211,5 +213,9 @@ export type Input = Asset | Data;
211
213
  export declare const make: (input: Input, mediaType?: string) => Asset;
212
214
  /** Read a file through `FileSystem` and sniff its media type from magic bytes, then the extension. */
213
215
  export declare const file: (path: string, options?: AssetOptions) => Effect.Effect<Asset, AIError, FileSystem.FileSystem>;
214
- /** Materialize an asset and write its bytes through `FileSystem`. */
216
+ /**
217
+ * Stream an asset's bytes into a file through `FileSystem` without buffering `url` downloads. The bytes go to a temporary
218
+ * file next to `path` that replaces it only once the download finished, so a failed download leaves an existing file as
219
+ * it was.
220
+ */
215
221
  export declare const write: (asset: Asset, path: string) => Effect.Effect<void, AIError, FileSystem.FileSystem | Service>;
package/dist/media.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export * as Media from "./media.js";
2
- import { Effect, FileSystem, Result, Schema, SchemaGetter } from "effect";
2
+ import { Effect, FileSystem, Result, Schema, SchemaGetter, Stream } from "effect";
3
3
  import { Base64 } from "effect/encoding";
4
4
  import { HttpClientRequest } from "effect/http";
5
5
  import { ProviderID } from "./schema/ids.js";
@@ -29,7 +29,7 @@ const UrlSource = Schema.Struct({
29
29
  /** Epoch milliseconds after which the provider no longer serves the URL. */
30
30
  expiresAt: Schema.optional(Schema.Number),
31
31
  });
32
- /** A provider-side handle: OpenAI `file_id`, Gemini file URI, `gs://`, `runway://`, or a prior generation id. */
32
+ /** A provider-side handle: OpenAI `file_id`, Gemini file URI, `gs://`, or a prior generation id. */
33
33
  const RefSource = Schema.Struct({
34
34
  type: Schema.Literal("ref"),
35
35
  provider: ProviderID,
@@ -120,6 +120,13 @@ export class Asset {
120
120
  return decoded.pipe(Effect.tap((data) => Effect.sync(() => (this.#bytes = data))));
121
121
  });
122
122
  }
123
+ /** The payload as a byte stream; `url` sources stream from the network without being buffered or cached. */
124
+ stream() {
125
+ const source = this.source;
126
+ if (source.type !== "url" || this.#bytes !== undefined)
127
+ return Stream.fromEffect(this.bytes());
128
+ return Stream.unwrap(downloadStream(source, this.headers));
129
+ }
123
130
  base64() {
124
131
  return Effect.suspend(() => {
125
132
  const source = this.source;
@@ -183,6 +190,17 @@ const download = Effect.fn("Media.download")(function* (source, headers) {
183
190
  })));
184
191
  return new Uint8Array(buffer);
185
192
  });
193
+ const downloadStream = Effect.fn("Media.downloadStream")(function* (source, headers) {
194
+ const executor = yield* Service;
195
+ const response = yield* executor.execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})));
196
+ return response.stream.pipe(Stream.mapError((cause) => new AIError({
197
+ reason: new InvalidProviderOutputError({
198
+ message: `Failed to read media from ${source.url}`,
199
+ http: responseHttp(response),
200
+ cause,
201
+ }),
202
+ })));
203
+ });
186
204
  export const from = (source, options) => new Asset({ ...options, source });
187
205
  export const bytes = (data, mediaType, options) => from({ type: "bytes", data, mediaType: mediaType ?? detectMediaType(data) ?? OCTET_STREAM }, options);
188
206
  export const base64 = (data, mediaType, options) => from({ type: "base64", data, mediaType }, options);
@@ -247,11 +265,13 @@ export const file = (path, options) => Effect.gen(function* () {
247
265
  .pipe(Effect.mapError((cause) => invalid(`Failed to read media file ${path}`, cause)));
248
266
  return bytes(data, fileMediaType(data, path), options);
249
267
  });
250
- /** Materialize an asset and write its bytes through `FileSystem`. */
268
+ /**
269
+ * Stream an asset's bytes into a file through `FileSystem` without buffering `url` downloads. The bytes go to a temporary
270
+ * file next to `path` that replaces it only once the download finished, so a failed download leaves an existing file as
271
+ * it was.
272
+ */
251
273
  export const write = (asset, path) => Effect.gen(function* () {
252
274
  const fs = yield* FileSystem.FileSystem;
253
- const data = yield* asset.bytes();
254
- yield* fs
255
- .writeFile(path, data)
256
- .pipe(Effect.mapError((cause) => invalid(`Failed to write media file ${path}`, cause)));
275
+ const temporary = `${path}.${crypto.randomUUID()}.tmp`;
276
+ yield* asset.stream().pipe(Stream.run(fs.sink(temporary)), Effect.andThen(fs.rename(temporary, path)), Effect.onError(() => fs.remove(temporary).pipe(Effect.ignore)), Effect.mapError((cause) => cause instanceof AIError ? cause : invalid(`Failed to write media file ${path}`, cause)));
257
277
  });