@opencode/ai 2.2.4 → 2.2.6
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.
- package/README.md +133 -69
- package/dist/cache-policy.d.ts +1 -1
- package/dist/cache-policy.js +16 -4
- package/dist/decision-client.d.ts +3 -3
- package/dist/decision.d.ts +20 -125
- package/dist/decision.js +25 -15
- package/dist/effect.d.ts +4 -15
- package/dist/effect.js +2 -6
- package/dist/effort-updates.d.ts +3 -3
- package/dist/effort-updates.js +2 -2
- package/dist/experimental/cloudflare-run-extraction.d.ts +7 -3
- package/dist/experimental/cloudflare-run-extraction.js +4 -1
- package/dist/experimental/extraction.d.ts +10 -40
- package/dist/experimental/extraction.js +14 -13
- package/dist/experimental.d.ts +8 -8
- package/dist/experimental.js +4 -4
- package/dist/generation.d.ts +0 -2
- package/dist/generation.js +2 -2
- package/dist/image-client.d.ts +13 -7
- package/dist/image-client.js +1 -1
- package/dist/image.d.ts +357 -464
- package/dist/image.js +17 -15
- package/dist/index.d.ts +28 -465
- package/dist/index.js +18 -17
- package/dist/llm.d.ts +65 -266
- package/dist/llm.js +101 -92
- package/dist/loop.d.ts +38 -0
- package/dist/loop.js +136 -0
- package/dist/media-model.d.ts +1 -1
- package/dist/media-model.js +8 -6
- package/dist/media.d.ts +9 -0
- package/dist/media.js +37 -2
- package/dist/protocols/alibaba-chat.d.ts +5 -1
- package/dist/protocols/alibaba-chat.js +3 -3
- package/dist/protocols/alibaba-images.d.ts +2 -2
- package/dist/protocols/alibaba-messages.js +3 -3
- package/dist/protocols/alibaba-responses.js +8 -20
- package/dist/protocols/anthropic-messages.d.ts +1 -1
- package/dist/protocols/anthropic-messages.js +57 -185
- package/dist/protocols/assemblyai-transcription.d.ts +2 -2
- package/dist/protocols/bedrock-converse.js +11 -22
- package/dist/protocols/cartesia-speech.d.ts +2 -2
- package/dist/protocols/cloudflare-workers-ai-images.d.ts +2 -2
- package/dist/protocols/cohere-chat.js +9 -12
- package/dist/protocols/deepgram-speech.d.ts +2 -2
- package/dist/protocols/deepgram-transcription.d.ts +2 -2
- package/dist/protocols/elevenlabs-speech.d.ts +2 -2
- package/dist/protocols/elevenlabs-transcription.d.ts +2 -2
- package/dist/protocols/gemini.d.ts +3 -0
- package/dist/protocols/gemini.js +56 -89
- package/dist/protocols/google-images.d.ts +2 -2
- package/dist/protocols/google-interactions.d.ts +3 -4
- package/dist/protocols/google-interactions.js +54 -32
- package/dist/protocols/google-speech.d.ts +2 -2
- package/dist/protocols/google-transcription.d.ts +2 -2
- package/dist/protocols/google-video.d.ts +2 -2
- package/dist/protocols/meta-images.d.ts +2 -2
- package/dist/protocols/meta-responses.js +26 -23
- package/dist/protocols/minimax-images.d.ts +2 -2
- package/dist/protocols/mistral-chat.js +14 -20
- package/dist/protocols/open-responses-channel.js +6 -19
- package/dist/protocols/open-responses-continuation.d.ts +1 -5
- package/dist/protocols/open-responses-continuation.js +1 -3
- package/dist/protocols/open-responses.d.ts +1 -21
- package/dist/protocols/open-responses.js +10 -15
- package/dist/protocols/openai-chat.d.ts +3 -23
- package/dist/protocols/openai-chat.js +26 -47
- package/dist/protocols/openai-compatible-chat.d.ts +1 -1
- package/dist/protocols/openai-compatible-responses.d.ts +2 -2
- package/dist/protocols/openai-compatible-responses.js +1 -1
- package/dist/protocols/openai-decisions.js +1 -1
- package/dist/protocols/openai-images.d.ts +2 -2
- package/dist/protocols/openai-responses.js +10 -29
- package/dist/protocols/openai-speech.d.ts +2 -2
- package/dist/protocols/openai-transcription.d.ts +2 -2
- package/dist/protocols/runway-video.d.ts +2 -2
- package/dist/protocols/shared.d.ts +1 -4
- package/dist/protocols/shared.js +13 -11
- package/dist/protocols/system-one.d.ts +4 -4
- package/dist/protocols/utils/bedrock-cache.js +2 -5
- package/dist/protocols/utils/bedrock-media.d.ts +0 -3
- package/dist/protocols/utils/cache.d.ts +3 -0
- package/dist/protocols/utils/cache.js +15 -2
- package/dist/protocols/utils/image-sizing.d.ts +1 -1
- package/dist/protocols/utils/responses-checkpoint.js +1 -1
- package/dist/protocols/utils/responses-compaction.d.ts +1 -1
- package/dist/protocols/utils/responses-compaction.js +6 -5
- package/dist/protocols/utils/responses-hosted-tools.d.ts +97 -1
- package/dist/protocols/utils/responses-hosted-tools.js +31 -0
- package/dist/protocols/utils/tool-stream.d.ts +5 -271
- package/dist/protocols/utils/tool-stream.js +3 -13
- package/dist/protocols/venice-chat.d.ts +3 -1
- package/dist/protocols/venice-chat.js +4 -4
- package/dist/protocols/xai-images.d.ts +2 -2
- package/dist/protocols/xai-responses.js +5 -25
- package/dist/protocols/xai-video.d.ts +2 -2
- package/dist/protocols/zai-chat.d.ts +5 -1
- package/dist/protocols/zai-chat.js +1 -1
- package/dist/protocols/zai-images.d.ts +2 -2
- package/dist/protocols/zai-messages.js +3 -3
- package/dist/provider-error.d.ts +0 -1
- package/dist/provider-error.js +9 -80
- package/dist/providers/alibaba.d.ts +67 -4
- package/dist/providers/alibaba.js +6 -1
- package/dist/providers/amazon-bedrock-mantle.d.ts +6 -3
- package/dist/providers/amazon-bedrock-mantle.js +6 -3
- package/dist/providers/amazon-bedrock.d.ts +6 -7
- package/dist/providers/amazon-bedrock.js +1 -1
- package/dist/providers/anthropic-compatible.d.ts +7 -8
- package/dist/providers/anthropic-compatible.js +2 -5
- package/dist/providers/anthropic.d.ts +8 -9
- package/dist/providers/anthropic.js +2 -7
- package/dist/providers/assemblyai.d.ts +2 -2
- package/dist/providers/assemblyai.js +2 -7
- package/dist/providers/azure/messages.d.ts +2 -0
- package/dist/providers/azure/messages.js +1 -0
- package/dist/providers/azure.d.ts +322 -7
- package/dist/providers/azure.js +25 -9
- package/dist/providers/baseten.d.ts +5 -5
- package/dist/providers/baseten.js +7 -21
- package/dist/providers/cartesia.d.ts +1 -1
- package/dist/providers/cerebras.d.ts +5 -5
- package/dist/providers/cerebras.js +4 -15
- package/dist/providers/cloudflare-ai-gateway.d.ts +21 -13
- package/dist/providers/cloudflare-ai-gateway.js +28 -40
- package/dist/providers/cloudflare-shared.d.ts +9 -0
- package/dist/providers/cloudflare-shared.js +25 -0
- package/dist/providers/cloudflare-workers-ai.d.ts +4 -4
- package/dist/providers/cloudflare-workers-ai.js +4 -20
- package/dist/providers/cohere/chat.js +2 -7
- package/dist/providers/cohere.d.ts +6 -5
- package/dist/providers/cohere.js +7 -13
- package/dist/providers/deepgram.d.ts +2 -2
- package/dist/providers/deepgram.js +2 -7
- package/dist/providers/deepinfra.d.ts +5 -5
- package/dist/providers/deepinfra.js +5 -13
- package/dist/providers/deepseek.d.ts +5 -5
- package/dist/providers/deepseek.js +3 -14
- package/dist/providers/digitalocean.d.ts +8 -5
- package/dist/providers/digitalocean.js +13 -14
- package/dist/providers/elevenlabs.d.ts +2 -2
- package/dist/providers/elevenlabs.js +2 -7
- package/dist/providers/fireworks.d.ts +5 -5
- package/dist/providers/fireworks.js +4 -15
- package/dist/providers/google/interactions.d.ts +1 -1
- package/dist/providers/google/interactions.js +2 -7
- package/dist/providers/google-vertex-chat.d.ts +3 -3
- package/dist/providers/google-vertex-chat.js +3 -29
- package/dist/providers/google-vertex-interactions.d.ts +3 -3
- package/dist/providers/google-vertex-messages.d.ts +3 -3
- package/dist/providers/google-vertex-messages.js +3 -29
- package/dist/providers/google-vertex-mistral.d.ts +3 -3
- package/dist/providers/google-vertex-mistral.js +3 -29
- package/dist/providers/google-vertex-responses.d.ts +3 -3
- package/dist/providers/google-vertex-responses.js +4 -30
- package/dist/providers/google-vertex-shared.d.ts +31 -0
- package/dist/providers/google-vertex-shared.js +25 -0
- package/dist/providers/google-vertex.d.ts +3 -3
- package/dist/providers/google.d.ts +15 -13
- package/dist/providers/google.js +9 -19
- package/dist/providers/groq.d.ts +5 -5
- package/dist/providers/groq.js +4 -15
- package/dist/providers/meta.d.ts +5 -5
- package/dist/providers/meta.js +10 -24
- package/dist/providers/minimax/chat.js +2 -7
- package/dist/providers/minimax/responses.js +2 -7
- package/dist/providers/minimax.d.ts +5 -5
- package/dist/providers/minimax.js +11 -23
- package/dist/providers/mistral.d.ts +10 -11
- package/dist/providers/mistral.js +3 -14
- package/dist/providers/moonshot/messages.js +2 -7
- package/dist/providers/moonshot/responses.js +2 -7
- package/dist/providers/moonshot.d.ts +5 -5
- package/dist/providers/moonshot.js +4 -16
- package/dist/providers/openai-compatible-responses.d.ts +6 -7
- package/dist/providers/openai-compatible-responses.js +2 -8
- package/dist/providers/openai-compatible.d.ts +6 -7
- package/dist/providers/openai-compatible.js +4 -10
- package/dist/providers/openai.d.ts +4 -4
- package/dist/providers/openai.js +3 -3
- package/dist/providers/opencode.d.ts +4 -4
- package/dist/providers/opencode.js +6 -2
- package/dist/providers/openrouter.d.ts +8 -5
- package/dist/providers/openrouter.js +16 -24
- package/dist/providers/runway.d.ts +1 -1
- package/dist/providers/settings.d.ts +40 -0
- package/dist/providers/settings.js +19 -0
- package/dist/providers/togetherai.d.ts +5 -5
- package/dist/providers/togetherai.js +5 -15
- package/dist/providers/typesafe-ai.d.ts +4 -4
- package/dist/providers/typesafe-ai.js +6 -2
- package/dist/providers/venice.d.ts +4 -4
- package/dist/providers/venice.js +6 -2
- package/dist/providers/vercel-ai-gateway.d.ts +5 -5
- package/dist/providers/vercel-ai-gateway.js +15 -28
- package/dist/providers/xai.d.ts +4 -4
- package/dist/providers/xai.js +4 -12
- package/dist/providers/zai-coding-plan/messages.js +2 -7
- package/dist/providers/zai-coding-plan/responses.js +2 -7
- package/dist/providers/zai-coding-plan.d.ts +5 -5
- package/dist/providers/zai-coding-plan.js +8 -15
- package/dist/providers/zai.d.ts +5 -5
- package/dist/providers/zai.js +10 -22
- package/dist/public.d.ts +12 -0
- package/dist/public.js +5 -0
- package/dist/route/auth-options.d.ts +9 -5
- package/dist/route/auth-options.js +10 -7
- package/dist/route/client.d.ts +50 -37
- package/dist/route/client.js +42 -53
- package/dist/route/decision.d.ts +8 -8
- package/dist/route/decision.js +3 -3
- package/dist/route/executor.d.ts +5 -0
- package/dist/route/executor.js +10 -0
- package/dist/route/index.d.ts +5 -7
- package/dist/route/index.js +1 -1
- package/dist/route/media.d.ts +7 -11
- package/dist/route/media.js +22 -26
- package/dist/route/transport/http.js +6 -5
- package/dist/route/transport/websocket.js +7 -1
- package/dist/schema/errors.d.ts +16 -17
- package/dist/schema/errors.js +63 -12
- package/dist/schema/events.d.ts +2563 -2954
- package/dist/schema/events.js +54 -109
- package/dist/schema/messages.d.ts +194 -137
- package/dist/schema/messages.js +66 -83
- package/dist/schema/options.d.ts +112 -65
- package/dist/schema/options.js +52 -101
- package/dist/speech-client.d.ts +7 -7
- package/dist/speech.d.ts +306 -316
- package/dist/speech.js +16 -14
- package/dist/testing.d.ts +31 -175
- package/dist/testing.js +60 -5
- package/dist/tool-history.d.ts +1 -1
- package/dist/tool-history.js +3 -10
- package/dist/tool-runtime.d.ts +9 -2
- package/dist/tool-runtime.js +17 -31
- package/dist/tool.d.ts +39 -43
- package/dist/tool.js +16 -26
- package/dist/transcription-client.d.ts +7 -7
- package/dist/transcription.d.ts +314 -265
- package/dist/transcription.js +16 -14
- package/dist/utils/provider-codes.d.ts +3 -0
- package/dist/utils/provider-codes.js +41 -0
- package/dist/video-client.d.ts +7 -7
- package/dist/video-client.js +1 -1
- package/dist/video.d.ts +269 -287
- package/dist/video.js +16 -14
- package/package.json +9 -9
- package/dist/experimental/testing.d.ts +0 -3
- package/dist/experimental/testing.js +0 -3
- package/dist/testing/decision.d.ts +0 -16
- package/dist/testing/decision.js +0 -20
- package/dist/testing/image.d.ts +0 -14
- package/dist/testing/image.js +0 -12
- package/dist/testing/media.d.ts +0 -18
- package/dist/testing/media.js +0 -36
- package/dist/testing/script.d.ts +0 -28
- package/dist/testing/script.js +0 -60
- package/dist/testing/speech.d.ts +0 -14
- package/dist/testing/speech.js +0 -12
- package/dist/testing/transcription.d.ts +0 -14
- package/dist/testing/transcription.js +0 -12
- package/dist/testing/video.d.ts +0 -14
- package/dist/testing/video.js +0 -12
package/dist/protocols/gemini.js
CHANGED
|
@@ -13,23 +13,11 @@ import { GeminiGenerateContent } from "./utils/gemini-generate-content.js";
|
|
|
13
13
|
import { Lifecycle } from "./utils/lifecycle.js";
|
|
14
14
|
const ADAPTER = "gemini";
|
|
15
15
|
const CONTINUATION = "CONTINUATION";
|
|
16
|
-
// Google documents this sentinel for replaying
|
|
16
|
+
// Google documents this sentinel for replaying function calls after their original signature was lost.
|
|
17
17
|
const SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator";
|
|
18
18
|
// Gemini 2.5 rejects a budget under the model's minimum: 512 on Flash-Lite, the highest, and 128 on Pro.
|
|
19
19
|
const MIN_THINKING_BUDGET = 512;
|
|
20
20
|
export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
|
|
21
|
-
// Gemini 3 rejects replayed function calls without a thought signature. Google's SDKs avoid that in normal chats by
|
|
22
|
-
// retaining complete model responses, but OpenCode reconstructs durable history and may encounter an unsigned call
|
|
23
|
-
// from an older or external session. Model IDs are open-ended, so unknown Gemini aliases inherit current behavior.
|
|
24
|
-
const requiresThoughtSignatureFallback = (modelID) => {
|
|
25
|
-
if (!/(^|\/)gemini-/i.test(modelID))
|
|
26
|
-
return false;
|
|
27
|
-
if (/(^|\/)gemini-(?:1|2)(?:[.-]|$)/i.test(modelID))
|
|
28
|
-
return false;
|
|
29
|
-
if (/(^|\/)gemini-pro(?:-vision)?$/i.test(modelID))
|
|
30
|
-
return false;
|
|
31
|
-
return !/(^|\/)gemini-robotics-er-1\.5(?:[.-]|$)/i.test(modelID);
|
|
32
|
-
};
|
|
33
21
|
// Gemini 3 accepts media nested inside function responses; matched Gemini 2.5 variants reject it,
|
|
34
22
|
// so their tool-result attachments lower as a separate user turn instead.
|
|
35
23
|
const routesLegacyToolMedia = (modelID) => /gemini-2[.-]5(?:[.-]|$)/i.test(modelID);
|
|
@@ -169,6 +157,7 @@ const GeminiUsage = Schema.Struct({
|
|
|
169
157
|
cachedContentTokenCount: optionalNull(Schema.Number),
|
|
170
158
|
thoughtsTokenCount: optionalNull(Schema.Number),
|
|
171
159
|
promptTokenCount: optionalNull(Schema.Number),
|
|
160
|
+
toolUsePromptTokenCount: optionalNull(Schema.Number),
|
|
172
161
|
candidatesTokenCount: optionalNull(Schema.Number),
|
|
173
162
|
totalTokenCount: optionalNull(Schema.Number),
|
|
174
163
|
...ProviderShared.ReportedBilling.fields,
|
|
@@ -214,6 +203,7 @@ const lowerContentPart = Effect.fnUntraced(function* (part) {
|
|
|
214
203
|
return yield* GeminiGenerateContent.mediaPart("Gemini", part.media);
|
|
215
204
|
});
|
|
216
205
|
const providerMetadata = (key, metadata) => ({ [key]: metadata });
|
|
206
|
+
const signatureMetadata = (key, signature) => signature ? providerMetadata(key, { thoughtSignature: signature }) : undefined;
|
|
217
207
|
const thoughtSignature = (metadata, key) => {
|
|
218
208
|
const value = metadata?.[key];
|
|
219
209
|
return typeof value?.thoughtSignature === "string" ? value.thoughtSignature : undefined;
|
|
@@ -251,8 +241,6 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
|
|
|
251
241
|
if (message.role === "user") {
|
|
252
242
|
const parts = [];
|
|
253
243
|
for (const part of message.content) {
|
|
254
|
-
if (!ProviderShared.supportsContent(part, ["text", "media"]))
|
|
255
|
-
return yield* ProviderShared.unsupportedContent("Gemini", "user", ["text", "media"]);
|
|
256
244
|
parts.push(yield* lowerContentPart(part));
|
|
257
245
|
}
|
|
258
246
|
contents.push({ role: "user", parts });
|
|
@@ -293,10 +281,7 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
|
|
|
293
281
|
const signature = lowered.thoughtSignature;
|
|
294
282
|
parts.push({
|
|
295
283
|
...lowered,
|
|
296
|
-
thoughtSignature: signature ??
|
|
297
|
-
(requiresThoughtSignatureFallback(request.model.id) && !hasSignedToolCall
|
|
298
|
-
? SKIP_THOUGHT_SIGNATURE_VALIDATOR
|
|
299
|
-
: undefined),
|
|
284
|
+
thoughtSignature: signature ?? (!hasSignedToolCall ? SKIP_THOUGHT_SIGNATURE_VALIDATOR : undefined),
|
|
300
285
|
});
|
|
301
286
|
if (signature !== undefined)
|
|
302
287
|
hasSignedToolCall = true;
|
|
@@ -308,8 +293,6 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
|
|
|
308
293
|
}
|
|
309
294
|
const parts = [];
|
|
310
295
|
for (const part of message.content) {
|
|
311
|
-
if (!ProviderShared.supportsContent(part, ["tool-result"]))
|
|
312
|
-
return yield* ProviderShared.unsupportedContent("Gemini", "tool", ["tool-result"]);
|
|
313
296
|
if (part.result.type !== "content") {
|
|
314
297
|
parts.push({
|
|
315
298
|
functionResponse: {
|
|
@@ -362,17 +345,16 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
|
|
|
362
345
|
const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request) {
|
|
363
346
|
const flattened = ProviderShared.flattenToolRequest(request);
|
|
364
347
|
const hasTools = flattened.tools.length > 0;
|
|
365
|
-
const generation = request.generation;
|
|
366
348
|
const options = yield* decodeOptions(request.providerOptions ?? {});
|
|
367
349
|
const generationConfig = {
|
|
368
|
-
maxOutputTokens:
|
|
369
|
-
temperature:
|
|
370
|
-
topP:
|
|
371
|
-
topK:
|
|
372
|
-
frequencyPenalty:
|
|
373
|
-
presencePenalty:
|
|
374
|
-
seed:
|
|
375
|
-
stopSequences:
|
|
350
|
+
maxOutputTokens: request.maxTokens,
|
|
351
|
+
temperature: request.temperature,
|
|
352
|
+
topP: request.topP,
|
|
353
|
+
topK: request.topK,
|
|
354
|
+
frequencyPenalty: request.frequencyPenalty,
|
|
355
|
+
presencePenalty: request.presencePenalty,
|
|
356
|
+
seed: request.seed,
|
|
357
|
+
stopSequences: request.stop,
|
|
376
358
|
// Gemini accepts a budget above `maxOutputTokens`, but thinking then leaves the answer empty.
|
|
377
359
|
thinkingConfig: options.thinkingConfig === undefined
|
|
378
360
|
? undefined
|
|
@@ -381,7 +363,7 @@ const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request) {
|
|
|
381
363
|
includeThoughts: options.thinkingConfig.includeThoughts ?? true,
|
|
382
364
|
thinkingBudget: options.thinkingConfig.thinkingBudget === undefined
|
|
383
365
|
? undefined
|
|
384
|
-
: ProviderShared.fitThinkingBudget(options.thinkingConfig.thinkingBudget,
|
|
366
|
+
: ProviderShared.fitThinkingBudget(options.thinkingConfig.thinkingBudget, request.maxTokens, MIN_THINKING_BUDGET),
|
|
385
367
|
},
|
|
386
368
|
};
|
|
387
369
|
return {
|
|
@@ -406,8 +388,8 @@ const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request) {
|
|
|
406
388
|
// =============================================================================
|
|
407
389
|
// Stream Parsing
|
|
408
390
|
// =============================================================================
|
|
409
|
-
// Gemini reports `promptTokenCount`
|
|
410
|
-
// `
|
|
391
|
+
// Gemini reports `promptTokenCount` with a `cachedContentTokenCount` subset;
|
|
392
|
+
// `toolUsePromptTokenCount` is additional billed input. `candidatesTokenCount` is *exclusive*
|
|
411
393
|
// of `thoughtsTokenCount` — visible-only, not a total — so we sum the two
|
|
412
394
|
// to produce the inclusive `outputTokens` the rest of the contract expects.
|
|
413
395
|
const mapUsage = (usage, metadataKey, metadata = usage ?? {}) => {
|
|
@@ -415,7 +397,7 @@ const mapUsage = (usage, metadataKey, metadata = usage ?? {}) => {
|
|
|
415
397
|
return undefined;
|
|
416
398
|
// Explicit provider nulls decode as `null`; normalize to `undefined` so the
|
|
417
399
|
// token arithmetic below treats them like absent counts.
|
|
418
|
-
const promptTokens = usage.promptTokenCount ?? undefined;
|
|
400
|
+
const promptTokens = ProviderShared.sumTokens(usage.promptTokenCount ?? undefined, usage.toolUsePromptTokenCount ?? undefined);
|
|
419
401
|
const cached = usage.cachedContentTokenCount ?? undefined;
|
|
420
402
|
const thoughts = usage.thoughtsTokenCount ?? undefined;
|
|
421
403
|
const visible = usage.candidatesTokenCount ?? undefined;
|
|
@@ -436,13 +418,13 @@ const mapUsage = (usage, metadataKey, metadata = usage ?? {}) => {
|
|
|
436
418
|
providerMetadata: providerMetadata(metadataKey, metadata),
|
|
437
419
|
});
|
|
438
420
|
};
|
|
439
|
-
//
|
|
440
|
-
//
|
|
441
|
-
// remain in provider metadata.
|
|
421
|
+
// Continued requests retain the first request's input instead of summing re-billed prompts.
|
|
422
|
+
// Complete billed counts, including tool-use prompts from later requests, remain in provider metadata.
|
|
442
423
|
const mapContinuedUsage = (requests, metadataKey) => {
|
|
443
424
|
const sum = (field) => ProviderShared.sumTokens(...requests.map((usage) => usage[field] ?? undefined));
|
|
444
425
|
return mapUsage({
|
|
445
426
|
promptTokenCount: requests[0].promptTokenCount,
|
|
427
|
+
toolUsePromptTokenCount: requests[0].toolUsePromptTokenCount,
|
|
446
428
|
cachedContentTokenCount: requests[0].cachedContentTokenCount,
|
|
447
429
|
candidatesTokenCount: sum("candidatesTokenCount"),
|
|
448
430
|
thoughtsTokenCount: sum("thoughtsTokenCount"),
|
|
@@ -450,6 +432,7 @@ const mapContinuedUsage = (requests, metadataKey) => {
|
|
|
450
432
|
cost: sum("cost"),
|
|
451
433
|
}, metadataKey, {
|
|
452
434
|
promptTokenCount: sum("promptTokenCount"),
|
|
435
|
+
toolUsePromptTokenCount: sum("toolUsePromptTokenCount"),
|
|
453
436
|
cachedContentTokenCount: sum("cachedContentTokenCount"),
|
|
454
437
|
candidatesTokenCount: sum("candidatesTokenCount"),
|
|
455
438
|
thoughtsTokenCount: sum("thoughtsTokenCount"),
|
|
@@ -457,6 +440,8 @@ const mapContinuedUsage = (requests, metadataKey) => {
|
|
|
457
440
|
requests: requests.length,
|
|
458
441
|
});
|
|
459
442
|
};
|
|
443
|
+
const terminalFinishReason = (finishReason) => finishReason && finishReason !== "FINISH_REASON_UNSPECIFIED" ? finishReason : undefined;
|
|
444
|
+
const RECOVERABLE_FINISH_REASONS = new Set(["MALFORMED_RESPONSE", "MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL"]);
|
|
460
445
|
const mapFinishReason = (finishReason, hasToolCalls) => {
|
|
461
446
|
if (finishReason === undefined)
|
|
462
447
|
return hasToolCalls ? "tool-calls" : "unknown";
|
|
@@ -485,13 +470,9 @@ const finish = (state) => {
|
|
|
485
470
|
const events = [];
|
|
486
471
|
let lifecycle = state.lifecycle;
|
|
487
472
|
if (state.reasoningId !== undefined)
|
|
488
|
-
lifecycle = Lifecycle.reasoningEnd(lifecycle, events, state.reasoningId, state.reasoningSignature
|
|
489
|
-
? undefined
|
|
490
|
-
: providerMetadata(state.providerMetadataKey, { thoughtSignature: state.reasoningSignature }));
|
|
473
|
+
lifecycle = Lifecycle.reasoningEnd(lifecycle, events, state.reasoningId, signatureMetadata(state.providerMetadataKey, state.reasoningSignature));
|
|
491
474
|
if (state.textId !== undefined)
|
|
492
|
-
lifecycle = Lifecycle.textEnd(lifecycle, events, state.textId, state.textSignature
|
|
493
|
-
? undefined
|
|
494
|
-
: providerMetadata(state.providerMetadataKey, { thoughtSignature: state.textSignature }));
|
|
475
|
+
lifecycle = Lifecycle.textEnd(lifecycle, events, state.textId, signatureMetadata(state.providerMetadataKey, state.textSignature));
|
|
495
476
|
Lifecycle.finish(lifecycle, events, {
|
|
496
477
|
reason: {
|
|
497
478
|
normalized: promptBlockReason === undefined ? mapFinishReason(finishReason, state.hasToolCalls) : "content-filter",
|
|
@@ -530,24 +511,22 @@ const step = (state, event) => {
|
|
|
530
511
|
}));
|
|
531
512
|
}
|
|
532
513
|
const candidate = event.candidates?.[0];
|
|
514
|
+
const finishReason = terminalFinishReason(candidate?.finishReason);
|
|
533
515
|
const nextState = {
|
|
534
516
|
...state,
|
|
535
517
|
promptFeedback: event.promptFeedback ?? state.promptFeedback,
|
|
536
518
|
usage: event.usageMetadata ?? state.usage,
|
|
537
|
-
finishReason:
|
|
519
|
+
finishReason: finishReason ?? state.finishReason,
|
|
538
520
|
};
|
|
539
|
-
|
|
540
|
-
if (candidate?.finishReason === "MALFORMED_RESPONSE")
|
|
521
|
+
if (finishReason && mapFinishReason(finishReason, state.hasToolCalls) === "error")
|
|
541
522
|
return Effect.fail(new AIError({
|
|
542
523
|
reason: new InvalidProviderOutputError({
|
|
543
524
|
route: state.route,
|
|
544
|
-
message: `Gemini stopped with ${
|
|
525
|
+
message: `Gemini stopped with ${finishReason}`,
|
|
545
526
|
body: ProviderShared.encodeJson(event),
|
|
546
|
-
classification: "incomplete-stream",
|
|
527
|
+
classification: RECOVERABLE_FINISH_REASONS.has(finishReason) ? "incomplete-stream" : undefined,
|
|
547
528
|
}),
|
|
548
529
|
}));
|
|
549
|
-
if (candidate?.finishReason && mapFinishReason(candidate.finishReason, state.hasToolCalls) === "error")
|
|
550
|
-
return Effect.fail(ProviderShared.eventError(state.route, `Gemini stopped with ${candidate.finishReason}`, ProviderShared.encodeJson(event)));
|
|
551
530
|
if (!candidate?.content)
|
|
552
531
|
return Effect.succeed([nextState, []]);
|
|
553
532
|
const events = [];
|
|
@@ -561,6 +540,21 @@ const step = (state, event) => {
|
|
|
561
540
|
let nextTextId = nextState.nextTextId;
|
|
562
541
|
// Supplier ids must be tracked across chunks of the same response, not just within one event's parts.
|
|
563
542
|
const seenCallIds = new Set(nextState.seenCallIds);
|
|
543
|
+
const signed = (signature) => signatureMetadata(state.providerMetadataKey, signature);
|
|
544
|
+
const endReasoning = () => {
|
|
545
|
+
if (reasoningId === undefined)
|
|
546
|
+
return;
|
|
547
|
+
lifecycle = Lifecycle.reasoningEnd(lifecycle, events, reasoningId, signed(reasoningSignature));
|
|
548
|
+
reasoningId = undefined;
|
|
549
|
+
reasoningSignature = undefined;
|
|
550
|
+
};
|
|
551
|
+
const endText = () => {
|
|
552
|
+
if (textId === undefined)
|
|
553
|
+
return;
|
|
554
|
+
lifecycle = Lifecycle.textEnd(lifecycle, events, textId, signed(textSignature));
|
|
555
|
+
textId = undefined;
|
|
556
|
+
textSignature = undefined;
|
|
557
|
+
};
|
|
564
558
|
for (const input of candidate.content.parts ?? []) {
|
|
565
559
|
if (ProviderShared.isRecord(input) &&
|
|
566
560
|
!("text" in input) &&
|
|
@@ -584,40 +578,26 @@ const step = (state, event) => {
|
|
|
584
578
|
lifecycle = Lifecycle.stepStart(lifecycle, events);
|
|
585
579
|
events.push(LLMEvent.media({
|
|
586
580
|
media: Media.base64(part.inlineData.data, part.inlineData.mimeType),
|
|
587
|
-
providerMetadata: signature
|
|
588
|
-
? providerMetadata(state.providerMetadataKey, { thoughtSignature: signature })
|
|
589
|
-
: undefined,
|
|
581
|
+
providerMetadata: signed(signature),
|
|
590
582
|
}));
|
|
591
583
|
continue;
|
|
592
584
|
}
|
|
593
585
|
if ("text" in part && part.text.length > 0) {
|
|
594
586
|
if (part.thought) {
|
|
595
|
-
|
|
596
|
-
lifecycle = Lifecycle.textEnd(lifecycle, events, textId, textSignature
|
|
597
|
-
? providerMetadata(state.providerMetadataKey, { thoughtSignature: textSignature })
|
|
598
|
-
: undefined);
|
|
599
|
-
textId = undefined;
|
|
600
|
-
textSignature = undefined;
|
|
601
|
-
}
|
|
587
|
+
endText();
|
|
602
588
|
if (reasoningId === undefined) {
|
|
603
589
|
reasoningId = `reasoning-${nextReasoningId}`;
|
|
604
590
|
nextReasoningId += 1;
|
|
605
591
|
}
|
|
606
|
-
lifecycle = Lifecycle.reasoningDelta(lifecycle, events, reasoningId, part.text,
|
|
592
|
+
lifecycle = Lifecycle.reasoningDelta(lifecycle, events, reasoningId, part.text, signed(signature));
|
|
607
593
|
continue;
|
|
608
594
|
}
|
|
609
|
-
|
|
610
|
-
lifecycle = Lifecycle.reasoningEnd(lifecycle, events, reasoningId, reasoningSignature
|
|
611
|
-
? providerMetadata(state.providerMetadataKey, { thoughtSignature: reasoningSignature })
|
|
612
|
-
: undefined);
|
|
613
|
-
reasoningId = undefined;
|
|
614
|
-
reasoningSignature = undefined;
|
|
615
|
-
}
|
|
595
|
+
endReasoning();
|
|
616
596
|
if (textId === undefined) {
|
|
617
597
|
textId = `text-${nextTextId}`;
|
|
618
598
|
nextTextId += 1;
|
|
619
599
|
}
|
|
620
|
-
lifecycle = Lifecycle.textDelta(lifecycle, events, textId, part.text,
|
|
600
|
+
lifecycle = Lifecycle.textDelta(lifecycle, events, textId, part.text, signed(textSignature));
|
|
621
601
|
textSignature = undefined;
|
|
622
602
|
continue;
|
|
623
603
|
}
|
|
@@ -632,26 +612,14 @@ const step = (state, event) => {
|
|
|
632
612
|
if (supplied !== undefined)
|
|
633
613
|
seenCallIds.add(supplied);
|
|
634
614
|
const id = supplied !== undefined && !duplicate ? supplied : `tool_${crypto.randomUUID().replaceAll("-", "")}`;
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
? providerMetadata(state.providerMetadataKey, { thoughtSignature: reasoningSignature })
|
|
638
|
-
: undefined);
|
|
639
|
-
reasoningId = undefined;
|
|
640
|
-
reasoningSignature = undefined;
|
|
641
|
-
}
|
|
642
|
-
if (textId !== undefined) {
|
|
643
|
-
lifecycle = Lifecycle.textEnd(lifecycle, events, textId, textSignature ? providerMetadata(state.providerMetadataKey, { thoughtSignature: textSignature }) : undefined);
|
|
644
|
-
textId = undefined;
|
|
645
|
-
textSignature = undefined;
|
|
646
|
-
}
|
|
615
|
+
endReasoning();
|
|
616
|
+
endText();
|
|
647
617
|
lifecycle = Lifecycle.stepStart(lifecycle, events);
|
|
648
618
|
events.push(LLMEvent.toolCall({
|
|
649
619
|
id,
|
|
650
620
|
name: part.functionCall.name,
|
|
651
621
|
input,
|
|
652
|
-
providerMetadata:
|
|
653
|
-
? providerMetadata(state.providerMetadataKey, { thoughtSignature: part.thoughtSignature })
|
|
654
|
-
: undefined,
|
|
622
|
+
providerMetadata: signed(signature),
|
|
655
623
|
}));
|
|
656
624
|
hasToolCalls = true;
|
|
657
625
|
}
|
|
@@ -707,8 +675,9 @@ export const transport = {
|
|
|
707
675
|
if (typeof event === "object" && event !== null)
|
|
708
676
|
raw.set(event, frame);
|
|
709
677
|
const candidate = Option.getOrUndefined(decodeCheckpoint(event))?.candidates?.[0];
|
|
710
|
-
|
|
711
|
-
|
|
678
|
+
const candidateFinishReason = terminalFinishReason(candidate?.finishReason);
|
|
679
|
+
token = candidate?.continuationToken ?? (candidateFinishReason ? undefined : token);
|
|
680
|
+
finishReason = candidateFinishReason ?? finishReason;
|
|
712
681
|
return event;
|
|
713
682
|
}))), Stream.catchIf(
|
|
714
683
|
// A connection failure may resume; a timeout keeps its meaning and ends the response.
|
|
@@ -725,9 +694,7 @@ export const transport = {
|
|
|
725
694
|
return Stream.empty;
|
|
726
695
|
})));
|
|
727
696
|
});
|
|
728
|
-
const next = (continuationToken) => Stream.unwrap(sse
|
|
729
|
-
.prepare({ ...prepared.input, body: { ...prepared.input.body, continuationToken } })
|
|
730
|
-
.pipe(Effect.flatMap((continued) => sse.execute(continued, request, runtime)), Effect.map(respond)));
|
|
697
|
+
const next = (continuationToken) => Stream.unwrap(sse.prepare({ ...prepared.input, body: { ...prepared.input.body, continuationToken } }).pipe(Effect.flatMap((continued) => sse.execute(continued, request, runtime)), Effect.map(respond)));
|
|
731
698
|
const first = yield* sse.execute(prepared.http, request, runtime);
|
|
732
699
|
return {
|
|
733
700
|
frames: respond(first),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ImageModel, ImageResponse, type
|
|
1
|
+
import { ImageModel, ImageResponse, type ImageRequest } from "../image.js";
|
|
2
2
|
import { MediaProtocol } from "../route/media-protocol.js";
|
|
3
3
|
import { MediaRoute } from "../route/media.js";
|
|
4
4
|
import { type OpenString } from "../schema/index.js";
|
|
@@ -9,7 +9,7 @@ export type GoogleImageOptions = {
|
|
|
9
9
|
readonly thinkingLevel?: OpenString<"MINIMAL" | "LOW" | "MEDIUM" | "HIGH">;
|
|
10
10
|
readonly includeThoughts?: boolean;
|
|
11
11
|
} & Record<string, unknown>;
|
|
12
|
-
export type Request =
|
|
12
|
+
export type Request = ImageRequest<ImageModel<GoogleImageOptions>>;
|
|
13
13
|
export declare const protocol: MediaProtocol.Inline<Request, ImageResponse>;
|
|
14
14
|
export declare const model: (input: MediaRoute.ModelInput) => ImageModel<GoogleImageOptions>;
|
|
15
15
|
export declare const GoogleImages: {
|
|
@@ -35,7 +35,6 @@ interface ParserState {
|
|
|
35
35
|
readonly lifecycle: Lifecycle.State;
|
|
36
36
|
readonly steps: Partial<Record<number, OutputStep>>;
|
|
37
37
|
readonly tools: ToolStream.State<number>;
|
|
38
|
-
readonly completed: boolean;
|
|
39
38
|
}
|
|
40
39
|
export declare const protocol: Protocol<{
|
|
41
40
|
readonly model: string;
|
|
@@ -170,13 +169,13 @@ export declare const protocol: Protocol<{
|
|
|
170
169
|
readonly message?: string | undefined;
|
|
171
170
|
}[] | undefined;
|
|
172
171
|
};
|
|
173
|
-
} | {
|
|
174
|
-
readonly event_type: "error";
|
|
175
|
-
readonly error: unknown;
|
|
176
172
|
} | {
|
|
177
173
|
readonly event_type: "interaction.status_update";
|
|
178
174
|
readonly interaction_id?: string | undefined;
|
|
179
175
|
readonly status: string;
|
|
176
|
+
} | {
|
|
177
|
+
readonly event_type: "error";
|
|
178
|
+
readonly error?: unknown;
|
|
180
179
|
}, ParserState>;
|
|
181
180
|
export declare const route: Route<{
|
|
182
181
|
readonly model: string;
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { Effect, Schema, SchemaGetter } from "effect";
|
|
1
|
+
import { Effect, Option, Schema, SchemaGetter } from "effect";
|
|
2
2
|
import { Route } from "../route/client.js";
|
|
3
3
|
import { Auth } from "../route/auth.js";
|
|
4
4
|
import { Endpoint } from "../route/endpoint.js";
|
|
5
5
|
import { Framing } from "../route/framing.js";
|
|
6
6
|
import { Protocol } from "../route/protocol.js";
|
|
7
|
-
import { AIError, LLMEvent, ProviderID, Usage, } from "../schema/index.js";
|
|
7
|
+
import { AIError, ContentPolicyError, InvalidProviderOutputError, LLMEvent, ProviderID, Usage, } from "../schema/index.js";
|
|
8
8
|
import { Media } from "../media.js";
|
|
9
9
|
import { classifyProviderFailure, providerErrorMessage } from "../provider-error.js";
|
|
10
10
|
import { encodeJson } from "../utils/json.js";
|
|
@@ -14,6 +14,7 @@ import { MediaInput } from "./utils/media-input.js";
|
|
|
14
14
|
import { GeminiGenerateContent } from "./utils/gemini-generate-content.js";
|
|
15
15
|
import { ToolStream } from "./utils/tool-stream.js";
|
|
16
16
|
const ADAPTER = "google-interactions";
|
|
17
|
+
const SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator";
|
|
17
18
|
export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
|
|
18
19
|
// =============================================================================
|
|
19
20
|
// Public Model Input
|
|
@@ -146,6 +147,11 @@ const UnknownEvent = Schema.Struct({
|
|
|
146
147
|
decode: SchemaGetter.transform(() => ({ event_type: "unknown" })),
|
|
147
148
|
encode: SchemaGetter.forbidden(() => "Unknown Google Interactions stream events are decode-only"),
|
|
148
149
|
}));
|
|
150
|
+
const ErrorDetail = Schema.StructWithRest(Schema.Struct({
|
|
151
|
+
code: lenient(Schema.String),
|
|
152
|
+
error_type: lenient(Schema.String),
|
|
153
|
+
message: lenient(Schema.String),
|
|
154
|
+
}), [Schema.Record(Schema.String, Schema.Unknown)]);
|
|
149
155
|
const Event = Schema.Union([
|
|
150
156
|
Schema.Struct({ event_type: Schema.Literal("step.start"), index: Schema.Number, step: OutputStep }),
|
|
151
157
|
Schema.Struct({ event_type: Schema.Literal("step.delta"), index: Schema.Number, delta: Delta }),
|
|
@@ -160,7 +166,7 @@ const Event = Schema.Union([
|
|
|
160
166
|
status: Schema.String,
|
|
161
167
|
}),
|
|
162
168
|
Schema.Struct({ event_type: Schema.Literal("interaction.completed"), interaction: Interaction }),
|
|
163
|
-
Schema.Struct({ event_type: Schema.Literal("error"), error: Schema.Unknown }),
|
|
169
|
+
Schema.Struct({ event_type: Schema.Literal("error"), error: Schema.optionalKey(Schema.Unknown) }),
|
|
164
170
|
UnknownEvent,
|
|
165
171
|
]);
|
|
166
172
|
// =============================================================================
|
|
@@ -205,6 +211,7 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
|
|
|
205
211
|
else
|
|
206
212
|
steps.push({ type, content: [content] });
|
|
207
213
|
};
|
|
214
|
+
let hasSignedStep = false;
|
|
208
215
|
for (const part of message.content) {
|
|
209
216
|
if (message.role === "tool") {
|
|
210
217
|
if (part.type !== "tool-result")
|
|
@@ -227,21 +234,27 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
|
|
|
227
234
|
continue;
|
|
228
235
|
}
|
|
229
236
|
if (message.role === "assistant" && part.type === "reasoning") {
|
|
237
|
+
const thoughtSignature = signature(part.providerMetadata, key);
|
|
230
238
|
steps.push({
|
|
231
239
|
type: "thought",
|
|
232
|
-
signature:
|
|
240
|
+
signature: thoughtSignature,
|
|
233
241
|
summary: part.text ? [{ type: "text", text: part.text }] : undefined,
|
|
234
242
|
});
|
|
243
|
+
if (thoughtSignature !== undefined)
|
|
244
|
+
hasSignedStep = true;
|
|
235
245
|
continue;
|
|
236
246
|
}
|
|
237
247
|
if (message.role === "assistant" && part.type === "tool-call") {
|
|
248
|
+
const toolSignature = signature(part.providerMetadata, key);
|
|
238
249
|
steps.push({
|
|
239
250
|
type: "function_call",
|
|
240
251
|
id: part.id,
|
|
241
252
|
name: part.name,
|
|
242
253
|
arguments: part.input,
|
|
243
|
-
signature:
|
|
254
|
+
signature: toolSignature ?? (!hasSignedStep ? SKIP_THOUGHT_SIGNATURE_VALIDATOR : undefined),
|
|
244
255
|
});
|
|
256
|
+
if (toolSignature !== undefined)
|
|
257
|
+
hasSignedStep = true;
|
|
245
258
|
continue;
|
|
246
259
|
}
|
|
247
260
|
return yield* ProviderShared.unsupportedContent(ADAPTER, message.role, message.role === "user" ? ["text", "media"] : ["text", "media", "reasoning", "tool-call"]);
|
|
@@ -265,9 +278,7 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque
|
|
|
265
278
|
const flattened = ProviderShared.flattenToolRequest(request);
|
|
266
279
|
if (flattened.tools.some((tool) => tool.native !== undefined))
|
|
267
280
|
return yield* ProviderShared.invalidRequest("Google Interactions hosted tools are not supported");
|
|
268
|
-
if (request.
|
|
269
|
-
request.generation?.frequencyPenalty !== undefined ||
|
|
270
|
-
request.generation?.presencePenalty !== undefined)
|
|
281
|
+
if (request.topK !== undefined || request.frequencyPenalty !== undefined || request.presencePenalty !== undefined)
|
|
271
282
|
return yield* ProviderShared.invalidRequest("Google Interactions does not support topK, frequencyPenalty, or presencePenalty");
|
|
272
283
|
const choice = request.toolChoice === undefined
|
|
273
284
|
? undefined
|
|
@@ -295,11 +306,11 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque
|
|
|
295
306
|
}))
|
|
296
307
|
: undefined,
|
|
297
308
|
generation_config: {
|
|
298
|
-
max_output_tokens: request.
|
|
299
|
-
temperature: request.
|
|
300
|
-
top_p: request.
|
|
301
|
-
seed: request.
|
|
302
|
-
stop_sequences: request.
|
|
309
|
+
max_output_tokens: request.maxTokens,
|
|
310
|
+
temperature: request.temperature,
|
|
311
|
+
top_p: request.topP,
|
|
312
|
+
seed: request.seed,
|
|
313
|
+
stop_sequences: request.stop,
|
|
303
314
|
thinking_level: options.thinkingLevel,
|
|
304
315
|
thinking_summaries: options.thinkingSummaries,
|
|
305
316
|
tool_choice: choice,
|
|
@@ -419,6 +430,23 @@ const onStop = Effect.fnUntraced(function* (state, index) {
|
|
|
419
430
|
const result = yield* ToolStream.finish(ADAPTER, state.tools, index);
|
|
420
431
|
return [{ ...state, tools: result.tools }, result.events ?? []];
|
|
421
432
|
});
|
|
433
|
+
const RECOVERABLE_CODES = new Set([
|
|
434
|
+
"MALFORMED_FUNCTION_CALL",
|
|
435
|
+
"MALFORMED_TOOL_CALL",
|
|
436
|
+
"UNEXPECTED_TOOL_CALL",
|
|
437
|
+
"MALFORMED_RESPONSE",
|
|
438
|
+
]);
|
|
439
|
+
const INVALID_OUTPUT_CODES = new Set(["MISSING_THOUGHT_SIGNATURE", "TOO_MANY_TOOL_CALLS", "NO_IMAGE"]);
|
|
440
|
+
const failureReason = (route, code, message, data, rawBody) => {
|
|
441
|
+
const normalized = code?.trim().toUpperCase().replaceAll("-", "_");
|
|
442
|
+
if (normalized && RECOVERABLE_CODES.has(normalized))
|
|
443
|
+
return new InvalidProviderOutputError({ route, message, body: rawBody, classification: "incomplete-stream" });
|
|
444
|
+
if (normalized && INVALID_OUTPUT_CODES.has(normalized))
|
|
445
|
+
return new InvalidProviderOutputError({ route, message, body: rawBody });
|
|
446
|
+
if (normalized && (normalized === "CONTENT_BLOCKED" || GeminiGenerateContent.contentFiltered(normalized)))
|
|
447
|
+
return new ContentPolicyError({ message, body: rawBody });
|
|
448
|
+
return classifyProviderFailure({ message, data, rawBody });
|
|
449
|
+
};
|
|
422
450
|
const step = Effect.fnUntraced(function* (state, event) {
|
|
423
451
|
switch (event.event_type) {
|
|
424
452
|
case "step.start":
|
|
@@ -431,34 +459,32 @@ const step = Effect.fnUntraced(function* (state, event) {
|
|
|
431
459
|
case "interaction.status_update":
|
|
432
460
|
case "unknown":
|
|
433
461
|
return [state, []];
|
|
434
|
-
case "error":
|
|
462
|
+
case "error": {
|
|
463
|
+
const rawBody = encodeJson(event);
|
|
464
|
+
const detail = Option.getOrUndefined(Schema.decodeUnknownOption(ErrorDetail)(event.error));
|
|
435
465
|
return yield* new AIError({
|
|
436
|
-
reason:
|
|
437
|
-
message: providerErrorMessage(encodeJson(event)) ?? "Google Interactions stream error",
|
|
438
|
-
data: event.error,
|
|
439
|
-
rawBody: encodeJson(event),
|
|
440
|
-
}),
|
|
466
|
+
reason: failureReason(state.route, detail?.code ?? detail?.error_type, detail?.message?.trim() || providerErrorMessage(rawBody) || "Google Interactions stream error", event.error, rawBody),
|
|
441
467
|
});
|
|
468
|
+
}
|
|
442
469
|
case "interaction.completed": {
|
|
443
470
|
const interaction = event.interaction;
|
|
444
471
|
if (interaction.status === "failed" || interaction.status === "cancelled") {
|
|
445
472
|
const messages = (interaction.errors ?? []).flatMap((error) => (error.message?.trim() ? [error.message] : []));
|
|
473
|
+
const coded = interaction.errors?.find((error) => error.code);
|
|
446
474
|
return yield* new AIError({
|
|
447
|
-
reason:
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
data: interaction.errors?.find((error) => error.code) ?? interaction,
|
|
451
|
-
rawBody: encodeJson(event),
|
|
452
|
-
}),
|
|
475
|
+
reason: failureReason(state.route, coded?.code, messages.length > 0 ? messages.join("\n") : `Google Interactions ${interaction.status}`,
|
|
476
|
+
// The first coded error decides the classification; every message stays visible.
|
|
477
|
+
coded ?? interaction, encodeJson(event)),
|
|
453
478
|
});
|
|
454
479
|
}
|
|
455
480
|
if (!["completed", "requires_action", "incomplete"].includes(interaction.status))
|
|
456
481
|
return yield* ProviderShared.eventError(ADAPTER, `Unexpected terminal Interactions status: ${interaction.status}`, encodeJson(event));
|
|
457
482
|
const pending = yield* ToolStream.finishAll(ADAPTER, state.tools);
|
|
458
483
|
const events = [...pending.events];
|
|
484
|
+
const hasToolCalls = Object.values(state.steps).some((item) => item?.type === "function_call");
|
|
459
485
|
const lifecycle = Lifecycle.finish(state.lifecycle, events, {
|
|
460
486
|
reason: {
|
|
461
|
-
normalized: interaction.status === "requires_action"
|
|
487
|
+
normalized: interaction.status === "requires_action" || (interaction.status === "completed" && hasToolCalls)
|
|
462
488
|
? "tool-calls"
|
|
463
489
|
: interaction.status === "incomplete"
|
|
464
490
|
? "length"
|
|
@@ -468,7 +494,7 @@ const step = Effect.fnUntraced(function* (state, event) {
|
|
|
468
494
|
usage: mapUsage(interaction.usage, state.metadataKey),
|
|
469
495
|
providerMetadata: { [state.metadataKey]: { interactionId: interaction.id } },
|
|
470
496
|
});
|
|
471
|
-
return [{ ...state, lifecycle, tools: pending.tools
|
|
497
|
+
return [{ ...state, lifecycle, tools: pending.tools }, events];
|
|
472
498
|
}
|
|
473
499
|
}
|
|
474
500
|
});
|
|
@@ -482,18 +508,14 @@ export const protocol = Protocol.make({
|
|
|
482
508
|
stream: {
|
|
483
509
|
event: Protocol.jsonEvent(Event),
|
|
484
510
|
initial: (request) => ({
|
|
485
|
-
route: `${request.model.provider}/${
|
|
511
|
+
route: `${request.model.provider}/${request.model.route.id}`,
|
|
486
512
|
metadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
|
|
487
513
|
lifecycle: Lifecycle.initial(),
|
|
488
514
|
steps: {},
|
|
489
515
|
tools: ToolStream.empty(),
|
|
490
|
-
completed: false,
|
|
491
516
|
}),
|
|
492
517
|
step,
|
|
493
518
|
terminal: (event) => event.event_type === "interaction.completed",
|
|
494
|
-
onHalt: (state) => state.completed
|
|
495
|
-
? Effect.succeed([])
|
|
496
|
-
: Effect.fail(ProviderShared.eventError(ADAPTER, "Google Interactions stream ended before interaction.completed")),
|
|
497
519
|
},
|
|
498
520
|
});
|
|
499
521
|
export const route = Route.make({
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { MediaProtocol } from "../route/media-protocol.js";
|
|
2
2
|
import { MediaRoute } from "../route/media.js";
|
|
3
|
-
import { SpeechModel, type
|
|
3
|
+
import { SpeechModel, type SpeechRequest } from "../speech.js";
|
|
4
4
|
import { GeminiGenerateContent } from "./utils/gemini-generate-content.js";
|
|
5
5
|
import { SpeechStream } from "./utils/speech-stream.js";
|
|
6
6
|
export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
|
|
@@ -21,7 +21,7 @@ export type GoogleSpeechOptions = {
|
|
|
21
21
|
};
|
|
22
22
|
};
|
|
23
23
|
} & Record<string, unknown>;
|
|
24
|
-
export type Request =
|
|
24
|
+
export type Request = SpeechRequest<SpeechModel<GoogleSpeechOptions>>;
|
|
25
25
|
interface State extends SpeechStream.Audio, GeminiGenerateContent.Metadata {
|
|
26
26
|
readonly mimeType?: string;
|
|
27
27
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { MediaProtocol } from "../route/media-protocol.js";
|
|
2
2
|
import { MediaRoute } from "../route/media.js";
|
|
3
3
|
import { type OpenString } from "../schema/index.js";
|
|
4
|
-
import { TranscriptionModel, type
|
|
4
|
+
import { TranscriptionModel, type TranscriptionRequest, type TranscriptionSegment, type TranscriptionWord } from "../transcription.js";
|
|
5
5
|
import { GeminiGenerateContent } from "./utils/gemini-generate-content.js";
|
|
6
6
|
export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
|
|
7
7
|
/**
|
|
@@ -15,7 +15,7 @@ export type GoogleTranscriptionOptions = {
|
|
|
15
15
|
readonly languageCodes?: ReadonlyArray<string>;
|
|
16
16
|
};
|
|
17
17
|
} & Record<string, unknown>;
|
|
18
|
-
export type Request =
|
|
18
|
+
export type Request = TranscriptionRequest<TranscriptionModel<GoogleTranscriptionOptions>>;
|
|
19
19
|
interface State extends GeminiGenerateContent.Metadata {
|
|
20
20
|
readonly text: string;
|
|
21
21
|
readonly segments: Array<TranscriptionSegment>;
|
|
@@ -2,13 +2,13 @@ import { Schema } from "effect";
|
|
|
2
2
|
import { MediaProtocol } from "../route/media-protocol.js";
|
|
3
3
|
import { MediaRoute } from "../route/media.js";
|
|
4
4
|
import { type OpenString } from "../schema/index.js";
|
|
5
|
-
import { VideoModel, VideoResponse, type
|
|
5
|
+
import { VideoModel, VideoResponse, type VideoRequest } from "../video.js";
|
|
6
6
|
export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
|
|
7
7
|
/** Provider-native `parameters`. Common fields (`aspect`, `resolution`, `durationSeconds`, `seed`) live on the request. */
|
|
8
8
|
export type GoogleVideoOptions = {
|
|
9
9
|
readonly personGeneration?: OpenString<"allow_all" | "allow_adult" | "dont_allow">;
|
|
10
10
|
} & Record<string, unknown>;
|
|
11
|
-
export type Request =
|
|
11
|
+
export type Request = VideoRequest<VideoModel<GoogleVideoOptions>>;
|
|
12
12
|
/** The long-running operation name, e.g. `models/veo-3.1-generate-preview/operations/abc123`. */
|
|
13
13
|
export declare const Token: Schema.Struct<{
|
|
14
14
|
readonly operation: Schema.String;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ImageModel, ImageResponse, type
|
|
1
|
+
import { ImageModel, ImageResponse, type ImageRequest } from "../image.js";
|
|
2
2
|
import { MediaProtocol } from "../route/media-protocol.js";
|
|
3
3
|
import { MediaRoute } from "../route/media.js";
|
|
4
4
|
import { type OpenString } from "../schema/index.js";
|
|
@@ -20,7 +20,7 @@ export type ImageOptions = {
|
|
|
20
20
|
};
|
|
21
21
|
readonly [key: string]: unknown;
|
|
22
22
|
};
|
|
23
|
-
export type Request =
|
|
23
|
+
export type Request = ImageRequest<ImageModel<ImageOptions>>;
|
|
24
24
|
export declare const protocol: MediaProtocol.Inline<Request, ImageResponse>;
|
|
25
25
|
export declare const model: (input: MediaRoute.ModelInput) => ImageModel<ImageOptions>;
|
|
26
26
|
export * as MetaImages from "./meta-images.js";
|