@opencode/ai 0.0.0-dev-1320 → 0.0.0-dev-1321

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.
@@ -1,6 +1,7 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  import { Route } from "../route/client.js";
3
3
  import { Protocol } from "../route/protocol.js";
4
+ import { HttpTransport, type Transport, type TransportPrepareInput } from "../route/transport/index.js";
4
5
  import { AIError } from "../schema/index.js";
5
6
  import { Media } from "../media.js";
6
7
  import { Lifecycle } from "./utils/lifecycle.js";
@@ -15,6 +16,76 @@ declare const Options: Schema.Struct<{
15
16
  }>;
16
17
  export type OptionsInput = typeof Options.Encoded;
17
18
  export type ProviderOptionsInput = OptionsInput;
19
+ declare const Body: Schema.Struct<{
20
+ readonly model: Schema.String;
21
+ readonly input: Schema.optional<Schema.$Array<Schema.Union<readonly [Schema.Struct<{
22
+ readonly type: Schema.Literals<readonly ["user_input", "model_output"]>;
23
+ readonly content: Schema.$Array<Schema.Union<readonly [Schema.Struct<{
24
+ readonly type: Schema.Literal<"text">;
25
+ readonly text: Schema.String;
26
+ }>, Schema.Struct<{
27
+ readonly type: Schema.Literals<readonly ["image", "audio", "video", "document"]>;
28
+ readonly data: Schema.optional<Schema.String>;
29
+ readonly uri: Schema.optional<Schema.String>;
30
+ readonly mime_type: Schema.String;
31
+ }>]>>;
32
+ }>, Schema.Struct<{
33
+ readonly type: Schema.Literal<"thought">;
34
+ readonly signature: Schema.optional<Schema.String>;
35
+ readonly summary: Schema.optional<Schema.$Array<Schema.Struct<{
36
+ readonly type: Schema.Literal<"text">;
37
+ readonly text: Schema.String;
38
+ }>>>;
39
+ }>, Schema.Struct<{
40
+ readonly type: Schema.Literal<"function_call">;
41
+ readonly id: Schema.String;
42
+ readonly name: Schema.String;
43
+ readonly arguments: Schema.Unknown;
44
+ readonly signature: Schema.optional<Schema.String>;
45
+ }>, Schema.Struct<{
46
+ readonly type: Schema.Literal<"function_result">;
47
+ readonly call_id: Schema.String;
48
+ readonly name: Schema.String;
49
+ readonly result: Schema.Unknown;
50
+ readonly is_error: Schema.optional<Schema.Boolean>;
51
+ }>]>>>;
52
+ readonly stream: Schema.Literal<true>;
53
+ readonly store: Schema.Boolean;
54
+ readonly previous_interaction_id: Schema.optional<Schema.String>;
55
+ readonly continuation_token: Schema.optional<Schema.String>;
56
+ readonly system_instruction: Schema.optional<Schema.String>;
57
+ readonly service_tier: Schema.optional<Schema.String>;
58
+ readonly tools: Schema.optional<Schema.$Array<Schema.Struct<{
59
+ readonly type: Schema.Literal<"function">;
60
+ readonly name: Schema.String;
61
+ readonly description: Schema.String;
62
+ readonly parameters: Schema.$Record<Schema.String, Schema.Unknown>;
63
+ }>>>;
64
+ readonly generation_config: Schema.Struct<{
65
+ readonly max_output_tokens: Schema.optional<Schema.Number>;
66
+ readonly temperature: Schema.optional<Schema.Number>;
67
+ readonly top_p: Schema.optional<Schema.Number>;
68
+ readonly seed: Schema.optional<Schema.Number>;
69
+ readonly stop_sequences: Schema.optional<Schema.$Array<Schema.String>>;
70
+ readonly thinking_level: Schema.optional<Schema.declare<import("../schema/options.js").OpenString<"high" | "low" | "medium" | "minimal">, import("../schema/options.js").OpenString<"high" | "low" | "medium" | "minimal">>>;
71
+ readonly thinking_summaries: Schema.optional<Schema.String>;
72
+ readonly tool_choice: Schema.optional<Schema.Union<readonly [Schema.Literals<readonly ["auto", "any", "none"]>, Schema.Struct<{
73
+ readonly allowed_tools: Schema.Struct<{
74
+ readonly mode: Schema.Literal<"any">;
75
+ readonly tools: Schema.$Array<Schema.String>;
76
+ }>;
77
+ }>]>>;
78
+ }>;
79
+ }>;
80
+ declare const RawUsage: Schema.StructWithRest<Schema.Struct<{
81
+ readonly total_input_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
82
+ readonly total_cached_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
83
+ readonly total_output_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
84
+ readonly total_thought_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
85
+ readonly total_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
86
+ readonly raw_prompt_token: Schema.optional<Schema.NullOr<Schema.Number>>;
87
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>;
88
+ type RawUsage = typeof RawUsage.Type;
18
89
  declare const OutputStep: Schema.Struct<{
19
90
  readonly type: Schema.String;
20
91
  readonly id: Schema.optional<Schema.String>;
@@ -31,10 +102,105 @@ declare const OutputStep: Schema.Struct<{
31
102
  }>>>;
32
103
  }>;
33
104
  type OutputStep = typeof OutputStep.Type;
105
+ declare const Event: Schema.Union<readonly [Schema.Struct<{
106
+ readonly event_type: Schema.Literal<"step.start">;
107
+ readonly index: Schema.Number;
108
+ readonly step: Schema.Struct<{
109
+ readonly type: Schema.String;
110
+ readonly id: Schema.optional<Schema.String>;
111
+ readonly name: Schema.optional<Schema.String>;
112
+ readonly arguments: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
113
+ readonly signature: Schema.optional<Schema.String>;
114
+ readonly summary: Schema.optional<Schema.$Array<Schema.Struct<{
115
+ readonly type: Schema.Literal<"text">;
116
+ readonly text: Schema.String;
117
+ }>>>;
118
+ readonly content: Schema.optional<Schema.$Array<Schema.Struct<{
119
+ readonly type: Schema.String;
120
+ readonly text: Schema.optional<Schema.String>;
121
+ }>>>;
122
+ }>;
123
+ }>, Schema.Struct<{
124
+ readonly event_type: Schema.Literal<"step.delta">;
125
+ readonly index: Schema.Number;
126
+ readonly delta: Schema.Union<readonly [Schema.Struct<{
127
+ readonly type: Schema.Literal<"text">;
128
+ readonly text: Schema.String;
129
+ }>, Schema.Struct<{
130
+ readonly type: Schema.Literal<"arguments_delta">;
131
+ readonly arguments: Schema.String;
132
+ }>, Schema.Struct<{
133
+ readonly type: Schema.Literal<"thought_signature">;
134
+ readonly signature: Schema.String;
135
+ }>, Schema.Struct<{
136
+ readonly type: Schema.Literal<"thought_summary">;
137
+ readonly content: Schema.Struct<{
138
+ readonly type: Schema.Literal<"text">;
139
+ readonly text: Schema.String;
140
+ }>;
141
+ }>, Schema.decodeTo<Schema.Struct<{
142
+ readonly type: Schema.Literal<"unknown">;
143
+ readonly rawType: Schema.String;
144
+ }>, Schema.Struct<{
145
+ readonly type: Schema.String;
146
+ }>, never, never>]>;
147
+ }>, Schema.Struct<{
148
+ readonly event_type: Schema.Literal<"step.stop">;
149
+ readonly index: Schema.Number;
150
+ }>, Schema.Struct<{
151
+ readonly event_type: Schema.Literal<"interaction.created">;
152
+ readonly interaction: Schema.Struct<{
153
+ readonly id: Schema.optional<Schema.String>;
154
+ }>;
155
+ }>, Schema.Struct<{
156
+ readonly event_type: Schema.Literal<"interaction.status_update">;
157
+ readonly interaction_id: Schema.optional<Schema.String>;
158
+ readonly status: Schema.String;
159
+ readonly continuation_token: Schema.optional<Schema.NullOr<Schema.String>>;
160
+ readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
161
+ readonly total_input_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
162
+ readonly total_cached_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
163
+ readonly total_output_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
164
+ readonly total_thought_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
165
+ readonly total_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
166
+ readonly raw_prompt_token: Schema.optional<Schema.NullOr<Schema.Number>>;
167
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
168
+ }>, Schema.Struct<{
169
+ readonly event_type: Schema.Literal<"interaction.completed">;
170
+ readonly interaction: Schema.StructWithRest<Schema.Struct<{
171
+ readonly id: Schema.optional<Schema.String>;
172
+ readonly status: Schema.String;
173
+ readonly continuation_token: Schema.optional<Schema.NullOr<Schema.String>>;
174
+ readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
175
+ readonly total_input_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
176
+ readonly total_cached_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
177
+ readonly total_output_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
178
+ readonly total_thought_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
179
+ readonly total_tokens: Schema.optional<Schema.NullOr<Schema.Number>>;
180
+ readonly raw_prompt_token: Schema.optional<Schema.NullOr<Schema.Number>>;
181
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
182
+ readonly errors: Schema.optional<Schema.$Array<Schema.Struct<{
183
+ readonly code: Schema.optional<Schema.String>;
184
+ readonly message: Schema.optional<Schema.String>;
185
+ }>>>;
186
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>;
187
+ }>, Schema.Struct<{
188
+ readonly event_type: Schema.Literal<"error">;
189
+ readonly error: Schema.optionalKey<Schema.Unknown>;
190
+ }>, Schema.decodeTo<Schema.Struct<{
191
+ readonly event_type: Schema.Literal<"unknown">;
192
+ }>, Schema.Struct<{
193
+ readonly event_type: Schema.String;
194
+ }>, never, never>]>;
195
+ type Event = typeof Event.Type;
34
196
  interface ParserState {
35
197
  readonly route: string;
36
198
  readonly metadataKey: string;
37
199
  readonly lifecycle: Lifecycle.State;
200
+ readonly hop: number;
201
+ readonly hasToolCalls: boolean;
202
+ readonly usage?: RawUsage;
203
+ readonly continuedUsage: ReadonlyArray<RawUsage | undefined>;
38
204
  readonly steps: Partial<Record<number, OutputStep>>;
39
205
  readonly tools: ToolStream.State<number>;
40
206
  }
@@ -49,9 +215,17 @@ export declare const mediaContent: (asset: Media.Asset) => Effect.Effect<{
49
215
  data: string;
50
216
  mime_type: string;
51
217
  }, AIError, never>;
218
+ declare class NextRequest {
219
+ }
220
+ type Body = typeof Body.Type;
221
+ export interface Prepared {
222
+ readonly http: HttpTransport.HttpPrepared<string>;
223
+ readonly input: TransportPrepareInput<Body>;
224
+ }
225
+ export declare const transport: Transport<Body, Prepared, Event | NextRequest>;
52
226
  export declare const protocol: Protocol<{
53
227
  readonly model: string;
54
- readonly input: readonly ({
228
+ readonly input?: readonly ({
55
229
  readonly type: "model_output" | "user_input";
56
230
  readonly content: readonly ({
57
231
  readonly type: "text";
@@ -81,10 +255,11 @@ export declare const protocol: Protocol<{
81
255
  readonly name: string;
82
256
  readonly result: unknown;
83
257
  readonly is_error?: boolean | undefined;
84
- })[];
258
+ })[] | undefined;
85
259
  readonly stream: true;
86
260
  readonly store: boolean;
87
261
  readonly previous_interaction_id?: string | undefined;
262
+ readonly continuation_token?: string | undefined;
88
263
  readonly system_instruction?: string | undefined;
89
264
  readonly service_tier?: string | undefined;
90
265
  readonly tools?: readonly {
@@ -110,7 +285,97 @@ export declare const protocol: Protocol<{
110
285
  };
111
286
  } | undefined;
112
287
  };
113
- }, string, {
288
+ }, string | NextRequest | {
289
+ readonly event_type: "unknown";
290
+ } | {
291
+ readonly event_type: "step.start";
292
+ readonly index: number;
293
+ readonly step: {
294
+ readonly type: string;
295
+ readonly id?: string | undefined;
296
+ readonly name?: string | undefined;
297
+ readonly arguments?: {
298
+ readonly [x: string]: unknown;
299
+ } | undefined;
300
+ readonly signature?: string | undefined;
301
+ readonly summary?: readonly {
302
+ readonly type: "text";
303
+ readonly text: string;
304
+ }[] | undefined;
305
+ readonly content?: readonly {
306
+ readonly type: string;
307
+ readonly text?: string | undefined;
308
+ }[] | undefined;
309
+ };
310
+ } | {
311
+ readonly event_type: "step.delta";
312
+ readonly index: number;
313
+ readonly delta: {
314
+ readonly type: "unknown";
315
+ readonly rawType: string;
316
+ } | {
317
+ readonly type: "text";
318
+ readonly text: string;
319
+ } | {
320
+ readonly type: "arguments_delta";
321
+ readonly arguments: string;
322
+ } | {
323
+ readonly type: "thought_signature";
324
+ readonly signature: string;
325
+ } | {
326
+ readonly type: "thought_summary";
327
+ readonly content: {
328
+ readonly type: "text";
329
+ readonly text: string;
330
+ };
331
+ };
332
+ } | {
333
+ readonly event_type: "step.stop";
334
+ readonly index: number;
335
+ } | {
336
+ readonly event_type: "interaction.created";
337
+ readonly interaction: {
338
+ readonly id?: string | undefined;
339
+ };
340
+ } | {
341
+ readonly event_type: "interaction.completed";
342
+ readonly interaction: {
343
+ readonly [x: string]: unknown;
344
+ readonly id?: string | undefined;
345
+ readonly status: string;
346
+ readonly continuation_token?: string | null | undefined;
347
+ readonly usage?: {
348
+ readonly [x: string]: unknown;
349
+ readonly total_input_tokens?: number | null | undefined;
350
+ readonly total_cached_tokens?: number | null | undefined;
351
+ readonly total_output_tokens?: number | null | undefined;
352
+ readonly total_thought_tokens?: number | null | undefined;
353
+ readonly total_tokens?: number | null | undefined;
354
+ readonly raw_prompt_token?: number | null | undefined;
355
+ } | undefined;
356
+ readonly errors?: readonly {
357
+ readonly code?: string | undefined;
358
+ readonly message?: string | undefined;
359
+ }[] | undefined;
360
+ };
361
+ } | {
362
+ readonly event_type: "interaction.status_update";
363
+ readonly interaction_id?: string | undefined;
364
+ readonly status: string;
365
+ readonly continuation_token?: string | null | undefined;
366
+ readonly usage?: {
367
+ readonly [x: string]: unknown;
368
+ readonly total_input_tokens?: number | null | undefined;
369
+ readonly total_cached_tokens?: number | null | undefined;
370
+ readonly total_output_tokens?: number | null | undefined;
371
+ readonly total_thought_tokens?: number | null | undefined;
372
+ readonly total_tokens?: number | null | undefined;
373
+ readonly raw_prompt_token?: number | null | undefined;
374
+ } | undefined;
375
+ } | {
376
+ readonly event_type: "error";
377
+ readonly error?: unknown;
378
+ }, NextRequest | {
114
379
  readonly event_type: "unknown";
115
380
  } | {
116
381
  readonly event_type: "step.start";
@@ -168,6 +433,7 @@ export declare const protocol: Protocol<{
168
433
  readonly [x: string]: unknown;
169
434
  readonly id?: string | undefined;
170
435
  readonly status: string;
436
+ readonly continuation_token?: string | null | undefined;
171
437
  readonly usage?: {
172
438
  readonly [x: string]: unknown;
173
439
  readonly total_input_tokens?: number | null | undefined;
@@ -186,13 +452,23 @@ export declare const protocol: Protocol<{
186
452
  readonly event_type: "interaction.status_update";
187
453
  readonly interaction_id?: string | undefined;
188
454
  readonly status: string;
455
+ readonly continuation_token?: string | null | undefined;
456
+ readonly usage?: {
457
+ readonly [x: string]: unknown;
458
+ readonly total_input_tokens?: number | null | undefined;
459
+ readonly total_cached_tokens?: number | null | undefined;
460
+ readonly total_output_tokens?: number | null | undefined;
461
+ readonly total_thought_tokens?: number | null | undefined;
462
+ readonly total_tokens?: number | null | undefined;
463
+ readonly raw_prompt_token?: number | null | undefined;
464
+ } | undefined;
189
465
  } | {
190
466
  readonly event_type: "error";
191
467
  readonly error?: unknown;
192
468
  }, ParserState>;
193
469
  export declare const route: Route<{
194
470
  readonly model: string;
195
- readonly input: readonly ({
471
+ readonly input?: readonly ({
196
472
  readonly type: "model_output" | "user_input";
197
473
  readonly content: readonly ({
198
474
  readonly type: "text";
@@ -222,10 +498,11 @@ export declare const route: Route<{
222
498
  readonly name: string;
223
499
  readonly result: unknown;
224
500
  readonly is_error?: boolean | undefined;
225
- })[];
501
+ })[] | undefined;
226
502
  readonly stream: true;
227
503
  readonly store: boolean;
228
504
  readonly previous_interaction_id?: string | undefined;
505
+ readonly continuation_token?: string | undefined;
229
506
  readonly system_instruction?: string | undefined;
230
507
  readonly service_tier?: string | undefined;
231
508
  readonly tools?: readonly {
@@ -251,5 +528,5 @@ export declare const route: Route<{
251
528
  };
252
529
  } | undefined;
253
530
  };
254
- }, import("../route/transport/http.js").HttpPrepared<string>, import("../route/client.js").CompactionOperations | undefined>;
531
+ }, Prepared, import("../route/client.js").CompactionOperations | undefined>;
255
532
  export * as GoogleInteractions from "./google-interactions.js";
@@ -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
  // =============================================================================
@@ -67,10 +70,11 @@ const ToolChoice = Schema.Union([
67
70
  ]);
68
71
  const Body = Schema.Struct({
69
72
  model: Schema.String,
70
- input: Schema.Array(InputStep),
73
+ input: Schema.optional(Schema.Array(InputStep)),
71
74
  stream: Schema.Literal(true),
72
75
  store: Schema.Boolean,
73
76
  previous_interaction_id: Schema.optional(Schema.String),
77
+ continuation_token: Schema.optional(Schema.String),
74
78
  system_instruction: Schema.optional(Schema.String),
75
79
  service_tier: Schema.optional(Schema.String),
76
80
  tools: Schema.optional(Schema.Array(Schema.Struct({
@@ -128,6 +132,7 @@ const Delta = Schema.Union([
128
132
  const Interaction = Schema.StructWithRest(Schema.Struct({
129
133
  id: Schema.optional(Schema.String),
130
134
  status: Schema.String,
135
+ continuation_token: optionalNull(Schema.String),
131
136
  usage: Schema.optional(RawUsage),
132
137
  errors: Schema.optional(Schema.Array(Schema.Struct({ code: Schema.optional(Schema.String), message: Schema.optional(Schema.String) }))),
133
138
  }), [Schema.Record(Schema.String, Schema.Unknown)]);
@@ -164,6 +169,8 @@ const Event = Schema.Union([
164
169
  event_type: Schema.Literal("interaction.status_update"),
165
170
  interaction_id: Schema.optional(Schema.String),
166
171
  status: Schema.String,
172
+ continuation_token: optionalNull(Schema.String),
173
+ usage: Schema.optional(RawUsage),
167
174
  }),
168
175
  Schema.Struct({ event_type: Schema.Literal("interaction.completed"), interaction: Interaction }),
169
176
  Schema.Struct({ event_type: Schema.Literal("error"), error: Schema.optionalKey(Schema.Unknown) }),
@@ -323,31 +330,52 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque
323
330
  const metadata = (state, step) => ({
324
331
  [state.metadataKey]: { interactionSignature: step.signature },
325
332
  });
326
- const mapUsage = (usage, key) => {
327
- if (!usage)
333
+ const mapUsage = (usage, key, continued) => {
334
+ if (!usage && continued.every((hop) => !hop))
328
335
  return undefined;
329
- const input = usage.total_input_tokens ?? undefined;
330
- const cached = usage.total_cached_tokens ?? undefined;
331
- const reasoning = usage.total_thought_tokens ?? undefined;
332
- const output = usage.total_output_tokens === undefined || usage.total_output_tokens === null
333
- ? undefined
334
- : usage.total_output_tokens + (reasoning ?? 0);
336
+ const first = continued.length ? continued[0] : usage;
337
+ const hops = [...continued, usage];
338
+ const sum = (field) => ProviderShared.sumTokens(...hops.map((hop) => (hop ? (field(hop) ?? undefined) : undefined)));
339
+ const input = first?.total_input_tokens ?? undefined;
340
+ const cached = first?.total_cached_tokens ?? undefined;
341
+ const reasoning = sum((hop) => hop.total_thought_tokens);
342
+ const text = sum((hop) => hop.total_output_tokens);
343
+ const output = continued.length
344
+ ? ProviderShared.sumTokens(text, reasoning)
345
+ : text === undefined
346
+ ? undefined
347
+ : text + (reasoning ?? 0);
335
348
  return new Usage({
336
- contextTokens: usage.raw_prompt_token ?? input,
349
+ contextTokens: first?.raw_prompt_token ?? input,
337
350
  inputTokens: input,
338
351
  outputTokens: output,
339
352
  nonCachedInputTokens: ProviderShared.subtractTokens(input, cached),
340
353
  cacheReadInputTokens: cached,
341
354
  reasoningTokens: reasoning,
342
- totalTokens: usage.total_tokens ?? undefined,
343
- providerMetadata: { [key]: usage },
355
+ totalTokens: continued.length
356
+ ? ProviderShared.totalTokens(input, output, undefined)
357
+ : (usage?.total_tokens ?? undefined),
358
+ // Keep re-billed input in provider metadata, separate from the logical call's input.
359
+ providerMetadata: {
360
+ [key]: continued.length
361
+ ? {
362
+ total_input_tokens: sum((hop) => hop.total_input_tokens),
363
+ total_cached_tokens: sum((hop) => hop.total_cached_tokens),
364
+ total_output_tokens: text,
365
+ total_thought_tokens: reasoning,
366
+ total_tokens: sum((hop) => hop.total_tokens),
367
+ requests: hops.length,
368
+ }
369
+ : (usage ?? {}),
370
+ },
344
371
  });
345
372
  };
373
+ const blockID = (state, index) => (state.hop === 0 ? String(index) : `${state.hop}:${index}`);
346
374
  const onStart = Effect.fnUntraced(function* (state, index, step) {
347
375
  const events = [];
348
376
  let lifecycle = Lifecycle.stepStart(state.lifecycle, events);
349
377
  let tools = state.tools;
350
- const id = String(index);
378
+ const id = blockID(state, index);
351
379
  if (step.type === "thought") {
352
380
  lifecycle = Lifecycle.reasoningStart(lifecycle, events, id, metadata(state, step));
353
381
  for (const part of step.summary ?? [])
@@ -375,7 +403,16 @@ const onStart = Effect.fnUntraced(function* (state, index, step) {
375
403
  }
376
404
  else
377
405
  return yield* ProviderShared.eventError(ADAPTER, `Unsupported Interactions step: ${step.type}`, encodeJson(step));
378
- return [{ ...state, lifecycle, tools, steps: { ...state.steps, [index]: step } }, events];
406
+ return [
407
+ {
408
+ ...state,
409
+ lifecycle,
410
+ tools,
411
+ hasToolCalls: state.hasToolCalls || step.type === "function_call",
412
+ steps: { ...state.steps, [index]: step },
413
+ },
414
+ events,
415
+ ];
379
416
  });
380
417
  const onDelta = Effect.fnUntraced(function* (state, index, delta) {
381
418
  const step = state.steps[index];
@@ -384,12 +421,15 @@ const onDelta = Effect.fnUntraced(function* (state, index, delta) {
384
421
  const events = [];
385
422
  if (delta.type === "text" && step.type === "model_output")
386
423
  return [
387
- { ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events, String(index), delta.text) },
424
+ { ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events, blockID(state, index), delta.text) },
388
425
  events,
389
426
  ];
390
427
  if (delta.type === "thought_summary" && step.type === "thought")
391
428
  return [
392
- { ...state, lifecycle: Lifecycle.reasoningDelta(state.lifecycle, events, String(index), delta.content.text) },
429
+ {
430
+ ...state,
431
+ lifecycle: Lifecycle.reasoningDelta(state.lifecycle, events, blockID(state, index), delta.content.text),
432
+ },
393
433
  events,
394
434
  ];
395
435
  if (delta.type === "thought_signature") {
@@ -419,12 +459,15 @@ const onStop = Effect.fnUntraced(function* (state, index) {
419
459
  const events = [];
420
460
  if (step.type === "thought")
421
461
  return [
422
- { ...state, lifecycle: Lifecycle.reasoningEnd(state.lifecycle, events, String(index), metadata(state, step)) },
462
+ {
463
+ ...state,
464
+ lifecycle: Lifecycle.reasoningEnd(state.lifecycle, events, blockID(state, index), metadata(state, step)),
465
+ },
423
466
  events,
424
467
  ];
425
468
  if (step.type === "model_output")
426
469
  return [
427
- { ...state, lifecycle: Lifecycle.textEnd(state.lifecycle, events, String(index)) },
470
+ { ...state, lifecycle: Lifecycle.textEnd(state.lifecycle, events, blockID(state, index)) },
428
471
  events,
429
472
  ];
430
473
  const result = yield* ToolStream.finish(ADAPTER, state.tools, index);
@@ -447,7 +490,34 @@ const failureReason = (route, code, message, data, rawBody) => {
447
490
  return new ContentPolicyError({ message, body: rawBody });
448
491
  return classifyProviderFailure({ message, data, rawBody });
449
492
  };
493
+ // Marks a request boundary without adding another logical LLM step or finish.
494
+ class NextRequest {
495
+ }
450
496
  const step = Effect.fnUntraced(function* (state, event) {
497
+ if (event instanceof NextRequest) {
498
+ const pending = yield* ToolStream.finishAll(ADAPTER, state.tools);
499
+ const events = [...pending.events];
500
+ let lifecycle = state.lifecycle;
501
+ for (const [index, step] of Object.entries(state.steps)) {
502
+ const id = blockID(state, Number(index));
503
+ if (step?.type === "thought")
504
+ lifecycle = Lifecycle.reasoningEnd(lifecycle, events, id, metadata(state, step));
505
+ if (step?.type === "model_output")
506
+ lifecycle = Lifecycle.textEnd(lifecycle, events, id);
507
+ }
508
+ return [
509
+ {
510
+ ...state,
511
+ hop: state.hop + 1,
512
+ lifecycle,
513
+ steps: {},
514
+ tools: ToolStream.empty(),
515
+ usage: undefined,
516
+ continuedUsage: [...state.continuedUsage, state.usage],
517
+ },
518
+ events,
519
+ ];
520
+ }
451
521
  switch (event.event_type) {
452
522
  case "step.start":
453
523
  return yield* onStart(state, event.index, event.step);
@@ -455,8 +525,9 @@ const step = Effect.fnUntraced(function* (state, event) {
455
525
  return yield* onDelta(state, event.index, event.delta);
456
526
  case "step.stop":
457
527
  return yield* onStop(state, event.index);
458
- case "interaction.created":
459
528
  case "interaction.status_update":
529
+ return [{ ...state, usage: event.usage ?? state.usage }, []];
530
+ case "interaction.created":
460
531
  case "unknown":
461
532
  return [state, []];
462
533
  case "error": {
@@ -468,6 +539,8 @@ const step = Effect.fnUntraced(function* (state, event) {
468
539
  }
469
540
  case "interaction.completed": {
470
541
  const interaction = event.interaction;
542
+ if (interaction.status === CONTINUATION)
543
+ return [{ ...state, usage: interaction.usage ?? state.usage }, []];
471
544
  if (interaction.status === "failed" || interaction.status === "cancelled") {
472
545
  const messages = (interaction.errors ?? []).flatMap((error) => (error.message?.trim() ? [error.message] : []));
473
546
  const coded = interaction.errors?.find((error) => error.code);
@@ -481,23 +554,143 @@ const step = Effect.fnUntraced(function* (state, event) {
481
554
  return yield* ProviderShared.eventError(ADAPTER, `Unexpected terminal Interactions status: ${interaction.status}`, encodeJson(event));
482
555
  const pending = yield* ToolStream.finishAll(ADAPTER, state.tools);
483
556
  const events = [...pending.events];
484
- const hasToolCalls = Object.values(state.steps).some((item) => item?.type === "function_call");
485
557
  const lifecycle = Lifecycle.finish(state.lifecycle, events, {
486
558
  reason: {
487
- normalized: interaction.status === "requires_action" || (interaction.status === "completed" && hasToolCalls)
559
+ normalized: interaction.status === "requires_action" || (interaction.status === "completed" && state.hasToolCalls)
488
560
  ? "tool-calls"
489
561
  : interaction.status === "incomplete"
490
562
  ? "length"
491
563
  : "stop",
492
564
  raw: interaction.status,
493
565
  },
494
- usage: mapUsage(interaction.usage, state.metadataKey),
566
+ usage: mapUsage(interaction.usage ?? state.usage, state.metadataKey, state.continuedUsage),
495
567
  providerMetadata: { [state.metadataKey]: { interactionId: interaction.id } },
496
568
  });
497
569
  return [{ ...state, lifecycle, tools: pending.tools }, events];
498
570
  }
499
571
  }
500
572
  });
573
+ const sse = HttpTransport.sseJson.with();
574
+ const WireEvent = Protocol.jsonEvent(Event);
575
+ const decodeEvent = Schema.decodeUnknownEffect(WireEvent);
576
+ export const transport = {
577
+ id: sse.id,
578
+ prepare: (input) => sse.prepare(input).pipe(Effect.map((http) => ({ http, input }))),
579
+ execute: (prepared, request, runtime) => Effect.gen(function* () {
580
+ const label = `${request.model.provider}/${request.model.route.id}`;
581
+ const raw = new WeakMap();
582
+ const respond = (execution, resume) => Stream.suspend(() => {
583
+ let token = resume?.token;
584
+ let owner;
585
+ let status;
586
+ let contentSinceToken = false;
587
+ let terminal = false;
588
+ let dropped;
589
+ const pendingTools = new Set();
590
+ 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) => {
591
+ raw.set(event, frame);
592
+ switch (event.event_type) {
593
+ case "interaction.created":
594
+ owner = event.interaction.id;
595
+ break;
596
+ case "interaction.status_update":
597
+ status = event.status;
598
+ owner = event.interaction_id ?? owner;
599
+ if (event.continuation_token && event.continuation_token !== token) {
600
+ token = event.continuation_token;
601
+ contentSinceToken = false;
602
+ }
603
+ break;
604
+ case "interaction.completed":
605
+ terminal = true;
606
+ status = event.interaction.status;
607
+ owner = event.interaction.id ?? owner;
608
+ if (event.interaction.continuation_token) {
609
+ token = event.interaction.continuation_token;
610
+ contentSinceToken = false;
611
+ }
612
+ break;
613
+ case "step.start":
614
+ if (event.step.type === "function_call")
615
+ pendingTools.add(event.index);
616
+ if (pendingTools.has(event.index) ||
617
+ event.step.content?.length ||
618
+ event.step.summary?.length ||
619
+ event.step.signature)
620
+ contentSinceToken = true;
621
+ break;
622
+ case "step.delta":
623
+ contentSinceToken = true;
624
+ break;
625
+ case "step.stop":
626
+ if (pendingTools.delete(event.index))
627
+ contentSinceToken = true;
628
+ break;
629
+ }
630
+ return event;
631
+ }))), Stream.takeUntil((event) => event.event_type === "interaction.completed"), Stream.catchIf((error) => error.reason._tag === "Transport" && error.reason.code !== "Timeout", (error) => {
632
+ dropped = error;
633
+ return Stream.empty;
634
+ }), Stream.concat(Stream.suspend(() => {
635
+ const needsContinuation = status === CONTINUATION;
636
+ const resumable = needsContinuation || (!terminal && (status === undefined || status === "in_progress"));
637
+ const newToken = token !== resume?.token;
638
+ // An interrupted tool call may carry arguments across the checkpoint. Don't finalize it on EOF.
639
+ if (token &&
640
+ resumable &&
641
+ !contentSinceToken &&
642
+ (terminal || pendingTools.size === 0) &&
643
+ (!needsContinuation || newToken)) {
644
+ const reconnectsWithoutProgress = newToken ? 0 : (resume?.reconnectsWithoutProgress ?? 0) + 1;
645
+ const lastError = dropped ?? (newToken ? undefined : resume?.lastError);
646
+ if (reconnectsWithoutProgress > MAX_STREAM_RECONNECTS_WITHOUT_PROGRESS) {
647
+ if (!lastError)
648
+ return Stream.empty;
649
+ return Stream.fail(new AIError({
650
+ reason: new InvalidProviderOutputError({
651
+ route: label,
652
+ message: lastError.reason.message,
653
+ classification: "incomplete-stream",
654
+ cause: lastError,
655
+ http: lastError.reason.http,
656
+ }),
657
+ }));
658
+ }
659
+ return Stream.concat(Stream.succeed(new NextRequest()), next({ token, owner: newToken ? owner : resume?.owner, reconnectsWithoutProgress, lastError }));
660
+ }
661
+ if (dropped)
662
+ return Stream.fail(dropped);
663
+ if (terminal && needsContinuation && !token)
664
+ return Stream.fail(ProviderShared.eventError(label, "Google Interactions continued without a token"));
665
+ // No safe checkpoint. Leave EOF for the route's incomplete-stream check.
666
+ return Stream.empty;
667
+ })));
668
+ });
669
+ const next = (resume) => {
670
+ const body = prepared.input.body;
671
+ return Stream.unwrap(sse
672
+ .prepare({
673
+ ...prepared.input,
674
+ body: {
675
+ ...body,
676
+ continuation_token: resume.token,
677
+ ...(body.store && resume.owner ? { input: undefined, previous_interaction_id: resume.owner } : {}),
678
+ },
679
+ })
680
+ .pipe(Effect.flatMap((continued) => sse.execute(continued, request, runtime)), Effect.map((execution) => respond(execution, resume))));
681
+ };
682
+ const first = yield* sse.execute(prepared.http, request, runtime);
683
+ return {
684
+ frames: respond(first),
685
+ http: first.http,
686
+ body: (frame) => raw.get(frame),
687
+ raw: (frame) => {
688
+ const body = raw.get(frame);
689
+ return body === undefined ? undefined : ProviderShared.decodeJson(body);
690
+ },
691
+ };
692
+ }),
693
+ };
501
694
  // =============================================================================
502
695
  // Protocol And Route
503
696
  // =============================================================================
@@ -506,16 +699,21 @@ export const protocol = Protocol.make({
506
699
  sanitizer: "gemini",
507
700
  body: { schema: Body, from: fromRequest },
508
701
  stream: {
509
- event: Protocol.jsonEvent(Event),
702
+ event: Schema.Union([Schema.instanceOf(NextRequest), Schema.toType(Event), WireEvent]),
510
703
  initial: (request) => ({
511
704
  route: `${request.model.provider}/${request.model.route.id}`,
512
705
  metadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
513
706
  lifecycle: Lifecycle.initial(),
707
+ hop: 0,
708
+ hasToolCalls: false,
709
+ continuedUsage: [],
514
710
  steps: {},
515
711
  tools: ToolStream.empty(),
516
712
  }),
517
713
  step,
518
- terminal: (event) => event.event_type === "interaction.completed",
714
+ terminal: (event) => !(event instanceof NextRequest) &&
715
+ event.event_type === "interaction.completed" &&
716
+ event.interaction.status !== CONTINUATION,
519
717
  },
520
718
  });
521
719
  export const route = Route.make({
@@ -525,6 +723,6 @@ export const route = Route.make({
525
723
  protocol,
526
724
  endpoint: Endpoint.path("/interactions", { baseURL: DEFAULT_BASE_URL }),
527
725
  auth: Auth.none,
528
- framing: Framing.sse,
726
+ transport,
529
727
  });
530
728
  export * as GoogleInteractions from "./google-interactions.js";
@@ -24,7 +24,7 @@ export type Settings = ProviderPackage.Settings & GoogleInteractions.ProviderOpt
24
24
  };
25
25
  export declare const routes: Route<{
26
26
  readonly model: string;
27
- readonly input: readonly ({
27
+ readonly input?: readonly ({
28
28
  readonly type: "model_output" | "user_input";
29
29
  readonly content: readonly ({
30
30
  readonly type: "text";
@@ -54,10 +54,11 @@ export declare const routes: Route<{
54
54
  readonly name: string;
55
55
  readonly result: unknown;
56
56
  readonly is_error?: boolean | undefined;
57
- })[];
57
+ })[] | undefined;
58
58
  readonly stream: true;
59
59
  readonly store: boolean;
60
60
  readonly previous_interaction_id?: string | undefined;
61
+ readonly continuation_token?: string | undefined;
61
62
  readonly system_instruction?: string | undefined;
62
63
  readonly service_tier?: string | undefined;
63
64
  readonly tools?: readonly {
@@ -83,7 +84,7 @@ export declare const routes: Route<{
83
84
  };
84
85
  } | undefined;
85
86
  };
86
- }, import("../route/transport/http.js").HttpPrepared<string>, import("../route/client.js").CompactionOperations | undefined>[];
87
+ }, GoogleInteractions.Prepared, import("../route/client.js").CompactionOperations | undefined>[];
87
88
  export declare const configure: (input?: Config) => {
88
89
  id: string & import("effect/Brand").Brand<"AI.ProviderID">;
89
90
  model: (modelID: string | ModelID) => import("../schema/options.js").LanguageModel<{
@@ -2,7 +2,6 @@ import { GoogleInteractions } from "../protocols/google-interactions.js";
2
2
  import { Auth } from "../route/auth.js";
3
3
  import { Route } from "../route/client.js";
4
4
  import { Endpoint } from "../route/endpoint.js";
5
- import { Framing } from "../route/framing.js";
6
5
  import { ProviderConfigurationError, ProviderID } from "../schema/index.js";
7
6
  import { GoogleVertexShared } from "./google-vertex-shared.js";
8
7
  export const id = ProviderID.make("google-vertex");
@@ -17,7 +16,7 @@ const route = Route.make({
17
16
  const serviceTier = request.providerOptions?.serviceTier;
18
17
  return typeof serviceTier === "string" ? { "x-vertex-ai-llm-shared-request-type": serviceTier } : {};
19
18
  },
20
- framing: Framing.sse,
19
+ transport: GoogleInteractions.transport,
21
20
  });
22
21
  export const routes = [route];
23
22
  const configuredRoute = (input) => {
@@ -102,7 +102,7 @@ export declare const routes: (import("../route.js").Route<{
102
102
  readonly continuationToken?: string | undefined;
103
103
  }, Gemini.Prepared, import("../route.js").CompactionOperations | undefined> | import("../route.js").Route<{
104
104
  readonly model: string;
105
- readonly input: readonly ({
105
+ readonly input?: readonly ({
106
106
  readonly type: "model_output" | "user_input";
107
107
  readonly content: readonly ({
108
108
  readonly type: "text";
@@ -132,10 +132,11 @@ export declare const routes: (import("../route.js").Route<{
132
132
  readonly name: string;
133
133
  readonly result: unknown;
134
134
  readonly is_error?: boolean | undefined;
135
- })[];
135
+ })[] | undefined;
136
136
  readonly stream: true;
137
137
  readonly store: boolean;
138
138
  readonly previous_interaction_id?: string | undefined;
139
+ readonly continuation_token?: string | undefined;
139
140
  readonly system_instruction?: string | undefined;
140
141
  readonly service_tier?: string | undefined;
141
142
  readonly tools?: readonly {
@@ -161,7 +162,7 @@ export declare const routes: (import("../route.js").Route<{
161
162
  };
162
163
  } | undefined;
163
164
  };
164
- }, import("../route/transport/http.js").HttpPrepared<string>, import("../route.js").CompactionOperations | undefined>)[];
165
+ }, GoogleInteractions.Prepared, import("../route.js").CompactionOperations | undefined>)[];
165
166
  export type Config = RequestOptions & ProviderAuthOption<"optional"> & {
166
167
  readonly baseURL?: string;
167
168
  readonly providerOptions?: Gemini.ProviderOptionsInput & GoogleInteractions.ProviderOptionsInput;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
- "version": "0.0.0-dev-1320",
3
+ "version": "0.0.0-dev-1321",
4
4
  "name": "@opencode/ai",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -624,7 +624,7 @@
624
624
  "devDependencies": {
625
625
  "@clack/prompts": "1.0.0-alpha.1",
626
626
  "@effect/platform-node": "4.1.0",
627
- "@opencode/http-recorder": "0.0.0-dev-1320",
627
+ "@opencode/http-recorder": "0.0.0-dev-1321",
628
628
  "@tsconfig/bun": "1.0.9",
629
629
  "@types/bun": "1.4.3",
630
630
  "@typescript/native": "npm:typescript@7.1.0-beta",
@@ -634,7 +634,7 @@
634
634
  "@aws-sdk/credential-providers": "3.1057.0",
635
635
  "@smithy/eventstream-codec": "4.2.14",
636
636
  "@smithy/util-utf8": "4.2.2",
637
- "@opencode/schema": "0.0.0-dev-1320",
637
+ "@opencode/schema": "0.0.0-dev-1321",
638
638
  "aws4fetch": "1.0.20",
639
639
  "effect": "4.1.0",
640
640
  "google-auth-library": "10.5.0"