@opencode/ai 0.0.0-dev-20880 → 0.0.0-dev-20927

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 { 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 { type ProviderOptions } from "../schema/index.js";
5
6
  import { Lifecycle } from "./utils/lifecycle.js";
6
7
  export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
@@ -100,8 +101,54 @@ declare const GeminiBody: Schema.Struct<{
100
101
  readonly thinkingLevel: Schema.optional<Schema.declare<import("../schema/options.js").OpenString<"minimal" | "low" | "medium" | "high">, import("../schema/options.js").OpenString<"minimal" | "low" | "medium" | "high">>>;
101
102
  }>>;
102
103
  }>>;
104
+ continuationToken: Schema.optional<Schema.String>;
103
105
  }>;
104
106
  export type GeminiBody = Schema.Schema.Type<typeof GeminiBody>;
107
+ declare const GeminiUsage: Schema.Struct<{
108
+ readonly cachedContentTokenCount: Schema.optional<Schema.NullOr<Schema.Number>>;
109
+ readonly thoughtsTokenCount: Schema.optional<Schema.NullOr<Schema.Number>>;
110
+ readonly promptTokenCount: Schema.optional<Schema.NullOr<Schema.Number>>;
111
+ readonly candidatesTokenCount: Schema.optional<Schema.NullOr<Schema.Number>>;
112
+ readonly totalTokenCount: Schema.optional<Schema.NullOr<Schema.Number>>;
113
+ }>;
114
+ type GeminiUsage = Schema.Schema.Type<typeof GeminiUsage>;
115
+ declare const GeminiPromptFeedback: Schema.StructWithRest<Schema.Struct<{
116
+ readonly blockReason: Schema.optional<Schema.NullOr<Schema.String>>;
117
+ readonly blockReasonMessage: Schema.optional<Schema.NullOr<Schema.String>>;
118
+ readonly safetyRatings: Schema.optional<Schema.NullOr<Schema.Unknown>>;
119
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>;
120
+ type GeminiPromptFeedback = Schema.Schema.Type<typeof GeminiPromptFeedback>;
121
+ interface ParserState {
122
+ readonly route: string;
123
+ readonly providerMetadataKey: string;
124
+ readonly finishReason?: string;
125
+ readonly hasToolCalls: boolean;
126
+ readonly promptFeedback?: GeminiPromptFeedback;
127
+ readonly usage?: GeminiUsage;
128
+ /** Usage of the earlier requests of a response Gemini continued across requests. */
129
+ readonly continuedUsage?: ReadonlyArray<GeminiUsage>;
130
+ readonly lifecycle: Lifecycle.State;
131
+ readonly reasoningSignature?: string;
132
+ readonly textSignature?: string;
133
+ readonly reasoningId?: string;
134
+ readonly textId?: string;
135
+ readonly nextReasoningId: number;
136
+ readonly nextTextId: number;
137
+ readonly seenCallIds?: ReadonlySet<string>;
138
+ }
139
+ /** Marks where the transport starts another request for the same response; provider JSON can never match it. */
140
+ declare class NextRequest {
141
+ }
142
+ export interface Prepared {
143
+ readonly http: HttpTransport.HttpPrepared<string>;
144
+ readonly input: TransportPrepareInput<GeminiBody>;
145
+ }
146
+ /**
147
+ * SSE transport that continues responses Gemini splits across requests. Chunks carry `continuationToken` checkpoints,
148
+ * and a request that reaches its output cap finishes with `CONTINUATION`. The transport resends the original body with
149
+ * the latest token, which also resumes a request that ended or dropped before finishing.
150
+ */
151
+ export declare const transport: Transport<GeminiBody, Prepared, unknown>;
105
152
  /**
106
153
  * The Gemini protocol — request body construction, body schema, and the
107
154
  * streaming-event state machine shared by Google AI Studio and Vertex Gemini.
@@ -190,7 +237,8 @@ export declare const protocol: Protocol<{
190
237
  } | undefined;
191
238
  readonly maxOutputTokens?: number | undefined;
192
239
  } | undefined;
193
- }, string, {
240
+ readonly continuationToken?: string | undefined;
241
+ }, NextRequest | {
194
242
  readonly error?: unknown;
195
243
  readonly candidates?: readonly {
196
244
  readonly content?: {
@@ -213,13 +261,28 @@ export declare const protocol: Protocol<{
213
261
  readonly thoughtsTokenCount?: number | null | undefined;
214
262
  } | null | undefined;
215
263
  }, {
216
- route: string;
217
- providerMetadataKey: string;
218
- hasToolCalls: boolean;
219
- lifecycle: Lifecycle.State;
220
- nextReasoningId: number;
221
- nextTextId: number;
222
- }>;
264
+ readonly error?: unknown;
265
+ readonly candidates?: readonly {
266
+ readonly content?: {
267
+ readonly parts?: readonly unknown[] | null | undefined;
268
+ readonly role?: "model" | "user" | null | undefined;
269
+ } | null | undefined;
270
+ readonly finishReason?: string | null | undefined;
271
+ }[] | null | undefined;
272
+ readonly promptFeedback?: {
273
+ readonly [x: string]: unknown;
274
+ readonly blockReason?: string | null | undefined;
275
+ readonly blockReasonMessage?: string | null | undefined;
276
+ readonly safetyRatings?: unknown;
277
+ } | null | undefined;
278
+ readonly usageMetadata?: {
279
+ readonly promptTokenCount?: number | null | undefined;
280
+ readonly candidatesTokenCount?: number | null | undefined;
281
+ readonly totalTokenCount?: number | null | undefined;
282
+ readonly cachedContentTokenCount?: number | null | undefined;
283
+ readonly thoughtsTokenCount?: number | null | undefined;
284
+ } | null | undefined;
285
+ } | NextRequest, ParserState>;
223
286
  export declare const route: Route<{
224
287
  readonly contents: readonly {
225
288
  readonly parts?: readonly ({
@@ -304,5 +367,6 @@ export declare const route: Route<{
304
367
  } | undefined;
305
368
  readonly maxOutputTokens?: number | undefined;
306
369
  } | undefined;
307
- }, import("../route/transport/http.js").HttpPrepared<string>, import("../route/client.js").CompactionOperations | undefined>;
370
+ readonly continuationToken?: string | undefined;
371
+ }, Prepared, import("../route/client.js").CompactionOperations | undefined>;
308
372
  export * as Gemini from "./gemini.js";
@@ -1,10 +1,10 @@
1
- import { Effect, Option, Schema } from "effect";
1
+ import { Effect, Option, Schema, Stream } from "effect";
2
2
  import { Tool } from "@opencode/schema/tool";
3
3
  import { Route } from "../route/client.js";
4
4
  import { Auth } from "../route/auth.js";
5
5
  import { Endpoint } from "../route/endpoint.js";
6
- import { Framing } from "../route/framing.js";
7
6
  import { Protocol } from "../route/protocol.js";
7
+ import { HttpTransport, } from "../route/transport/index.js";
8
8
  import { AIError, LLMEvent, Usage, } from "../schema/index.js";
9
9
  import { classifyProviderFailure } from "../provider-error.js";
10
10
  import { Media } from "../media.js";
@@ -12,6 +12,7 @@ import { JsonObject, knownString, lenient, optionalArray, optionalNull, Provider
12
12
  import { GeminiGenerateContent } from "./utils/gemini-generate-content.js";
13
13
  import { Lifecycle } from "./utils/lifecycle.js";
14
14
  const ADAPTER = "gemini";
15
+ const CONTINUATION = "CONTINUATION";
15
16
  // Google documents this sentinel for replaying Gemini 3 function calls after their original signature was lost.
16
17
  const SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator";
17
18
  // Gemini 2.5 rejects a budget under the model's minimum: 512 on Flash-Lite, the highest, and 128 on Pro.
@@ -162,6 +163,7 @@ const GeminiBodyFields = {
162
163
  tools: optionalArray(GeminiTool),
163
164
  toolConfig: Schema.optional(GeminiToolConfig),
164
165
  generationConfig: Schema.optional(GeminiGenerationConfig),
166
+ continuationToken: Schema.optional(Schema.String),
165
167
  };
166
168
  const GeminiBody = Schema.Struct(GeminiBodyFields);
167
169
  const GeminiUsage = Schema.Struct({
@@ -403,7 +405,7 @@ const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request) {
403
405
  // `cachedContentTokenCount` subset. `candidatesTokenCount` is *exclusive*
404
406
  // of `thoughtsTokenCount` — visible-only, not a total — so we sum the two
405
407
  // to produce the inclusive `outputTokens` the rest of the contract expects.
406
- const mapUsage = (usage, metadataKey) => {
408
+ const mapUsage = (usage, metadataKey, metadata = usage ?? {}) => {
407
409
  if (!usage)
408
410
  return undefined;
409
411
  // Explicit provider nulls decode as `null`; normalize to `undefined` so the
@@ -425,7 +427,26 @@ const mapUsage = (usage, metadataKey) => {
425
427
  cacheReadInputTokens: cached,
426
428
  reasoningTokens: thoughts,
427
429
  totalTokens: ProviderShared.totalTokens(promptTokens, outputTokens, usage.totalTokenCount ?? undefined),
428
- providerMetadata: providerMetadata(metadataKey, usage),
430
+ providerMetadata: providerMetadata(metadataKey, metadata),
431
+ });
432
+ };
433
+ // Each continued request re-bills the output so far as input. Reporting the first request's input with all output keeps
434
+ // input plus output equal to the response's final context size, under-reporting billed input; the summed billed counts
435
+ // remain in provider metadata.
436
+ const mapContinuedUsage = (requests, metadataKey) => {
437
+ const sum = (field) => ProviderShared.sumTokens(...requests.map((usage) => usage[field] ?? undefined));
438
+ return mapUsage({
439
+ promptTokenCount: requests[0].promptTokenCount,
440
+ cachedContentTokenCount: requests[0].cachedContentTokenCount,
441
+ candidatesTokenCount: sum("candidatesTokenCount"),
442
+ thoughtsTokenCount: sum("thoughtsTokenCount"),
443
+ }, metadataKey, {
444
+ promptTokenCount: sum("promptTokenCount"),
445
+ cachedContentTokenCount: sum("cachedContentTokenCount"),
446
+ candidatesTokenCount: sum("candidatesTokenCount"),
447
+ thoughtsTokenCount: sum("thoughtsTokenCount"),
448
+ totalTokenCount: sum("totalTokenCount"),
449
+ requests: requests.length,
429
450
  });
430
451
  };
431
452
  const mapFinishReason = (finishReason, hasToolCalls) => {
@@ -451,7 +472,7 @@ const finish = (state) => {
451
472
  // the "nothing to finish" check below keeps its meaning.
452
473
  const promptBlockReason = state.finishReason === undefined ? (state.promptFeedback?.blockReason ?? undefined) : undefined;
453
474
  const finishReason = state.finishReason ?? promptBlockReason;
454
- if (finishReason === undefined && state.usage === undefined)
475
+ if (finishReason === undefined && state.usage === undefined && state.continuedUsage === undefined)
455
476
  return [];
456
477
  const events = [];
457
478
  let lifecycle = state.lifecycle;
@@ -468,7 +489,9 @@ const finish = (state) => {
468
489
  normalized: promptBlockReason === undefined ? mapFinishReason(finishReason, state.hasToolCalls) : "content-filter",
469
490
  raw: finishReason,
470
491
  },
471
- usage: state.usage,
492
+ usage: state.continuedUsage === undefined
493
+ ? mapUsage(state.usage, state.providerMetadataKey)
494
+ : mapContinuedUsage([...state.continuedUsage, state.usage ?? {}], state.providerMetadataKey),
472
495
  providerMetadata: state.promptFeedback === undefined
473
496
  ? undefined
474
497
  : providerMetadata(state.providerMetadataKey, { promptFeedback: state.promptFeedback }),
@@ -476,6 +499,18 @@ const finish = (state) => {
476
499
  return events;
477
500
  };
478
501
  const step = (state, event) => {
502
+ // Usage is cumulative within one request, so the next request of the same response counts from zero.
503
+ if (event instanceof NextRequest)
504
+ return Effect.succeed([
505
+ {
506
+ ...state,
507
+ finishReason: undefined,
508
+ promptFeedback: undefined,
509
+ usage: undefined,
510
+ continuedUsage: [...(state.continuedUsage ?? []), state.usage ?? {}],
511
+ },
512
+ [],
513
+ ]);
479
514
  if (ProviderShared.isRecord(event.error)) {
480
515
  const body = ProviderShared.encodeJson(event);
481
516
  return Effect.fail(new AIError({
@@ -492,21 +527,17 @@ const step = (state, event) => {
492
527
  }
493
528
  if ("error" in event)
494
529
  return Effect.fail(ProviderShared.eventError(state.route, `Invalid ${state.route} stream event`, ProviderShared.encodeJson(event)));
530
+ const candidate = event.candidates?.[0];
495
531
  const nextState = {
496
532
  ...state,
497
533
  promptFeedback: event.promptFeedback ?? state.promptFeedback,
498
- usage: event.usageMetadata
499
- ? (mapUsage(event.usageMetadata, state.providerMetadataKey) ?? state.usage)
500
- : state.usage,
534
+ usage: event.usageMetadata ?? state.usage,
535
+ finishReason: candidate?.finishReason ?? state.finishReason,
501
536
  };
502
- const candidate = event.candidates?.[0];
503
537
  if (candidate?.finishReason && mapFinishReason(candidate.finishReason, state.hasToolCalls) === "error")
504
538
  return Effect.fail(ProviderShared.eventError(state.route, `Gemini stopped with ${candidate.finishReason}`, ProviderShared.encodeJson(event)));
505
539
  if (!candidate?.content)
506
- return Effect.succeed([
507
- { ...nextState, finishReason: candidate?.finishReason ?? nextState.finishReason },
508
- [],
509
- ]);
540
+ return Effect.succeed([nextState, []]);
510
541
  const events = [];
511
542
  let hasToolCalls = nextState.hasToolCalls;
512
543
  let lifecycle = nextState.lifecycle;
@@ -625,12 +656,75 @@ const step = (state, event) => {
625
656
  nextReasoningId,
626
657
  nextTextId,
627
658
  seenCallIds,
628
- finishReason: candidate.finishReason ?? nextState.finishReason,
629
659
  },
630
660
  events,
631
661
  ]);
632
662
  };
633
663
  // =============================================================================
664
+ // Transport
665
+ // =============================================================================
666
+ const GeminiCheckpoint = Schema.Struct({
667
+ candidates: optionalNull(Schema.Array(Schema.Struct({
668
+ finishReason: optionalNull(Schema.String),
669
+ continuationToken: optionalNull(Schema.String),
670
+ }))),
671
+ });
672
+ const decodeCheckpoint = Schema.decodeUnknownOption(GeminiCheckpoint);
673
+ /** Marks where the transport starts another request for the same response; provider JSON can never match it. */
674
+ class NextRequest {
675
+ }
676
+ const sse = HttpTransport.sseJson.with();
677
+ /**
678
+ * SSE transport that continues responses Gemini splits across requests. Chunks carry `continuationToken` checkpoints,
679
+ * and a request that reaches its output cap finishes with `CONTINUATION`. The transport resends the original body with
680
+ * the latest token, which also resumes a request that ended or dropped before finishing.
681
+ */
682
+ export const transport = {
683
+ id: sse.id,
684
+ prepare: (input) => sse.prepare(input).pipe(Effect.map((http) => ({ http, input }))),
685
+ execute: (prepared, request, runtime) => Effect.gen(function* () {
686
+ const route = request.model.route.id;
687
+ const label = `${request.model.provider}/${route}`;
688
+ // Frames are parsed once here, so errors recover each frame's raw text for their body.
689
+ const raw = new WeakMap();
690
+ const respond = (execution) => Stream.suspend(() => {
691
+ let token;
692
+ let finishReason;
693
+ let dropped;
694
+ return execution.frames.pipe(Stream.mapEffect((frame) => ProviderShared.parseJson(route, frame, `Invalid ${label} stream event`).pipe(Effect.map((event) => {
695
+ if (typeof event === "object" && event !== null)
696
+ raw.set(event, frame);
697
+ const candidate = Option.getOrUndefined(decodeCheckpoint(event))?.candidates?.[0];
698
+ token = candidate?.continuationToken ?? (candidate?.finishReason ? undefined : token);
699
+ finishReason = candidate?.finishReason ?? finishReason;
700
+ return event;
701
+ }))), Stream.catchIf(
702
+ // A connection failure may resume; a timeout keeps its meaning and ends the response.
703
+ (error) => error.reason._tag === "Transport" && error.reason.code !== "Timeout", (error) => {
704
+ dropped = error;
705
+ return Stream.empty;
706
+ }), Stream.concat(Stream.suspend(() => {
707
+ if (token !== undefined && (finishReason === undefined || finishReason === CONTINUATION))
708
+ return Stream.concat(Stream.succeed(new NextRequest()), next(token));
709
+ if (dropped)
710
+ return Stream.fail(dropped);
711
+ if (finishReason === CONTINUATION)
712
+ return Stream.fail(ProviderShared.eventError(label, "Gemini continued the response without a token"));
713
+ return Stream.empty;
714
+ })));
715
+ });
716
+ const next = (continuationToken) => Stream.unwrap(sse
717
+ .prepare({ ...prepared.input, body: { ...prepared.input.body, continuationToken } })
718
+ .pipe(Effect.flatMap((continued) => sse.execute(continued, request, runtime)), Effect.map(respond)));
719
+ const first = yield* sse.execute(prepared.http, request, runtime);
720
+ return {
721
+ frames: respond(first),
722
+ http: first.http,
723
+ body: (frame) => (typeof frame === "object" && frame !== null ? raw.get(frame) : undefined),
724
+ };
725
+ }),
726
+ };
727
+ // =============================================================================
634
728
  // Protocol And Gemini Route
635
729
  // =============================================================================
636
730
  /**
@@ -646,7 +740,7 @@ export const protocol = Protocol.make({
646
740
  // Gemini's schema rules are this API's default, including for tuned endpoints whose IDs do not name Gemini.
647
741
  sanitizer: "gemini",
648
742
  stream: {
649
- event: Protocol.jsonEvent(GeminiEvent),
743
+ event: Schema.Union([Schema.instanceOf(NextRequest), GeminiEvent]),
650
744
  initial: (request) => ({
651
745
  route: `${request.model.provider}/${request.model.route.id}`,
652
746
  providerMetadataKey: request.model.route.providerMetadataKey ?? String(request.model.provider),
@@ -669,6 +763,6 @@ export const route = Route.make({
669
763
  baseURL: DEFAULT_BASE_URL,
670
764
  }),
671
765
  auth: Auth.none,
672
- framing: Framing.sse,
766
+ transport,
673
767
  });
674
768
  export * as Gemini from "./gemini.js";
@@ -109,7 +109,8 @@ export declare const routes: Route<{
109
109
  } | undefined;
110
110
  readonly maxOutputTokens?: number | undefined;
111
111
  } | undefined;
112
- }, import("../route/transport/http.js").HttpPrepared<string>, import("../route/client.js").CompactionOperations | undefined>[];
112
+ readonly continuationToken?: string | undefined;
113
+ }, Gemini.Prepared, import("../route/client.js").CompactionOperations | undefined>[];
113
114
  export declare const configure: (input?: Config) => {
114
115
  id: string & import("effect/Brand").Brand<"AI.ProviderID">;
115
116
  model: (modelID: string | ModelID) => import("../schema/options.js").LanguageModel<GeminiOptionsInput, import("../route/client.js").CompactionOperations | undefined>;
@@ -4,7 +4,6 @@ import { ProviderShared } from "../protocols/shared.js";
4
4
  import { Auth } from "../route/auth.js";
5
5
  import { Route } from "../route/client.js";
6
6
  import { Endpoint } from "../route/endpoint.js";
7
- import { Framing } from "../route/framing.js";
8
7
  import { ProviderConfigurationError, ProviderID } from "../schema/index.js";
9
8
  import { GoogleVertexShared } from "./google-vertex-shared.js";
10
9
  export const id = ProviderID.make("google-vertex");
@@ -37,7 +36,7 @@ const route = Route.make({
37
36
  const serviceTier = request.providerOptions?.serviceTier;
38
37
  return typeof serviceTier === "string" ? { "x-vertex-ai-llm-shared-request-type": serviceTier } : {};
39
38
  },
40
- framing: Framing.sse,
39
+ transport: Gemini.transport,
41
40
  });
42
41
  export const routes = [route];
43
42
  const configuredRoute = (input, modelID) => {
@@ -96,7 +96,8 @@ export declare const routes: (import("../route/client.js").Route<{
96
96
  } | undefined;
97
97
  readonly maxOutputTokens?: number | undefined;
98
98
  } | undefined;
99
- }, import("../route/transport/http.js").HttpPrepared<string>, import("../route/client.js").CompactionOperations | undefined> | import("../route/client.js").Route<{
99
+ readonly continuationToken?: string | undefined;
100
+ }, Gemini.Prepared, import("../route/client.js").CompactionOperations | undefined> | import("../route/client.js").Route<{
100
101
  readonly input: readonly ({
101
102
  readonly type: "user_input" | "model_output";
102
103
  readonly content: readonly ({
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-20880",
3
+ "version": "0.0.0-dev-20927",
4
4
  "name": "@opencode/ai",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -34,7 +34,7 @@
34
34
  "devDependencies": {
35
35
  "@clack/prompts": "1.0.0-alpha.1",
36
36
  "@effect/platform-node": "4.0.1",
37
- "@opencode/http-recorder": "0.0.0-dev-20880",
37
+ "@opencode/http-recorder": "0.0.0-dev-20927",
38
38
  "@tsconfig/bun": "1.0.9",
39
39
  "@types/bun": "1.4.0",
40
40
  "@typescript/native-preview": "7.0.0-dev.20251207.1",
@@ -44,7 +44,7 @@
44
44
  "@aws-sdk/credential-providers": "3.1057.0",
45
45
  "@smithy/eventstream-codec": "4.2.14",
46
46
  "@smithy/util-utf8": "4.2.2",
47
- "@opencode/schema": "0.0.0-dev-20880",
47
+ "@opencode/schema": "0.0.0-dev-20927",
48
48
  "aws4fetch": "1.0.20",
49
49
  "effect": "4.0.1",
50
50
  "google-auth-library": "10.5.0"