@opencode/ai 0.0.0-dev-1280 → 0.0.0-dev-1285

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.
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,72 @@ 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` facade.
1040
+
1041
+ ```ts
1042
+ import { Effect } from "effect"
1043
+ import { ai, Media } from "@opencode/ai/effect"
1044
+ import { XAI } from "@opencode/ai/providers"
1045
+
1046
+ const model = XAI.configure({ apiKey: process.env.XAI_API_KEY }).video("grok-imagine-video-1.5")
1047
+
1048
+ const program = Effect.gen(function* () {
1049
+ const job = yield* ai.video.start({
1050
+ model,
1051
+ prompt: "Panning wide shot of a calico kitten sleeping in the sunshine",
1052
+ start: "https://example.com/first-frame.png", // exact first frame; `end` pins the last one
1053
+ references: [], // images, videos or audio that guide subject or style
1054
+ duration: "8 seconds",
1055
+ aspect: "16:9", // or "auto" to follow the start image
1056
+ resolution: "720p", // 480p | 720p | 1080p | 4k, or any provider value
1057
+ sound: false,
1058
+ })
1059
+ job.token // `{ requestID }` for xAI: store it with the provider and model ID
1060
+
1061
+ const status = yield* ai.video.status(model, job.token)
1062
+ status.status // "queued" | "running" | "completed" | "failed" | "cancelled" | "expired"
1063
+ status.progress // 0..1, only when the provider reports it
1064
+
1065
+ const response = yield* ai.video.result(model, job.token)
1066
+ yield* Media.write(response.video, "./kitten.mp4") // streams the download to disk
1067
+ })
1068
+ ```
1069
+
1070
+ The shared fields are `prompt`, `start`, `end`, `references`, `duration`, `aspect`, `resolution` and `sound`;
1071
+ everything else is provider-specific and goes under `providerOptions`, typed from the selected model. A request only
1072
+ fails before sending when its protocol has no way to express it, such as a reference video on xAI. Values the provider
1073
+ may reject, like an unsupported duration or too many references, go to the provider, and its error comes back typed.
1074
+
1075
+ `status` is one read; `result` fails with an `InvalidRequest` reason when the job hasn't finished, and with the
1076
+ provider's reason (and terminal document on `reason.body`) when it failed, was cancelled or expired. Moderation
1077
+ outcomes (xAI `respect_moderation`) fail with a `ContentPolicy` reason when no video comes back. Status and result reads
1078
+ retry transient failures (rate limits, provider 5xx, network errors) with backoff that honors `retry-after`; `start`
1079
+ and `cancel` never retry. `cancel` fails with an `UnsupportedOperation` reason on providers without a cancel endpoint,
1080
+ such as xAI, where the job keeps running and billing. Finished videos are usually URLs that expire (`expiresAt` when the
1081
+ provider documents it): download them with `Media.write`, `asset.stream()` or `materialize()` before then.
1082
+
1083
+ Provider notes:
1084
+
1085
+ - **xAI** maps `start` to `image`, `end` to `last_frame`, image references to `reference_images`, audio references to
1086
+ `reference_audios`, and `sound` to `generate_audio`, and leaves `aspect: "auto"` out when a start frame sets the
1087
+ shape. It has no reference video input. `providerOptions.mode: "edit" | "extend"` sends a native `video: { url }`
1088
+ source to `/videos/edits` or `/videos/extensions`.
1089
+
1090
+ The promise client has the same calls, each accepting `{ signal }`:
1091
+
1092
+ ```ts
1093
+ import { ai } from "@opencode/ai"
1094
+
1095
+ const job = await ai.video.start({ model, prompt })
1096
+ const status = await ai.video.status(model, job.token)
1097
+ if (status.status === "completed") await ai.write((await ai.video.result(model, job.token)).video, "./kite.mp4")
1098
+ ```
1099
+
1034
1100
  ## Public API
1035
1101
 
1036
1102
  Everything below is exported from `@opencode/ai/effect` unless noted.
@@ -1044,108 +1110,30 @@ Everything below is exported from `@opencode/ai/effect` unless noted.
1044
1110
  - **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
1045
1111
  - **`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
1112
  - **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`.
1113
+ - **`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
1114
  - **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests.
1048
1115
  - **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
1049
1116
  - **`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
1117
  - **`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
1118
  - **`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).
1119
+ - **`@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`.
1120
+ - **`@opencode/ai/experimental`** — APIs that may change without compatibility guarantees: `Speech`, `Transcription`, `Extraction`, and `Realtime`. See [Experimental](#experimental).
1054
1121
 
1055
1122
  ## Experimental
1056
1123
 
1057
1124
  These APIs may change without compatibility guarantees. The Effect API is exported from `@opencode/ai/experimental`,
1058
1125
  and the Promise client exposes it under `ai.experimental`.
1059
1126
 
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`.
1127
+ - **`Speech`** and **`Transcription`** — speech generation and speech-to-text, with `SpeechClient` and
1128
+ `TranscriptionClient` as their Effect services. Promise: `ai.experimental.speech` and `.transcription`.
1063
1129
  - **`Extraction`** — typed values read out of text.
1064
1130
  - **`Realtime`** — `Realtime.connect` starts an OpenAI, xAI, or Gemini voice session and returns a WebRTC answer SDP or
1065
1131
  a short-lived WebSocket URL and token.
1066
1132
 
1067
- The provider selectors for these modalities (`.video(...)`, `.speech(...)`, `.transcription(...)`,
1133
+ The provider selectors for these modalities (`.speech(...)`, `.transcription(...)`,
1068
1134
  `.experimental.extraction(...)`) and their protocol entrypoints (such as `@opencode/ai/protocols/openai-speech`) are
1069
1135
  part of the same experimental surface.
1070
1136
 
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 `XAI` facade.
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 { XAI } from "@opencode/ai/providers"
1082
-
1083
- const xai = XAI.configure({ apiKey: process.env.XAI_API_KEY })
1084
-
1085
- // Simple: submit and wait.
1086
- const program = Effect.gen(function* () {
1087
- const response = yield* Video.generate(
1088
- {
1089
- model: xai.video("grok-imagine-video-1.5"),
1090
- prompt: "Panning wide shot of a calico kitten sleeping in the sunshine",
1091
- aspect: "16:9",
1092
- resolution: "720p",
1093
- durationSeconds: 10,
1094
- },
1095
- { poll: { interval: "10 seconds", timeout: "10 minutes" } },
1096
- )
1097
- // xAI returns a temporary URL: materialize before persisting, or the persisted URL may stop working.
1098
- return yield* response.video.materialize()
1099
- })
1100
-
1101
- // Explicit control: keep the handle, persist the token, resume elsewhere.
1102
- const controlled = Effect.gen(function* () {
1103
- const generation = yield* Video.start({ model: xai.video("grok-imagine-video-1.5"), prompt })
1104
- generation.id // provider request id
1105
- generation.status // "queued" | "running" | "completed" | "failed" | "cancelled" | "expired"
1106
- generation.token // route-owned JSON, `{ requestID }` for xAI
1107
- // The token carries no route identity: persist the provider and model ID alongside it, since `resume` needs the model.
1108
- const saved = JSON.stringify(generation.token)
1109
-
1110
- const resumed = yield* Video.resume(xai.video("grok-imagine-video-1.5"), JSON.parse(saved))
1111
- return yield* resumed.await({ poll: { interval: "10 seconds" } })
1112
- })
1113
-
1114
- // Progress as a stream: generation-queued | generation-progress | video | finish.
1115
- const events = Video.stream({ model: xai.video("grok-imagine-video-1.5"), prompt }, { poll })
1116
- ```
1117
-
1118
- Status polls, result fetches, and cancels all run through the same request executor with the route's
1119
- auth. `Generation.await` and `Generation.events` fail with a
1120
- `Timeout` reason when `poll.timeout` (default 10 minutes) elapses. Status polls and result fetches retry transient
1121
- failures (rate limits, provider 5xx, network errors) with backoff that honors `retry-after`, always within
1122
- `poll.timeout`; submits and cancels never retry. Interrupting a wait (or aborting its `signal`) does not cancel the
1123
- provider job, which keeps running and billing: call `cancel()` to stop it on providers with a cancel endpoint (xAI has
1124
- none, so `cancel()` sends nothing there). Failed, cancelled, and expired generations fail typed with the provider's
1125
- terminal document on `reason.body`; moderation outcomes (xAI `respect_moderation`) fail with a `ContentPolicy` reason
1126
- when no video comes back; when one still does, the raw outcome stays in `providerMetadata`.
1127
-
1128
- Provider notes:
1129
-
1130
- - **xAI** sends a `video` input to `/videos/edits`, or `/videos/extensions` with `providerOptions.mode: "extend"`.
1131
- `seed` and `negativePrompt` are not supported.
1132
-
1133
- The promise client exposes the same surface: `ai.experimental.video.start(...)` resolves to a handle with `await`, `events`,
1134
- `result`, `refresh`, `cancel`, and `token`; `ai.experimental.video.generate`, `ai.experimental.video.resume(model, token)`, and
1135
- `ai.experimental.video.stream` mirror the Effect API. The handle's `status` and `progress` are a snapshot from when it was
1136
- created; `refresh()` resolves to a new handle. Every promise method and stream accepts `{ signal }`: like `fetch`,
1137
- aborting rejects the Promise or throws from the `for await` loop with `signal.reason` (an `AbortError` `DOMException`
1138
- unless `abort(reason)` passed one), while `break` stops a stream without throwing.
1139
-
1140
- ```ts
1141
- import { ai } from "@opencode/ai"
1142
-
1143
- const generation = await ai.experimental.video.start({ model, prompt })
1144
- for await (const event of generation.events({ poll: { interval: 10_000 } })) console.log(event.type)
1145
- const video = await generation.result({ signal })
1146
- await ai.write(video.video, "./kite.mp4")
1147
- ```
1148
-
1149
1137
  ### Speech generation
1150
1138
 
1151
1139
  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";
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
  /**
@@ -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";
@@ -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
  });
@@ -8,11 +8,17 @@ export declare const EDIT_PATH = "/videos/edits";
8
8
  export declare const EXTEND_PATH = "/videos/extensions";
9
9
  export declare const STATUS_PATH = "/videos";
10
10
  /**
11
- * Provider-native options. Common fields (`frames`, `references`, `video`, `durationSeconds`, `aspect`,
12
- * `resolution`, `audio`) live on the request. `mode` selects the endpoint a `video` input is sent to.
11
+ * Provider-native options. Common fields (`start`, `end`, `references`, `duration`, `aspect`, `resolution`,
12
+ * `sound`) live on the request. `mode` sends the request to the edit or extension endpoint with a native
13
+ * `video: { url }` source; `reference_audios` takes preset `voice_id`s.
13
14
  */
14
15
  export type XAIVideoOptions = {
15
16
  readonly mode?: "edit" | "extend";
17
+ readonly video?: {
18
+ readonly url: string;
19
+ } | {
20
+ readonly file_id: string;
21
+ };
16
22
  readonly reference_audios?: ReadonlyArray<{
17
23
  readonly voice_id: string;
18
24
  }>;
@@ -3,7 +3,7 @@ import { Media } from "../media.js";
3
3
  import { MediaProtocol } from "../route/media-protocol.js";
4
4
  import { MediaRoute } from "../route/media.js";
5
5
  import { mergeJsonRecords } from "../schema/index.js";
6
- import { VideoModel, VideoResponse } from "../video.js";
6
+ import { VideoModel, VideoResponse, seconds } from "../video.js";
7
7
  import { ProviderShared, optionalNull } from "./shared.js";
8
8
  const route = MediaProtocol.identity({ id: "xai-video", name: "xAI Video", provider: "xai" });
9
9
  export const DEFAULT_BASE_URL = "https://api.x.ai/v1";
@@ -53,21 +53,25 @@ const nativeOptions = (options) => {
53
53
  return native;
54
54
  };
55
55
  const fromRequest = Effect.fn("XAIVideo.fromRequest")(function* (request) {
56
- const image = request.frames?.first === undefined ? undefined : yield* mediaInput(request.frames.first);
57
- const lastFrame = request.frames?.last === undefined ? undefined : yield* mediaInput(request.frames.last);
58
- const video = request.video === undefined ? undefined : yield* mediaInput(request.video);
59
- const references = yield* Effect.forEach(request.references ?? [], mediaInput);
56
+ const references = request.references ?? [];
57
+ if (references.some((asset) => asset.kind === "video"))
58
+ return yield* route.unsupported("video.references", `${route.name} has no reference video input`);
59
+ const image = request.start === undefined ? undefined : yield* mediaInput(request.start);
60
+ const lastFrame = request.end === undefined ? undefined : yield* mediaInput(request.end);
61
+ const images = yield* Effect.forEach(references.filter((asset) => asset.kind !== "audio"), mediaInput);
62
+ const audios = yield* Effect.forEach(references.filter((asset) => asset.kind === "audio"), (asset) => ProviderShared.mediaReference(asset, route.provider, route.name).pipe(Effect.map((reference) => ({ url: reference.value }))));
60
63
  return MediaProtocol.json(mergeJsonRecords({
61
64
  model: request.model.id,
62
65
  prompt: request.prompt,
63
66
  image,
64
67
  last_frame: lastFrame,
65
- reference_images: references.length === 0 ? undefined : references,
66
- video,
67
- duration: request.durationSeconds,
68
- aspect_ratio: request.aspect,
68
+ reference_images: images.length === 0 ? undefined : images,
69
+ reference_audios: audios.length === 0 ? undefined : audios,
70
+ duration: request.duration === undefined ? undefined : seconds(request.duration),
71
+ // xAI follows the input image's shape when a start frame is set, which is what `auto` asks for.
72
+ aspect_ratio: request.aspect === "auto" && request.start !== undefined ? undefined : request.aspect,
69
73
  resolution: request.resolution,
70
- generate_audio: request.audio,
74
+ generate_audio: request.sound,
71
75
  }, nativeOptions(request.providerOptions), request.http?.body) ?? {});
72
76
  });
73
77
  // ---------------------------------------------------------------------------
@@ -128,16 +132,17 @@ const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* (response, con
128
132
  const statusPath = (token) => `${STATUS_PATH}/${token.requestID}`;
129
133
  export const protocol = MediaProtocol.queued(route, {
130
134
  token: Token,
131
- unsupported: ["n", "seed", "negativePrompt"],
132
135
  start: { body: { from: fromRequest }, decode: decodeStart },
133
136
  status: { path: statusPath, decode: decodeStatus },
134
137
  result: { path: statusPath, decode: decodeResult },
135
138
  });
136
- // A source video goes to `/videos/edits` unless `providerOptions.mode` asks for an extension.
139
+ // `providerOptions.mode` sends the native `video` source to the edit or extension endpoint.
137
140
  const startPath = (request) => {
138
- if (request.video === undefined)
139
- return PATH;
140
- return request.providerOptions?.mode === "extend" ? EXTEND_PATH : EDIT_PATH;
141
+ if (request.providerOptions?.mode === "edit")
142
+ return EDIT_PATH;
143
+ if (request.providerOptions?.mode === "extend")
144
+ return EXTEND_PATH;
145
+ return PATH;
141
146
  };
142
147
  export const model = (input) => VideoModel.fromRoute({
143
148
  protocol,
package/dist/public.d.ts CHANGED
@@ -3,6 +3,8 @@ export { ProtocolID, RouteID, ModelID, ProviderID, ResponseID, ContentBlockID, T
3
3
  export type { BaseRequest, ContentPartInput, GenerationOptionsFields, HttpOptions, RequestOptions, LanguageModelInput, LanguageModelProviderOptions, LLMRequest, MediaPartInput, RequestTimeout, TimeoutConfig, ToolDefinitionInput, ToolNamespaceInput, ToolNamespaceEntryInput, ToolEntryInput, TransportOptions, UsageInput, } from "./schema/index.js";
4
4
  export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageResponse } from "./image.js";
5
5
  export type { ImageModelOptions, ImageOptions, ImageRequest, ImageRequestInput, ImageResolution, ImageRoute, } from "./image.js";
6
+ export { VideoAspectRatio, VideoDuration, VideoModel, VideoModelSchema, VideoResponse } from "./video.js";
7
+ export type { VideoJob, VideoModelOptions, VideoOptions, VideoRequest, VideoRequestInput, VideoResolution, VideoRoute, VideoStatus, } from "./video.js";
6
8
  export { ChoiceAnswer, ChoiceQuestion, ChoiceValue, DecisionAnswer, DecisionJsonPart, DecisionMediaPart, DecisionModel, DecisionModelCompatibility, DecisionModelSchema, DecisionPart, DecisionQuestion, DecisionResponse, DecisionTextPart, DecisionUsage, ErrorAnswer, ErrorReason, PredicateAnswer, PredicateQuestion, ScoreAnswer, ScoreQuestion, } from "./decision.js";
7
9
  export type { AnswerFor, AnswersFor, DecisionInput, DecisionMediaPartInput, DecisionModelOptions, DecisionOptions, DecisionPartInput, DecisionQuestions, DecisionRequest, DecisionRequestInput, DecisionResponseFor, DecisionModelRoute, } from "./decision.js";
8
10
  export { EmbeddingModel, EmbeddingModelSchema, EmbeddingResponse, EmbeddingUsage, EmbeddingValue } from "./embedding.js";