@opencode/ai 2.2.6 → 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 (177) hide show
  1. package/README.md +208 -98
  2. package/dist/ai-client.d.ts +2 -2
  3. package/dist/ai-client.js +2 -1
  4. package/dist/decision.d.ts +10 -0
  5. package/dist/decision.js +2 -0
  6. package/dist/effect.d.ts +14 -7
  7. package/dist/effect.js +6 -1
  8. package/dist/embedding-client.d.ts +21 -0
  9. package/dist/embedding-client.js +30 -0
  10. package/dist/embedding.d.ts +111 -0
  11. package/dist/embedding.js +75 -0
  12. package/dist/experimental.d.ts +0 -4
  13. package/dist/experimental.js +0 -3
  14. package/dist/image-client.d.ts +1 -1
  15. package/dist/image-client.js +2 -6
  16. package/dist/image.d.ts +0 -1
  17. package/dist/image.js +0 -3
  18. package/dist/index.d.ts +18 -50
  19. package/dist/index.js +35 -13
  20. package/dist/media-model.d.ts +2 -0
  21. package/dist/media-model.js +3 -1
  22. package/dist/media.d.ts +9 -3
  23. package/dist/media.js +27 -7
  24. package/dist/protocols/alibaba-chat.d.ts +4 -0
  25. package/dist/protocols/anthropic-messages.js +3 -3
  26. package/dist/protocols/google-decisions.d.ts +13 -0
  27. package/dist/protocols/google-decisions.js +133 -0
  28. package/dist/protocols/google-embed-content.d.ts +34 -0
  29. package/dist/protocols/google-embed-content.js +110 -0
  30. package/dist/protocols/google-interactions-video.d.ts +43 -0
  31. package/dist/protocols/google-interactions-video.js +186 -0
  32. package/dist/protocols/google-interactions.d.ts +14 -1
  33. package/dist/protocols/google-interactions.js +1 -1
  34. package/dist/protocols/google-vertex-predict-embeddings.d.ts +18 -0
  35. package/dist/protocols/google-vertex-predict-embeddings.js +74 -0
  36. package/dist/protocols/index.d.ts +4 -0
  37. package/dist/protocols/index.js +4 -0
  38. package/dist/protocols/minimax-video.d.ts +54 -0
  39. package/dist/protocols/minimax-video.js +292 -0
  40. package/dist/protocols/open-responses.d.ts +1 -1
  41. package/dist/protocols/open-responses.js +31 -8
  42. package/dist/protocols/openai-chat.d.ts +24 -0
  43. package/dist/protocols/openai-chat.js +37 -11
  44. package/dist/protocols/openai-compatible-chat.d.ts +1 -0
  45. package/dist/protocols/openai-decisions.js +14 -1
  46. package/dist/protocols/openai-embeddings.d.ts +16 -0
  47. package/dist/protocols/openai-embeddings.js +76 -0
  48. package/dist/protocols/openrouter-video.d.ts +41 -0
  49. package/dist/protocols/openrouter-video.js +138 -0
  50. package/dist/protocols/seedance-video.d.ts +50 -0
  51. package/dist/protocols/seedance-video.js +216 -0
  52. package/dist/protocols/shared.d.ts +13 -3
  53. package/dist/protocols/shared.js +27 -4
  54. package/dist/protocols/system-one.d.ts +45 -1
  55. package/dist/protocols/system-one.js +50 -8
  56. package/dist/protocols/utils/responses-compaction.js +1 -1
  57. package/dist/protocols/venice-chat.d.ts +4 -0
  58. package/dist/protocols/xai-video.d.ts +8 -2
  59. package/dist/protocols/xai-video.js +20 -15
  60. package/dist/protocols/zai-chat.d.ts +4 -0
  61. package/dist/provider-error.js +7 -1
  62. package/dist/providers/alibaba/embeddings.d.ts +2 -0
  63. package/dist/providers/alibaba/embeddings.js +1 -0
  64. package/dist/providers/alibaba.d.ts +3 -0
  65. package/dist/providers/alibaba.js +14 -1
  66. package/dist/providers/amazon-bedrock-mantle.d.ts +1 -0
  67. package/dist/providers/azure/embeddings.d.ts +2 -0
  68. package/dist/providers/azure/embeddings.js +1 -0
  69. package/dist/providers/azure.d.ts +3 -0
  70. package/dist/providers/azure.js +15 -0
  71. package/dist/providers/baseten.d.ts +2 -0
  72. package/dist/providers/byteplus/videos.d.ts +2 -0
  73. package/dist/providers/byteplus/videos.js +1 -0
  74. package/dist/providers/byteplus.d.ts +26 -0
  75. package/dist/providers/byteplus.js +21 -0
  76. package/dist/providers/cerebras.d.ts +2 -0
  77. package/dist/providers/cloudflare-ai-gateway.d.ts +2 -0
  78. package/dist/providers/cloudflare-workers-ai.d.ts +2 -0
  79. package/dist/providers/cohere/embeddings.d.ts +2 -0
  80. package/dist/providers/cohere/embeddings.js +1 -0
  81. package/dist/providers/cohere.d.ts +8 -0
  82. package/dist/providers/cohere.js +17 -1
  83. package/dist/providers/deepinfra/embeddings.d.ts +2 -0
  84. package/dist/providers/deepinfra/embeddings.js +1 -0
  85. package/dist/providers/deepinfra.d.ts +6 -1
  86. package/dist/providers/deepinfra.js +15 -1
  87. package/dist/providers/deepseek.d.ts +2 -0
  88. package/dist/providers/digitalocean/embeddings.d.ts +2 -0
  89. package/dist/providers/digitalocean/embeddings.js +1 -0
  90. package/dist/providers/digitalocean.d.ts +10 -0
  91. package/dist/providers/digitalocean.js +15 -0
  92. package/dist/providers/fireworks/embeddings.d.ts +2 -0
  93. package/dist/providers/fireworks/embeddings.js +1 -0
  94. package/dist/providers/fireworks.d.ts +6 -1
  95. package/dist/providers/fireworks.js +15 -1
  96. package/dist/providers/google/decisions.d.ts +2 -0
  97. package/dist/providers/google/decisions.js +1 -0
  98. package/dist/providers/google/embeddings.d.ts +2 -0
  99. package/dist/providers/google/embeddings.js +1 -0
  100. package/dist/providers/google/videos.d.ts +2 -0
  101. package/dist/providers/google/videos.js +1 -0
  102. package/dist/providers/google-vertex/embeddings.d.ts +2 -0
  103. package/dist/providers/google-vertex/embeddings.js +1 -0
  104. package/dist/providers/google-vertex-chat.d.ts +1 -0
  105. package/dist/providers/google-vertex.d.ts +7 -0
  106. package/dist/providers/google-vertex.js +52 -0
  107. package/dist/providers/google.d.ts +17 -4
  108. package/dist/providers/google.js +27 -3
  109. package/dist/providers/groq.d.ts +5 -0
  110. package/dist/providers/index.d.ts +2 -1
  111. package/dist/providers/index.js +2 -1
  112. package/dist/providers/meta.d.ts +1 -0
  113. package/dist/providers/minimax/videos.d.ts +3 -0
  114. package/dist/providers/minimax/videos.js +1 -0
  115. package/dist/providers/minimax.d.ts +7 -1
  116. package/dist/providers/minimax.js +10 -1
  117. package/dist/providers/moonshot.d.ts +1 -0
  118. package/dist/providers/openai/embeddings.d.ts +2 -0
  119. package/dist/providers/openai/embeddings.js +1 -0
  120. package/dist/providers/openai-compatible/decisions.d.ts +2 -0
  121. package/dist/providers/openai-compatible/decisions.js +1 -0
  122. package/dist/providers/openai-compatible/embeddings.d.ts +2 -0
  123. package/dist/providers/openai-compatible/embeddings.js +1 -0
  124. package/dist/providers/openai-compatible.d.ts +6 -0
  125. package/dist/providers/openai-compatible.js +27 -0
  126. package/dist/providers/openai.d.ts +7 -0
  127. package/dist/providers/openai.js +14 -0
  128. package/dist/providers/openrouter/embeddings.d.ts +2 -0
  129. package/dist/providers/openrouter/embeddings.js +1 -0
  130. package/dist/providers/openrouter/videos.d.ts +2 -0
  131. package/dist/providers/openrouter/videos.js +1 -0
  132. package/dist/providers/openrouter.d.ts +21 -0
  133. package/dist/providers/openrouter.js +23 -0
  134. package/dist/providers/togetherai.d.ts +2 -0
  135. package/dist/providers/venice.d.ts +1 -0
  136. package/dist/providers/vercel-ai-gateway/embeddings.d.ts +2 -0
  137. package/dist/providers/vercel-ai-gateway/embeddings.js +1 -0
  138. package/dist/providers/vercel-ai-gateway.d.ts +4 -0
  139. package/dist/providers/vercel-ai-gateway.js +15 -1
  140. package/dist/providers/volcengine/videos.d.ts +2 -0
  141. package/dist/providers/volcengine/videos.js +1 -0
  142. package/dist/providers/volcengine.d.ts +26 -0
  143. package/dist/providers/volcengine.js +21 -0
  144. package/dist/providers/xai.d.ts +1 -0
  145. package/dist/providers/zai-coding-plan.d.ts +1 -0
  146. package/dist/providers/zai.d.ts +1 -0
  147. package/dist/public.d.ts +4 -0
  148. package/dist/public.js +2 -0
  149. package/dist/route/embedding.d.ts +61 -0
  150. package/dist/route/embedding.js +88 -0
  151. package/dist/route/executor-service.d.ts +6 -0
  152. package/dist/route/executor-service.js +7 -0
  153. package/dist/route/executor.d.ts +7 -1
  154. package/dist/route/executor.js +7 -2
  155. package/dist/route/media-protocol.d.ts +12 -11
  156. package/dist/route/media.d.ts +2 -0
  157. package/dist/route/media.js +31 -22
  158. package/dist/route/transport/http.js +1 -1
  159. package/dist/schema/messages.d.ts +1 -1
  160. package/dist/schema/messages.js +1 -5
  161. package/dist/schema/options.d.ts +8 -0
  162. package/dist/schema/options.js +1 -0
  163. package/dist/speech-client.d.ts +1 -1
  164. package/dist/speech-client.js +4 -4
  165. package/dist/transcription-client.d.ts +1 -1
  166. package/dist/transcription-client.js +1 -2
  167. package/dist/video-client.d.ts +16 -84
  168. package/dist/video-client.js +28 -13
  169. package/dist/video.d.ts +56 -1072
  170. package/dist/video.js +28 -65
  171. package/package.json +355 -255
  172. package/dist/protocols/google-video.d.ts +0 -26
  173. package/dist/protocols/google-video.js +0 -146
  174. package/dist/protocols/runway-video.d.ts +0 -38
  175. package/dist/protocols/runway-video.js +0 -141
  176. package/dist/providers/runway.d.ts +0 -20
  177. 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
+ };
@@ -17,10 +17,20 @@ export declare const lenient: <const S extends Schema.Top>(schema: S) => Schema.
17
17
  export declare const ReportedBilling: Schema.Struct<{
18
18
  readonly cost: Schema.optionalKey<Schema.middlewareDecoding<Schema.UndefinedOr<Schema.Finite>, never>>;
19
19
  }>;
20
- /** Reads `ReportedBilling` from a raw usage object, which provider metadata keeps as the endpoint sent it. */
21
- export declare const reportedBilling: (usage: unknown) => {} | {
22
- cost: number | undefined;
20
+ /**
21
+ * Reads `ReportedBilling` from a raw usage object, which provider metadata keeps as the endpoint sent it, or
22
+ * Copilot's billing from the frames that carry the usage.
23
+ */
24
+ export declare const reportedBilling: (usage: unknown, ...frames: ReadonlyArray<unknown>) => {
25
+ cost: number;
26
+ } | {
27
+ cost?: undefined;
23
28
  };
29
+ /**
30
+ * The filter that blocked a response, from maps keyed by filter name: Azure's `content_filter_results`
31
+ * (`{ hate: { filtered: true } }`) or GitHub Copilot's `copilot_annotations` (`{ TextCopyright: [...] }`).
32
+ */
33
+ export declare const contentFilterCategory: (...sources: ReadonlyArray<unknown>) => string | undefined;
24
34
  /**
25
35
  * Accepts stream frames that carry no `type`, alongside the typed event schema. Gateways inject such frames as
26
36
  * keep-alives, so they decode as an ignored event; one with an `error` still decodes as an error event.
@@ -23,11 +23,34 @@ const billedAmount = lenient(Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0
23
23
  export const ReportedBilling = Schema.Struct({
24
24
  cost: billedAmount,
25
25
  });
26
- /** Reads `ReportedBilling` from a raw usage object, which provider metadata keeps as the endpoint sent it. */
27
- export const reportedBilling = (usage) => Option.match(Schema.decodeUnknownOption(ReportedBilling)(usage), {
28
- onNone: () => ({}),
29
- onSome: (billing) => ({ cost: billing.cost }),
26
+ /**
27
+ * GitHub Copilot reports its charge beside usage on the frame that carries it, as `copilot_usage.total_nano_aiu`:
28
+ * billionths of an AI credit, which costs $0.01.
29
+ */
30
+ const CopilotBilling = Schema.Struct({
31
+ copilot_usage: Schema.Struct({ total_nano_aiu: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)) }),
30
32
  });
33
+ const decodeCopilotBilling = Schema.decodeUnknownOption(CopilotBilling);
34
+ /**
35
+ * Reads `ReportedBilling` from a raw usage object, which provider metadata keeps as the endpoint sent it, or
36
+ * Copilot's billing from the frames that carry the usage.
37
+ */
38
+ export const reportedBilling = (usage, ...frames) => {
39
+ const reported = Option.getOrUndefined(Schema.decodeUnknownOption(ReportedBilling)(usage))?.cost;
40
+ if (reported !== undefined)
41
+ return { cost: reported };
42
+ const nanoAiu = frames
43
+ .map((frame) => Option.getOrUndefined(decodeCopilotBilling(frame))?.copilot_usage.total_nano_aiu)
44
+ .find((value) => value !== undefined);
45
+ return nanoAiu === undefined ? {} : { cost: nanoAiu / 100_000_000_000 };
46
+ };
47
+ /**
48
+ * The filter that blocked a response, from maps keyed by filter name: Azure's `content_filter_results`
49
+ * (`{ hate: { filtered: true } }`) or GitHub Copilot's `copilot_annotations` (`{ TextCopyright: [...] }`).
50
+ */
51
+ export const contentFilterCategory = (...sources) => sources
52
+ .flatMap((source) => (isRecord(source) ? Object.entries(source) : []))
53
+ .find(([, value]) => (isRecord(value) && "filtered" in value ? value.filtered === true : Boolean(value)))?.[0];
31
54
  /**
32
55
  * Accepts stream frames that carry no `type`, alongside the typed event schema. Gateways inject such frames as
33
56
  * keep-alives, so they decode as an ignored event; one with an `error` still decodes as an error event.
@@ -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),
@@ -47,7 +49,14 @@ export const encodeBody = Effect.fn("SystemOne.encodeBody")(function* (request,
47
49
  });
48
50
  const encodeQuestions = (questions) => Effect.forEach(questions, (question) => {
49
51
  if (question.type === "predicate")
50
- return Effect.succeed([question.name, { type: "noul", instructions: question.instructions }]);
52
+ return Effect.succeed([
53
+ question.name,
54
+ {
55
+ type: "noul",
56
+ instructions: question.instructions,
57
+ ...(question.criteria === undefined ? {} : { criteria: question.criteria }),
58
+ },
59
+ ]);
51
60
  if (question.type === "score")
52
61
  return Effect.succeed([
53
62
  question.name,
@@ -60,7 +69,7 @@ const encodeQuestions = (questions) => Effect.forEach(questions, (question) => {
60
69
  // Options are map keys, so `true` is sent as "true" and mapped back by `choiceValue`.
61
70
  const keys = question.choices.map((choice) => String(choice.value));
62
71
  if (new Set(keys).size !== keys.length)
63
- 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`));
64
73
  return Effect.succeed([
65
74
  question.name,
66
75
  {
@@ -84,7 +93,7 @@ const placeMedia = Effect.fnUntraced(function* (request, mediaInput) {
84
93
  if (media.length === 0)
85
94
  return { state: state(parts.map(plain)) };
86
95
  if (mediaInput === "state")
87
- return { state: yield* Effect.forEach(parts, (part) => stateItem(part, unsupported)) };
96
+ return { state: yield* Effect.forEach(parts, (part) => stateItem(part, unsupported, true)) };
88
97
  // Chat-style content in one user message: text and JSON as text parts, media as in `state`.
89
98
  if (mediaInput === "state.messages")
90
99
  return {
@@ -93,7 +102,7 @@ const placeMedia = Effect.fnUntraced(function* (request, mediaInput) {
93
102
  {
94
103
  role: "user",
95
104
  content: yield* Effect.forEach(parts, (part) => part.type === "media"
96
- ? stateItem(part, unsupported)
105
+ ? stateItem(part, unsupported, false)
97
106
  : Effect.succeed({ type: "text", text: part.type === "text" ? part.text : encodeJson(part.value) })),
98
107
  },
99
108
  ],
@@ -137,20 +146,37 @@ const plain = (part) => {
137
146
  return part.value;
138
147
  return undefined;
139
148
  };
140
- 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) => {
141
151
  if (part.type !== "media")
142
152
  return Effect.succeed(plain(part));
143
153
  const asset = part.media;
144
- if (asset.kind !== "image" && asset.kind !== "audio" && asset.kind !== "video")
154
+ if (!files && asset.kind !== "image" && asset.kind !== "audio" && asset.kind !== "video")
145
155
  return Effect.fail(unsupported(asset, "images, audio and video"));
146
156
  return ProviderShared.requireInlineMedia(NAME, asset).pipe(Effect.map((inline) => {
147
157
  if (asset.kind === "image")
148
158
  return { type: "image_url", image_url: { url: inline.dataUrl } };
149
159
  if (asset.kind === "video")
150
160
  return { type: "video_url", video_url: { url: inline.dataUrl } };
151
- 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
+ };
152
169
  }));
153
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
+ };
154
180
  /** Map System One's answers, keyed by question name, back to the request's question order. */
155
181
  export const toResponse = (data, request, providerMetadataKey, invalid) => {
156
182
  const names = request.questions.map((question) => question.name);
@@ -178,6 +204,13 @@ export const toResponse = (data, request, providerMetadataKey, invalid) => {
178
204
  }));
179
205
  };
180
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
+ };
181
214
  if (answer.type === "noul")
182
215
  return { name: question.name, type: "predicate", probability: answer.noul };
183
216
  if (answer.type === "choice") {
@@ -227,4 +260,13 @@ export const route = DecisionRoute.make({
227
260
  protocol,
228
261
  endpoint: Endpoint.path("/systemone", { baseURL: DEFAULT_BASE_URL }),
229
262
  });
230
- 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,
@@ -202,6 +202,7 @@ export declare const protocol: Protocol<{
202
202
  readonly reasoning?: string | undefined;
203
203
  readonly reasoning_text?: string | undefined;
204
204
  readonly reasoning_details?: unknown;
205
+ readonly reasoning_opaque?: string | undefined;
205
206
  readonly tool_calls?: readonly ({
206
207
  readonly id: string;
207
208
  readonly type: "custom";
@@ -262,6 +263,7 @@ export declare const protocol: Protocol<{
262
263
  readonly prompt_cache_hit_tokens?: number | null | undefined;
263
264
  readonly cache_read_input_tokens?: number | null | undefined;
264
265
  readonly cache_created_input_tokens?: number | null | undefined;
266
+ readonly reasoning_tokens?: number | null | undefined;
265
267
  readonly prompt_tokens_details?: {
266
268
  readonly [x: string]: unknown;
267
269
  readonly cached_tokens?: number | null | undefined;
@@ -282,6 +284,7 @@ export declare const protocol: Protocol<{
282
284
  readonly reasoning?: string | null | undefined;
283
285
  readonly reasoning_text?: string | null | undefined;
284
286
  readonly reasoning_details?: unknown;
287
+ readonly reasoning_opaque?: string | null | undefined;
285
288
  readonly tool_calls?: readonly {
286
289
  readonly index?: number | null | undefined;
287
290
  readonly id?: string | null | undefined;
@@ -308,6 +311,7 @@ export declare const protocol: Protocol<{
308
311
  readonly prompt_cache_hit_tokens?: number | null | undefined;
309
312
  readonly cache_read_input_tokens?: number | null | undefined;
310
313
  readonly cache_created_input_tokens?: number | null | undefined;
314
+ readonly reasoning_tokens?: number | null | undefined;
311
315
  readonly completion_tokens_details?: {
312
316
  readonly [x: string]: unknown;
313
317
  readonly reasoning_tokens?: number | null | undefined;
@@ -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,
@@ -129,6 +129,7 @@ export declare const protocol: Protocol<{
129
129
  readonly reasoning?: string | undefined;
130
130
  readonly reasoning_text?: string | undefined;
131
131
  readonly reasoning_details?: unknown;
132
+ readonly reasoning_opaque?: string | undefined;
132
133
  })[];
133
134
  readonly tools?: readonly ({
134
135
  readonly type: "function";
@@ -224,6 +225,7 @@ export declare const protocol: Protocol<{
224
225
  readonly reasoning?: string | null | undefined;
225
226
  readonly reasoning_text?: string | null | undefined;
226
227
  readonly reasoning_details?: unknown;
228
+ readonly reasoning_opaque?: string | null | undefined;
227
229
  readonly tool_calls?: readonly {
228
230
  readonly index?: number | null | undefined;
229
231
  readonly id?: string | null | undefined;
@@ -249,6 +251,7 @@ export declare const protocol: Protocol<{
249
251
  readonly prompt_cache_hit_tokens?: number | null | undefined;
250
252
  readonly cache_read_input_tokens?: number | null | undefined;
251
253
  readonly cache_created_input_tokens?: number | null | undefined;
254
+ readonly reasoning_tokens?: number | null | undefined;
252
255
  readonly prompt_tokens_details?: {
253
256
  readonly [x: string]: unknown;
254
257
  readonly cached_tokens?: number | null | undefined;
@@ -271,6 +274,7 @@ export declare const protocol: Protocol<{
271
274
  readonly prompt_cache_hit_tokens?: number | null | undefined;
272
275
  readonly cache_read_input_tokens?: number | null | undefined;
273
276
  readonly cache_created_input_tokens?: number | null | undefined;
277
+ readonly reasoning_tokens?: number | null | undefined;
274
278
  readonly prompt_tokens_details?: {
275
279
  readonly [x: string]: unknown;
276
280
  readonly cached_tokens?: number | null | undefined;