@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,133 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { DecisionResponse, DecisionUsage } from "../decision.js";
3
+ import { DecisionRoute } from "../route/decision.js";
4
+ import { Endpoint } from "../route/endpoint.js";
5
+ import { MediaProtocol } from "../route/media-protocol.js";
6
+ import { AIError, ProviderID, UnsupportedOperationError, mergeJsonRecords, } from "../schema/index.js";
7
+ import { encodeJson } from "../utils/json.js";
8
+ import { JsonObject, knownString, ProviderShared } from "./shared.js";
9
+ import { SystemOne } from "./system-one.js";
10
+ import { MediaInput } from "./utils/media-input.js";
11
+ const ID = "google-decisions";
12
+ const NAME = "Google Decisions";
13
+ export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
14
+ const Options = Schema.Struct({
15
+ /** Token budget for every image and video input; `ultra_high` applies to images only. */
16
+ mediaResolution: Schema.optional(knownString()),
17
+ });
18
+ const Usage = Schema.StructWithRest(Schema.Struct({
19
+ total_input_tokens: Schema.optional(Schema.Number),
20
+ total_output_tokens: Schema.optional(Schema.Number),
21
+ total_tokens: Schema.optional(Schema.Number),
22
+ }), [JsonObject]);
23
+ const Response = Schema.Struct({
24
+ answers: Schema.Record(Schema.String, SystemOne.Answer),
25
+ usage: Schema.optional(Usage),
26
+ });
27
+ const decodeOptions = ProviderShared.validateWith(Schema.decodeUnknownEffect(Options));
28
+ const fromRequest = Effect.fn("GoogleDecisions.fromRequest")(function* (request) {
29
+ const options = yield* decodeOptions(request.providerOptions ?? {});
30
+ const { mediaResolution: _, ...native } = request.providerOptions ?? {};
31
+ return {
32
+ ...mergeJsonRecords(native, request.http?.body),
33
+ model: request.model.id,
34
+ input: separateText(yield* Effect.forEach(request.input, (part) => inputPart(request, part, options.mediaResolution))),
35
+ questions: {
36
+ ...(yield* SystemOne.encodeQuestions(request.questions)),
37
+ // Google names System One's predicate criteria `true_description` and `false_description`.
38
+ ...Object.fromEntries(request.questions.flatMap((question) => question.type === "predicate" && question.criteria !== undefined
39
+ ? [
40
+ [
41
+ question.name,
42
+ {
43
+ type: "noul",
44
+ instructions: question.instructions,
45
+ criteria: {
46
+ ...(question.criteria.true === undefined ? {} : { true_description: question.criteria.true }),
47
+ ...(question.criteria.false === undefined ? {} : { false_description: question.criteria.false }),
48
+ },
49
+ },
50
+ ],
51
+ ]
52
+ : [])),
53
+ },
54
+ };
55
+ });
56
+ const inputPart = (request, part, resolution) => {
57
+ if (part.type === "text")
58
+ return Effect.succeed({ type: "text", text: part.text });
59
+ // Google reads every text block as text; JSON is serialized so its keys are never parsed as content blocks.
60
+ if (part.type === "json")
61
+ return Effect.succeed({ type: "text", text: encodeJson(part.value) });
62
+ return mediaPart(request, part.media, resolution);
63
+ };
64
+ // Google joins adjacent text blocks with no separator, so each one after another starts on a new line.
65
+ const separateText = (blocks) => blocks.map((block, index) => block.type === "text" && blocks[index - 1]?.type === "text" ? { ...block, text: `\n${block.text}` } : block);
66
+ const mediaPart = (request, asset, resolution) => {
67
+ const type = asset.kind === "image" || asset.kind === "audio" || asset.kind === "video"
68
+ ? asset.kind
69
+ : asset.mediaType.toLowerCase() === "application/pdf"
70
+ ? "document"
71
+ : undefined;
72
+ if (type === undefined)
73
+ return Effect.fail(new AIError({
74
+ reason: new UnsupportedOperationError({
75
+ operation: "decision.media",
76
+ provider: request.model.provider,
77
+ route: request.model.route.id,
78
+ message: `${NAME} takes images, audio, video and PDFs; got ${asset.mediaType}`,
79
+ }),
80
+ }));
81
+ const block = {
82
+ type,
83
+ mime_type: asset.mediaType.toLowerCase(),
84
+ // `ultra_high` is image-only, so video keeps Google's default for it.
85
+ ...(resolution !== undefined && (type === "image" || (type === "video" && resolution !== "ultra_high"))
86
+ ? { resolution }
87
+ : {}),
88
+ };
89
+ const inline = asset.inline();
90
+ if (inline)
91
+ return Effect.succeed({ ...block, data: inline.base64 });
92
+ // Google fetches URLs itself, so one that needs our download credentials can't be forwarded.
93
+ if (asset.source.type === "url" && /^https:\/\//i.test(asset.source.url) && asset.headers === undefined)
94
+ return Effect.succeed({ ...block, uri: asset.source.url });
95
+ const file = MediaInput.refID(asset, ProviderID.make("google"));
96
+ if (file !== undefined)
97
+ return Effect.succeed({ ...block, uri: file });
98
+ return Effect.fail(ProviderShared.invalidRequest(`${NAME} accepts inline media, public HTTPS URLs and Google Files API URIs; materialize ${asset.source.type} media first`));
99
+ };
100
+ const decodeDocument = MediaProtocol.identity({ id: ID, name: NAME, provider: "google" }).decodeJson(Response);
101
+ export const protocol = DecisionRoute.protocol({
102
+ id: ID,
103
+ name: NAME,
104
+ body: { from: fromRequest },
105
+ response: {
106
+ decode: Effect.fn("GoogleDecisions.decodeResponse")(function* (response, context) {
107
+ const output = yield* decodeDocument(response);
108
+ const data = output.value;
109
+ const answers = data.answers;
110
+ const names = context.request.questions.map((question) => question.name);
111
+ if (Object.keys(answers).length !== names.length || !names.every((name) => Object.hasOwn(answers, name)))
112
+ return yield* output.invalid(`${NAME} answers do not match the requested questions`);
113
+ return new DecisionResponse({
114
+ answers: context.request.questions.map((question) => SystemOne.toAnswer(question, answers[question.name])),
115
+ usage: data.usage === undefined
116
+ ? undefined
117
+ : new DecisionUsage({
118
+ inputTokens: data.usage.total_input_tokens,
119
+ outputTokens: data.usage.total_output_tokens,
120
+ totalTokens: ProviderShared.totalTokens(data.usage.total_input_tokens, data.usage.total_output_tokens, data.usage.total_tokens),
121
+ }),
122
+ providerMetadata: data.usage === undefined ? undefined : { [context.providerMetadataKey]: { usage: data.usage } },
123
+ });
124
+ }),
125
+ },
126
+ });
127
+ export const route = DecisionRoute.make({
128
+ id: ID,
129
+ provider: "google",
130
+ protocol,
131
+ endpoint: Endpoint.path("/decisions", { baseURL: DEFAULT_BASE_URL }),
132
+ });
133
+ export * as GoogleDecisions from "./google-decisions.js";
@@ -0,0 +1,34 @@
1
+ import { EmbeddingRoute } from "../route/embedding.js";
2
+ import { type OpenString } from "../schema/index.js";
3
+ export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
4
+ /** `batchEmbedContents` takes at most 100 requests. */
5
+ export declare const MAX_BATCH = 100;
6
+ export type TaskType = OpenString<"RETRIEVAL_QUERY" | "RETRIEVAL_DOCUMENT" | "SEMANTIC_SIMILARITY" | "CLASSIFICATION" | "CLUSTERING" | "QUESTION_ANSWERING" | "FACT_VERIFICATION" | "CODE_RETRIEVAL_QUERY">;
7
+ /**
8
+ * Per-value embedding fields, sent with each value. `taskType` replaces the one `inputType` maps to; Gemini Embedding 2
9
+ * ignores task types and documents task prefixes in the text instead (`task: search result | query: …`).
10
+ */
11
+ export interface OptionsInput {
12
+ readonly [key: string]: unknown;
13
+ readonly taskType?: TaskType;
14
+ readonly title?: string;
15
+ }
16
+ /** Vertex `embedContentConfig` fields; Vertex alone takes `autoTruncate`, `documentOcr` and `audioTrackExtraction`. */
17
+ export interface VertexOptionsInput extends OptionsInput {
18
+ readonly autoTruncate?: boolean;
19
+ readonly documentOcr?: boolean;
20
+ readonly audioTrackExtraction?: boolean;
21
+ }
22
+ /** Gemini API `batchEmbedContents`: one request per value, so every value gets its own vector. */
23
+ export declare const protocol: EmbeddingRoute.Protocol;
24
+ /**
25
+ * Vertex `embedContent`: one content per request, with options under `embedContentConfig`. Routes using it set
26
+ * `maxValues: 1`.
27
+ */
28
+ export declare const vertexProtocol: EmbeddingRoute.Protocol;
29
+ export declare const route: EmbeddingRoute.Route;
30
+ export declare const GoogleEmbedContent: {
31
+ readonly protocol: EmbeddingRoute.Protocol;
32
+ readonly vertexProtocol: EmbeddingRoute.Protocol;
33
+ readonly route: EmbeddingRoute.Route;
34
+ };
@@ -0,0 +1,110 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { EmbeddingResponse, EmbeddingUsage } from "../embedding.js";
3
+ import { EmbeddingRoute } from "../route/embedding.js";
4
+ import { Endpoint } from "../route/endpoint.js";
5
+ import { MediaProtocol } from "../route/media-protocol.js";
6
+ import { mergeJsonRecords } from "../schema/index.js";
7
+ import { GeminiGenerateContent } from "./utils/gemini-generate-content.js";
8
+ const ID = "google-embed-content";
9
+ const NAME = "Google embedContent";
10
+ export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
11
+ /** `batchEmbedContents` takes at most 100 requests. */
12
+ export const MAX_BATCH = 100;
13
+ const Values = Schema.Struct({ values: Schema.Array(Schema.Number) });
14
+ const UsageMetadata = Schema.StructWithRest(Schema.Struct({ promptTokenCount: Schema.optional(Schema.Number) }), [
15
+ Schema.Record(Schema.String, Schema.Unknown),
16
+ ]);
17
+ const BatchResponse = Schema.Struct({
18
+ embeddings: Schema.Array(Values),
19
+ usageMetadata: Schema.optional(UsageMetadata),
20
+ });
21
+ const SingleResponse = Schema.Struct({
22
+ embedding: Values,
23
+ usageMetadata: Schema.optional(UsageMetadata),
24
+ truncated: Schema.optional(Schema.Boolean),
25
+ });
26
+ const TASK_TYPES = { query: "RETRIEVAL_QUERY", document: "RETRIEVAL_DOCUMENT" };
27
+ // Each value is its own content: several parts in one content embed into one aggregated vector.
28
+ const content = (value) => typeof value === "string"
29
+ ? Effect.succeed({ parts: [{ text: value }] })
30
+ : GeminiGenerateContent.mediaPart(NAME, value).pipe(Effect.map((part) => ({ parts: [part] })));
31
+ const config = (request) => ({
32
+ ...(request.inputType === undefined ? {} : { taskType: TASK_TYPES[request.inputType] }),
33
+ ...(request.dimensions === undefined ? {} : { outputDimensionality: request.dimensions }),
34
+ ...request.providerOptions,
35
+ });
36
+ const identity = MediaProtocol.identity({ id: ID, name: NAME, provider: "google" });
37
+ const decodeBatch = identity.decodeJson(BatchResponse);
38
+ const decodeSingle = identity.decodeJson(SingleResponse);
39
+ const usage = (metadata) => metadata?.promptTokenCount === undefined ? undefined : new EmbeddingUsage({ inputTokens: metadata.promptTokenCount });
40
+ /** Gemini API `batchEmbedContents`: one request per value, so every value gets its own vector. */
41
+ export const protocol = EmbeddingRoute.protocol({
42
+ id: ID,
43
+ name: NAME,
44
+ body: {
45
+ from: Effect.fn("GoogleEmbedContent.fromRequest")(function* (request) {
46
+ const contents = yield* Effect.forEach(request.values, content);
47
+ const fields = config(request);
48
+ return (mergeJsonRecords({ requests: contents.map((item) => ({ model: `models/${request.model.id}`, content: item, ...fields })) }, request.http?.body) ?? {});
49
+ }),
50
+ },
51
+ response: {
52
+ decode: Effect.fn("GoogleEmbedContent.decodeResponse")(function* (response, context) {
53
+ const output = yield* decodeBatch(response);
54
+ return new EmbeddingResponse({
55
+ embeddings: output.value.embeddings.map((item) => item.values),
56
+ usage: usage(output.value.usageMetadata),
57
+ providerMetadata: {
58
+ [context.providerMetadataKey]: output.value.usageMetadata === undefined ? {} : { usageMetadata: output.value.usageMetadata },
59
+ },
60
+ });
61
+ }),
62
+ },
63
+ });
64
+ /**
65
+ * Vertex `embedContent`: one content per request, with options under `embedContentConfig`. Routes using it set
66
+ * `maxValues: 1`.
67
+ */
68
+ export const vertexProtocol = EmbeddingRoute.protocol({
69
+ id: "google-vertex-embed-content",
70
+ name: "Google Vertex embedContent",
71
+ body: {
72
+ from: Effect.fn("GoogleEmbedContent.vertexFromRequest")(function* (request) {
73
+ const contents = yield* Effect.forEach(request.values, content);
74
+ const fields = config(request);
75
+ return (mergeJsonRecords({
76
+ content: contents[0],
77
+ ...(Object.keys(fields).length === 0 ? {} : { embedContentConfig: fields }),
78
+ }, request.http?.body) ?? {});
79
+ }),
80
+ },
81
+ response: {
82
+ decode: Effect.fn("GoogleEmbedContent.vertexDecodeResponse")(function* (response, context) {
83
+ const output = yield* decodeSingle(response);
84
+ return new EmbeddingResponse({
85
+ embeddings: [output.value.embedding.values],
86
+ usage: usage(output.value.usageMetadata),
87
+ providerMetadata: {
88
+ [context.providerMetadataKey]: {
89
+ ...(output.value.usageMetadata === undefined ? {} : { usageMetadata: output.value.usageMetadata }),
90
+ ...(output.value.truncated === undefined ? {} : { truncated: output.value.truncated }),
91
+ },
92
+ },
93
+ });
94
+ }),
95
+ },
96
+ });
97
+ export const route = EmbeddingRoute.make({
98
+ id: ID,
99
+ provider: "google",
100
+ protocol,
101
+ endpoint: Endpoint.path(({ request }) => `/models/${request.model.id}:batchEmbedContents`, {
102
+ baseURL: DEFAULT_BASE_URL,
103
+ }),
104
+ maxValues: MAX_BATCH,
105
+ });
106
+ export const GoogleEmbedContent = {
107
+ protocol,
108
+ vertexProtocol,
109
+ route,
110
+ };
@@ -0,0 +1,43 @@
1
+ import { Schema } from "effect";
2
+ import { MediaProtocol } from "../route/media-protocol.js";
3
+ import { MediaRoute } from "../route/media.js";
4
+ import { type OpenString } from "../schema/index.js";
5
+ import { VideoModel, VideoResponse, type VideoRequest } from "../video.js";
6
+ export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
7
+ export declare const PATH = "/interactions";
8
+ /**
9
+ * Provider-native Interactions fields, merged into the body. Common fields (`start`, `end`, `references`,
10
+ * `duration`, `aspect`, `resolution`) live on the request. Edit or extend a video by passing it as a reference with
11
+ * `generation_config.video_config.task`, or continue a generated one with `previous_interaction_id`.
12
+ */
13
+ export type GoogleVideoOptions = {
14
+ readonly previous_interaction_id?: string;
15
+ readonly generation_config?: {
16
+ readonly video_config?: {
17
+ readonly task?: OpenString<"text_to_video" | "image_to_video" | "reference_to_video" | "edit" | "extend">;
18
+ } & Record<string, unknown>;
19
+ } & Record<string, unknown>;
20
+ readonly response_format?: {
21
+ readonly delivery?: OpenString<"inline" | "uri">;
22
+ } & Record<string, unknown>;
23
+ readonly service_tier?: OpenString<"flex" | "standard" | "priority">;
24
+ readonly webhook_config?: {
25
+ readonly uris?: ReadonlyArray<string>;
26
+ readonly user_metadata?: Record<string, unknown>;
27
+ };
28
+ } & Record<string, unknown>;
29
+ export type Request = VideoRequest<VideoModel<GoogleVideoOptions>>;
30
+ export declare const Token: Schema.Struct<{
31
+ readonly interactionID: Schema.String;
32
+ }>;
33
+ export type Token = Schema.Schema.Type<typeof Token>;
34
+ export declare const protocol: MediaProtocol.Queued<Request, VideoResponse, {
35
+ readonly interactionID: string;
36
+ }>;
37
+ export declare const model: (input: MediaRoute.ModelInput) => VideoModel<GoogleVideoOptions>;
38
+ export declare const GoogleInteractionsVideo: {
39
+ readonly protocol: MediaProtocol.Queued<Request, VideoResponse, {
40
+ readonly interactionID: string;
41
+ }>;
42
+ readonly model: typeof model;
43
+ };
@@ -0,0 +1,186 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { Media } from "../media.js";
3
+ import { MediaProtocol } from "../route/media-protocol.js";
4
+ import { MediaRoute } from "../route/media.js";
5
+ import { mergeJsonRecords, tokenUsage } from "../schema/index.js";
6
+ import { VideoModel, VideoResponse, seconds } from "../video.js";
7
+ import { GoogleInteractions } from "./google-interactions.js";
8
+ import { optionalNull } from "./shared.js";
9
+ import { GeminiGenerateContent } from "./utils/gemini-generate-content.js";
10
+ import { MediaInput } from "./utils/media-input.js";
11
+ const route = MediaProtocol.identity({
12
+ id: "google-interactions-video",
13
+ name: "Google Interactions Video",
14
+ provider: "google",
15
+ });
16
+ export const DEFAULT_BASE_URL = GoogleInteractions.DEFAULT_BASE_URL;
17
+ export const PATH = "/interactions";
18
+ // ---------------------------------------------------------------------------
19
+ // 2. Token and response schemas
20
+ // ---------------------------------------------------------------------------
21
+ export const Token = Schema.Struct({ interactionID: Schema.String });
22
+ const Content = Schema.Struct({
23
+ type: Schema.String,
24
+ data: optionalNull(Schema.String),
25
+ uri: optionalNull(Schema.String),
26
+ mime_type: optionalNull(Schema.String),
27
+ text: optionalNull(Schema.String),
28
+ });
29
+ const Usage = Schema.StructWithRest(Schema.Struct({
30
+ total_input_tokens: optionalNull(Schema.Number),
31
+ total_output_tokens: optionalNull(Schema.Number),
32
+ total_thought_tokens: optionalNull(Schema.Number),
33
+ total_tokens: optionalNull(Schema.Number),
34
+ }), [Schema.Record(Schema.String, Schema.Unknown)]);
35
+ const Interaction = Schema.Struct({
36
+ id: Schema.String,
37
+ status: Schema.String,
38
+ model: optionalNull(Schema.String),
39
+ steps: optionalNull(Schema.Array(Schema.Struct({ type: Schema.String, content: optionalNull(Schema.Array(Content)) }))),
40
+ usage: optionalNull(Usage),
41
+ errors: optionalNull(Schema.Array(Schema.Struct({ code: optionalNull(Schema.String), message: optionalNull(Schema.String) }))),
42
+ });
43
+ // `incomplete` is terminal ("completed, but contains incomplete results"); the result read decides whether a video
44
+ // came back. `requires_action` and `requires_continuation` are not documented for video and stay running.
45
+ const STATUS = {
46
+ in_progress: "running",
47
+ completed: "completed",
48
+ incomplete: "completed",
49
+ failed: "failed",
50
+ cancelled: "cancelled",
51
+ };
52
+ // ---------------------------------------------------------------------------
53
+ // 3. Failures
54
+ // ---------------------------------------------------------------------------
55
+ // Interaction error codes are documented only as "a URI that identifies the error type"; the last segment carries the
56
+ // canonical Google status name.
57
+ const FAILURE = {
58
+ INVALID_ARGUMENT: "InvalidRequest",
59
+ FAILED_PRECONDITION: "InvalidRequest",
60
+ OUT_OF_RANGE: "InvalidRequest",
61
+ PERMISSION_DENIED: "Authentication",
62
+ UNAUTHENTICATED: "Authentication",
63
+ RESOURCE_EXHAUSTED: "RateLimit",
64
+ };
65
+ const errorCode = (code) => code?.split("/").at(-1)?.trim().toUpperCase().replaceAll("-", "_") || undefined;
66
+ // ---------------------------------------------------------------------------
67
+ // 5. Request body construction
68
+ // ---------------------------------------------------------------------------
69
+ // Omni has no role field for media: it reads one image as the start frame and two as start and end. The task hint
70
+ // pins that reading when only frames, or only references, are sent; with both, the prompt decides.
71
+ const task = (request) => {
72
+ const frames = request.start !== undefined || request.end !== undefined;
73
+ const references = (request.references ?? []).length > 0;
74
+ if (frames && !references)
75
+ return "image_to_video";
76
+ if (references && !frames)
77
+ return "reference_to_video";
78
+ return undefined;
79
+ };
80
+ const fromRequest = Effect.fn("GoogleInteractionsVideo.fromRequest")(function* (request) {
81
+ if (request.end !== undefined && request.start === undefined)
82
+ return yield* route.unsupported("video.end", `${route.name} reads a lone image as the start frame; send start too`);
83
+ if (request.sound === false)
84
+ return yield* route.unsupported("video.sound", `${route.name} always generates audio and has no option to turn it off`);
85
+ const media = yield* Effect.forEach([request.start, request.end, ...(request.references ?? [])].filter((asset) => asset !== undefined), GoogleInteractions.mediaContent);
86
+ const responseFormat = {
87
+ // `auto` follows the input image, which Omni expresses by leaving the ratio out.
88
+ aspect_ratio: request.aspect === "auto" ? undefined : request.aspect,
89
+ resolution: request.resolution?.toLowerCase(),
90
+ duration: request.duration === undefined ? undefined : `${seconds(request.duration)}s`,
91
+ };
92
+ const videoTask = task(request);
93
+ return MediaProtocol.json(mergeJsonRecords({
94
+ model: request.model.id,
95
+ input: [...media, { type: "text", text: request.prompt }],
96
+ background: true,
97
+ response_format: Object.values(responseFormat).some((value) => value !== undefined)
98
+ ? { type: "video", ...responseFormat }
99
+ : undefined,
100
+ generation_config: videoTask === undefined ? undefined : { video_config: { task: videoTask } },
101
+ }, request.providerOptions, request.http?.body) ?? {});
102
+ });
103
+ // ---------------------------------------------------------------------------
104
+ // 6. Response decoding
105
+ // ---------------------------------------------------------------------------
106
+ const decodeStart = route.decodeStarted(Interaction, (value) => ({
107
+ token: { interactionID: value.id },
108
+ snapshot: { id: value.id, status: MediaProtocol.status(STATUS, value.status) },
109
+ }));
110
+ const decodeInteraction = route.decodeJson(Interaction);
111
+ const decodeStatus = Effect.fn("GoogleInteractionsVideo.decodeStatus")(function* (response, context) {
112
+ const output = yield* decodeInteraction(response);
113
+ return { id: context.token.interactionID, status: MediaProtocol.status(STATUS, output.value.status) };
114
+ });
115
+ const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function* (response, context) {
116
+ const output = yield* decodeInteraction(response);
117
+ const decoded = output.value;
118
+ const status = MediaProtocol.status(STATUS, decoded.status);
119
+ if (status === "running")
120
+ return yield* output.pending(context.token.interactionID);
121
+ const errors = decoded.errors ?? [];
122
+ const codes = errors.flatMap((error) => {
123
+ const code = errorCode(error.code);
124
+ return code === undefined ? [] : [code];
125
+ });
126
+ const messages = errors.flatMap((error) => (error.message?.trim() ? [error.message.trim()] : []));
127
+ if (status === "cancelled")
128
+ return yield* output.ended("cancelled", `${route.name} interaction ${context.token.interactionID} was cancelled`);
129
+ if (status === "failed") {
130
+ const message = `${route.name} generation failed${codes.length === 0 ? "" : ` (${codes.join(", ")})`}${messages.length === 0 ? "" : `: ${messages.join("\n")}`}`;
131
+ if (codes.some((code) => code === "CONTENT_BLOCKED" || GeminiGenerateContent.contentFiltered(code)))
132
+ return yield* output.contentPolicy(message);
133
+ return yield* output.ended("failed", message, MediaProtocol.failure(FAILURE, codes[0]));
134
+ }
135
+ const contents = (decoded.steps ?? []).flatMap((step) => (step.type === "model_output" ? (step.content ?? []) : []));
136
+ const videos = yield* Effect.forEach(contents.filter((content) => content.type === "video"), (content, index) => {
137
+ const mediaType = content.mime_type ?? undefined;
138
+ if (content.data)
139
+ return MediaInput.decodedAsset(output.invalid, `${route.name} video ${index}`, content.data, mediaType);
140
+ // `GET /interactions/{id}` documents inline data even for `delivery: "uri"`; a Files API URI needs the API key
141
+ // to download, so it stays a Google reference that can be passed back as input.
142
+ if (content.uri)
143
+ return Effect.succeed(Media.ref(route.provider, content.uri, mediaType));
144
+ return Effect.fail(output.invalid(`${route.name} returned a video without data or a URI`));
145
+ });
146
+ if (videos.length === 0) {
147
+ if (codes.some((code) => code === "CONTENT_BLOCKED" || GeminiGenerateContent.contentFiltered(code)))
148
+ return yield* output.contentPolicy(`${route.name} withheld the video${messages.length === 0 ? "" : `: ${messages.join("\n")}`}`);
149
+ return yield* output.invalid(`${route.name} ${decoded.status} without a video`);
150
+ }
151
+ const usage = decoded.usage ?? undefined;
152
+ return new VideoResponse({
153
+ videos,
154
+ usage: usage === undefined
155
+ ? undefined
156
+ : tokenUsage({
157
+ input: usage.total_input_tokens ?? undefined,
158
+ output: usage.total_output_tokens ?? undefined,
159
+ total: usage.total_tokens ?? undefined,
160
+ details: { reasoningTokens: usage.total_thought_tokens ?? undefined, google: usage },
161
+ }),
162
+ providerMetadata: {
163
+ google: {
164
+ interactionId: decoded.id,
165
+ model: decoded.model ?? undefined,
166
+ status: decoded.status,
167
+ },
168
+ },
169
+ });
170
+ });
171
+ // ---------------------------------------------------------------------------
172
+ // 7. Protocol and route
173
+ // ---------------------------------------------------------------------------
174
+ const interactionPath = (token) => `${PATH}/${token.interactionID}`;
175
+ export const protocol = MediaProtocol.queued(route, {
176
+ token: Token,
177
+ start: { body: { from: fromRequest }, decode: decodeStart },
178
+ status: { path: interactionPath, decode: decodeStatus },
179
+ result: { path: interactionPath, decode: decodeResult },
180
+ cancel: { method: "POST", path: (token) => `${interactionPath(token)}/cancel` },
181
+ });
182
+ export const model = (input) => VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input);
183
+ export const GoogleInteractionsVideo = {
184
+ protocol,
185
+ model,
186
+ };
@@ -1,6 +1,8 @@
1
- import { Schema } from "effect";
1
+ import { Effect, Schema } from "effect";
2
2
  import { Route } from "../route/client.js";
3
3
  import { Protocol } from "../route/protocol.js";
4
+ import { AIError } from "../schema/index.js";
5
+ import { Media } from "../media.js";
4
6
  import { Lifecycle } from "./utils/lifecycle.js";
5
7
  import { ToolStream } from "./utils/tool-stream.js";
6
8
  export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
@@ -36,6 +38,17 @@ interface ParserState {
36
38
  readonly steps: Partial<Record<number, OutputStep>>;
37
39
  readonly tools: ToolStream.State<number>;
38
40
  }
41
+ export declare const mediaContent: (asset: Media.Asset) => Effect.Effect<{
42
+ type: "audio" | "document" | "image" | "video";
43
+ uri: string;
44
+ mime_type: string;
45
+ data?: undefined;
46
+ } | {
47
+ uri?: undefined;
48
+ type: "audio" | "document" | "image" | "video";
49
+ data: string;
50
+ mime_type: string;
51
+ }, AIError, never>;
39
52
  export declare const protocol: Protocol<{
40
53
  readonly model: string;
41
54
  readonly input: readonly ({
@@ -172,7 +172,7 @@ const Event = Schema.Union([
172
172
  // =============================================================================
173
173
  // Request Body Construction
174
174
  // =============================================================================
175
- const mediaContent = Effect.fnUntraced(function* (asset) {
175
+ export const mediaContent = Effect.fnUntraced(function* (asset) {
176
176
  if (asset.kind !== "image" &&
177
177
  asset.kind !== "audio" &&
178
178
  asset.kind !== "video" &&
@@ -0,0 +1,18 @@
1
+ import { EmbeddingRoute } from "../route/embedding.js";
2
+ import type { TaskType } from "./google-embed-content.js";
3
+ /** `text-embedding-005` and `text-multilingual-embedding-002` take up to 250 instances per request. */
4
+ export declare const MAX_INSTANCES = 250;
5
+ /**
6
+ * The same option names as `embedContent`, so a model can move between the two APIs: `taskType` and `title` go on
7
+ * each instance (`task_type`, `title`), and `autoTruncate` and anything else go under `parameters`.
8
+ */
9
+ export interface OptionsInput {
10
+ readonly [key: string]: unknown;
11
+ readonly taskType?: TaskType;
12
+ readonly title?: string;
13
+ readonly autoTruncate?: boolean;
14
+ }
15
+ export declare const protocol: EmbeddingRoute.Protocol;
16
+ export declare const GoogleVertexPredictEmbeddings: {
17
+ readonly protocol: EmbeddingRoute.Protocol;
18
+ };
@@ -0,0 +1,74 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { EmbeddingResponse, EmbeddingUsage } from "../embedding.js";
3
+ import { EmbeddingRoute } from "../route/embedding.js";
4
+ import { MediaProtocol } from "../route/media-protocol.js";
5
+ import { AIError, UnsupportedOperationError, mergeJsonRecords } from "../schema/index.js";
6
+ const ID = "google-vertex-predict-embeddings";
7
+ const NAME = "Google Vertex text embeddings";
8
+ /** `text-embedding-005` and `text-multilingual-embedding-002` take up to 250 instances per request. */
9
+ export const MAX_INSTANCES = 250;
10
+ const Statistics = Schema.StructWithRest(Schema.Struct({ token_count: Schema.optional(Schema.Number), truncated: Schema.optional(Schema.Boolean) }), [Schema.Record(Schema.String, Schema.Unknown)]);
11
+ const Response = Schema.Struct({
12
+ predictions: Schema.Array(Schema.Struct({
13
+ embeddings: Schema.Struct({ values: Schema.Array(Schema.Number), statistics: Schema.optional(Statistics) }),
14
+ })),
15
+ metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
16
+ });
17
+ const TASK_TYPES = { query: "RETRIEVAL_QUERY", document: "RETRIEVAL_DOCUMENT" };
18
+ const fromRequest = Effect.fn("GoogleVertexPredictEmbeddings.fromRequest")(function* (request) {
19
+ const contents = request.values.filter((value) => typeof value === "string");
20
+ if (contents.length !== request.values.length)
21
+ return yield* new AIError({
22
+ reason: new UnsupportedOperationError({
23
+ operation: "embedding.media",
24
+ provider: request.model.provider,
25
+ route: request.model.route.id,
26
+ message: `${request.model.id} on Vertex :predict embeds text only; use gemini-embedding-2 for media values`,
27
+ }),
28
+ });
29
+ const { taskType, title, ...parameters } = request.providerOptions ?? {};
30
+ const instance = {
31
+ ...(taskType === undefined
32
+ ? request.inputType === undefined
33
+ ? {}
34
+ : { task_type: TASK_TYPES[request.inputType] }
35
+ : { task_type: taskType }),
36
+ ...(title === undefined ? {} : { title }),
37
+ };
38
+ const merged = {
39
+ ...(request.dimensions === undefined ? {} : { outputDimensionality: request.dimensions }),
40
+ ...parameters,
41
+ };
42
+ return (mergeJsonRecords({
43
+ instances: contents.map((content) => ({ content, ...instance })),
44
+ ...(Object.keys(merged).length === 0 ? {} : { parameters: merged }),
45
+ }, request.http?.body) ?? {});
46
+ });
47
+ const decodeDocument = MediaProtocol.identity({ id: ID, name: NAME, provider: "google-vertex" }).decodeJson(Response);
48
+ export const protocol = EmbeddingRoute.protocol({
49
+ id: ID,
50
+ name: NAME,
51
+ body: { from: fromRequest },
52
+ response: {
53
+ decode: Effect.fn("GoogleVertexPredictEmbeddings.decodeResponse")(function* (response, context) {
54
+ const output = yield* decodeDocument(response);
55
+ const statistics = output.value.predictions.map((prediction) => prediction.embeddings.statistics ?? {});
56
+ const tokens = statistics.map((item) => item.token_count);
57
+ return new EmbeddingResponse({
58
+ embeddings: output.value.predictions.map((prediction) => prediction.embeddings.values),
59
+ usage: tokens.every((count) => count !== undefined)
60
+ ? new EmbeddingUsage({ inputTokens: tokens.reduce((sum, count) => sum + count, 0) })
61
+ : undefined,
62
+ providerMetadata: {
63
+ [context.providerMetadataKey]: {
64
+ statistics,
65
+ ...(output.value.metadata === undefined ? {} : { metadata: output.value.metadata }),
66
+ },
67
+ },
68
+ });
69
+ }),
70
+ },
71
+ });
72
+ export const GoogleVertexPredictEmbeddings = {
73
+ protocol,
74
+ };
@@ -3,10 +3,14 @@ export * as BedrockConverse from "./bedrock-converse.js";
3
3
  export * as CloudflareRunDecisions from "./cloudflare-run-decisions.js";
4
4
  export * as CohereChat from "./cohere-chat.js";
5
5
  export * as Gemini from "./gemini.js";
6
+ export * as GoogleDecisions from "./google-decisions.js";
7
+ export * as GoogleEmbedContent from "./google-embed-content.js";
6
8
  export * as GoogleInteractions from "./google-interactions.js";
9
+ export * as GoogleVertexPredictEmbeddings from "./google-vertex-predict-embeddings.js";
7
10
  export * as MistralChat from "./mistral-chat.js";
8
11
  export * as OpenAIChat from "./openai-chat.js";
9
12
  export * as OpenAIDecisions from "./openai-decisions.js";
13
+ export * as OpenAIEmbeddings from "./openai-embeddings.js";
10
14
  export * as OpenAIImages from "./openai-images.js";
11
15
  export * as OpenAICompatibleChat from "./openai-compatible-chat.js";
12
16
  export * as OpenAICompatibleResponses from "./openai-compatible-responses.js";