@opencode/ai 2.3.1 → 2.4.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.
- package/dist/decision.d.ts +4 -3
- package/dist/decision.js +3 -2
- package/dist/embedding.d.ts +4 -3
- package/dist/embedding.js +3 -2
- package/dist/experimental/cloudflare-run-extraction.js +1 -2
- package/dist/experimental/realtime.d.ts +12 -43
- package/dist/experimental/realtime.js +14 -30
- package/dist/experimental.d.ts +1 -1
- package/dist/image.js +1 -1
- package/dist/media-model.d.ts +5 -4
- package/dist/media-model.js +5 -4
- package/dist/media.js +4 -17
- package/dist/protocols/anthropic-messages.js +7 -11
- package/dist/protocols/bedrock-converse.js +6 -6
- package/dist/protocols/cohere-chat.js +3 -3
- package/dist/protocols/gemini.js +6 -10
- package/dist/protocols/google-interactions.d.ts +299 -6
- package/dist/protocols/google-interactions.js +251 -33
- package/dist/protocols/meta-messages.js +3 -3
- package/dist/protocols/minimax-video.js +7 -1
- package/dist/protocols/mistral-chat.d.ts +1 -0
- package/dist/protocols/mistral-chat.js +3 -3
- package/dist/protocols/open-responses-continuation.js +2 -0
- package/dist/protocols/open-responses.d.ts +162 -114
- package/dist/protocols/open-responses.js +12 -7
- package/dist/protocols/openai-chat.d.ts +1 -0
- package/dist/protocols/openai-chat.js +6 -5
- package/dist/protocols/openai-responses.js +2 -1
- package/dist/protocols/shared.d.ts +12 -1
- package/dist/protocols/shared.js +56 -9
- package/dist/protocols/utils/gateway-protocol.js +1 -0
- package/dist/protocols/utils/gemini-generate-content.d.ts +4 -0
- package/dist/protocols/utils/gemini-generate-content.js +5 -1
- package/dist/protocols/utils/responses-compaction.js +10 -4
- package/dist/protocols/xai-responses.d.ts +2 -1
- package/dist/protocols/xai-responses.js +4 -1
- package/dist/provider-error.js +3 -1
- package/dist/providers/alibaba.js +2 -3
- package/dist/providers/assemblyai.d.ts +2 -4
- package/dist/providers/azure.js +5 -11
- package/dist/providers/baseten.js +2 -3
- package/dist/providers/byteplus.d.ts +2 -4
- package/dist/providers/cartesia.d.ts +2 -4
- package/dist/providers/cloudflare-ai-gateway.js +3 -3
- package/dist/providers/cloudflare-workers-ai.js +2 -3
- package/dist/providers/cohere.js +2 -3
- package/dist/providers/deepgram.d.ts +2 -4
- package/dist/providers/deepinfra.js +2 -3
- package/dist/providers/digitalocean.js +3 -5
- package/dist/providers/elevenlabs.d.ts +2 -4
- package/dist/providers/fireworks.js +2 -3
- package/dist/providers/google-vertex-interactions.d.ts +12 -3
- package/dist/providers/google-vertex-interactions.js +1 -2
- package/dist/providers/google-vertex.js +6 -2
- package/dist/providers/google.d.ts +20 -3
- package/dist/providers/google.js +7 -4
- package/dist/providers/openai-compatible.js +3 -5
- package/dist/providers/openai.js +4 -10
- package/dist/providers/opencode.d.ts +2 -4
- package/dist/providers/opencode.js +2 -3
- package/dist/providers/openrouter.js +3 -5
- package/dist/providers/typesafe-ai.d.ts +2 -4
- package/dist/providers/typesafe-ai.js +2 -3
- package/dist/providers/vercel-ai-gateway.js +3 -5
- package/dist/providers/volcengine.d.ts +2 -4
- package/dist/route/decision.d.ts +4 -7
- package/dist/route/decision.js +8 -10
- package/dist/route/embedding.d.ts +4 -7
- package/dist/route/embedding.js +4 -7
- package/dist/route/executor-service.d.ts +20 -3
- package/dist/route/executor-service.js +72 -2
- package/dist/route/executor.d.ts +5 -5
- package/dist/route/executor.js +68 -73
- package/dist/route/media-protocol.d.ts +2 -1
- package/dist/route/media-protocol.js +2 -10
- package/dist/route/media.d.ts +6 -8
- package/dist/route/media.js +8 -8
- package/dist/route/protocol.d.ts +2 -0
- package/dist/route/protocol.js +4 -1
- package/dist/route/transport/http.d.ts +1 -2
- package/dist/route/transport/http.js +5 -28
- package/dist/schema/errors.js +2 -1
- package/dist/schema/options.d.ts +1 -1
- package/dist/speech.js +1 -1
- package/dist/transcription.js +1 -1
- package/dist/video.js +1 -1
- package/package.json +3 -3
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { Effect, Option, Schema, SchemaGetter } from "effect";
|
|
1
|
+
import { Effect, Option, Schema, SchemaGetter, Stream } 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
|
-
import { Framing } from "../route/framing.js";
|
|
6
5
|
import { Protocol } from "../route/protocol.js";
|
|
6
|
+
import { HttpTransport, } from "../route/transport/index.js";
|
|
7
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";
|
|
@@ -14,6 +14,9 @@ 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 CONTINUATION = "requires_continuation";
|
|
18
|
+
// Matches Google's GenAI SDKs (Python, JS, and Go).
|
|
19
|
+
const MAX_STREAM_RECONNECTS_WITHOUT_PROGRESS = 3;
|
|
17
20
|
const SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator";
|
|
18
21
|
export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
|
|
19
22
|
// =============================================================================
|
|
@@ -26,6 +29,7 @@ const Options = Schema.Struct({
|
|
|
26
29
|
thinkingLevel: lenient(ThinkingLevel),
|
|
27
30
|
thinkingSummaries: lenient(knownString()),
|
|
28
31
|
serviceTier: lenient(knownString()),
|
|
32
|
+
safetySettings: lenient(Schema.Array(GeminiGenerateContent.SafetySetting)),
|
|
29
33
|
});
|
|
30
34
|
const decodeOptions = ProviderShared.validateWith(Schema.decodeUnknownEffect(Options));
|
|
31
35
|
// =============================================================================
|
|
@@ -67,12 +71,14 @@ const ToolChoice = Schema.Union([
|
|
|
67
71
|
]);
|
|
68
72
|
const Body = Schema.Struct({
|
|
69
73
|
model: Schema.String,
|
|
70
|
-
input: Schema.Array(InputStep),
|
|
74
|
+
input: Schema.optional(Schema.Array(InputStep)),
|
|
71
75
|
stream: Schema.Literal(true),
|
|
72
76
|
store: Schema.Boolean,
|
|
73
77
|
previous_interaction_id: Schema.optional(Schema.String),
|
|
78
|
+
continuation_token: Schema.optional(Schema.String),
|
|
74
79
|
system_instruction: Schema.optional(Schema.String),
|
|
75
80
|
service_tier: Schema.optional(Schema.String),
|
|
81
|
+
safety_settings: Schema.optional(Schema.Array(Schema.Struct({ type: Schema.String, threshold: Schema.String }))),
|
|
76
82
|
tools: Schema.optional(Schema.Array(Schema.Struct({
|
|
77
83
|
type: Schema.Literal("function"),
|
|
78
84
|
name: Schema.String,
|
|
@@ -128,6 +134,7 @@ const Delta = Schema.Union([
|
|
|
128
134
|
const Interaction = Schema.StructWithRest(Schema.Struct({
|
|
129
135
|
id: Schema.optional(Schema.String),
|
|
130
136
|
status: Schema.String,
|
|
137
|
+
continuation_token: optionalNull(Schema.String),
|
|
131
138
|
usage: Schema.optional(RawUsage),
|
|
132
139
|
errors: Schema.optional(Schema.Array(Schema.Struct({ code: Schema.optional(Schema.String), message: Schema.optional(Schema.String) }))),
|
|
133
140
|
}), [Schema.Record(Schema.String, Schema.Unknown)]);
|
|
@@ -164,6 +171,8 @@ const Event = Schema.Union([
|
|
|
164
171
|
event_type: Schema.Literal("interaction.status_update"),
|
|
165
172
|
interaction_id: Schema.optional(Schema.String),
|
|
166
173
|
status: Schema.String,
|
|
174
|
+
continuation_token: optionalNull(Schema.String),
|
|
175
|
+
usage: Schema.optional(RawUsage),
|
|
167
176
|
}),
|
|
168
177
|
Schema.Struct({ event_type: Schema.Literal("interaction.completed"), interaction: Interaction }),
|
|
169
178
|
Schema.Struct({ event_type: Schema.Literal("error"), error: Schema.optionalKey(Schema.Unknown) }),
|
|
@@ -172,12 +181,26 @@ const Event = Schema.Union([
|
|
|
172
181
|
// =============================================================================
|
|
173
182
|
// Request Body Construction
|
|
174
183
|
// =============================================================================
|
|
184
|
+
// https://aistudio.google.com/docs/document-processing#office-documents
|
|
185
|
+
const OFFICE_DOCUMENT_MIME_TYPES = new Set([
|
|
186
|
+
"application/msword",
|
|
187
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
188
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.template",
|
|
189
|
+
"application/vnd.oasis.opendocument.text",
|
|
190
|
+
"application/vnd.ms-powerpoint",
|
|
191
|
+
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
192
|
+
"application/vnd.oasis.opendocument.presentation",
|
|
193
|
+
"application/vnd.ms-excel",
|
|
194
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
195
|
+
"application/vnd.oasis.opendocument.spreadsheet",
|
|
196
|
+
]);
|
|
175
197
|
export const mediaContent = Effect.fnUntraced(function* (asset) {
|
|
176
198
|
if (asset.kind !== "image" &&
|
|
177
199
|
asset.kind !== "audio" &&
|
|
178
200
|
asset.kind !== "video" &&
|
|
179
201
|
asset.mediaType !== "application/pdf" &&
|
|
180
|
-
asset.mediaType !== "text/csv"
|
|
202
|
+
asset.mediaType !== "text/csv" &&
|
|
203
|
+
!OFFICE_DOCUMENT_MIME_TYPES.has(asset.mediaType))
|
|
181
204
|
return yield* ProviderShared.invalidRequest(`Google Interactions does not support ${asset.mediaType} document input`);
|
|
182
205
|
const type = asset.kind === "image" || asset.kind === "audio" || asset.kind === "video" ? asset.kind : "document";
|
|
183
206
|
const uri = asset.kind === "video" && asset.source.type === "url" && /^https?:\/\//i.test(asset.source.url)
|
|
@@ -275,8 +298,8 @@ const lowerToolResult = Effect.fnUntraced(function* (part) {
|
|
|
275
298
|
});
|
|
276
299
|
const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (request) {
|
|
277
300
|
const options = yield* decodeOptions(request.providerOptions ?? {});
|
|
278
|
-
const
|
|
279
|
-
if (
|
|
301
|
+
const definitions = ProviderShared.flattenTools(request.tools);
|
|
302
|
+
if (definitions.some((tool) => tool.native !== undefined))
|
|
280
303
|
return yield* ProviderShared.invalidRequest("Google Interactions hosted tools are not supported");
|
|
281
304
|
if (request.topK !== undefined || request.frequencyPenalty !== undefined || request.presencePenalty !== undefined)
|
|
282
305
|
return yield* ProviderShared.invalidRequest("Google Interactions does not support topK, frequencyPenalty, or presencePenalty");
|
|
@@ -290,15 +313,19 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque
|
|
|
290
313
|
});
|
|
291
314
|
return {
|
|
292
315
|
model: request.model.id,
|
|
293
|
-
input: yield* lowerMessages(
|
|
316
|
+
input: yield* lowerMessages(request),
|
|
294
317
|
stream: true,
|
|
295
318
|
// Full-history replay need not create retained provider resources. Continuation callers opt in to storage.
|
|
296
319
|
store: options.store ?? false,
|
|
297
320
|
previous_interaction_id: options.previousInteractionId,
|
|
298
321
|
system_instruction: request.system.length ? ProviderShared.joinText(request.system) : undefined,
|
|
299
322
|
service_tier: options.serviceTier,
|
|
300
|
-
|
|
301
|
-
|
|
323
|
+
safety_settings: options.safetySettings?.map((setting) => ({
|
|
324
|
+
type: setting.category.replace(/^HARM_CATEGORY_/, "").toLowerCase(),
|
|
325
|
+
threshold: setting.threshold.toLowerCase(),
|
|
326
|
+
})),
|
|
327
|
+
tools: definitions.length
|
|
328
|
+
? definitions.map((tool) => ({
|
|
302
329
|
type: "function",
|
|
303
330
|
name: tool.name,
|
|
304
331
|
description: tool.description,
|
|
@@ -323,31 +350,52 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque
|
|
|
323
350
|
const metadata = (state, step) => ({
|
|
324
351
|
[state.metadataKey]: { interactionSignature: step.signature },
|
|
325
352
|
});
|
|
326
|
-
const mapUsage = (usage, key) => {
|
|
327
|
-
if (!usage)
|
|
353
|
+
const mapUsage = (usage, key, continued) => {
|
|
354
|
+
if (!usage && continued.every((hop) => !hop))
|
|
328
355
|
return undefined;
|
|
329
|
-
const
|
|
330
|
-
const
|
|
331
|
-
const
|
|
332
|
-
const
|
|
333
|
-
|
|
334
|
-
|
|
356
|
+
const first = continued.length ? continued[0] : usage;
|
|
357
|
+
const hops = [...continued, usage];
|
|
358
|
+
const sum = (field) => ProviderShared.sumTokens(...hops.map((hop) => (hop ? (field(hop) ?? undefined) : undefined)));
|
|
359
|
+
const input = first?.total_input_tokens ?? undefined;
|
|
360
|
+
const cached = first?.total_cached_tokens ?? undefined;
|
|
361
|
+
const reasoning = sum((hop) => hop.total_thought_tokens);
|
|
362
|
+
const text = sum((hop) => hop.total_output_tokens);
|
|
363
|
+
const output = continued.length
|
|
364
|
+
? ProviderShared.sumTokens(text, reasoning)
|
|
365
|
+
: text === undefined
|
|
366
|
+
? undefined
|
|
367
|
+
: text + (reasoning ?? 0);
|
|
335
368
|
return new Usage({
|
|
336
|
-
contextTokens:
|
|
369
|
+
contextTokens: first?.raw_prompt_token ?? input,
|
|
337
370
|
inputTokens: input,
|
|
338
371
|
outputTokens: output,
|
|
339
372
|
nonCachedInputTokens: ProviderShared.subtractTokens(input, cached),
|
|
340
373
|
cacheReadInputTokens: cached,
|
|
341
374
|
reasoningTokens: reasoning,
|
|
342
|
-
totalTokens:
|
|
343
|
-
|
|
375
|
+
totalTokens: continued.length
|
|
376
|
+
? ProviderShared.totalTokens(input, output, undefined)
|
|
377
|
+
: (usage?.total_tokens ?? undefined),
|
|
378
|
+
// Keep re-billed input in provider metadata, separate from the logical call's input.
|
|
379
|
+
providerMetadata: {
|
|
380
|
+
[key]: continued.length
|
|
381
|
+
? {
|
|
382
|
+
total_input_tokens: sum((hop) => hop.total_input_tokens),
|
|
383
|
+
total_cached_tokens: sum((hop) => hop.total_cached_tokens),
|
|
384
|
+
total_output_tokens: text,
|
|
385
|
+
total_thought_tokens: reasoning,
|
|
386
|
+
total_tokens: sum((hop) => hop.total_tokens),
|
|
387
|
+
requests: hops.length,
|
|
388
|
+
}
|
|
389
|
+
: (usage ?? {}),
|
|
390
|
+
},
|
|
344
391
|
});
|
|
345
392
|
};
|
|
393
|
+
const blockID = (state, index) => (state.hop === 0 ? String(index) : `${state.hop}:${index}`);
|
|
346
394
|
const onStart = Effect.fnUntraced(function* (state, index, step) {
|
|
347
395
|
const events = [];
|
|
348
396
|
let lifecycle = Lifecycle.stepStart(state.lifecycle, events);
|
|
349
397
|
let tools = state.tools;
|
|
350
|
-
const id =
|
|
398
|
+
const id = blockID(state, index);
|
|
351
399
|
if (step.type === "thought") {
|
|
352
400
|
lifecycle = Lifecycle.reasoningStart(lifecycle, events, id, metadata(state, step));
|
|
353
401
|
for (const part of step.summary ?? [])
|
|
@@ -375,7 +423,16 @@ const onStart = Effect.fnUntraced(function* (state, index, step) {
|
|
|
375
423
|
}
|
|
376
424
|
else
|
|
377
425
|
return yield* ProviderShared.eventError(ADAPTER, `Unsupported Interactions step: ${step.type}`, encodeJson(step));
|
|
378
|
-
return [
|
|
426
|
+
return [
|
|
427
|
+
{
|
|
428
|
+
...state,
|
|
429
|
+
lifecycle,
|
|
430
|
+
tools,
|
|
431
|
+
hasToolCalls: state.hasToolCalls || step.type === "function_call",
|
|
432
|
+
steps: { ...state.steps, [index]: step },
|
|
433
|
+
},
|
|
434
|
+
events,
|
|
435
|
+
];
|
|
379
436
|
});
|
|
380
437
|
const onDelta = Effect.fnUntraced(function* (state, index, delta) {
|
|
381
438
|
const step = state.steps[index];
|
|
@@ -384,12 +441,15 @@ const onDelta = Effect.fnUntraced(function* (state, index, delta) {
|
|
|
384
441
|
const events = [];
|
|
385
442
|
if (delta.type === "text" && step.type === "model_output")
|
|
386
443
|
return [
|
|
387
|
-
{ ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events,
|
|
444
|
+
{ ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events, blockID(state, index), delta.text) },
|
|
388
445
|
events,
|
|
389
446
|
];
|
|
390
447
|
if (delta.type === "thought_summary" && step.type === "thought")
|
|
391
448
|
return [
|
|
392
|
-
{
|
|
449
|
+
{
|
|
450
|
+
...state,
|
|
451
|
+
lifecycle: Lifecycle.reasoningDelta(state.lifecycle, events, blockID(state, index), delta.content.text),
|
|
452
|
+
},
|
|
393
453
|
events,
|
|
394
454
|
];
|
|
395
455
|
if (delta.type === "thought_signature") {
|
|
@@ -419,12 +479,15 @@ const onStop = Effect.fnUntraced(function* (state, index) {
|
|
|
419
479
|
const events = [];
|
|
420
480
|
if (step.type === "thought")
|
|
421
481
|
return [
|
|
422
|
-
{
|
|
482
|
+
{
|
|
483
|
+
...state,
|
|
484
|
+
lifecycle: Lifecycle.reasoningEnd(state.lifecycle, events, blockID(state, index), metadata(state, step)),
|
|
485
|
+
},
|
|
423
486
|
events,
|
|
424
487
|
];
|
|
425
488
|
if (step.type === "model_output")
|
|
426
489
|
return [
|
|
427
|
-
{ ...state, lifecycle: Lifecycle.textEnd(state.lifecycle, events,
|
|
490
|
+
{ ...state, lifecycle: Lifecycle.textEnd(state.lifecycle, events, blockID(state, index)) },
|
|
428
491
|
events,
|
|
429
492
|
];
|
|
430
493
|
const result = yield* ToolStream.finish(ADAPTER, state.tools, index);
|
|
@@ -447,7 +510,34 @@ const failureReason = (route, code, message, data, rawBody) => {
|
|
|
447
510
|
return new ContentPolicyError({ message, body: rawBody });
|
|
448
511
|
return classifyProviderFailure({ message, data, rawBody });
|
|
449
512
|
};
|
|
513
|
+
// Marks a request boundary without adding another logical LLM step or finish.
|
|
514
|
+
class NextRequest {
|
|
515
|
+
}
|
|
450
516
|
const step = Effect.fnUntraced(function* (state, event) {
|
|
517
|
+
if (event instanceof NextRequest) {
|
|
518
|
+
const pending = yield* ToolStream.finishAll(ADAPTER, state.tools);
|
|
519
|
+
const events = [...pending.events];
|
|
520
|
+
let lifecycle = state.lifecycle;
|
|
521
|
+
for (const [index, step] of Object.entries(state.steps)) {
|
|
522
|
+
const id = blockID(state, Number(index));
|
|
523
|
+
if (step?.type === "thought")
|
|
524
|
+
lifecycle = Lifecycle.reasoningEnd(lifecycle, events, id, metadata(state, step));
|
|
525
|
+
if (step?.type === "model_output")
|
|
526
|
+
lifecycle = Lifecycle.textEnd(lifecycle, events, id);
|
|
527
|
+
}
|
|
528
|
+
return [
|
|
529
|
+
{
|
|
530
|
+
...state,
|
|
531
|
+
hop: state.hop + 1,
|
|
532
|
+
lifecycle,
|
|
533
|
+
steps: {},
|
|
534
|
+
tools: ToolStream.empty(),
|
|
535
|
+
usage: undefined,
|
|
536
|
+
continuedUsage: [...state.continuedUsage, state.usage],
|
|
537
|
+
},
|
|
538
|
+
events,
|
|
539
|
+
];
|
|
540
|
+
}
|
|
451
541
|
switch (event.event_type) {
|
|
452
542
|
case "step.start":
|
|
453
543
|
return yield* onStart(state, event.index, event.step);
|
|
@@ -455,8 +545,9 @@ const step = Effect.fnUntraced(function* (state, event) {
|
|
|
455
545
|
return yield* onDelta(state, event.index, event.delta);
|
|
456
546
|
case "step.stop":
|
|
457
547
|
return yield* onStop(state, event.index);
|
|
458
|
-
case "interaction.created":
|
|
459
548
|
case "interaction.status_update":
|
|
549
|
+
return [{ ...state, usage: event.usage ?? state.usage }, []];
|
|
550
|
+
case "interaction.created":
|
|
460
551
|
case "unknown":
|
|
461
552
|
return [state, []];
|
|
462
553
|
case "error": {
|
|
@@ -468,6 +559,8 @@ const step = Effect.fnUntraced(function* (state, event) {
|
|
|
468
559
|
}
|
|
469
560
|
case "interaction.completed": {
|
|
470
561
|
const interaction = event.interaction;
|
|
562
|
+
if (interaction.status === CONTINUATION)
|
|
563
|
+
return [{ ...state, usage: interaction.usage ?? state.usage }, []];
|
|
471
564
|
if (interaction.status === "failed" || interaction.status === "cancelled") {
|
|
472
565
|
const messages = (interaction.errors ?? []).flatMap((error) => (error.message?.trim() ? [error.message] : []));
|
|
473
566
|
const coded = interaction.errors?.find((error) => error.code);
|
|
@@ -481,23 +574,143 @@ const step = Effect.fnUntraced(function* (state, event) {
|
|
|
481
574
|
return yield* ProviderShared.eventError(ADAPTER, `Unexpected terminal Interactions status: ${interaction.status}`, encodeJson(event));
|
|
482
575
|
const pending = yield* ToolStream.finishAll(ADAPTER, state.tools);
|
|
483
576
|
const events = [...pending.events];
|
|
484
|
-
const hasToolCalls = Object.values(state.steps).some((item) => item?.type === "function_call");
|
|
485
577
|
const lifecycle = Lifecycle.finish(state.lifecycle, events, {
|
|
486
578
|
reason: {
|
|
487
|
-
normalized: interaction.status === "requires_action" || (interaction.status === "completed" && hasToolCalls)
|
|
579
|
+
normalized: interaction.status === "requires_action" || (interaction.status === "completed" && state.hasToolCalls)
|
|
488
580
|
? "tool-calls"
|
|
489
581
|
: interaction.status === "incomplete"
|
|
490
582
|
? "length"
|
|
491
583
|
: "stop",
|
|
492
584
|
raw: interaction.status,
|
|
493
585
|
},
|
|
494
|
-
usage: mapUsage(interaction.usage, state.metadataKey),
|
|
586
|
+
usage: mapUsage(interaction.usage ?? state.usage, state.metadataKey, state.continuedUsage),
|
|
495
587
|
providerMetadata: { [state.metadataKey]: { interactionId: interaction.id } },
|
|
496
588
|
});
|
|
497
589
|
return [{ ...state, lifecycle, tools: pending.tools }, events];
|
|
498
590
|
}
|
|
499
591
|
}
|
|
500
592
|
});
|
|
593
|
+
const sse = HttpTransport.sseJson.with();
|
|
594
|
+
const WireEvent = Protocol.jsonEvent(Event);
|
|
595
|
+
const decodeEvent = Schema.decodeUnknownEffect(WireEvent);
|
|
596
|
+
export const transport = {
|
|
597
|
+
id: sse.id,
|
|
598
|
+
prepare: (input) => sse.prepare(input).pipe(Effect.map((http) => ({ http, input }))),
|
|
599
|
+
execute: (prepared, request, runtime) => Effect.gen(function* () {
|
|
600
|
+
const label = `${request.model.provider}/${request.model.route.id}`;
|
|
601
|
+
const raw = new WeakMap();
|
|
602
|
+
const respond = (execution, resume) => Stream.suspend(() => {
|
|
603
|
+
let token = resume?.token;
|
|
604
|
+
let owner;
|
|
605
|
+
let status;
|
|
606
|
+
let contentSinceToken = false;
|
|
607
|
+
let terminal = false;
|
|
608
|
+
let dropped;
|
|
609
|
+
const pendingTools = new Set();
|
|
610
|
+
return execution.frames.pipe(Stream.mapEffect((frame) => decodeEvent(frame).pipe(Effect.mapError((cause) => ProviderShared.eventError(ADAPTER, `Invalid ${label} stream event`, frame, cause)), Effect.map((event) => {
|
|
611
|
+
raw.set(event, frame);
|
|
612
|
+
switch (event.event_type) {
|
|
613
|
+
case "interaction.created":
|
|
614
|
+
owner = event.interaction.id;
|
|
615
|
+
break;
|
|
616
|
+
case "interaction.status_update":
|
|
617
|
+
status = event.status;
|
|
618
|
+
owner = event.interaction_id ?? owner;
|
|
619
|
+
if (event.continuation_token && event.continuation_token !== token) {
|
|
620
|
+
token = event.continuation_token;
|
|
621
|
+
contentSinceToken = false;
|
|
622
|
+
}
|
|
623
|
+
break;
|
|
624
|
+
case "interaction.completed":
|
|
625
|
+
terminal = true;
|
|
626
|
+
status = event.interaction.status;
|
|
627
|
+
owner = event.interaction.id ?? owner;
|
|
628
|
+
if (event.interaction.continuation_token) {
|
|
629
|
+
token = event.interaction.continuation_token;
|
|
630
|
+
contentSinceToken = false;
|
|
631
|
+
}
|
|
632
|
+
break;
|
|
633
|
+
case "step.start":
|
|
634
|
+
if (event.step.type === "function_call")
|
|
635
|
+
pendingTools.add(event.index);
|
|
636
|
+
if (pendingTools.has(event.index) ||
|
|
637
|
+
event.step.content?.length ||
|
|
638
|
+
event.step.summary?.length ||
|
|
639
|
+
event.step.signature)
|
|
640
|
+
contentSinceToken = true;
|
|
641
|
+
break;
|
|
642
|
+
case "step.delta":
|
|
643
|
+
contentSinceToken = true;
|
|
644
|
+
break;
|
|
645
|
+
case "step.stop":
|
|
646
|
+
if (pendingTools.delete(event.index))
|
|
647
|
+
contentSinceToken = true;
|
|
648
|
+
break;
|
|
649
|
+
}
|
|
650
|
+
return event;
|
|
651
|
+
}))), Stream.takeUntil((event) => event.event_type === "interaction.completed"), Stream.catchIf((error) => error.reason._tag === "Transport" && error.reason.code !== "Timeout", (error) => {
|
|
652
|
+
dropped = error;
|
|
653
|
+
return Stream.empty;
|
|
654
|
+
}), Stream.concat(Stream.suspend(() => {
|
|
655
|
+
const needsContinuation = status === CONTINUATION;
|
|
656
|
+
const resumable = needsContinuation || (!terminal && (status === undefined || status === "in_progress"));
|
|
657
|
+
const newToken = token !== resume?.token;
|
|
658
|
+
// An interrupted tool call may carry arguments across the checkpoint. Don't finalize it on EOF.
|
|
659
|
+
if (token &&
|
|
660
|
+
resumable &&
|
|
661
|
+
!contentSinceToken &&
|
|
662
|
+
(terminal || pendingTools.size === 0) &&
|
|
663
|
+
(!needsContinuation || newToken)) {
|
|
664
|
+
const reconnectsWithoutProgress = newToken ? 0 : (resume?.reconnectsWithoutProgress ?? 0) + 1;
|
|
665
|
+
const lastError = dropped ?? (newToken ? undefined : resume?.lastError);
|
|
666
|
+
if (reconnectsWithoutProgress > MAX_STREAM_RECONNECTS_WITHOUT_PROGRESS) {
|
|
667
|
+
if (!lastError)
|
|
668
|
+
return Stream.empty;
|
|
669
|
+
return Stream.fail(new AIError({
|
|
670
|
+
reason: new InvalidProviderOutputError({
|
|
671
|
+
route: label,
|
|
672
|
+
message: lastError.reason.message,
|
|
673
|
+
classification: "incomplete-stream",
|
|
674
|
+
cause: lastError,
|
|
675
|
+
http: lastError.reason.http,
|
|
676
|
+
}),
|
|
677
|
+
}));
|
|
678
|
+
}
|
|
679
|
+
return Stream.concat(Stream.succeed(new NextRequest()), next({ token, owner: newToken ? owner : resume?.owner, reconnectsWithoutProgress, lastError }));
|
|
680
|
+
}
|
|
681
|
+
if (dropped)
|
|
682
|
+
return Stream.fail(dropped);
|
|
683
|
+
if (terminal && needsContinuation && !token)
|
|
684
|
+
return Stream.fail(ProviderShared.eventError(label, "Google Interactions continued without a token"));
|
|
685
|
+
// No safe checkpoint. Leave EOF for the route's incomplete-stream check.
|
|
686
|
+
return Stream.empty;
|
|
687
|
+
})));
|
|
688
|
+
});
|
|
689
|
+
const next = (resume) => {
|
|
690
|
+
const body = prepared.input.body;
|
|
691
|
+
return Stream.unwrap(sse
|
|
692
|
+
.prepare({
|
|
693
|
+
...prepared.input,
|
|
694
|
+
body: {
|
|
695
|
+
...body,
|
|
696
|
+
continuation_token: resume.token,
|
|
697
|
+
...(body.store && resume.owner ? { input: undefined, previous_interaction_id: resume.owner } : {}),
|
|
698
|
+
},
|
|
699
|
+
})
|
|
700
|
+
.pipe(Effect.flatMap((continued) => sse.execute(continued, request, runtime)), Effect.map((execution) => respond(execution, resume))));
|
|
701
|
+
};
|
|
702
|
+
const first = yield* sse.execute(prepared.http, request, runtime);
|
|
703
|
+
return {
|
|
704
|
+
frames: respond(first),
|
|
705
|
+
http: first.http,
|
|
706
|
+
body: (frame) => raw.get(frame),
|
|
707
|
+
raw: (frame) => {
|
|
708
|
+
const body = raw.get(frame);
|
|
709
|
+
return body === undefined ? undefined : ProviderShared.decodeJson(body);
|
|
710
|
+
},
|
|
711
|
+
};
|
|
712
|
+
}),
|
|
713
|
+
};
|
|
501
714
|
// =============================================================================
|
|
502
715
|
// Protocol And Route
|
|
503
716
|
// =============================================================================
|
|
@@ -506,16 +719,21 @@ export const protocol = Protocol.make({
|
|
|
506
719
|
sanitizer: "gemini",
|
|
507
720
|
body: { schema: Body, from: fromRequest },
|
|
508
721
|
stream: {
|
|
509
|
-
event:
|
|
722
|
+
event: Schema.Union([Schema.instanceOf(NextRequest), Schema.toType(Event), WireEvent]),
|
|
510
723
|
initial: (request) => ({
|
|
511
724
|
route: `${request.model.provider}/${request.model.route.id}`,
|
|
512
725
|
metadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
|
|
513
726
|
lifecycle: Lifecycle.initial(),
|
|
727
|
+
hop: 0,
|
|
728
|
+
hasToolCalls: false,
|
|
729
|
+
continuedUsage: [],
|
|
514
730
|
steps: {},
|
|
515
731
|
tools: ToolStream.empty(),
|
|
516
732
|
}),
|
|
517
733
|
step,
|
|
518
|
-
terminal: (event) => event
|
|
734
|
+
terminal: (event) => !(event instanceof NextRequest) &&
|
|
735
|
+
event.event_type === "interaction.completed" &&
|
|
736
|
+
event.interaction.status !== CONTINUATION,
|
|
519
737
|
},
|
|
520
738
|
});
|
|
521
739
|
export const route = Route.make({
|
|
@@ -525,6 +743,6 @@ export const route = Route.make({
|
|
|
525
743
|
protocol,
|
|
526
744
|
endpoint: Endpoint.path("/interactions", { baseURL: DEFAULT_BASE_URL }),
|
|
527
745
|
auth: Auth.none,
|
|
528
|
-
|
|
746
|
+
transport,
|
|
529
747
|
});
|
|
530
748
|
export * as GoogleInteractions from "./google-interactions.js";
|
|
@@ -24,8 +24,8 @@ const Body = Schema.Struct({
|
|
|
24
24
|
tools: optionalArray(Schema.Union([FunctionTool, WebSearch])),
|
|
25
25
|
});
|
|
26
26
|
const fromRequest = Effect.fn("MetaMessages.fromRequest")(function* (request) {
|
|
27
|
-
const
|
|
28
|
-
const
|
|
27
|
+
const body = yield* AnthropicMessages.protocol.body.from(request);
|
|
28
|
+
const definitions = ProviderShared.flattenTools(request.tools);
|
|
29
29
|
return {
|
|
30
30
|
...body,
|
|
31
31
|
messages: body.messages.map((message) => {
|
|
@@ -43,7 +43,7 @@ const fromRequest = Effect.fn("MetaMessages.fromRequest")(function* (request) {
|
|
|
43
43
|
tools: body.tools === undefined
|
|
44
44
|
? undefined
|
|
45
45
|
: yield* Effect.forEach(body.tools, (tool, index) => Effect.gen(function* () {
|
|
46
|
-
const native =
|
|
46
|
+
const native = definitions[index]?.native;
|
|
47
47
|
if (native === undefined)
|
|
48
48
|
return tool;
|
|
49
49
|
const search = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(MetaResponses.WebSearch))(native.meta);
|
|
@@ -121,12 +121,18 @@ const fromRequest = Effect.fn("MiniMaxVideo.fromRequest")(function* (request) {
|
|
|
121
121
|
...(request.end === undefined ? [] : [yield* item(request.end, "last_frame")]),
|
|
122
122
|
...(yield* Effect.forEach(request.references ?? [], reference)),
|
|
123
123
|
];
|
|
124
|
+
// H3 rejects a t2va (text-only) request without a concrete `ratio`, so `auto` and unset default to `16:9`.
|
|
125
|
+
const ratio = content.length === 1 && (request.aspect === undefined || request.aspect === "auto")
|
|
126
|
+
? "16:9"
|
|
127
|
+
: request.aspect === "auto"
|
|
128
|
+
? "adaptive"
|
|
129
|
+
: request.aspect;
|
|
124
130
|
return MediaProtocol.json(mergeJsonRecords({
|
|
125
131
|
model: request.model.id,
|
|
126
132
|
content,
|
|
127
133
|
resolution: resolution(request),
|
|
128
134
|
duration: request.duration === undefined ? undefined : seconds(request.duration),
|
|
129
|
-
ratio
|
|
135
|
+
ratio,
|
|
130
136
|
}, request.providerOptions, request.http?.body) ?? {});
|
|
131
137
|
});
|
|
132
138
|
/** v1 documents URLs and data URLs only, so MiniMax file references aren't sent. */
|
|
@@ -123,6 +123,7 @@ export declare const MistralBody: Schema.Struct<{
|
|
|
123
123
|
readonly prompt_mode: Schema.optional<Schema.Literal<"reasoning">>;
|
|
124
124
|
}>;
|
|
125
125
|
export type MistralBody = Schema.Schema.Type<typeof MistralBody>;
|
|
126
|
+
/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
|
|
126
127
|
export declare const fromRequest: (request: LLMRequest<import("../schema/options.js").LanguageModel<{
|
|
127
128
|
readonly [x: string]: unknown;
|
|
128
129
|
}, import("../route/client.js").CompactionOperations | undefined>>) => Effect.Effect<{
|
|
@@ -283,6 +283,7 @@ const lowerTool = (tool) => ({
|
|
|
283
283
|
type: "function",
|
|
284
284
|
function: { name: tool.name, description: tool.description, parameters: tool.inputSchema, strict: false },
|
|
285
285
|
});
|
|
286
|
+
/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
|
|
286
287
|
export const fromRequest = Effect.fn("MistralChat.fromRequest")(function* (request) {
|
|
287
288
|
const options = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(MistralOptions))(request.providerOptions ?? {});
|
|
288
289
|
if (options.reasoningEffort !== undefined && options.promptMode !== undefined)
|
|
@@ -295,11 +296,10 @@ export const fromRequest = Effect.fn("MistralChat.fromRequest")(function* (reque
|
|
|
295
296
|
tool: (name) => ({ type: "function", function: { name } }),
|
|
296
297
|
})
|
|
297
298
|
: undefined;
|
|
298
|
-
const flattened = ProviderShared.flattenToolRequest(request);
|
|
299
299
|
return {
|
|
300
300
|
model: request.model.id,
|
|
301
|
-
messages: yield* lowerMessages(
|
|
302
|
-
tools:
|
|
301
|
+
messages: yield* lowerMessages(request),
|
|
302
|
+
tools: request.tools.length > 0 ? ProviderShared.flattenTools(request.tools).map(lowerTool) : undefined,
|
|
303
303
|
tool_choice: toolChoice,
|
|
304
304
|
stream: true,
|
|
305
305
|
max_tokens: request.maxTokens,
|
|
@@ -57,6 +57,8 @@ const comparable = (value) => {
|
|
|
57
57
|
name: value.name,
|
|
58
58
|
arguments: json(value.arguments),
|
|
59
59
|
};
|
|
60
|
+
if (value.type === "custom_tool_call")
|
|
61
|
+
return { type: value.type, call_id: value.call_id, name: value.name, input: value.input };
|
|
60
62
|
if (value.type === "reasoning")
|
|
61
63
|
return {
|
|
62
64
|
type: value.type,
|