@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
@@ -0,0 +1,216 @@
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 { mergeJsonRecords } from "../schema/index.js";
6
+ import { VideoModel, VideoResponse, seconds } from "../video.js";
7
+ import { ProviderShared, optionalNull } from "./shared.js";
8
+ // One Ark API (`/contents/generations/tasks`) served by Volcengine Ark in China and BytePlus ModelArk elsewhere.
9
+ export const VOLCENGINE_BASE_URL = "https://ark.cn-beijing.volces.com/api/v3";
10
+ export const BYTEPLUS_BASE_URL = "https://ark.ap-southeast.bytepluses.com/api/v3";
11
+ export const PATH = "/contents/generations/tasks";
12
+ // Video and last-frame URLs are documented as valid for 24 hours.
13
+ const OUTPUT_RETENTION = Duration.hours(24);
14
+ // ---------------------------------------------------------------------------
15
+ // 2. Token and response schemas
16
+ // ---------------------------------------------------------------------------
17
+ export const Token = Schema.Struct({ taskID: Schema.String });
18
+ const StartResponse = Schema.Struct({ id: Schema.String });
19
+ const Task = Schema.Struct({
20
+ id: optionalNull(Schema.String),
21
+ model: optionalNull(Schema.String),
22
+ status: Schema.String,
23
+ content: optionalNull(Schema.Struct({
24
+ video_url: optionalNull(Schema.String),
25
+ last_frame_url: optionalNull(Schema.String),
26
+ })),
27
+ error: optionalNull(Schema.Struct({
28
+ code: optionalNull(Schema.String),
29
+ message: optionalNull(Schema.String),
30
+ })),
31
+ usage: optionalNull(Schema.Struct({
32
+ completion_tokens: optionalNull(Schema.Number),
33
+ total_tokens: optionalNull(Schema.Number),
34
+ })),
35
+ updated_at: optionalNull(Schema.Number),
36
+ seed: optionalNull(Schema.Number),
37
+ resolution: optionalNull(Schema.String),
38
+ ratio: optionalNull(Schema.String),
39
+ duration: optionalNull(Schema.Number),
40
+ frames: optionalNull(Schema.Number),
41
+ framespersecond: optionalNull(Schema.Number),
42
+ generate_audio: optionalNull(Schema.Boolean),
43
+ output_format: optionalNull(Schema.String),
44
+ draft: optionalNull(Schema.Boolean),
45
+ service_tier: optionalNull(Schema.String),
46
+ });
47
+ const STATUS = {
48
+ queued: "queued",
49
+ running: "running",
50
+ succeeded: "completed",
51
+ failed: "failed",
52
+ cancelled: "cancelled",
53
+ expired: "expired",
54
+ };
55
+ // ---------------------------------------------------------------------------
56
+ // 3. Failures
57
+ // ---------------------------------------------------------------------------
58
+ // Ark error codes are dotted (`InvalidParameter.TaskTypeConstraint`); the leading segment is the category.
59
+ // `InternalServiceError`, `ServerOverloaded` and unknown codes are provider-side.
60
+ const FAILURE = {
61
+ InvalidParameter: "InvalidRequest",
62
+ MissingParameter: "InvalidRequest",
63
+ InvalidArgumentError: "InvalidRequest",
64
+ InvalidImageURL: "InvalidRequest",
65
+ AuthenticationError: "Authentication",
66
+ AccessDenied: "Authentication",
67
+ QuotaExceeded: "RateLimit",
68
+ RateLimitExceeded: "RateLimit",
69
+ };
70
+ // Input and output moderation codes: `InputImageSensitiveContentDetected.PrivacyInformation`,
71
+ // `OutputVideoSensitiveContentDetected`, `SensitiveContentDetected`, ...
72
+ const moderated = (code) => code !== undefined && code.includes("SensitiveContentDetected");
73
+ // ---------------------------------------------------------------------------
74
+ // 4. Request body construction
75
+ // ---------------------------------------------------------------------------
76
+ const nativeOptions = (options) => {
77
+ if (!options)
78
+ return undefined;
79
+ const { draft_task: _draftTask, ...native } = options;
80
+ return native;
81
+ };
82
+ // ---------------------------------------------------------------------------
83
+ // 5. Response decoding
84
+ // ---------------------------------------------------------------------------
85
+ // Ark returns `frames` when the request set it, otherwise `duration` rounded down to whole seconds.
86
+ const durationSeconds = (task) => {
87
+ if (task.frames !== undefined && task.frames !== null && task.framespersecond)
88
+ return task.frames / task.framespersecond;
89
+ return task.duration ?? undefined;
90
+ };
91
+ const make = (provider) => {
92
+ const route = MediaProtocol.identity({ id: "seedance-video", name: "Seedance Video", provider });
93
+ // `asset://<ID>` addresses a ModelArk digital character or authorized asset.
94
+ const item = (asset, type, role) => ProviderShared.mediaReference(asset, route.provider, route.name).pipe(Effect.map((reference) => ({
95
+ type,
96
+ [type]: { url: reference.type === "ref" ? `asset://${reference.value}` : reference.value },
97
+ role,
98
+ })));
99
+ const reference = (asset) => {
100
+ if (asset.kind === "video")
101
+ return item(asset, "video_url", "reference_video");
102
+ if (asset.kind === "audio")
103
+ return item(asset, "audio_url", "reference_audio");
104
+ return item(asset, "image_url", "reference_image");
105
+ };
106
+ // Frames and references are separate Seedance modes; mixing them is sent as-is and rejected by the provider.
107
+ const fromRequest = Effect.fn("SeedanceVideo.fromRequest")(function* (request) {
108
+ const content = [
109
+ // Every media mode accepts an optional prompt, so an empty one adds no text item.
110
+ ...(request.prompt === "" ? [] : [{ type: "text", text: request.prompt }]),
111
+ ...(request.start === undefined ? [] : [yield* item(request.start, "image_url", "first_frame")]),
112
+ ...(request.end === undefined ? [] : [yield* item(request.end, "image_url", "last_frame")]),
113
+ ...(yield* Effect.forEach(request.references ?? [], reference)),
114
+ ...(request.providerOptions?.draft_task === undefined
115
+ ? []
116
+ : [{ type: "draft_task", draft_task: request.providerOptions.draft_task }]),
117
+ ];
118
+ return MediaProtocol.json(mergeJsonRecords({
119
+ model: request.model.id,
120
+ content,
121
+ duration: request.duration === undefined ? undefined : seconds(request.duration),
122
+ ratio: request.aspect === "auto" ? "adaptive" : request.aspect,
123
+ resolution: request.resolution,
124
+ generate_audio: request.sound,
125
+ }, nativeOptions(request.providerOptions), request.http?.body) ?? {});
126
+ });
127
+ const decodeStart = route.decodeStarted(StartResponse, (value) => ({
128
+ token: { taskID: value.id },
129
+ snapshot: { id: value.id, status: "queued" },
130
+ }));
131
+ const decodeTask = route.decodeJson(Task);
132
+ const decodeStatus = Effect.fn("SeedanceVideo.decodeStatus")(function* (response, context) {
133
+ const output = yield* decodeTask(response);
134
+ return { id: context.token.taskID, status: MediaProtocol.status(STATUS, output.value.status) };
135
+ });
136
+ const decodeResult = Effect.fn("SeedanceVideo.decodeResult")(function* (response, context) {
137
+ const output = yield* decodeTask(response);
138
+ const task = output.value;
139
+ const status = MediaProtocol.status(STATUS, task.status);
140
+ if (status === "queued" || status === "running")
141
+ return yield* output.pending(context.token.taskID);
142
+ if (status === "failed") {
143
+ const code = task.error?.code ?? undefined;
144
+ const detail = task.error?.message ?? undefined;
145
+ const message = `${route.name} generation failed${code === undefined ? "" : ` (${code})`}${detail === undefined ? "" : `: ${detail}`}`;
146
+ if (moderated(code))
147
+ return yield* output.contentPolicy(message);
148
+ return yield* output.ended("failed", message, MediaProtocol.failure(FAILURE, code?.split(".")[0]));
149
+ }
150
+ if (status === "cancelled")
151
+ return yield* output.ended("cancelled", `${route.name} task ${context.token.taskID} was cancelled`);
152
+ if (status === "expired")
153
+ return yield* output.ended("expired", `${route.name} task ${context.token.taskID} expired`);
154
+ const videoURL = task.content?.video_url ?? undefined;
155
+ if (videoURL === undefined)
156
+ return yield* output.invalid(`${route.name} completed without a video URL`);
157
+ const duration = durationSeconds(task);
158
+ const options = {
159
+ mediaType: task.output_format === "mov" ? "video/quicktime" : "video/mp4",
160
+ info: duration === undefined ? undefined : { durationSeconds: duration },
161
+ };
162
+ // `updated_at` is when the task reached `succeeded`, which starts the URL's retention window.
163
+ const video = task.updated_at === undefined || task.updated_at === null
164
+ ? yield* MediaProtocol.expiringUrl(videoURL, OUTPUT_RETENTION, options)
165
+ : Media.url(videoURL, {
166
+ ...options,
167
+ expiresAt: task.updated_at * 1000 + Duration.toMillis(OUTPUT_RETENTION),
168
+ });
169
+ return new VideoResponse({
170
+ videos: [video],
171
+ usage: task.usage?.completion_tokens === undefined || task.usage.completion_tokens === null
172
+ ? undefined
173
+ : {
174
+ type: "tokens",
175
+ output: task.usage.completion_tokens,
176
+ total: task.usage.total_tokens ?? undefined,
177
+ },
178
+ providerMetadata: {
179
+ [provider]: {
180
+ taskId: context.token.taskID,
181
+ model: task.model ?? undefined,
182
+ seed: task.seed ?? undefined,
183
+ ratio: task.ratio ?? undefined,
184
+ resolution: task.resolution ?? undefined,
185
+ duration: task.duration ?? undefined,
186
+ frames: task.frames ?? undefined,
187
+ framesPerSecond: task.framespersecond ?? undefined,
188
+ generateAudio: task.generate_audio ?? undefined,
189
+ outputFormat: task.output_format ?? undefined,
190
+ draft: task.draft ?? undefined,
191
+ serviceTier: task.service_tier ?? undefined,
192
+ lastFrameUrl: task.content?.last_frame_url ?? undefined,
193
+ },
194
+ },
195
+ });
196
+ });
197
+ const taskPath = (token) => `${PATH}/${token.taskID}`;
198
+ // DELETE cancels a queued task. Ark refuses it for a running task, and deletes the record of a finished one.
199
+ const protocol = MediaProtocol.queued(route, {
200
+ token: Token,
201
+ start: { body: { from: fromRequest }, decode: decodeStart },
202
+ status: { path: taskPath, decode: decodeStatus },
203
+ result: { path: taskPath, decode: decodeResult },
204
+ cancel: { method: "DELETE", path: taskPath },
205
+ });
206
+ const model = (input) => VideoModel.fromRoute({
207
+ protocol,
208
+ baseURL: provider === "volcengine" ? VOLCENGINE_BASE_URL : BYTEPLUS_BASE_URL,
209
+ path: PATH,
210
+ }, input);
211
+ return { protocol, model };
212
+ };
213
+ export const SeedanceVideo = {
214
+ volcengine: make("volcengine"),
215
+ byteplus: make("byteplus"),
216
+ };
@@ -1,11 +1,28 @@
1
1
  import { Effect, Schema } from "effect";
2
- import { DecisionResponse, type DecisionModelCompatibility, type DecisionRequest } from "../decision.js";
2
+ import { DecisionResponse, type DecisionAnswer, type DecisionModelCompatibility, type DecisionQuestion, type DecisionRequest } from "../decision.js";
3
3
  import { DecisionRoute } from "../route/decision.js";
4
4
  import { AIError } from "../schema/index.js";
5
5
  export declare const DEFAULT_PATH = "/systemone";
6
6
  export declare const DEFAULT_BASE_URL = "https://api.typesafe.ai/v1";
7
7
  /** `state.messages` is Baseten's own placement (parts in a user message inside `state.messages`), set by its provider. */
8
8
  type MediaInput = NonNullable<DecisionModelCompatibility["mediaInput"]> | "state.messages";
9
+ declare const Answer: Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
10
+ readonly type: Schema.Literal<"noul">;
11
+ readonly noul: Schema.Number;
12
+ }>, Schema.Struct<{
13
+ readonly type: Schema.Literal<"choice">;
14
+ readonly choice: Schema.String;
15
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
16
+ readonly confidence: Schema.Number;
17
+ }>, Schema.Struct<{
18
+ readonly type: Schema.Literal<"score">;
19
+ readonly score: Schema.Number;
20
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
21
+ readonly confidence: Schema.Number;
22
+ }>, Schema.Struct<{
23
+ readonly type: Schema.Literal<"refusal">;
24
+ readonly message: Schema.optional<Schema.String>;
25
+ }>]>;
9
26
  export declare const Response: Schema.Struct<{
10
27
  readonly model: Schema.String;
11
28
  readonly answers: Schema.$Record<Schema.String, Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
@@ -21,6 +38,9 @@ export declare const Response: Schema.Struct<{
21
38
  readonly score: Schema.Number;
22
39
  readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
23
40
  readonly confidence: Schema.Number;
41
+ }>, Schema.Struct<{
42
+ readonly type: Schema.Literal<"refusal">;
43
+ readonly message: Schema.optional<Schema.String>;
24
44
  }>]>>;
25
45
  readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
26
46
  readonly input_tokens: Schema.optional<Schema.Number>;
@@ -48,12 +68,31 @@ export declare const encodeBody: (request: DecisionRequest<import("../decision.j
48
68
  };
49
69
  };
50
70
  }, AIError, never>;
71
+ declare const encodeQuestions: (questions: ReadonlyArray<DecisionQuestion>) => Effect.Effect<any, AIError, never>;
51
72
  /** Map System One's answers, keyed by question name, back to the request's question order. */
52
73
  export declare const toResponse: (data: Response, request: DecisionRequest, providerMetadataKey: string, invalid: (message: string) => AIError) => Effect.Effect<never, AIError, never> | Effect.Effect<DecisionResponse, never, never>;
74
+ declare const toAnswer: (question: DecisionQuestion, answer: typeof Answer.Type) => DecisionAnswer;
53
75
  export declare const protocol: DecisionRoute.Protocol;
54
76
  /** TypeSafe's API, the reference System One host; other hosts change the endpoint and auth with `route.with(...)`. */
55
77
  export declare const route: DecisionRoute.Route;
56
78
  export declare const SystemOne: {
79
+ readonly Answer: Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
80
+ readonly type: Schema.Literal<"noul">;
81
+ readonly noul: Schema.Number;
82
+ }>, Schema.Struct<{
83
+ readonly type: Schema.Literal<"choice">;
84
+ readonly choice: Schema.String;
85
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
86
+ readonly confidence: Schema.Number;
87
+ }>, Schema.Struct<{
88
+ readonly type: Schema.Literal<"score">;
89
+ readonly score: Schema.Number;
90
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
91
+ readonly confidence: Schema.Number;
92
+ }>, Schema.Struct<{
93
+ readonly type: Schema.Literal<"refusal">;
94
+ readonly message: Schema.optional<Schema.String>;
95
+ }>]>;
57
96
  readonly Response: Schema.Struct<{
58
97
  readonly model: Schema.String;
59
98
  readonly answers: Schema.$Record<Schema.String, Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
@@ -69,6 +108,9 @@ export declare const SystemOne: {
69
108
  readonly score: Schema.Number;
70
109
  readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
71
110
  readonly confidence: Schema.Number;
111
+ }>, Schema.Struct<{
112
+ readonly type: Schema.Literal<"refusal">;
113
+ readonly message: Schema.optional<Schema.String>;
72
114
  }>]>>;
73
115
  readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
74
116
  readonly input_tokens: Schema.optional<Schema.Number>;
@@ -94,6 +136,8 @@ export declare const SystemOne: {
94
136
  };
95
137
  };
96
138
  }, AIError, never>;
139
+ readonly encodeQuestions: typeof encodeQuestions;
140
+ readonly toAnswer: typeof toAnswer;
97
141
  readonly toResponse: typeof toResponse;
98
142
  readonly protocol: DecisionRoute.Protocol;
99
143
  readonly route: DecisionRoute.Route;
@@ -23,6 +23,8 @@ const Answer = Schema.Union([
23
23
  probabilities: Schema.Record(Schema.String, Probability),
24
24
  confidence: Probability,
25
25
  }),
26
+ // OpenRouter's and OpenCode Zen's answer for a question the upstream model declined.
27
+ Schema.Struct({ type: Schema.Literal("refusal"), message: Schema.optional(Schema.String) }),
26
28
  ]).pipe(Schema.toTaggedUnion("type"));
27
29
  const NativeUsage = Schema.StructWithRest(Schema.Struct({
28
30
  input_tokens: Schema.optional(Schema.Number),
@@ -67,7 +69,7 @@ const encodeQuestions = (questions) => Effect.forEach(questions, (question) => {
67
69
  // Options are map keys, so `true` is sent as "true" and mapped back by `choiceValue`.
68
70
  const keys = question.choices.map((choice) => String(choice.value));
69
71
  if (new Set(keys).size !== keys.length)
70
- return Effect.fail(ProviderShared.invalidRequest(`System One choice options are strings; "${question.name}" has a boolean and a string with the same text`));
72
+ return Effect.fail(ProviderShared.invalidRequest(`Decision choice options are sent as string keys; "${question.name}" has a boolean and a string with the same text`));
71
73
  return Effect.succeed([
72
74
  question.name,
73
75
  {
@@ -91,7 +93,7 @@ const placeMedia = Effect.fnUntraced(function* (request, mediaInput) {
91
93
  if (media.length === 0)
92
94
  return { state: state(parts.map(plain)) };
93
95
  if (mediaInput === "state")
94
- return { state: yield* Effect.forEach(parts, (part) => stateItem(part, unsupported)) };
96
+ return { state: yield* Effect.forEach(parts, (part) => stateItem(part, unsupported, true)) };
95
97
  // Chat-style content in one user message: text and JSON as text parts, media as in `state`.
96
98
  if (mediaInput === "state.messages")
97
99
  return {
@@ -100,7 +102,7 @@ const placeMedia = Effect.fnUntraced(function* (request, mediaInput) {
100
102
  {
101
103
  role: "user",
102
104
  content: yield* Effect.forEach(parts, (part) => part.type === "media"
103
- ? stateItem(part, unsupported)
105
+ ? stateItem(part, unsupported, false)
104
106
  : Effect.succeed({ type: "text", text: part.type === "text" ? part.text : encodeJson(part.value) })),
105
107
  },
106
108
  ],
@@ -144,20 +146,37 @@ const plain = (part) => {
144
146
  return part.value;
145
147
  return undefined;
146
148
  };
147
- const stateItem = (part, unsupported) => {
149
+ /** A media part as a Chat Completions content part; `files` sends other media, such as PDFs, as `file` parts. */
150
+ const stateItem = (part, unsupported, files) => {
148
151
  if (part.type !== "media")
149
152
  return Effect.succeed(plain(part));
150
153
  const asset = part.media;
151
- if (asset.kind !== "image" && asset.kind !== "audio" && asset.kind !== "video")
154
+ if (!files && asset.kind !== "image" && asset.kind !== "audio" && asset.kind !== "video")
152
155
  return Effect.fail(unsupported(asset, "images, audio and video"));
153
156
  return ProviderShared.requireInlineMedia(NAME, asset).pipe(Effect.map((inline) => {
154
157
  if (asset.kind === "image")
155
158
  return { type: "image_url", image_url: { url: inline.dataUrl } };
156
159
  if (asset.kind === "video")
157
160
  return { type: "video_url", video_url: { url: inline.dataUrl } };
158
- return { type: "input_audio", input_audio: { data: inline.base64, format: inline.mime.slice("audio/".length) } };
161
+ if (asset.kind === "audio") {
162
+ const format = inline.mime.slice("audio/".length).toLowerCase();
163
+ return { type: "input_audio", input_audio: { data: inline.base64, format: audioFormats[format] ?? format } };
164
+ }
165
+ return {
166
+ type: "file",
167
+ file: { file_data: inline.dataUrl, ...(part.filename === undefined ? {} : { filename: part.filename }) },
168
+ };
159
169
  }));
160
170
  };
171
+ /** OpenRouter's `input_audio` format names for MIME subtypes that aren't one themselves. */
172
+ const audioFormats = {
173
+ "x-wav": "wav",
174
+ wave: "wav",
175
+ "vnd.wave": "wav",
176
+ "x-m4a": "m4a",
177
+ "x-aiff": "aiff",
178
+ "x-flac": "flac",
179
+ };
161
180
  /** Map System One's answers, keyed by question name, back to the request's question order. */
162
181
  export const toResponse = (data, request, providerMetadataKey, invalid) => {
163
182
  const names = request.questions.map((question) => question.name);
@@ -185,6 +204,13 @@ export const toResponse = (data, request, providerMetadataKey, invalid) => {
185
204
  }));
186
205
  };
187
206
  const toAnswer = (question, answer) => {
207
+ if (answer.type === "refusal")
208
+ return {
209
+ name: question.name,
210
+ type: "error",
211
+ reason: "refusal",
212
+ ...(answer.message === undefined ? {} : { message: answer.message }),
213
+ };
188
214
  if (answer.type === "noul")
189
215
  return { name: question.name, type: "predicate", probability: answer.noul };
190
216
  if (answer.type === "choice") {
@@ -234,4 +260,13 @@ export const route = DecisionRoute.make({
234
260
  protocol,
235
261
  endpoint: Endpoint.path("/systemone", { baseURL: DEFAULT_BASE_URL }),
236
262
  });
237
- export const SystemOne = { Response, encodeBody, toResponse, protocol, route };
263
+ export const SystemOne = {
264
+ Answer,
265
+ Response,
266
+ encodeBody,
267
+ encodeQuestions,
268
+ toAnswer,
269
+ toResponse,
270
+ protocol,
271
+ route,
272
+ };
@@ -88,7 +88,7 @@ export const make = (adapter, lowerTools) => Effect.fn("ResponsesCompaction.exec
88
88
  auth: route.auth,
89
89
  encodeBody: Schema.encodeSync(Schema.fromJsonString(Body)),
90
90
  });
91
- const response = yield* executor.execute(ProviderShared.jsonPost({
91
+ const response = yield* RequestExecutor.withTls(executor.execute, request.http?.tls)(ProviderShared.jsonPost({
92
92
  url: parts.url,
93
93
  body: parts.bodyText,
94
94
  headers: parts.headers,
@@ -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,
@@ -110,6 +110,12 @@ const CONTENT_POLICY_CODES = new Set([
110
110
  "refusal",
111
111
  "datainspectionfailed",
112
112
  "moderation_blocked",
113
+ // Gemini Decisions rejects blocked input with these `error.code` strings on a 400.
114
+ "safety",
115
+ "prohibited_content",
116
+ "blocklist",
117
+ "image_safety",
118
+ "content_blocked",
113
119
  ]);
114
120
  // OpenCode Zen replaces upstream codes outside its allow-list but keeps the original
115
121
  // as a `[code]` label at the start of the rewritten message.
@@ -120,7 +126,7 @@ const RATE_LIMIT_TEXT = /rate increased too quickly|rate[-_\s]?limit|too[_\s]?ma
120
126
  // Only consulted on 429, where throttles and account caps share a status.
121
127
  // Z.ai reports balance, plan expiry, plan limits, and plan model access on 429.
122
128
  // Cerebras reports its per-minute token throttle as `token_quota_exceeded`; that is a rate limit.
123
- const QUOTA_TEXT = /insufficient[-_\s]?(?:quota|balance)|(?<!token_)quota[-_\s]?exceeded|budget exceeded|usage limit|limit exhausted|package has expired|plan does not yet include/i;
129
+ const QUOTA_TEXT = /insufficient[-_\s]?(?:quota|balance)|(?<!token_)quota[-_\s]?exceeded|budget exceeded|usage limit|(?<!rate[-_\s]?)limit exhausted|package has expired|plan does not yet include/i;
124
130
  // Policy rejections without a dedicated code, matched against the provider's own
125
131
  // explanation only. OpenAI reuses `invalid_prompt` for usage-policy rejections while
126
132
  // Bedrock Mantle reuses it for schema validation; Anthropic reports blocked output
@@ -0,0 +1,2 @@
1
+ export { videoModel as model } from "../byteplus.js";
2
+ export type { Settings } from "../byteplus.js";
@@ -0,0 +1 @@
1
+ export { videoModel as model } from "../byteplus.js";
@@ -0,0 +1,26 @@
1
+ import type { ProviderPackage } from "../provider-package.js";
2
+ import { type ProviderAuthOption } from "../route/auth-options.js";
3
+ import { type HttpOptions, type ModelID, type ProviderOptions } from "../schema/index.js";
4
+ export declare const id: string & import("effect/Brand").Brand<"AI.ProviderID">;
5
+ export type Config = ProviderAuthOption<"optional"> & {
6
+ readonly baseURL?: string;
7
+ readonly headers?: Record<string, string>;
8
+ readonly http?: HttpOptions;
9
+ };
10
+ export type Settings = ProviderPackage.Settings & {
11
+ readonly apiKey?: string | false;
12
+ readonly baseURL?: string;
13
+ };
14
+ export type { SeedanceVideoOptions } from "../protocols/seedance-video.js";
15
+ export declare const configure: (input?: Config) => {
16
+ id: string & import("effect/Brand").Brand<"AI.ProviderID">;
17
+ video: (modelID: string | ModelID, providerOptions?: ProviderOptions) => import("../video.js").VideoModel<import("../protocols/seedance-video.js").SeedanceVideoOptions>;
18
+ configure: typeof configure;
19
+ };
20
+ export declare const provider: {
21
+ id: string & import("effect/Brand").Brand<"AI.ProviderID">;
22
+ video: (modelID: string | ModelID, providerOptions?: ProviderOptions) => import("../video.js").VideoModel<import("../protocols/seedance-video.js").SeedanceVideoOptions>;
23
+ configure: typeof configure;
24
+ };
25
+ export declare const videoModel: (modelID: string, settings?: Settings) => import("../video.js").VideoModel<import("../protocols/seedance-video.js").SeedanceVideoOptions>;
26
+ export declare const video: (modelID: string | ModelID, providerOptions?: ProviderOptions) => import("../video.js").VideoModel<import("../protocols/seedance-video.js").SeedanceVideoOptions>;
@@ -0,0 +1,21 @@
1
+ import { SeedanceVideo } from "../protocols/seedance-video.js";
2
+ import { AuthOptions } from "../route/auth-options.js";
3
+ import { MediaRoute } from "../route/media.js";
4
+ import { ProviderID } from "../schema/index.js";
5
+ import { toConfig } from "./settings.js";
6
+ export const id = ProviderID.make("byteplus");
7
+ const auth = (options) => AuthOptions.bearer(options, "BYTEPLUS_API_KEY");
8
+ export const configure = (input = {}) => {
9
+ const media = MediaRoute.deployment(input, auth(input));
10
+ return {
11
+ id,
12
+ video: (modelID, providerOptions) => SeedanceVideo.byteplus.model({ ...media, id: modelID, providerOptions }),
13
+ configure,
14
+ };
15
+ };
16
+ export const provider = configure();
17
+ export const videoModel = (modelID, settings) => {
18
+ const input = toConfig(settings);
19
+ return configure(input).video(modelID, input.providerOptions);
20
+ };
21
+ export const video = provider.video;
@@ -0,0 +1,2 @@
1
+ export { decisionModel as model } from "../google.js";
2
+ export type { Settings } from "../google.js";
@@ -0,0 +1 @@
1
+ export { decisionModel as model } from "../google.js";
@@ -0,0 +1,2 @@
1
+ export { videoModel as model } from "../google.js";
2
+ export type { Settings } from "../google.js";
@@ -0,0 +1 @@
1
+ export { videoModel as model } from "../google.js";