@opencode/ai 0.0.0-dev-1286 → 0.0.0-dev-1288

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 (52) hide show
  1. package/README.md +52 -10
  2. package/dist/effect.d.ts +3 -1
  3. package/dist/image-client.d.ts +52 -59
  4. package/dist/image-client.js +47 -8
  5. package/dist/image.d.ts +27 -7
  6. package/dist/image.js +10 -6
  7. package/dist/index.d.ts +12 -7
  8. package/dist/index.js +12 -7
  9. package/dist/media-client.d.ts +13 -5
  10. package/dist/media-client.js +42 -37
  11. package/dist/media.d.ts +8 -0
  12. package/dist/media.js +14 -0
  13. package/dist/protocols/google-interactions-video.d.ts +38 -0
  14. package/dist/protocols/google-interactions-video.js +187 -0
  15. package/dist/protocols/google-interactions.d.ts +14 -1
  16. package/dist/protocols/google-interactions.js +1 -1
  17. package/dist/protocols/minimax-video.d.ts +45 -0
  18. package/dist/protocols/minimax-video.js +293 -0
  19. package/dist/protocols/openrouter-video.d.ts +4 -9
  20. package/dist/protocols/openrouter-video.js +8 -7
  21. package/dist/protocols/seedance-video.d.ts +4 -9
  22. package/dist/protocols/seedance-video.js +9 -8
  23. package/dist/protocols/utils/responses-compaction.js +1 -1
  24. package/dist/protocols/xai-video.d.ts +4 -9
  25. package/dist/protocols/xai-video.js +8 -7
  26. package/dist/providers/google/videos.d.ts +2 -0
  27. package/dist/providers/google/videos.js +1 -0
  28. package/dist/providers/google.d.ts +5 -0
  29. package/dist/providers/google.js +7 -0
  30. package/dist/providers/minimax/videos.d.ts +3 -0
  31. package/dist/providers/minimax/videos.js +1 -0
  32. package/dist/providers/minimax.d.ts +6 -1
  33. package/dist/providers/minimax.js +10 -1
  34. package/dist/providers/xai/videos.d.ts +2 -0
  35. package/dist/providers/xai/videos.js +1 -0
  36. package/dist/providers/xai.d.ts +4 -3
  37. package/dist/providers/xai.js +5 -1
  38. package/dist/public.d.ts +1 -1
  39. package/dist/route/executor-service.d.ts +6 -0
  40. package/dist/route/executor-service.js +7 -0
  41. package/dist/route/executor.d.ts +7 -1
  42. package/dist/route/executor.js +7 -2
  43. package/dist/route/media-protocol.d.ts +5 -0
  44. package/dist/route/media.js +4 -3
  45. package/dist/route/transport/http.js +1 -1
  46. package/dist/schema/options.d.ts +8 -0
  47. package/dist/schema/options.js +1 -0
  48. package/dist/video-client.d.ts +6 -6
  49. package/dist/video-client.js +13 -11
  50. package/dist/video.d.ts +14 -72
  51. package/dist/video.js +9 -8
  52. package/package.json +19 -3
package/dist/media.d.ts CHANGED
@@ -190,6 +190,12 @@ export declare const AssetSchema: Schema.decodeTo<Schema.declare<Asset, Asset>,
190
190
  }>>;
191
191
  readonly providerMetadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
192
192
  }>, never, never>;
193
+ /**
194
+ * An image, or a URL or provider file reference whose type it doesn't state, which the provider checks itself. Build one with
195
+ * `Media.image`; an asset known to be a video, audio or document is rejected.
196
+ */
197
+ export declare const ImageAssetSchema: Schema.brand<Schema.declare<Asset, Asset>, "Media.ImageAsset">;
198
+ export type ImageAsset = typeof ImageAssetSchema.Type;
193
199
  export type AssetOptions = Omit<Asset.Input, "source">;
194
200
  export declare const from: (source: Source, options?: AssetOptions) => Asset;
195
201
  export declare const bytes: (data: Uint8Array, mediaType?: string, options?: AssetOptions) => Asset;
@@ -206,6 +212,8 @@ export declare const fromDataUrl: (dataUrl: string, options?: AssetOptions) => A
206
212
  export type Data = Uint8Array | ArrayBuffer | URL | string;
207
213
  /** What file inputs accept: an `Asset` or plain `Data`. */
208
214
  export type Input = Asset | Data;
215
+ /** Normalize input into an `ImageAsset`; throws when it's known not to be an image. */
216
+ export declare const image: (input: Input, mediaType?: string) => ImageAsset;
209
217
  /**
210
218
  * Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic
211
219
  * bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged.
package/dist/media.js CHANGED
@@ -178,6 +178,13 @@ export const AssetSchema = AssetEncoded.pipe(Schema.decodeTo(AssetInstance, {
178
178
  decode: SchemaGetter.transform((encoded) => new Asset(encoded)),
179
179
  encode: SchemaGetter.transform(encodeAsset),
180
180
  }));
181
+ /**
182
+ * An image, or a URL or provider file reference whose type it doesn't state, which the provider checks itself. Build one with
183
+ * `Media.image`; an asset known to be a video, audio or document is rejected.
184
+ */
185
+ export const ImageAssetSchema = AssetInstance.check(Schema.makeFilter((asset) => asset.kind === "image" ||
186
+ ((asset.source.type === "url" || asset.source.type === "ref") && asset.source.mediaType === undefined) ||
187
+ `expected an image, got ${asset.mediaType}`)).pipe(Schema.brand("Media.ImageAsset"));
181
188
  const download = Effect.fn("Media.download")(function* (source, headers) {
182
189
  const executor = yield* Service;
183
190
  const response = yield* executor.execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})));
@@ -222,6 +229,13 @@ export const fromDataUrl = (dataUrl, options) => {
222
229
  throw invalid("Media data URLs must contain a MIME type and base64 data");
223
230
  return asset;
224
231
  };
232
+ /** Normalize input into an `ImageAsset`; throws when it's known not to be an image. */
233
+ export const image = (input, mediaType) => {
234
+ const asset = make(input, mediaType);
235
+ if (!Schema.is(ImageAssetSchema)(asset))
236
+ throw invalid(`expected an image, got ${asset.mediaType}`);
237
+ return asset;
238
+ };
225
239
  /**
226
240
  * Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic
227
241
  * bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged.
@@ -0,0 +1,38 @@
1
+ import { Schema } from "effect";
2
+ import { MediaProtocol } from "../route/media-protocol.js";
3
+ import { MediaRoute } from "../route/media.js";
4
+ import { type OpenString } from "../schema/index.js";
5
+ import { VideoModel, VideoResponse, type VideoRequest } from "../video.js";
6
+ export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
7
+ export declare const PATH = "/interactions";
8
+ /**
9
+ * Provider-native Interactions fields, merged into the body. Common fields (`start`, `end`, `references`,
10
+ * `duration`, `aspect`, `resolution`) live on the request. Edit or extend a video by passing it as a reference with
11
+ * `generation_config.video_config.task`, or continue a generated one with `previous_interaction_id`.
12
+ */
13
+ export type GoogleVideoOptions = {
14
+ readonly previous_interaction_id?: string;
15
+ readonly generation_config?: {
16
+ readonly video_config?: {
17
+ readonly task?: OpenString<"text_to_video" | "image_to_video" | "reference_to_video" | "edit" | "extend">;
18
+ } & Record<string, unknown>;
19
+ } & Record<string, unknown>;
20
+ readonly response_format?: {
21
+ readonly delivery?: OpenString<"inline" | "uri">;
22
+ } & Record<string, unknown>;
23
+ readonly service_tier?: OpenString<"flex" | "standard" | "priority">;
24
+ readonly webhook_config?: {
25
+ readonly uris?: ReadonlyArray<string>;
26
+ readonly user_metadata?: Record<string, unknown>;
27
+ };
28
+ } & Record<string, unknown>;
29
+ export type Request = VideoRequest<VideoModel<GoogleVideoOptions>>;
30
+ /** The provider's job ID; it is all a later status, result or cancel call needs. */
31
+ export declare const Token: Schema.String;
32
+ export type Token = Schema.Schema.Type<typeof Token>;
33
+ export declare const protocol: MediaProtocol.Queued<Request, VideoResponse, string>;
34
+ export declare const model: (input: MediaRoute.ModelInput) => VideoModel<GoogleVideoOptions>;
35
+ export declare const GoogleInteractionsVideo: {
36
+ readonly protocol: MediaProtocol.Queued<Request, VideoResponse, string>;
37
+ readonly model: typeof model;
38
+ };
@@ -0,0 +1,187 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { Media } from "../media.js";
3
+ import { MediaProtocol } from "../route/media-protocol.js";
4
+ import { MediaRoute } from "../route/media.js";
5
+ import { mergeJsonRecords, tokenUsage } from "../schema/index.js";
6
+ import { VideoModel, VideoResponse, seconds } from "../video.js";
7
+ import { GoogleInteractions } from "./google-interactions.js";
8
+ import { optionalNull } from "./shared.js";
9
+ import { GeminiGenerateContent } from "./utils/gemini-generate-content.js";
10
+ import { MediaInput } from "./utils/media-input.js";
11
+ const route = MediaProtocol.identity({
12
+ id: "google-interactions-video",
13
+ name: "Google Interactions Video",
14
+ provider: "google",
15
+ });
16
+ export const DEFAULT_BASE_URL = GoogleInteractions.DEFAULT_BASE_URL;
17
+ export const PATH = "/interactions";
18
+ // ---------------------------------------------------------------------------
19
+ // 2. Token and response schemas
20
+ // ---------------------------------------------------------------------------
21
+ /** The provider's job ID; it is all a later status, result or cancel call needs. */
22
+ export const Token = Schema.String;
23
+ const Content = Schema.Struct({
24
+ type: Schema.String,
25
+ data: optionalNull(Schema.String),
26
+ uri: optionalNull(Schema.String),
27
+ mime_type: optionalNull(Schema.String),
28
+ text: optionalNull(Schema.String),
29
+ });
30
+ const Usage = Schema.StructWithRest(Schema.Struct({
31
+ total_input_tokens: optionalNull(Schema.Number),
32
+ total_output_tokens: optionalNull(Schema.Number),
33
+ total_thought_tokens: optionalNull(Schema.Number),
34
+ total_tokens: optionalNull(Schema.Number),
35
+ }), [Schema.Record(Schema.String, Schema.Unknown)]);
36
+ const Interaction = Schema.Struct({
37
+ id: Schema.String,
38
+ status: Schema.String,
39
+ model: optionalNull(Schema.String),
40
+ steps: optionalNull(Schema.Array(Schema.Struct({ type: Schema.String, content: optionalNull(Schema.Array(Content)) }))),
41
+ usage: optionalNull(Usage),
42
+ errors: optionalNull(Schema.Array(Schema.Struct({ code: optionalNull(Schema.String), message: optionalNull(Schema.String) }))),
43
+ });
44
+ // `incomplete` is terminal ("completed, but contains incomplete results"); the result read decides whether a video
45
+ // came back. `requires_action` and `requires_continuation` are not documented for video and stay running.
46
+ const STATUS = {
47
+ in_progress: "running",
48
+ completed: "completed",
49
+ incomplete: "completed",
50
+ failed: "failed",
51
+ cancelled: "cancelled",
52
+ };
53
+ // ---------------------------------------------------------------------------
54
+ // 3. Failures
55
+ // ---------------------------------------------------------------------------
56
+ // Interaction error codes are documented only as "a URI that identifies the error type"; the last segment carries the
57
+ // canonical Google status name.
58
+ const FAILURE = {
59
+ INVALID_ARGUMENT: "InvalidRequest",
60
+ FAILED_PRECONDITION: "InvalidRequest",
61
+ OUT_OF_RANGE: "InvalidRequest",
62
+ PERMISSION_DENIED: "Authentication",
63
+ UNAUTHENTICATED: "Authentication",
64
+ RESOURCE_EXHAUSTED: "RateLimit",
65
+ };
66
+ const errorCode = (code) => code?.split("/").at(-1)?.trim().toUpperCase().replaceAll("-", "_") || undefined;
67
+ // ---------------------------------------------------------------------------
68
+ // 5. Request body construction
69
+ // ---------------------------------------------------------------------------
70
+ // Omni has no role field for media: it reads one image as the start frame and two as start and end. The task hint
71
+ // pins that reading when only frames, or only references, are sent; with both, the prompt decides.
72
+ const task = (request) => {
73
+ const frames = request.start !== undefined || request.end !== undefined;
74
+ const references = (request.references ?? []).length > 0;
75
+ if (frames && !references)
76
+ return "image_to_video";
77
+ if (references && !frames)
78
+ return "reference_to_video";
79
+ return undefined;
80
+ };
81
+ const fromRequest = Effect.fn("GoogleInteractionsVideo.fromRequest")(function* (request) {
82
+ if (request.end !== undefined && request.start === undefined)
83
+ return yield* route.unsupported("video.end", `${route.name} reads a lone image as the start frame; send start too`);
84
+ if (request.sound === false)
85
+ return yield* route.unsupported("video.sound", `${route.name} always generates audio and has no option to turn it off`);
86
+ const media = yield* Effect.forEach([request.start, request.end, ...(request.references ?? [])].filter((asset) => asset !== undefined), GoogleInteractions.mediaContent);
87
+ const responseFormat = {
88
+ // `auto` follows the input image, which Omni expresses by leaving the ratio out.
89
+ aspect_ratio: request.aspect === "auto" ? undefined : request.aspect,
90
+ resolution: request.resolution?.toLowerCase(),
91
+ duration: request.duration === undefined ? undefined : `${seconds(request.duration)}s`,
92
+ };
93
+ const videoTask = task(request);
94
+ return MediaProtocol.json(mergeJsonRecords({
95
+ model: request.model.id,
96
+ input: [...media, { type: "text", text: request.prompt }],
97
+ background: true,
98
+ response_format: Object.values(responseFormat).some((value) => value !== undefined)
99
+ ? { type: "video", ...responseFormat }
100
+ : undefined,
101
+ generation_config: videoTask === undefined ? undefined : { video_config: { task: videoTask } },
102
+ }, request.providerOptions, request.http?.body) ?? {});
103
+ });
104
+ // ---------------------------------------------------------------------------
105
+ // 6. Response decoding
106
+ // ---------------------------------------------------------------------------
107
+ const decodeStart = route.decodeStarted(Interaction, (value) => ({
108
+ token: value.id,
109
+ snapshot: { id: value.id, status: MediaProtocol.status(STATUS, value.status) },
110
+ }));
111
+ const decodeInteraction = route.decodeJson(Interaction);
112
+ const decodeStatus = Effect.fn("GoogleInteractionsVideo.decodeStatus")(function* (response, context) {
113
+ const output = yield* decodeInteraction(response);
114
+ return { id: context.token, status: MediaProtocol.status(STATUS, output.value.status) };
115
+ });
116
+ const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function* (response, context) {
117
+ const output = yield* decodeInteraction(response);
118
+ const decoded = output.value;
119
+ const status = MediaProtocol.status(STATUS, decoded.status);
120
+ if (status === "running")
121
+ return yield* output.pending(context.token);
122
+ const errors = decoded.errors ?? [];
123
+ const codes = errors.flatMap((error) => {
124
+ const code = errorCode(error.code);
125
+ return code === undefined ? [] : [code];
126
+ });
127
+ const messages = errors.flatMap((error) => (error.message?.trim() ? [error.message.trim()] : []));
128
+ if (status === "cancelled")
129
+ return yield* output.ended("cancelled", `${route.name} interaction ${context.token} was cancelled`);
130
+ if (status === "failed") {
131
+ const message = `${route.name} generation failed${codes.length === 0 ? "" : ` (${codes.join(", ")})`}${messages.length === 0 ? "" : `: ${messages.join("\n")}`}`;
132
+ if (codes.some((code) => code === "CONTENT_BLOCKED" || GeminiGenerateContent.contentFiltered(code)))
133
+ return yield* output.contentPolicy(message);
134
+ return yield* output.ended("failed", message, MediaProtocol.failure(FAILURE, codes[0]));
135
+ }
136
+ const contents = (decoded.steps ?? []).flatMap((step) => (step.type === "model_output" ? (step.content ?? []) : []));
137
+ const videos = yield* Effect.forEach(contents.filter((content) => content.type === "video"), (content, index) => {
138
+ const mediaType = content.mime_type ?? undefined;
139
+ if (content.data)
140
+ return MediaInput.decodedAsset(output.invalid, `${route.name} video ${index}`, content.data, mediaType);
141
+ // `GET /interactions/{id}` documents inline data even for `delivery: "uri"`; a Files API URI needs the API key
142
+ // to download, so it stays a Google reference that can be passed back as input.
143
+ if (content.uri)
144
+ return Effect.succeed(Media.ref(route.provider, content.uri, mediaType));
145
+ return Effect.fail(output.invalid(`${route.name} returned a video without data or a URI`));
146
+ });
147
+ if (videos.length === 0) {
148
+ if (codes.some((code) => code === "CONTENT_BLOCKED" || GeminiGenerateContent.contentFiltered(code)))
149
+ return yield* output.contentPolicy(`${route.name} withheld the video${messages.length === 0 ? "" : `: ${messages.join("\n")}`}`);
150
+ return yield* output.invalid(`${route.name} ${decoded.status} without a video`);
151
+ }
152
+ const usage = decoded.usage ?? undefined;
153
+ return new VideoResponse({
154
+ videos,
155
+ usage: usage === undefined
156
+ ? undefined
157
+ : tokenUsage({
158
+ input: usage.total_input_tokens ?? undefined,
159
+ output: usage.total_output_tokens ?? undefined,
160
+ total: usage.total_tokens ?? undefined,
161
+ details: { reasoningTokens: usage.total_thought_tokens ?? undefined, google: usage },
162
+ }),
163
+ providerMetadata: {
164
+ google: {
165
+ interactionId: decoded.id,
166
+ model: decoded.model ?? undefined,
167
+ status: decoded.status,
168
+ },
169
+ },
170
+ });
171
+ });
172
+ // ---------------------------------------------------------------------------
173
+ // 7. Protocol and route
174
+ // ---------------------------------------------------------------------------
175
+ const interactionPath = (token) => `${PATH}/${encodeURIComponent(token)}`;
176
+ export const protocol = MediaProtocol.queued(route, {
177
+ token: Token,
178
+ start: { body: { from: fromRequest }, decode: decodeStart },
179
+ status: { path: interactionPath, decode: decodeStatus },
180
+ result: { path: interactionPath, decode: decodeResult },
181
+ cancel: { method: "POST", path: (token) => `${interactionPath(token)}/cancel` },
182
+ });
183
+ export const model = (input) => VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input);
184
+ export const GoogleInteractionsVideo = {
185
+ protocol,
186
+ model,
187
+ };
@@ -1,6 +1,8 @@
1
- import { Schema } from "effect";
1
+ import { Effect, Schema } from "effect";
2
2
  import { Route } from "../route/client.js";
3
3
  import { Protocol } from "../route/protocol.js";
4
+ import { AIError } from "../schema/index.js";
5
+ import { Media } from "../media.js";
4
6
  import { Lifecycle } from "./utils/lifecycle.js";
5
7
  import { ToolStream } from "./utils/tool-stream.js";
6
8
  export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
@@ -36,6 +38,17 @@ interface ParserState {
36
38
  readonly steps: Partial<Record<number, OutputStep>>;
37
39
  readonly tools: ToolStream.State<number>;
38
40
  }
41
+ export declare const mediaContent: (asset: Media.Asset) => Effect.Effect<{
42
+ type: "audio" | "document" | "image" | "video";
43
+ uri: string;
44
+ mime_type: string;
45
+ data?: undefined;
46
+ } | {
47
+ uri?: undefined;
48
+ type: "audio" | "document" | "image" | "video";
49
+ data: string;
50
+ mime_type: string;
51
+ }, AIError, never>;
39
52
  export declare const protocol: Protocol<{
40
53
  readonly model: string;
41
54
  readonly input: readonly ({
@@ -172,7 +172,7 @@ const Event = Schema.Union([
172
172
  // =============================================================================
173
173
  // Request Body Construction
174
174
  // =============================================================================
175
- const mediaContent = Effect.fnUntraced(function* (asset) {
175
+ export const mediaContent = Effect.fnUntraced(function* (asset) {
176
176
  if (asset.kind !== "image" &&
177
177
  asset.kind !== "audio" &&
178
178
  asset.kind !== "video" &&
@@ -0,0 +1,45 @@
1
+ import { Schema } from "effect";
2
+ import { MediaProtocol } from "../route/media-protocol.js";
3
+ import { MediaRoute } from "../route/media.js";
4
+ import { type OpenString } from "../schema/index.js";
5
+ import { VideoModel, VideoResponse, type VideoRequest } from "../video.js";
6
+ /** The API host without a version: H3 is served under `/v2` and Hailuo under `/v1`. */
7
+ export declare const DEFAULT_BASE_URL = "https://api.minimax.io";
8
+ export declare const PATH = "/v2/video_generation";
9
+ export declare const STATUS_PATH = "/v2/query/video_generation";
10
+ export declare const HAILUO_PATH = "/v1/video_generation";
11
+ export declare const HAILUO_STATUS_PATH = "/v1/query/video_generation";
12
+ export declare const FILE_PATH = "/v1/files/retrieve";
13
+ /**
14
+ * Provider-native options, merged into the body. Common fields (`start`, `end`, `references`, `duration`, `aspect`,
15
+ * `resolution`, `sound`) live on the request. `extra` and `response_format` are H3 (v2) fields; `prompt_optimizer`
16
+ * and `fast_pretreatment` are Hailuo (v1) fields; both APIs take `callback_url`.
17
+ */
18
+ export type MiniMaxVideoOptions = {
19
+ readonly extra?: {
20
+ readonly prompt_expansion_mode?: OpenString<"disabled" | "balanced" | "quality">;
21
+ };
22
+ readonly response_format?: OpenString<"task" | "flat">;
23
+ readonly prompt_optimizer?: boolean;
24
+ readonly fast_pretreatment?: boolean;
25
+ readonly callback_url?: string;
26
+ } & Record<string, unknown>;
27
+ export type Request = VideoRequest<VideoModel<MiniMaxVideoOptions>>;
28
+ /** The provider's job ID; it is all a later status, result or cancel call needs. */
29
+ export declare const Token: Schema.String;
30
+ export type Token = Schema.Schema.Type<typeof Token>;
31
+ export declare const protocol: MediaProtocol.Queued<Request, VideoResponse, string>;
32
+ export declare const hailuoProtocol: MediaProtocol.Queued<Request, VideoResponse, string>;
33
+ /** H3 and later models on the v2 API. */
34
+ export declare const h3Model: (input: MediaRoute.ModelInput) => VideoModel<MiniMaxVideoOptions>;
35
+ /** Hailuo and the `*-01` models on the v1 API. */
36
+ export declare const hailuoModel: (input: MediaRoute.ModelInput) => VideoModel<MiniMaxVideoOptions>;
37
+ /** Picks the API by model family: Hailuo and `*-01` models use v1, everything else v2. */
38
+ export declare const model: (input: MediaRoute.ModelInput) => VideoModel<MiniMaxVideoOptions>;
39
+ export declare const MiniMaxVideo: {
40
+ readonly protocol: MediaProtocol.Queued<Request, VideoResponse, string>;
41
+ readonly hailuoProtocol: MediaProtocol.Queued<Request, VideoResponse, string>;
42
+ readonly model: typeof model;
43
+ readonly h3Model: typeof h3Model;
44
+ readonly hailuoModel: typeof hailuoModel;
45
+ };
@@ -0,0 +1,293 @@
1
+ import { Duration, Effect, Schema } from "effect";
2
+ import { Media } from "../media.js";
3
+ import { MediaProtocol } from "../route/media-protocol.js";
4
+ import { MediaRoute } from "../route/media.js";
5
+ import { AIError, QuotaExceededError, mergeJsonRecords } from "../schema/index.js";
6
+ import { VideoModel, VideoResponse, seconds } from "../video.js";
7
+ import { ProviderShared, optionalNull } from "./shared.js";
8
+ // MiniMax runs two video APIs with different bodies, statuses and results: H3 on v2 and Hailuo on v1.
9
+ const route = MediaProtocol.identity({ id: "minimax-video", name: "MiniMax Video", provider: "minimax" });
10
+ const hailuoRoute = MediaProtocol.identity({
11
+ id: "minimax-hailuo-video",
12
+ name: "MiniMax Hailuo Video",
13
+ provider: "minimax",
14
+ });
15
+ /** The API host without a version: H3 is served under `/v2` and Hailuo under `/v1`. */
16
+ export const DEFAULT_BASE_URL = "https://api.minimax.io";
17
+ export const PATH = "/v2/video_generation";
18
+ export const STATUS_PATH = "/v2/query/video_generation";
19
+ export const HAILUO_PATH = "/v1/video_generation";
20
+ export const HAILUO_STATUS_PATH = "/v1/query/video_generation";
21
+ export const FILE_PATH = "/v1/files/retrieve";
22
+ const DOWNLOAD_RETENTION = Duration.hours(1);
23
+ // ---------------------------------------------------------------------------
24
+ // 2. Token and response schemas
25
+ // ---------------------------------------------------------------------------
26
+ /** The provider's job ID; it is all a later status, result or cancel call needs. */
27
+ export const Token = Schema.String;
28
+ const BaseResp = optionalNull(Schema.Struct({
29
+ status_code: Schema.Number,
30
+ status_msg: optionalNull(Schema.String),
31
+ }));
32
+ const StartResponse = Schema.Struct({ task_id: Schema.String });
33
+ const Task = Schema.Struct({
34
+ id: optionalNull(Schema.String),
35
+ model: optionalNull(Schema.String),
36
+ status: optionalNull(Schema.String),
37
+ error: optionalNull(Schema.Struct({
38
+ code: optionalNull(Schema.Union([Schema.String, Schema.Number])),
39
+ message: optionalNull(Schema.String),
40
+ })),
41
+ content: optionalNull(Schema.Struct({ url: optionalNull(Schema.String) })),
42
+ resolution: optionalNull(Schema.String),
43
+ duration: optionalNull(Schema.Number),
44
+ ratio: optionalNull(Schema.String),
45
+ usage: optionalNull(Schema.Record(Schema.String, Schema.Unknown)),
46
+ });
47
+ // `response_format: "flat"` moves the task fields from `task` to the top level.
48
+ const TaskResponse = Schema.Struct({ ...Task.fields, task: optionalNull(Task) });
49
+ const HailuoStartResponse = Schema.Struct({ task_id: optionalNull(Schema.String), base_resp: BaseResp });
50
+ const HailuoTask = Schema.Struct({
51
+ status: optionalNull(Schema.String),
52
+ file_id: optionalNull(Schema.String),
53
+ video_width: optionalNull(Schema.Number),
54
+ video_height: optionalNull(Schema.Number),
55
+ base_resp: BaseResp,
56
+ });
57
+ const HailuoFile = Schema.Struct({
58
+ file: optionalNull(Schema.Struct({
59
+ download_url: optionalNull(Schema.String),
60
+ })),
61
+ base_resp: BaseResp,
62
+ });
63
+ const STATUS = {
64
+ queued: "queued",
65
+ running: "running",
66
+ succeeded: "completed",
67
+ failed: "failed",
68
+ cancelled: "cancelled",
69
+ };
70
+ const HAILUO_STATUS = {
71
+ Preparing: "queued",
72
+ Queueing: "queued",
73
+ Processing: "running",
74
+ Success: "completed",
75
+ Fail: "failed",
76
+ };
77
+ // ---------------------------------------------------------------------------
78
+ // 3. Failures
79
+ // ---------------------------------------------------------------------------
80
+ // Error codes from https://platform.minimax.io/docs/api-reference/errorcode; unknown codes are provider-side.
81
+ const FAILURE = {
82
+ 1002: "RateLimit",
83
+ 1004: "Authentication",
84
+ 1039: "RateLimit",
85
+ 2013: "InvalidRequest",
86
+ 2049: "Authentication",
87
+ };
88
+ const INSUFFICIENT_BALANCE = 1008;
89
+ // 1026 flags the input and 1027 the generated video.
90
+ const CONTENT_POLICY = new Set(["1026", "1027"]);
91
+ const failed = (output, name, code, detail) => {
92
+ const message = `${name} generation failed${code === undefined ? "" : ` (${code})`}${detail === undefined ? "" : `: ${detail}`}`;
93
+ if (code !== undefined && CONTENT_POLICY.has(String(code)))
94
+ return output.contentPolicy(message);
95
+ if (code !== undefined && Number(code) === INSUFFICIENT_BALANCE)
96
+ return new AIError({ reason: new QuotaExceededError({ message, body: output.body, http: output.http }) });
97
+ return output.ended("failed", message, MediaProtocol.failure(FAILURE, code));
98
+ };
99
+ // v1 answers errors with HTTP 200 and a non-zero `base_resp.status_code`.
100
+ const baseError = (output, base) => base === undefined || base === null || base.status_code === 0
101
+ ? undefined
102
+ : failed(output, hailuoRoute.name, base.status_code, base.status_msg ?? undefined);
103
+ // ---------------------------------------------------------------------------
104
+ // 5. Request body construction
105
+ // ---------------------------------------------------------------------------
106
+ /** H3 takes URLs, data URIs and `mm_file://{file_id}` references to MiniMax files. */
107
+ const mediaUrl = (asset) => ProviderShared.mediaReference(asset, route.provider, route.name).pipe(Effect.map((reference) => (reference.type === "ref" ? `mm_file://${reference.value}` : reference.value)));
108
+ const ROLES = { image: "reference_image", video: "reference_video", audio: "reference_audio" };
109
+ const item = (asset, role) => mediaUrl(asset).pipe(Effect.map((url) => {
110
+ const type = asset.kind === "video" ? "video_url" : asset.kind === "audio" ? "audio_url" : "image_url";
111
+ return { type, [type]: { url }, role };
112
+ }));
113
+ const reference = (asset) => item(asset, asset.kind === "video" || asset.kind === "audio" ? ROLES[asset.kind] : ROLES.image);
114
+ /** MiniMax spells resolutions in uppercase (`480P`, `768P`, `2K`). */
115
+ const resolution = (request) => request.resolution?.toUpperCase();
116
+ const fromRequest = Effect.fn("MiniMaxVideo.fromRequest")(function* (request) {
117
+ // H3 always generates a soundtrack and has no field to turn it off.
118
+ if (request.sound === false)
119
+ return yield* route.unsupported("video.sound", `${route.name} always generates sound and can't be silenced`);
120
+ const content = [
121
+ { type: "text", text: request.prompt },
122
+ ...(request.start === undefined ? [] : [yield* item(request.start, "first_frame")]),
123
+ ...(request.end === undefined ? [] : [yield* item(request.end, "last_frame")]),
124
+ ...(yield* Effect.forEach(request.references ?? [], reference)),
125
+ ];
126
+ return MediaProtocol.json(mergeJsonRecords({
127
+ model: request.model.id,
128
+ content,
129
+ resolution: resolution(request),
130
+ duration: request.duration === undefined ? undefined : seconds(request.duration),
131
+ ratio: request.aspect === "auto" ? "adaptive" : request.aspect,
132
+ }, request.providerOptions, request.http?.body) ?? {});
133
+ });
134
+ /** v1 documents URLs and data URLs only, so MiniMax file references aren't sent. */
135
+ const hailuoUrl = (asset) => ProviderShared.mediaReference(asset, undefined, hailuoRoute.name).pipe(Effect.map((reference) => reference.value));
136
+ const hailuoFromRequest = Effect.fn("MiniMaxHailuoVideo.fromRequest")(function* (request) {
137
+ const references = request.references ?? [];
138
+ if (references.some((asset) => asset.kind === "video" || asset.kind === "audio"))
139
+ return yield* hailuoRoute.unsupported("video.references", `${hailuoRoute.name} takes only image (subject) references`);
140
+ // Hailuo output is always silent and its shape follows the model or the first frame, with no field for either.
141
+ if (request.sound === true)
142
+ return yield* hailuoRoute.unsupported("video.sound", `${hailuoRoute.name} generates silent video only`);
143
+ if (request.aspect !== undefined && request.aspect !== "auto")
144
+ return yield* hailuoRoute.unsupported("video.aspect", `${hailuoRoute.name} has no aspect ratio input`);
145
+ const subjects = yield* Effect.forEach(references, (asset) => hailuoUrl(asset).pipe(Effect.map((url) => ({ type: "character", image: [url] }))));
146
+ return MediaProtocol.json(mergeJsonRecords({
147
+ model: request.model.id,
148
+ prompt: request.prompt,
149
+ first_frame_image: request.start === undefined ? undefined : yield* hailuoUrl(request.start),
150
+ last_frame_image: request.end === undefined ? undefined : yield* hailuoUrl(request.end),
151
+ subject_reference: subjects.length === 0 ? undefined : subjects,
152
+ duration: request.duration === undefined ? undefined : seconds(request.duration),
153
+ resolution: resolution(request),
154
+ }, request.providerOptions, request.http?.body) ?? {});
155
+ });
156
+ // ---------------------------------------------------------------------------
157
+ // 6. Response decoding
158
+ // ---------------------------------------------------------------------------
159
+ const decodeStart = route.decodeStarted(StartResponse, (value) => ({
160
+ token: value.task_id,
161
+ snapshot: { id: value.task_id, status: "queued" },
162
+ }));
163
+ const decodeTask = route.decodeJson(TaskResponse);
164
+ const decodeStatus = Effect.fn("MiniMaxVideo.decodeStatus")(function* (response, context) {
165
+ const output = yield* decodeTask(response);
166
+ const task = output.value.task ?? output.value;
167
+ return { id: context.token, status: MediaProtocol.status(STATUS, task.status ?? "") };
168
+ });
169
+ const decodeResult = Effect.fn("MiniMaxVideo.decodeResult")(function* (response, context) {
170
+ const output = yield* decodeTask(response);
171
+ const task = output.value.task ?? output.value;
172
+ const status = MediaProtocol.status(STATUS, task.status ?? "");
173
+ if (status === "queued" || status === "running")
174
+ return yield* output.pending(context.token);
175
+ if (status === "failed")
176
+ return yield* failed(output, route.name, task.error?.code ?? undefined, task.error?.message ?? undefined);
177
+ if (status !== "completed")
178
+ return yield* output.ended("cancelled", `${route.name} task ${context.token} was cancelled`);
179
+ const url = task.content?.url ?? undefined;
180
+ if (url === undefined)
181
+ return yield* output.invalid(`${route.name} completed without a video URL`);
182
+ const duration = task.duration ?? undefined;
183
+ const total = task.usage?.total_seconds;
184
+ return new VideoResponse({
185
+ // The URL is time-limited without a documented window; reading the result again returns a fresh one.
186
+ videos: [
187
+ Media.url(url, {
188
+ mediaType: "video/mp4",
189
+ info: duration === undefined ? undefined : { durationSeconds: duration },
190
+ }),
191
+ ],
192
+ usage: typeof total === "number" ? { type: "seconds", seconds: total } : undefined,
193
+ providerMetadata: {
194
+ minimax: {
195
+ taskId: context.token,
196
+ model: task.model ?? undefined,
197
+ resolution: task.resolution ?? undefined,
198
+ ratio: task.ratio ?? undefined,
199
+ usage: task.usage ?? undefined,
200
+ },
201
+ },
202
+ });
203
+ });
204
+ const decodeHailuoStart = Effect.fn("MiniMaxHailuoVideo.decodeStart")(function* (response) {
205
+ const output = yield* hailuoRoute.decodeJson(HailuoStartResponse)(response);
206
+ const error = baseError(output, output.value.base_resp);
207
+ if (error)
208
+ return yield* error;
209
+ const taskID = output.value.task_id ?? "";
210
+ if (taskID === "")
211
+ return yield* output.invalid(`${hailuoRoute.name} returned no task_id`);
212
+ return { token: taskID, snapshot: { id: taskID, status: "queued" } };
213
+ });
214
+ const decodeHailuoTask = hailuoRoute.decodeJson(HailuoTask);
215
+ const decodeHailuoStatus = Effect.fn("MiniMaxHailuoVideo.decodeStatus")(function* (response, context) {
216
+ const output = yield* decodeHailuoTask(response);
217
+ const status = MediaProtocol.status(HAILUO_STATUS, output.value.status ?? "");
218
+ // A failed task also carries its reason in `base_resp`; any other non-zero code is a failed read.
219
+ const error = status === "failed" ? undefined : baseError(output, output.value.base_resp);
220
+ if (error)
221
+ return yield* error;
222
+ return { id: context.token, status };
223
+ });
224
+ const decodeHailuoFile = hailuoRoute.decodeJson(HailuoFile);
225
+ const decodeHailuoResult = Effect.fn("MiniMaxHailuoVideo.decodeResult")(function* (response, context) {
226
+ const output = yield* decodeHailuoTask(response);
227
+ const task = output.value;
228
+ const status = MediaProtocol.status(HAILUO_STATUS, task.status ?? "");
229
+ const error = baseError(output, task.base_resp);
230
+ if (status === "failed")
231
+ return yield* error ?? failed(output, hailuoRoute.name, undefined, undefined);
232
+ if (error)
233
+ return yield* error;
234
+ if (status !== "completed")
235
+ return yield* output.pending(context.token);
236
+ const fileID = task.file_id ?? "";
237
+ if (fileID === "")
238
+ return yield* output.invalid(`${hailuoRoute.name} completed without a file_id`);
239
+ // The task names a file; its download URL takes a second lookup and is valid for one hour.
240
+ const file = yield* decodeHailuoFile(yield* context.get(`${FILE_PATH}?file_id=${encodeURIComponent(fileID)}`));
241
+ const fileError = baseError(file, file.value.base_resp);
242
+ if (fileError)
243
+ return yield* fileError;
244
+ const url = file.value.file?.download_url ?? undefined;
245
+ if (url === undefined)
246
+ return yield* file.invalid(`${hailuoRoute.name} returned no download_url for ${fileID}`);
247
+ const width = task.video_width ?? undefined;
248
+ const height = task.video_height ?? undefined;
249
+ return new VideoResponse({
250
+ videos: [
251
+ yield* MediaProtocol.expiringUrl(url, DOWNLOAD_RETENTION, {
252
+ mediaType: "video/mp4",
253
+ info: width === undefined && height === undefined ? undefined : { width, height },
254
+ }),
255
+ ],
256
+ providerMetadata: {
257
+ minimax: { taskId: context.token, fileId: fileID },
258
+ },
259
+ });
260
+ });
261
+ // ---------------------------------------------------------------------------
262
+ // 7. Protocol and route
263
+ // ---------------------------------------------------------------------------
264
+ export const protocol = MediaProtocol.queued(route, {
265
+ token: Token,
266
+ start: { body: { from: fromRequest }, decode: decodeStart },
267
+ status: { path: (token) => `${STATUS_PATH}/${encodeURIComponent(token)}`, decode: decodeStatus },
268
+ result: { path: (token) => `${STATUS_PATH}/${encodeURIComponent(token)}`, decode: decodeResult },
269
+ // Cancels a queued task; MiniMax rejects it once the task is running.
270
+ cancel: { method: "DELETE", path: (token) => `${PATH}/${encodeURIComponent(token)}` },
271
+ });
272
+ const hailuoStatusPath = (token) => `${HAILUO_STATUS_PATH}?task_id=${encodeURIComponent(token)}`;
273
+ export const hailuoProtocol = MediaProtocol.queued(hailuoRoute, {
274
+ token: Token,
275
+ start: { body: { from: hailuoFromRequest }, decode: decodeHailuoStart },
276
+ status: { path: hailuoStatusPath, decode: decodeHailuoStatus },
277
+ result: { path: hailuoStatusPath, decode: decodeHailuoResult },
278
+ });
279
+ /** H3 and later models on the v2 API. */
280
+ export const h3Model = (input) => VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input);
281
+ /** Hailuo and the `*-01` models on the v1 API. */
282
+ export const hailuoModel = (input) => VideoModel.fromRoute({ protocol: hailuoProtocol, baseURL: DEFAULT_BASE_URL, path: HAILUO_PATH }, input);
283
+ // v1 is MiniMax's legacy API with a fixed model list; every newer model ships on v2.
284
+ const isHailuo = (modelID) => /^(minimax-hailuo-|[tis]2v-01|video-01)/i.test(modelID);
285
+ /** Picks the API by model family: Hailuo and `*-01` models use v1, everything else v2. */
286
+ export const model = (input) => (isHailuo(input.id) ? hailuoModel(input) : h3Model(input));
287
+ export const MiniMaxVideo = {
288
+ protocol,
289
+ hailuoProtocol,
290
+ model,
291
+ h3Model,
292
+ hailuoModel,
293
+ };