@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
@@ -148,6 +148,7 @@ export const OpenAIChatMessage = Schema.Union([
148
148
  reasoning: Schema.optional(Schema.String),
149
149
  reasoning_text: Schema.optional(Schema.String),
150
150
  reasoning_details: Schema.optional(Schema.Unknown),
151
+ reasoning_opaque: Schema.optional(Schema.String),
151
152
  }), [Schema.Record(Schema.String, Schema.Unknown)]),
152
153
  Schema.Struct({
153
154
  role: Schema.Literal("tool"),
@@ -209,6 +210,8 @@ export const OpenAIChatUsage = Schema.StructWithRest(Schema.Struct({
209
210
  prompt_cache_hit_tokens: optionalNull(Schema.Number),
210
211
  cache_read_input_tokens: optionalNull(Schema.Number),
211
212
  cache_created_input_tokens: optionalNull(Schema.Number),
213
+ // GitHub Copilot reports reasoning at the top level instead of in `completion_tokens_details`.
214
+ reasoning_tokens: optionalNull(Schema.Number),
212
215
  prompt_tokens_details: optionalNull(Schema.StructWithRest(Schema.Struct({
213
216
  cached_tokens: optionalNull(Schema.Number),
214
217
  cache_write_tokens: optionalNull(Schema.Number),
@@ -237,6 +240,8 @@ export const OpenAIChatDelta = Schema.StructWithRest(Schema.Struct({
237
240
  reasoning: optionalNull(Schema.String),
238
241
  reasoning_text: optionalNull(Schema.String),
239
242
  reasoning_details: optionalNull(Schema.Unknown),
243
+ // GitHub Copilot's opaque reasoning state, which must be replayed for multi-turn reasoning.
244
+ reasoning_opaque: optionalNull(Schema.String),
240
245
  tool_calls: optionalNull(Schema.Array(OpenAIChatToolCallDelta)),
241
246
  }), [Schema.Record(Schema.String, Schema.Unknown)]);
242
247
  export const OpenAIChatChoice = Schema.StructWithRest(Schema.Struct({
@@ -346,6 +351,11 @@ const lowerReasoningDetail = (detail) => {
346
351
  return { type: detail.type, encrypted: detail.encrypted };
347
352
  return detail;
348
353
  };
354
+ // Interleaved reasoning yields one opaque value per segment; like the Copilot VS Code
355
+ // client, replay the latest one with the concatenated reasoning text.
356
+ const reasoningOpaque = (parts, providerMetadataKey) => parts
357
+ .map((part) => part.providerMetadata?.[providerMetadataKey]?.reasoningOpaque)
358
+ .findLast((value) => typeof value === "string");
349
359
  const isKimiDetail = (detail) => detail.type === "summary" || detail.type === "encrypted";
350
360
  const lowerUserMessage = Effect.fnUntraced(function* (message, options) {
351
361
  const content = [];
@@ -406,7 +416,8 @@ const lowerAssistantMessage = Effect.fnUntraced(function* (message, configuredFi
406
416
  if (details?.some(isKimiDetail))
407
417
  return "reasoning_content";
408
418
  })();
409
- const reasoningText = reasoning.length === 0 ? (requireReasoning ? "" : undefined) : text;
419
+ const opaque = reasoningOpaque(reasoning, options.providerMetadataKey);
420
+ const reasoningText = reasoning.length === 0 || (opaque !== undefined && text === "") ? (requireReasoning ? "" : undefined) : text;
410
421
  const result = {
411
422
  role: "assistant",
412
423
  content: (() => {
@@ -418,6 +429,7 @@ const lowerAssistantMessage = Effect.fnUntraced(function* (message, configuredFi
418
429
  })(),
419
430
  ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
420
431
  ...(details !== undefined ? { reasoning_details: details } : {}),
432
+ ...(opaque !== undefined ? { reasoning_opaque: opaque } : {}),
421
433
  };
422
434
  if (field === undefined || reasoningText === undefined)
423
435
  return result;
@@ -749,18 +761,24 @@ const mapFinishReason = Effect.fnUntraced(function* (event, reason) {
749
761
  // `prompt_tokens_details.cached_tokens`, DeepSeek uses
750
762
  // `prompt_cache_hit_tokens`, Zai uses top-level `cached_tokens`, and
751
763
  // DigitalOcean uses top-level `cache_read_input_tokens` / `cache_created_input_tokens`.
752
- const mapUsage = (usage, providerMetadataKey) => {
764
+ const mapUsage = (usage, providerMetadataKey, frame) => {
753
765
  if (!usage)
754
766
  return undefined;
755
767
  const input = usage.prompt_tokens ?? undefined;
756
- const output = usage.completion_tokens ?? undefined;
768
+ const completion = usage.completion_tokens ?? undefined;
757
769
  const cached = usage.prompt_tokens_details?.cached_tokens ??
758
770
  usage.prompt_cache_hit_tokens ??
759
771
  usage.cached_tokens ??
760
772
  usage.cache_read_input_tokens ??
761
773
  undefined;
762
774
  const cacheWrite = usage.prompt_tokens_details?.cache_write_tokens ?? usage.cache_created_input_tokens ?? undefined;
763
- const reasoning = usage.completion_tokens_details?.reasoning_tokens ?? undefined;
775
+ const reasoning = usage.completion_tokens_details?.reasoning_tokens ?? usage.reasoning_tokens ?? undefined;
776
+ // Copilot's Gemini counts reasoning beside `completion_tokens` rather than inside it; the total tells which.
777
+ const output = completion !== undefined &&
778
+ reasoning !== undefined &&
779
+ usage.total_tokens === ProviderShared.sumTokens(input, completion, reasoning)
780
+ ? completion + reasoning
781
+ : completion;
764
782
  const nonCached = ProviderShared.subtractTokens(input, ProviderShared.sumTokens(cached, cacheWrite));
765
783
  return new Usage({
766
784
  inputTokens: input,
@@ -770,7 +788,7 @@ const mapUsage = (usage, providerMetadataKey) => {
770
788
  cacheWriteInputTokens: cacheWrite,
771
789
  reasoningTokens: reasoning,
772
790
  totalTokens: ProviderShared.totalTokens(input, output, usage.total_tokens ?? undefined),
773
- ...ProviderShared.reportedBilling(usage),
791
+ ...ProviderShared.reportedBilling(usage, frame),
774
792
  providerMetadata: { [providerMetadataKey]: usage },
775
793
  });
776
794
  };
@@ -857,10 +875,11 @@ const conflictingReasoningDetails = (previous, current) => conflictingDetailValu
857
875
  conflictingDetailValue(previous.format, current.format) ||
858
876
  (Boolean(previous.signature) && Boolean(current.signature) && previous.signature !== current.signature);
859
877
  const conflictingDetailValue = (previous, current) => previous !== undefined && previous !== null && current !== undefined && current !== null && previous !== current;
860
- const reasoningMetadata = (providerMetadataKey, field, details) => ({
878
+ const reasoningMetadata = (providerMetadataKey, field, details, opaque) => ({
861
879
  [providerMetadataKey]: {
862
880
  ...(field ? { reasoningField: field } : {}),
863
881
  ...(details ? { reasoningDetails: details } : {}),
882
+ ...(opaque ? { reasoningOpaque: opaque } : {}),
864
883
  },
865
884
  });
866
885
  const step = (state, event) => Effect.gen(function* () {
@@ -878,14 +897,19 @@ const step = (state, event) => Effect.gen(function* () {
878
897
  const choice = event.choices?.[0];
879
898
  // Moonshot (and a few other OpenAI-compatible providers) attach usage to
880
899
  // `choice.usage` instead of the top-level `usage` field.
881
- const usage = mapUsage(event.usage, state.providerMetadataKey) ??
882
- mapUsage(choice?.usage, state.providerMetadataKey) ??
900
+ const usage = mapUsage(event.usage, state.providerMetadataKey, event) ??
901
+ mapUsage(choice?.usage, state.providerMetadataKey, event) ??
883
902
  state.usage;
884
903
  const rawFinishReason = choice?.finish_reason;
885
904
  const finishReason = rawFinishReason
886
905
  ? {
887
906
  normalized: yield* mapFinishReason(event, rawFinishReason),
888
907
  raw: choice?.native_finish_reason ?? rawFinishReason,
908
+ ...(rawFinishReason === "content_filter"
909
+ ? {
910
+ category: ProviderShared.contentFilterCategory(choice?.delta?.copilot_annotations, choice?.content_filter_results),
911
+ }
912
+ : {}),
889
913
  }
890
914
  : state.finishReason;
891
915
  const delta = choice?.delta;
@@ -911,13 +935,14 @@ const step = (state, event) => Effect.gen(function* () {
911
935
  if (detailDelta !== undefined)
912
936
  appendReasoningDetails(state.reasoningDetails, detailDelta);
913
937
  const reasoningDetailsObserved = state.reasoningDetailsObserved || detailDelta !== undefined;
938
+ const reasoningOpaque = delta?.reasoning_opaque || state.reasoningOpaque;
914
939
  const deltaMetadata = reasoningMetadata(state.providerMetadataKey, reasoningField);
915
940
  const text = detailDelta?.length
916
941
  ? (detailText(detailDelta, reasoningTextObserved) ?? reasoning?.text)
917
942
  : reasoning?.text;
918
943
  if (text !== undefined)
919
944
  lifecycle = Lifecycle.reasoningDelta(lifecycle, events, "reasoning-0", text, deltaMetadata);
920
- else if (reasoningDetailsObserved &&
945
+ else if ((reasoningDetailsObserved || reasoningOpaque !== undefined) &&
921
946
  !lifecycle.reasoning.has("reasoning-0") &&
922
947
  (Boolean(delta?.content) || Boolean(delta?.refusal) || toolDeltas.length > 0))
923
948
  lifecycle = Lifecycle.reasoningStart(lifecycle, events, "reasoning-0", deltaMetadata);
@@ -1013,6 +1038,7 @@ const step = (state, event) => Effect.gen(function* () {
1013
1038
  reasoningTextObserved,
1014
1039
  reasoningDetails: state.reasoningDetails,
1015
1040
  reasoningDetailsObserved,
1041
+ reasoningOpaque,
1016
1042
  reasoningEmitted,
1017
1043
  latestToolIndex,
1018
1044
  nextToolIndex,
@@ -1049,8 +1075,8 @@ export const finishEvents = Effect.fnUntraced(function* (state) {
1049
1075
  : { normalized: hasToolCalls ? "tool-calls" : "stop" };
1050
1076
  // Snapshot details at publish time so the emitted event never observes later
1051
1077
  // mutation of the accumulated `reasoningDetails` array.
1052
- const metadata = reasoningMetadata(state.providerMetadataKey, state.reasoningField, state.reasoningDetailsObserved ? [...state.reasoningDetails] : undefined);
1053
- const started = state.reasoningDetailsObserved && !state.reasoningEmitted
1078
+ const metadata = reasoningMetadata(state.providerMetadataKey, state.reasoningField, state.reasoningDetailsObserved ? [...state.reasoningDetails] : undefined, state.reasoningOpaque);
1079
+ const started = (state.reasoningDetailsObserved || state.reasoningOpaque !== undefined) && !state.reasoningEmitted
1054
1080
  ? Lifecycle.reasoningStart(state.lifecycle, events, "reasoning-0", reasoningMetadata(state.providerMetadataKey, state.reasoningField))
1055
1081
  : state.lifecycle;
1056
1082
  const ended = Lifecycle.reasoningEnd(started, events, "reasoning-0", metadata);
@@ -106,6 +106,7 @@ export declare const route: Route<{
106
106
  readonly reasoning?: string | undefined;
107
107
  readonly reasoning_text?: string | undefined;
108
108
  readonly reasoning_details?: unknown;
109
+ readonly reasoning_opaque?: string | undefined;
109
110
  })[];
110
111
  readonly tools?: readonly ({
111
112
  readonly type: "function";
@@ -54,7 +54,20 @@ const fromRequest = Effect.fn("OpenAIDecisions.fromRequest")(function* (request)
54
54
  }, request.http?.body),
55
55
  model: request.model.id,
56
56
  input: [{ role: "user", content: yield* Effect.forEach(request.input, (part) => inputPart(request, part)) }],
57
- questions: request.questions,
57
+ questions: request.questions.map((question) => {
58
+ if (question.type !== "predicate")
59
+ return question;
60
+ // Predicates have no criteria field, so what true and false mean is appended to the instructions.
61
+ const meanings = [
62
+ question.criteria?.true === undefined ? [] : [`True means: ${question.criteria.true}`],
63
+ question.criteria?.false === undefined ? [] : [`False means: ${question.criteria.false}`],
64
+ ].flat();
65
+ return {
66
+ name: question.name,
67
+ type: question.type,
68
+ instructions: meanings.length === 0 ? question.instructions : `${question.instructions}\n\n${meanings.join("\n")}`,
69
+ };
70
+ }),
58
71
  };
59
72
  });
60
73
  // `input_json` takes an object or a list of objects; other JSON values go as text.
@@ -0,0 +1,16 @@
1
+ import { EmbeddingRoute } from "../route/embedding.js";
2
+ import { type OpenString } from "../schema/index.js";
3
+ export declare const DEFAULT_BASE_URL = "https://api.openai.com/v1";
4
+ export declare const PATH = "/embeddings";
5
+ /** Sent as given; anything else a host accepts (`input_type`, `truncate`, …) goes alongside. */
6
+ export interface OptionsInput {
7
+ readonly [key: string]: unknown;
8
+ readonly user?: string;
9
+ readonly encoding_format?: OpenString<"float" | "base64">;
10
+ }
11
+ export declare const protocol: EmbeddingRoute.Protocol;
12
+ export declare const route: EmbeddingRoute.Route;
13
+ export declare const OpenAIEmbeddings: {
14
+ readonly protocol: EmbeddingRoute.Protocol;
15
+ readonly route: EmbeddingRoute.Route;
16
+ };
@@ -0,0 +1,76 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { Base64 } from "effect/encoding";
3
+ import { EmbeddingResponse, EmbeddingUsage } from "../embedding.js";
4
+ import { EmbeddingRoute } from "../route/embedding.js";
5
+ import { Endpoint } from "../route/endpoint.js";
6
+ import { MediaProtocol } from "../route/media-protocol.js";
7
+ import { AIError, UnsupportedOperationError, mergeJsonRecords } from "../schema/index.js";
8
+ const ID = "openai-embeddings";
9
+ const NAME = "OpenAI Embeddings";
10
+ export const DEFAULT_BASE_URL = "https://api.openai.com/v1";
11
+ export const PATH = "/embeddings";
12
+ const Response = Schema.Struct({
13
+ data: Schema.Array(Schema.Struct({
14
+ index: Schema.optional(Schema.Int),
15
+ // `base64` encoding returns little-endian float32 bytes instead of a number list.
16
+ embedding: Schema.Union([Schema.Array(Schema.Number), Schema.String]),
17
+ })),
18
+ model: Schema.optional(Schema.String),
19
+ usage: Schema.optional(Schema.StructWithRest(Schema.Struct({ prompt_tokens: Schema.optional(Schema.Number), total_tokens: Schema.optional(Schema.Number) }), [Schema.Record(Schema.String, Schema.Unknown)])),
20
+ });
21
+ // `inputType` has no field here; OpenAI's models embed queries and documents the same way.
22
+ const fromRequest = Effect.fn("OpenAIEmbeddings.fromRequest")(function* (request) {
23
+ const input = request.values.filter((value) => typeof value === "string");
24
+ if (input.length !== request.values.length)
25
+ return yield* new AIError({
26
+ reason: new UnsupportedOperationError({
27
+ operation: "embedding.media",
28
+ provider: request.model.provider,
29
+ route: request.model.route.id,
30
+ message: `${NAME} embeds text only; pass media values to a host with a multimodal embedding API`,
31
+ }),
32
+ });
33
+ return {
34
+ ...mergeJsonRecords({ encoding_format: "float", ...request.providerOptions }, request.http?.body),
35
+ model: request.model.id,
36
+ input,
37
+ ...(request.dimensions === undefined ? {} : { dimensions: request.dimensions }),
38
+ };
39
+ });
40
+ const decodeDocument = MediaProtocol.identity({ id: ID, name: NAME, provider: "openai" }).decodeJson(Response);
41
+ export const protocol = EmbeddingRoute.protocol({
42
+ id: ID,
43
+ name: NAME,
44
+ body: { from: fromRequest },
45
+ response: {
46
+ decode: Effect.fn("OpenAIEmbeddings.decodeResponse")(function* (response, context) {
47
+ const output = yield* decodeDocument(response);
48
+ const embeddings = yield* Effect.forEach(output.value.data
49
+ .map((item, position) => ({ index: item.index ?? position, embedding: item.embedding }))
50
+ .toSorted((a, b) => a.index - b.index), (item) => typeof item.embedding !== "string"
51
+ ? Effect.succeed(item.embedding)
52
+ : Effect.fromResult(Base64.decode(item.embedding)).pipe(Effect.map((bytes) => Array.from(new Float32Array(bytes.slice().buffer))), Effect.mapError((cause) => output.invalid(`${NAME} returned an invalid base64 embedding`, cause))));
53
+ const usage = output.value.usage;
54
+ return new EmbeddingResponse({
55
+ embeddings,
56
+ usage: usage?.prompt_tokens === undefined ? undefined : new EmbeddingUsage({ inputTokens: usage.prompt_tokens }),
57
+ providerMetadata: {
58
+ [context.providerMetadataKey]: {
59
+ ...(output.value.model === undefined ? {} : { model: output.value.model }),
60
+ ...(usage === undefined ? {} : { usage }),
61
+ },
62
+ },
63
+ });
64
+ }),
65
+ },
66
+ });
67
+ export const route = EmbeddingRoute.make({
68
+ id: ID,
69
+ provider: "openai",
70
+ protocol,
71
+ endpoint: Endpoint.path(PATH, { baseURL: DEFAULT_BASE_URL }),
72
+ });
73
+ export const OpenAIEmbeddings = {
74
+ protocol,
75
+ route,
76
+ };
@@ -0,0 +1,41 @@
1
+ import { Schema } from "effect";
2
+ import { MediaProtocol } from "../route/media-protocol.js";
3
+ import { MediaRoute } from "../route/media.js";
4
+ import { VideoModel, VideoResponse, type VideoRequest } from "../video.js";
5
+ export declare const DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
6
+ export declare const PATH = "/videos";
7
+ /**
8
+ * Provider-native options. Common fields (`start`, `end`, `references`, `duration`, `aspect`, `resolution`, `sound`)
9
+ * live on the request. `provider` routes the request and forwards the upstream provider's own parameters under
10
+ * `provider.options.<slug>` (see each model's `allowed_passthrough_parameters`); `previous_job_id` edits or extends a
11
+ * finished OpenRouter job on the same model.
12
+ */
13
+ export type OpenRouterVideoOptions = {
14
+ readonly provider?: {
15
+ readonly order?: ReadonlyArray<string>;
16
+ readonly only?: ReadonlyArray<string>;
17
+ readonly ignore?: ReadonlyArray<string>;
18
+ readonly options?: Readonly<Record<string, Record<string, unknown>>>;
19
+ } & Record<string, unknown>;
20
+ readonly previous_job_id?: string;
21
+ readonly seed?: number;
22
+ readonly size?: string;
23
+ readonly callback_url?: string;
24
+ readonly user?: string;
25
+ readonly session_id?: string;
26
+ } & Record<string, unknown>;
27
+ export type Request = VideoRequest<VideoModel<OpenRouterVideoOptions>>;
28
+ export declare const Token: Schema.Struct<{
29
+ readonly id: Schema.String;
30
+ }>;
31
+ export type Token = Schema.Schema.Type<typeof Token>;
32
+ export declare const protocol: MediaProtocol.Queued<Request, VideoResponse, {
33
+ readonly id: string;
34
+ }>;
35
+ export declare const model: (input: MediaRoute.ModelInput) => VideoModel<OpenRouterVideoOptions>;
36
+ export declare const OpenRouterVideo: {
37
+ readonly protocol: MediaProtocol.Queued<Request, VideoResponse, {
38
+ readonly id: string;
39
+ }>;
40
+ readonly model: typeof model;
41
+ };
@@ -0,0 +1,138 @@
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 } from "../schema/index.js";
6
+ import { VideoModel, VideoResponse, seconds } from "../video.js";
7
+ import { ProviderShared, optionalNull } from "./shared.js";
8
+ const route = MediaProtocol.identity({ id: "openrouter-video", name: "OpenRouter Video", provider: "openrouter" });
9
+ export const DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
10
+ export const PATH = "/videos";
11
+ // ---------------------------------------------------------------------------
12
+ // 2. Token and response schemas
13
+ // ---------------------------------------------------------------------------
14
+ export const Token = Schema.Struct({ id: Schema.String });
15
+ const StartResponse = Schema.Struct({ id: Schema.String, status: optionalNull(Schema.String) });
16
+ const Job = Schema.Struct({
17
+ id: optionalNull(Schema.String),
18
+ generation_id: optionalNull(Schema.String),
19
+ status: Schema.String,
20
+ unsigned_urls: optionalNull(Schema.Array(Schema.String)),
21
+ expires_at: optionalNull(Schema.Number),
22
+ error: optionalNull(Schema.String),
23
+ usage: optionalNull(Schema.Struct({
24
+ cost: optionalNull(Schema.Number),
25
+ is_byok: optionalNull(Schema.Boolean),
26
+ })),
27
+ });
28
+ // ---------------------------------------------------------------------------
29
+ // 3. Status
30
+ // ---------------------------------------------------------------------------
31
+ const STATUS = {
32
+ pending: "queued",
33
+ in_progress: "running",
34
+ completed: "completed",
35
+ failed: "failed",
36
+ cancelled: "cancelled",
37
+ expired: "expired",
38
+ };
39
+ // ---------------------------------------------------------------------------
40
+ // 4. Body construction
41
+ // ---------------------------------------------------------------------------
42
+ const imagePart = (asset) => ProviderShared.mediaReference(asset, undefined, route.name).pipe(Effect.map((reference) => ({ type: "image_url", image_url: { url: reference.value } })));
43
+ const referencePart = Effect.fn("OpenRouterVideo.referencePart")(function* (asset) {
44
+ // OpenRouter rejects inline video and audio ("Only HTTPS URLs are allowed", verified live); inline images work.
45
+ if ((asset.kind === "video" || asset.kind === "audio") && asset.source.type !== "url")
46
+ return yield* route.unsupported("video.references", `${route.name} only takes reference ${asset.kind} as http(s) URLs`);
47
+ const reference = yield* ProviderShared.mediaReference(asset, undefined, route.name);
48
+ if (asset.kind === "video")
49
+ return { type: "video_url", video_url: { url: reference.value } };
50
+ if (asset.kind === "audio")
51
+ return { type: "audio_url", audio_url: { url: reference.value } };
52
+ return { type: "image_url", image_url: { url: reference.value } };
53
+ });
54
+ const fromRequest = Effect.fn("OpenRouterVideo.fromRequest")(function* (request) {
55
+ const frames = [
56
+ ...(request.start === undefined
57
+ ? []
58
+ : [{ ...(yield* imagePart(request.start)), frame_type: "first_frame" }]),
59
+ ...(request.end === undefined ? [] : [{ ...(yield* imagePart(request.end)), frame_type: "last_frame" }]),
60
+ ];
61
+ const inputReferences = yield* Effect.forEach(request.references ?? [], referencePart);
62
+ return MediaProtocol.json(mergeJsonRecords({
63
+ model: request.model.id,
64
+ prompt: request.prompt,
65
+ frame_images: frames.length === 0 ? undefined : frames,
66
+ input_references: inputReferences.length === 0 ? undefined : inputReferences,
67
+ duration: request.duration === undefined ? undefined : seconds(request.duration),
68
+ // Leaving the aspect ratio out is how OpenRouter follows the input image on models that can.
69
+ aspect_ratio: request.aspect === "auto" ? undefined : request.aspect,
70
+ resolution: request.resolution === undefined ? undefined : resolution(request.resolution),
71
+ generate_audio: request.sound,
72
+ }, request.providerOptions, request.http?.body) ?? {});
73
+ });
74
+ // OpenRouter spells the K resolutions in upper case (`1K`, `2K`, `4K`).
75
+ const resolution = (value) => (/^\dk$/.test(value) ? value.toUpperCase() : value);
76
+ // ---------------------------------------------------------------------------
77
+ // 5. Response decoding
78
+ // ---------------------------------------------------------------------------
79
+ const decodeStart = route.decodeStarted(StartResponse, (value) => ({
80
+ token: { id: value.id },
81
+ snapshot: { id: value.id, status: MediaProtocol.status(STATUS, value.status ?? "pending") },
82
+ }));
83
+ const decodeJob = route.decodeJson(Job);
84
+ const decodeStatus = Effect.fn("OpenRouterVideo.decodeStatus")(function* (response, context) {
85
+ const output = yield* decodeJob(response);
86
+ return { id: context.token.id, status: MediaProtocol.status(STATUS, output.value.status) };
87
+ });
88
+ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* (response, context) {
89
+ const output = yield* decodeJob(response);
90
+ const job = output.value;
91
+ const status = MediaProtocol.status(STATUS, job.status);
92
+ if (status === "queued" || status === "running")
93
+ return yield* output.pending(context.token.id);
94
+ if (status === "failed") {
95
+ const message = `${route.name} generation failed${job.error ? `: ${job.error}` : ""}`;
96
+ if (job.error && /content policy|moderat/i.test(job.error))
97
+ return yield* output.contentPolicy(message);
98
+ return yield* output.ended("failed", message);
99
+ }
100
+ if (status !== "completed")
101
+ return yield* output.ended(status, `${route.name} job ${context.token.id} ${status}${job.error ? `: ${job.error}` : ""}`);
102
+ const urls = job.unsigned_urls ?? [];
103
+ if (urls.length === 0)
104
+ return yield* output.invalid(`${route.name} completed without a video URL`);
105
+ // The content URLs are OpenRouter's own and only download with the API key.
106
+ const videos = yield* Effect.forEach(urls, (url) => context.headers(url).pipe(Effect.map((headers) => Media.url(url, {
107
+ mediaType: "video/mp4",
108
+ expiresAt: job.expires_at === undefined || job.expires_at === null ? undefined : job.expires_at * 1000,
109
+ headers,
110
+ }))));
111
+ return new VideoResponse({
112
+ videos,
113
+ providerMetadata: {
114
+ openrouter: {
115
+ id: context.token.id,
116
+ generationId: job.generation_id ?? undefined,
117
+ cost: job.usage?.cost ?? undefined,
118
+ isByok: job.usage?.is_byok ?? undefined,
119
+ },
120
+ },
121
+ });
122
+ });
123
+ // ---------------------------------------------------------------------------
124
+ // 6. Protocol and route
125
+ // ---------------------------------------------------------------------------
126
+ const jobPath = (token) => `${PATH}/${encodeURIComponent(token.id)}`;
127
+ // OpenRouter has no cancel endpoint; `cancelled` only appears when it stops a job itself.
128
+ export const protocol = MediaProtocol.queued(route, {
129
+ token: Token,
130
+ start: { body: { from: fromRequest }, decode: decodeStart },
131
+ status: { path: jobPath, decode: decodeStatus },
132
+ result: { path: jobPath, decode: decodeResult },
133
+ });
134
+ export const model = (input) => VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input);
135
+ export const OpenRouterVideo = {
136
+ protocol,
137
+ model,
138
+ };
@@ -0,0 +1,50 @@
1
+ import { Schema } from "effect";
2
+ import { MediaProtocol } from "../route/media-protocol.js";
3
+ import { MediaRoute } from "../route/media.js";
4
+ import { VideoModel, VideoResponse, type VideoRequest } from "../video.js";
5
+ export declare const VOLCENGINE_BASE_URL = "https://ark.cn-beijing.volces.com/api/v3";
6
+ export declare const BYTEPLUS_BASE_URL = "https://ark.ap-southeast.bytepluses.com/api/v3";
7
+ export declare const PATH = "/contents/generations/tasks";
8
+ /**
9
+ * Provider-native options, merged into the task body. Common fields (`start`, `end`, `references`, `duration`,
10
+ * `aspect`, `resolution`, `sound`) live on the request. `draft_task` adds a `draft_task` content item that turns a
11
+ * Draft video into the final one.
12
+ */
13
+ export type SeedanceVideoOptions = {
14
+ readonly draft_task?: {
15
+ readonly id: string;
16
+ };
17
+ readonly draft?: boolean;
18
+ readonly frames?: number;
19
+ readonly seed?: number;
20
+ readonly camera_fixed?: boolean;
21
+ readonly watermark?: boolean;
22
+ readonly return_last_frame?: boolean;
23
+ readonly omni_reference_task_type?: "auto" | "reference" | "edit" | "extend" | (string & {});
24
+ readonly output_format?: "mp4" | "mov" | (string & {});
25
+ readonly service_tier?: "default" | "flex" | (string & {});
26
+ readonly callback_url?: string;
27
+ readonly execution_expires_after?: number;
28
+ readonly priority?: number;
29
+ readonly safety_identifier?: string;
30
+ } & Record<string, unknown>;
31
+ export type Request = VideoRequest<VideoModel<SeedanceVideoOptions>>;
32
+ export declare const Token: Schema.Struct<{
33
+ readonly taskID: Schema.String;
34
+ }>;
35
+ export type Token = Schema.Schema.Type<typeof Token>;
36
+ export type Provider = "volcengine" | "byteplus";
37
+ export declare const SeedanceVideo: {
38
+ readonly volcengine: {
39
+ protocol: MediaProtocol.Queued<Request, VideoResponse, {
40
+ readonly taskID: string;
41
+ }>;
42
+ model: (input: MediaRoute.ModelInput) => VideoModel<SeedanceVideoOptions>;
43
+ };
44
+ readonly byteplus: {
45
+ protocol: MediaProtocol.Queued<Request, VideoResponse, {
46
+ readonly taskID: string;
47
+ }>;
48
+ model: (input: MediaRoute.ModelInput) => VideoModel<SeedanceVideoOptions>;
49
+ };
50
+ };