@effect-uai/google 0.11.0 → 0.12.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/codec.d.mts CHANGED
@@ -2,12 +2,22 @@ import { Option, Schema } from "effect";
2
2
  import { CommonRequest } from "@effect-uai/core/LanguageModel";
3
3
  import { ToolDescriptor } from "@effect-uai/core/Tool";
4
4
  import { Turn } from "@effect-uai/core/Turn";
5
- import { HistoryItem } from "@effect-uai/core/Items";
5
+ import { Annotation, HistoryItem } from "@effect-uai/core/Items";
6
6
 
7
7
  //#region src/codec.d.ts
8
8
  declare namespace codec_d_exports {
9
- export { AccumulatedFunctionCall, Accumulator, ChunkPart, ChunkResult, GenerationConfig, RequestBody, RequestTool, ThinkingConfig, WireChunk, accumulatorToTurn, buildRequestBody, emptyAccumulator, hasUrlImageSource, ingestChunk };
9
+ export { AccumulatedFunctionCall, Accumulator, ChunkPart, ChunkResult, GenerationConfig, GroundingMetadata, RequestBody, RequestTool, ThinkingConfig, WireChunk, accumulatorToTurn, buildRequestBody, emptyAccumulator, groundingToAnnotations, hasUrlImageSource, ingestChunk };
10
10
  }
11
+ declare const GroundingMetadata: Schema.Struct<{
12
+ readonly groundingChunks: Schema.optional<Schema.NullOr<Schema.$Array<Schema.Struct<{
13
+ readonly web: Schema.optional<Schema.NullOr<Schema.Struct<{
14
+ readonly uri: Schema.optional<Schema.NullOr<Schema.String>>;
15
+ readonly title: Schema.optional<Schema.NullOr<Schema.String>>;
16
+ }>>>;
17
+ }>>>>;
18
+ }>;
19
+ type GroundingMetadata = typeof GroundingMetadata.Type;
20
+ declare const groundingToAnnotations: (...metas: ReadonlyArray<GroundingMetadata | null | undefined>) => ReadonlyArray<Annotation>;
11
21
  declare const WireChunk: Schema.Struct<{
12
22
  readonly candidates: Schema.optional<Schema.$Array<Schema.Struct<{
13
23
  readonly content: Schema.optional<Schema.Struct<{
@@ -29,6 +39,14 @@ declare const WireChunk: Schema.Struct<{
29
39
  readonly thoughtSignature: Schema.optional<Schema.String>;
30
40
  }>]>>>;
31
41
  }>>;
42
+ readonly groundingMetadata: Schema.optional<Schema.Struct<{
43
+ readonly groundingChunks: Schema.optional<Schema.NullOr<Schema.$Array<Schema.Struct<{
44
+ readonly web: Schema.optional<Schema.NullOr<Schema.Struct<{
45
+ readonly uri: Schema.optional<Schema.NullOr<Schema.String>>;
46
+ readonly title: Schema.optional<Schema.NullOr<Schema.String>>;
47
+ }>>>;
48
+ }>>>>;
49
+ }>>;
32
50
  readonly finishReason: Schema.optional<Schema.String>;
33
51
  readonly index: Schema.optional<Schema.Number>;
34
52
  }>>>;
@@ -57,6 +75,7 @@ type RequestPart = {
57
75
  readonly thoughtSignature?: string;
58
76
  } | {
59
77
  readonly functionResponse: {
78
+ readonly id?: string;
60
79
  readonly name: string;
61
80
  readonly response: Record<string, unknown>;
62
81
  };
@@ -132,7 +151,8 @@ type AccumulatedFunctionCall = {
132
151
  type Accumulator = {
133
152
  readonly text: string;
134
153
  readonly reasoning: string;
135
- readonly functionCalls: ReadonlyArray<AccumulatedFunctionCall>;
154
+ readonly functionCalls: ReadonlyArray<AccumulatedFunctionCall>; /** Grounding citations, accumulated (de-duped by url) across chunks. */
155
+ readonly annotations: ReadonlyArray<Annotation>;
136
156
  readonly finishReason: Option.Option<string>;
137
157
  readonly usage: {
138
158
  readonly input_tokens?: number;
@@ -173,5 +193,5 @@ type ChunkResult = {
173
193
  declare const ingestChunk: (acc: Accumulator, chunk: WireChunk) => ChunkResult;
174
194
  declare const accumulatorToTurn: (acc: Accumulator) => Turn;
175
195
  //#endregion
176
- export { AccumulatedFunctionCall, Accumulator, ChunkPart, ChunkResult, GenerationConfig, RequestBody, RequestTool, ThinkingConfig, WireChunk, accumulatorToTurn, buildRequestBody, emptyAccumulator, hasUrlImageSource, ingestChunk, codec_d_exports as t };
196
+ export { AccumulatedFunctionCall, Accumulator, ChunkPart, ChunkResult, GenerationConfig, GroundingMetadata, RequestBody, RequestTool, ThinkingConfig, WireChunk, accumulatorToTurn, buildRequestBody, emptyAccumulator, groundingToAnnotations, hasUrlImageSource, ingestChunk, codec_d_exports as t };
177
197
  //# sourceMappingURL=codec.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"codec.d.mts","names":[],"sources":["../src/codec.ts"],"mappings":";;;;;;;;;;cAkEa,SAAA,EAAS,MAAA,CAAA,MAAA;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAIV,SAAA,UAAmB,SAAA,CAAU,IAAA;AAAA,KAMpC,WAAA;EAAA,SACU,IAAA;AAAA;EAAA,SACA,UAAA;IAAA,SAAuB,QAAA;IAAA,SAA2B,IAAA;EAAA;AAAA;EAAA,SAElD,YAAA;IAAA,SACE,EAAA;IAAA,SACA,IAAA;IAAA,SACA,IAAA;EAAA;EAAA,SAEF,gBAAA;AAAA;EAAA,SAGA,gBAAA;IAAA,SACE,IAAA;IAAA,SACA,QAAA,EAAU,MAAA;EAAA;AAAA;AAAA,KAItB,cAAA;EAAA,SACM,IAAA;EAAA,SACA,KAAA,EAAO,aAAA,CAAc,WAAA;AAAA;AAAA,KAG3B,wBAAA;EAAA,SACM,KAAA,EAAO,aAAA;IAAA,SAAyB,IAAA;EAAA;AAAA;;;;;;;;KAU/B,WAAA;EAAA,SAEG,oBAAA,EAAsB,aAAA;IAAA,SACpB,IAAA;IAAA,SACA,WAAA;IAAA,SACA,UAAA,EAAY,MAAA;EAAA;AAAA;EAAA,SAGd,YAAA;AAAA;EAAA,SACA,UAAA;AAAA;EAAA,SACA,aAAA;AAAA;AAAA,KAEV,iBAAA;EAAA,SACM,qBAAA;IAAA,SACE,IAAA;IAAA,SACA,oBAAA,GAAuB,aAAA;EAAA;AAAA;AAAA,KAIxB,cAAA;EAAA,SACD,cAAA;AAAA;AAAA,KAGC,gBAAA;EAAA,SACD,WAAA;EAAA,SACA,eAAA;EAAA,SACA,IAAA;EAAA,SACA,cAAA,GAAiB,cAAA;WAEjB,gBAAA;WAEA,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A,oBAAA;MAAA,SAAkC,aAAA;IAAA;IAAA,SAClC,qBAAA;MAAA,SAAmC,gBAAA;IAAA;EAAA;AAAA;AAAA,cAInC,gBAAA,EAAkB,WAAA;;;;;;KAcnB,SAAA;EAAA,SACG,IAAA;EAAA,SAAuB,IAAA;AAAA;EAAA,SACvB,IAAA;EAAA,SAA4B,IAAA;AAAA;EAAA,SAE5B,IAAA;EAAA,SACA,EAAA,EAAI,MAAA,CAAO,MAAA;EAAA,SACX,SAAA,EAAW,MAAA,CAAO,MAAA;EAAA,SAClB,IAAA;EAAA,SACA,IAAA;AAAA;AAAA,KAGH,WAAA;EAAA,SACD,WAAA,EAAa,WAAA;EAAA,SACb,KAAA,EAAO,aAAA,CAAc,SAAA;EAAA,SACrB,QAAA;AAAA;AAAA,cAuGE,WAAA,GAAe,GAAA,EAAK,WAAA,EAAa,KAAA,EAAO,SAAA,KAAY,WAAA;AAAA,cA0DpD,iBAAA,GAAqB,GAAA,EAAK,WAAA,KAAc,IAAA"}
package/dist/codec.mjs CHANGED
@@ -2,10 +2,12 @@ import { n as __exportAll } from "./chunk-uyGKjUfl.mjs";
2
2
  import { Array as Array$1, Encoding, Match, Option, Result, Schema, pipe } from "effect";
3
3
  //#region src/codec.ts
4
4
  var codec_exports = /* @__PURE__ */ __exportAll({
5
+ GroundingMetadata: () => GroundingMetadata,
5
6
  WireChunk: () => WireChunk,
6
7
  accumulatorToTurn: () => accumulatorToTurn,
7
8
  buildRequestBody: () => buildRequestBody,
8
9
  emptyAccumulator: () => emptyAccumulator,
10
+ groundingToAnnotations: () => groundingToAnnotations,
9
11
  hasUrlImageSource: () => hasUrlImageSource,
10
12
  ingestChunk: () => ingestChunk
11
13
  });
@@ -37,8 +39,20 @@ const Content = Schema.Struct({
37
39
  role: Schema.optional(Schema.String),
38
40
  parts: Schema.optional(Schema.Array(Part))
39
41
  });
42
+ const GroundingChunk = Schema.Struct({ web: Schema.optional(Schema.NullOr(Schema.Struct({
43
+ uri: Schema.optional(Schema.NullOr(Schema.String)),
44
+ title: Schema.optional(Schema.NullOr(Schema.String))
45
+ }))) });
46
+ const GroundingMetadata = Schema.Struct({ groundingChunks: Schema.optional(Schema.NullOr(Schema.Array(GroundingChunk))) });
47
+ const sameUrlCitation = (a, b) => a.type === "url_citation" && b.type === "url_citation" && a.url === b.url;
48
+ const groundingToAnnotations = (...metas) => pipe(metas, Array$1.flatMap((meta) => meta?.groundingChunks ?? []), Array$1.filterMap((chunk) => chunk.web?.uri == null ? Result.failVoid : Result.succeed({
49
+ type: "url_citation",
50
+ url: chunk.web.uri,
51
+ title: chunk.web.title ?? chunk.web.uri
52
+ })), Array$1.dedupeWith(sameUrlCitation));
40
53
  const Candidate = Schema.Struct({
41
54
  content: Schema.optional(Content),
55
+ groundingMetadata: Schema.optional(GroundingMetadata),
42
56
  finishReason: Schema.optional(Schema.String),
43
57
  index: Schema.optional(Schema.Number)
44
58
  });
@@ -128,6 +142,7 @@ const geminiField = (item, pick) => pipe(decodeGemini(item.providerData), Result
128
142
  onFailure: () => Option.none()
129
143
  }));
130
144
  const providerIdFor = (item) => geminiField(item, (g) => g.id);
145
+ const providerIdForCallId = (history, call_id) => pipe(history, Array$1.findFirst((item) => isFunctionCallItem(item) && item.call_id === call_id), Option.flatMap(providerIdFor));
131
146
  const signatureFor = (item) => geminiField(item, (g) => g.thoughtSignature);
132
147
  const itemToContent = (history) => (item) => Match.value(item).pipe(Match.discriminatorsExhaustive("type")({
133
148
  message: messageToContent,
@@ -151,6 +166,10 @@ const itemToContent = (history) => (item) => Match.value(item).pipe(Match.discri
151
166
  function_call_output: (o) => Result.succeed({
152
167
  role: "user",
153
168
  parts: [{ functionResponse: {
169
+ ...Option.match(providerIdForCallId(history, o.call_id), {
170
+ onSome: (id) => ({ id }),
171
+ onNone: () => ({})
172
+ }),
154
173
  name: Option.getOrElse(nameForCallId(history, o.call_id), () => o.call_id),
155
174
  response: parsedResponse(o.output)
156
175
  } }]
@@ -215,6 +234,7 @@ const emptyAccumulator = {
215
234
  text: "",
216
235
  reasoning: "",
217
236
  functionCalls: [],
237
+ annotations: [],
218
238
  finishReason: Option.none(),
219
239
  usage: {}
220
240
  };
@@ -259,6 +279,7 @@ const chunkCallToAccumulated = (prior, call) => ({
259
279
  arguments: JSON.stringify(call.args)
260
280
  });
261
281
  const appendFunctionCalls = (prior, fromChunk) => fromChunk.reduce((acc, call) => [...acc, chunkCallToAccumulated(acc, call)], prior);
282
+ const mergeAnnotations = (prev, next) => next.length === 0 ? prev : Array$1.dedupeWith(Array$1.appendAll(prev, next), sameUrlCitation);
262
283
  const ingestChunk = (acc, chunk) => {
263
284
  const parts = chunkParts(chunk);
264
285
  const finishReason = Option.fromNullishOr(chunk.candidates?.[0]?.finishReason);
@@ -269,6 +290,7 @@ const ingestChunk = (acc, chunk) => {
269
290
  text: acc.text + sumStrings(parts, "text"),
270
291
  reasoning: acc.reasoning + sumStrings(parts, "reasoning"),
271
292
  functionCalls: appendFunctionCalls(acc.functionCalls, collectFunctionCalls(parts)),
293
+ annotations: mergeAnnotations(acc.annotations, groundingToAnnotations(chunk.candidates?.[0]?.groundingMetadata)),
272
294
  finishReason: Option.orElse(finishReason, () => acc.finishReason),
273
295
  usage: mergeUsage(acc.usage, chunk.usageMetadata)
274
296
  }
@@ -283,7 +305,8 @@ const assistantMessageItems = (acc) => acc.text.length === 0 ? [] : [{
283
305
  role: "assistant",
284
306
  content: [{
285
307
  type: "output_text",
286
- text: acc.text
308
+ text: acc.text,
309
+ ...acc.annotations.length > 0 && { annotations: acc.annotations }
287
310
  }]
288
311
  }];
289
312
  const functionCallItems = (acc) => pipe(acc.functionCalls, Array$1.map((c) => {
@@ -309,6 +332,6 @@ const accumulatorToTurn = (acc) => ({
309
332
  ]
310
333
  });
311
334
  //#endregion
312
- export { WireChunk, accumulatorToTurn, buildRequestBody, emptyAccumulator, hasUrlImageSource, ingestChunk, codec_exports as t };
335
+ export { GroundingMetadata, WireChunk, accumulatorToTurn, buildRequestBody, emptyAccumulator, groundingToAnnotations, hasUrlImageSource, ingestChunk, codec_exports as t };
313
336
 
314
337
  //# sourceMappingURL=codec.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"codec.mjs","names":["Arr"],"sources":["../src/codec.ts"],"sourcesContent":["import { Array as Arr, Encoding, Match, Option, Result, Schema, pipe } from \"effect\"\nimport type {\n ContentBlock,\n ToolCall,\n InputImage,\n HistoryItem,\n Message,\n} from \"@effect-uai/core/Items\"\nimport type { ToolDescriptor } from \"@effect-uai/core/Tool\"\nimport type { Turn } from \"@effect-uai/core/Turn\"\nimport type { CommonRequest } from \"@effect-uai/core/LanguageModel\"\n\n// ---------------------------------------------------------------------------\n// Wire schemas - the subset of Gemini's streamGenerateContent payload we\n// consume. Reference: https://ai.google.dev/api/generate-content\n// ---------------------------------------------------------------------------\n\nconst TextPart = Schema.Struct({\n text: Schema.String,\n /**\n * Gemini's flag for chain-of-thought parts. When `true`, the part is\n * reasoning trace, not the model's user-facing answer. Maps onto\n * `reasoning_delta { kind: \"trace\" }` in the canonical view.\n */\n thought: Schema.optional(Schema.Boolean),\n})\n\n/**\n * Gemini function-call part. Args are delivered as a whole JSON *object*\n * in a single chunk (Gemini does not stream tool-call args). On Gemini 3\n * the response also carries an `id` per call, which we echo back on the\n * corresponding `functionResponse`.\n */\nconst FunctionCallPart = Schema.Struct({\n functionCall: Schema.Struct({\n id: Schema.optional(Schema.String),\n name: Schema.String,\n args: Schema.optional(Schema.Unknown),\n }),\n // Gemini 3 thinking models attach an opaque signature to each function-call\n // part that must be replayed on the next request, or the call is rejected.\n thoughtSignature: Schema.optional(Schema.String),\n})\n\nconst Part = Schema.Union([TextPart, FunctionCallPart])\ntype WireFunctionCallPart = typeof FunctionCallPart.Type\n\nconst Content = Schema.Struct({\n role: Schema.optional(Schema.String),\n parts: Schema.optional(Schema.Array(Part)),\n})\n\nconst Candidate = Schema.Struct({\n content: Schema.optional(Content),\n finishReason: Schema.optional(Schema.String),\n index: Schema.optional(Schema.Number),\n})\n\nconst UsageMetadata = Schema.Struct({\n promptTokenCount: Schema.optional(Schema.Number),\n candidatesTokenCount: Schema.optional(Schema.Number),\n totalTokenCount: Schema.optional(Schema.Number),\n cachedContentTokenCount: Schema.optional(Schema.Number),\n thoughtsTokenCount: Schema.optional(Schema.Number),\n})\n\nexport const WireChunk = Schema.Struct({\n candidates: Schema.optional(Schema.Array(Candidate)),\n usageMetadata: Schema.optional(UsageMetadata),\n})\nexport type WireChunk = typeof WireChunk.Type\n\n// ---------------------------------------------------------------------------\n// History → request body\n// ---------------------------------------------------------------------------\n\ntype RequestPart =\n | { readonly text: string }\n | { readonly inlineData: { readonly mimeType: string; readonly data: string } }\n | {\n readonly functionCall: {\n readonly id?: string\n readonly name: string\n readonly args: unknown\n }\n readonly thoughtSignature?: string\n }\n | {\n readonly functionResponse: {\n readonly name: string\n readonly response: Record<string, unknown>\n }\n }\n\ntype RequestContent = {\n readonly role: \"user\" | \"model\"\n readonly parts: ReadonlyArray<RequestPart>\n}\n\ntype RequestSystemInstruction = {\n readonly parts: ReadonlyArray<{ readonly text: string }>\n}\n\n/**\n * Gemini's tool declaration. A `tools[]` entry is either a function-declaration\n * block (translated from `ToolDescriptor`s) or one of the native hosted-tool\n * entries. The native entries are empty objects keyed camelCase per the REST\n * v1beta `Tool` object, and sit as siblings of the declarations in the same\n * `tools` array.\n */\nexport type RequestTool =\n | {\n readonly functionDeclarations: ReadonlyArray<{\n readonly name: string\n readonly description: string\n readonly parameters: Record<string, unknown>\n }>\n }\n | { readonly googleSearch: {} }\n | { readonly urlContext: {} }\n | { readonly codeExecution: {} }\n\ntype RequestToolConfig = {\n readonly functionCallingConfig: {\n readonly mode: \"AUTO\" | \"ANY\" | \"NONE\"\n readonly allowedFunctionNames?: ReadonlyArray<string>\n }\n}\n\nexport type ThinkingConfig = {\n readonly thinkingBudget: number\n}\n\nexport type GenerationConfig = {\n readonly temperature?: number\n readonly maxOutputTokens?: number\n readonly topP?: number\n readonly thinkingConfig?: ThinkingConfig\n /** Set together with `responseJsonSchema` to constrain output to JSON. */\n readonly responseMimeType?: string\n /** JSON Schema constraint on the output. */\n readonly responseJsonSchema?: Record<string, unknown>\n}\n\nexport type RequestBody = {\n readonly contents: ReadonlyArray<RequestContent>\n readonly systemInstruction?: RequestSystemInstruction\n readonly generationConfig?: GenerationConfig\n readonly tools?: ReadonlyArray<RequestTool>\n readonly toolConfig?: RequestToolConfig\n}\n\nconst blockText = Match.type<ContentBlock>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (b) => b.text,\n input_image: () => \"\",\n output_text: (b) => b.text,\n refusal: (b) => b.text,\n }),\n)\n\nconst messageText = (message: Message): string => message.content.map(blockText).join(\"\")\n\n/**\n * Gemini's `inlineData` form expects a base64 payload. URL-form images\n * would need to go through Gemini's Files API (upload then `fileData`\n * with the returned URI); pre-uploading isn't free, so we skip those for\n * now and document as a follow-up.\n */\nconst imageSourceToParts = Match.type<InputImage[\"source\"]>().pipe(\n Match.tag(\"url\", (): ReadonlyArray<RequestPart> => []),\n Match.tag(\n \"base64\",\n (s): ReadonlyArray<RequestPart> => [{ inlineData: { mimeType: s.mimeType, data: s.base64 } }],\n ),\n Match.tag(\n \"bytes\",\n (s): ReadonlyArray<RequestPart> => [\n { inlineData: { mimeType: s.mimeType, data: Encoding.encodeBase64(s.bytes) } },\n ],\n ),\n Match.exhaustive,\n)\n\nconst blockToParts = Match.type<ContentBlock>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (b): ReadonlyArray<RequestPart> => (b.text.length === 0 ? [] : [{ text: b.text }]),\n input_image: (b): ReadonlyArray<RequestPart> => imageSourceToParts(b.source),\n output_text: (b): ReadonlyArray<RequestPart> => (b.text.length === 0 ? [] : [{ text: b.text }]),\n // Refusals are assistant-side content; they don't round-trip into Gemini's\n // request body as parts. Skip.\n refusal: (): ReadonlyArray<RequestPart> => [],\n }),\n)\n\nconst messageToContent = (message: Message): Result.Result<RequestContent, void> => {\n const parts = pipe(message.content, Arr.flatMap(blockToParts))\n if (parts.length === 0) return Result.failVoid\n return Match.value(message.role).pipe(\n Match.when(\"user\", () => Result.succeed({ role: \"user\" as const, parts })),\n Match.when(\"assistant\", () => Result.succeed({ role: \"model\" as const, parts })),\n Match.when(\"system\", () => Result.failVoid),\n Match.exhaustive,\n )\n}\n\nconst systemMessageText = (message: Message): Result.Result<string, void> => {\n if (message.role !== \"system\") return Result.failVoid\n const text = messageText(message)\n return text.length === 0 ? Result.failVoid : Result.succeed(text)\n}\n\nconst allMessages = (history: ReadonlyArray<HistoryItem>): ReadonlyArray<Message> =>\n pipe(\n history,\n Arr.filterMap((item) => (item.type === \"message\" ? Result.succeed(item) : Result.failVoid)),\n )\n\n// ---------------------------------------------------------------------------\n// Function-call round-trip\n//\n// `ToolCall.arguments` and `ToolCallOutput.output` are JSON-encoded\n// strings; Gemini's `functionCall.args` and `functionResponse.response`\n// expect parsed JSON *objects*. Decode via Schema:\n// - object payload → use as-is\n// - scalar / array / malformed → wrap as `{ output: <raw string> }` so the\n// model still sees *some* response without crashing the request.\n// ---------------------------------------------------------------------------\n\nconst JsonObject = Schema.Record(Schema.String, Schema.Unknown)\nconst decodeJsonObject = Schema.decodeResult(Schema.fromJsonString(JsonObject))\n\nconst parsedJsonObject =\n (fallback: (raw: string) => Record<string, unknown>) =>\n (encoded: string): Record<string, unknown> =>\n pipe(\n decodeJsonObject(encoded),\n Result.match({\n onSuccess: (v) => v,\n onFailure: () => fallback(encoded),\n }),\n )\n\nconst parsedArgs = parsedJsonObject(() => ({}))\nconst parsedResponse = parsedJsonObject((raw) => ({ output: raw }))\n\n/**\n * `ToolCallOutput` only carries `call_id`; Gemini's `functionResponse`\n * requires the declared function `name`. Resolve the name by scanning prior\n * `function_call` items in the history for a matching `call_id`. If we\n * cannot resolve, fall back to `call_id` as the name - imperfect but\n * preserves stream shape so the model sees *some* response.\n */\nconst isFunctionCallItem = (item: HistoryItem): item is ToolCall => item.type === \"function_call\"\n\nconst nameForCallId = (\n history: ReadonlyArray<HistoryItem>,\n call_id: string,\n): Option.Option<string> =>\n pipe(\n history,\n Arr.findFirst((item): item is ToolCall => isFunctionCallItem(item) && item.call_id === call_id),\n Option.map((f) => f.name),\n )\n\n/**\n * Extract the Gemini-3 wire id and thought signature we stashed in\n * `providerData` on the way out. Schema-driven so the shape lives in one\n * place; failure or absence → `Option.none()`.\n */\nconst ProviderDataGemini = Schema.Struct({\n gemini: Schema.Struct({\n id: Schema.optional(Schema.String),\n thoughtSignature: Schema.optional(Schema.String),\n }),\n})\nconst decodeGemini = Schema.decodeUnknownResult(ProviderDataGemini)\n\nconst geminiField = (\n item: ToolCall,\n pick: (g: {\n readonly id?: string | undefined\n readonly thoughtSignature?: string | undefined\n }) => string | undefined,\n): Option.Option<string> =>\n pipe(\n decodeGemini(item.providerData),\n Result.match({\n onSuccess: (d) => Option.fromNullishOr(pick(d.gemini)),\n onFailure: () => Option.none<string>(),\n }),\n )\n\nconst providerIdFor = (item: ToolCall): Option.Option<string> => geminiField(item, (g) => g.id)\nconst signatureFor = (item: ToolCall): Option.Option<string> =>\n geminiField(item, (g) => g.thoughtSignature)\n\nconst itemToContent =\n (history: ReadonlyArray<HistoryItem>) =>\n (item: HistoryItem): Result.Result<RequestContent, void> =>\n Match.value(item).pipe(\n Match.discriminatorsExhaustive(\"type\")({\n message: messageToContent,\n function_call: (f) =>\n Result.succeed({\n role: \"model\" as const,\n parts: [\n {\n ...Option.match(signatureFor(f), {\n onSome: (thoughtSignature) => ({ thoughtSignature }),\n onNone: () => ({}),\n }),\n functionCall: {\n ...Option.match(providerIdFor(f), {\n onSome: (id) => ({ id }),\n onNone: () => ({}),\n }),\n name: f.name,\n args: parsedArgs(f.arguments),\n },\n },\n ],\n }),\n function_call_output: (o) =>\n Result.succeed({\n role: \"user\" as const,\n parts: [\n {\n functionResponse: {\n name: Option.getOrElse(nameForCallId(history, o.call_id), () => o.call_id),\n response: parsedResponse(o.output),\n },\n },\n ],\n }),\n reasoning: () => Result.failVoid,\n }),\n )\n\n// ---------------------------------------------------------------------------\n// Tool descriptors → Gemini `functionDeclarations`. Gemini accepts only a\n// strict OpenAPI 3.0 subset for `parameters`; strip JSON-Schema keys it\n// rejects (`$schema`, `$ref`, `additionalProperties`, `oneOf`,\n// `definitions`).\n// ---------------------------------------------------------------------------\n\nconst UNSUPPORTED_SCHEMA_KEYS: ReadonlySet<string> = new Set([\n \"$schema\",\n \"$ref\",\n \"$defs\",\n \"definitions\",\n \"additionalProperties\",\n \"oneOf\",\n])\n\nconst sanitizeSchema = (schema: unknown): unknown => {\n if (Array.isArray(schema)) return schema.map(sanitizeSchema)\n if (schema === null || typeof schema !== \"object\") return schema\n return pipe(\n Object.entries(schema as Record<string, unknown>),\n Arr.filterMap(([k, v]) =>\n UNSUPPORTED_SCHEMA_KEYS.has(k)\n ? Result.failVoid\n : Result.succeed([k, sanitizeSchema(v)] as const),\n ),\n Object.fromEntries,\n )\n}\n\nconst toolDescriptorsToTools = (tools: ReadonlyArray<ToolDescriptor>): ReadonlyArray<RequestTool> =>\n tools.length === 0\n ? []\n : [\n {\n functionDeclarations: tools.map((t) => ({\n name: t.name,\n description: t.description,\n parameters: sanitizeSchema(t.inputSchema) as Record<string, unknown>,\n })),\n },\n ]\n\n/**\n * Map our cross-provider `toolChoice` onto Gemini's `functionCallingConfig`.\n * Gemini honours the same three modes plus a function allow-list, so the\n * choice is mapped, not dropped. `undefined` keeps the API default (`AUTO`).\n */\nconst toolChoiceToFunctionCallingConfig = (\n toolChoice: CommonRequest[\"toolChoice\"],\n): RequestToolConfig[\"functionCallingConfig\"] =>\n Match.value(toolChoice ?? \"auto\").pipe(\n Match.when(\"auto\", () => ({ mode: \"AUTO\" as const })),\n Match.when(\"required\", () => ({ mode: \"ANY\" as const })),\n Match.when(\"none\", () => ({ mode: \"NONE\" as const })),\n Match.orElse((tc) => ({ mode: \"ANY\" as const, allowedFunctionNames: [tc.name] })),\n )\n\n/**\n * URL-form images need Gemini's Files API (upload, then `fileData`); we\n * don't pre-upload, so such a part would otherwise vanish from the request.\n * The caller fails the request with `Unsupported` instead of silently\n * dropping the image.\n */\nexport const hasUrlImageSource = (history: ReadonlyArray<HistoryItem>): boolean =>\n history.some(\n (item) =>\n item.type === \"message\" &&\n item.content.some((b) => b.type === \"input_image\" && b.source._tag === \"url\"),\n )\n\nexport const buildRequestBody = (\n history: ReadonlyArray<HistoryItem>,\n generationConfig: Option.Option<GenerationConfig>,\n tools: ReadonlyArray<ToolDescriptor> = [],\n providerToolEntries: ReadonlyArray<RequestTool> = [],\n toolChoice: CommonRequest[\"toolChoice\"] = undefined,\n): RequestBody => {\n const systemTexts = pipe(allMessages(history), Arr.filterMap(systemMessageText))\n const contents = pipe(history, Arr.filterMap(itemToContent(history)))\n const functionTools = toolDescriptorsToTools(tools)\n const requestTools = [...functionTools, ...providerToolEntries]\n return {\n contents,\n ...(systemTexts.length > 0 && {\n systemInstruction: { parts: [{ text: systemTexts.join(\"\\n\") }] },\n }),\n ...Option.match(generationConfig, {\n onNone: () => ({}),\n onSome: (cfg) => ({ generationConfig: cfg }),\n }),\n ...(requestTools.length > 0 && { tools: requestTools }),\n // Only force a function-calling mode when there are function declarations;\n // a grounding-only request must keep the API default.\n ...(functionTools.length > 0 && {\n toolConfig: { functionCallingConfig: toolChoiceToFunctionCallingConfig(toolChoice) },\n }),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Stream-level state - accumulate chunk text + final usage/finish.\n//\n// `Accumulator` is immutable; `ingestChunk` returns a fresh one per chunk.\n// Drive it via `Stream.mapAccum` in the consumer.\n// ---------------------------------------------------------------------------\n\nconst finishReasonToStop = (reason: Option.Option<string>): Turn[\"stop_reason\"] =>\n Option.match(reason, {\n onNone: () => \"stop\" as const,\n onSome: (r) => (r === \"MAX_TOKENS\" ? (\"max_tokens\" as const) : (\"stop\" as const)),\n })\n\nexport type AccumulatedFunctionCall = {\n /** Synthesized id-or-name we surface as `call_id` on the canonical item. */\n readonly callId: string\n readonly name: string\n /** Wire id from Gemini 3, when present - echoed back on `functionResponse`. */\n readonly providerId: Option.Option<string>\n /** Thought signature from Gemini 3, replayed on the next request's part. */\n readonly signature: Option.Option<string>\n /** Args as JSON-encoded string, mirroring `Items.ToolCall.arguments`. */\n readonly arguments: string\n}\n\nexport type Accumulator = {\n readonly text: string\n readonly reasoning: string\n readonly functionCalls: ReadonlyArray<AccumulatedFunctionCall>\n readonly finishReason: Option.Option<string>\n readonly usage: {\n readonly input_tokens?: number\n readonly output_tokens?: number\n readonly total_tokens?: number\n readonly input_tokens_details?: { readonly cached_tokens?: number }\n readonly output_tokens_details?: { readonly reasoning_tokens?: number }\n }\n}\n\nexport const emptyAccumulator: Accumulator = {\n text: \"\",\n reasoning: \"\",\n functionCalls: [],\n finishReason: Option.none(),\n usage: {},\n}\n\n/**\n * One part's worth of streamable output. `text` and `reasoning` are\n * incremental string deltas; `function_call` arrives whole-in-one-chunk\n * (Gemini does not stream tool-call args).\n */\nexport type ChunkPart =\n | { readonly kind: \"text\"; readonly text: string }\n | { readonly kind: \"reasoning\"; readonly text: string }\n | {\n readonly kind: \"function_call\"\n readonly id: Option.Option<string>\n readonly signature: Option.Option<string>\n readonly name: string\n readonly args: unknown\n }\n\nexport type ChunkResult = {\n readonly accumulator: Accumulator\n readonly parts: ReadonlyArray<ChunkPart>\n readonly finished: boolean\n}\n\nconst isTextPart = (p: typeof Part.Type): p is typeof TextPart.Type => \"text\" in p\n\nconst textToChunkParts = (p: typeof TextPart.Type): ReadonlyArray<ChunkPart> =>\n p.text.length === 0 ? [] : [{ kind: p.thought === true ? \"reasoning\" : \"text\", text: p.text }]\n\nconst functionCallToChunkParts = (p: WireFunctionCallPart): ReadonlyArray<ChunkPart> => [\n {\n kind: \"function_call\",\n id: Option.fromNullishOr(p.functionCall.id),\n signature: Option.fromNullishOr(p.thoughtSignature),\n name: p.functionCall.name,\n args: p.functionCall.args ?? {},\n },\n]\n\nconst partToChunkParts = (p: typeof Part.Type): ReadonlyArray<ChunkPart> =>\n isTextPart(p) ? textToChunkParts(p) : functionCallToChunkParts(p)\n\nconst chunkParts = (chunk: WireChunk): ReadonlyArray<ChunkPart> =>\n pipe(chunk.candidates?.[0]?.content?.parts ?? [], Arr.flatMap(partToChunkParts))\n\nconst sumStrings = (parts: ReadonlyArray<ChunkPart>, kind: \"text\" | \"reasoning\"): string =>\n pipe(\n parts,\n Arr.filterMap((p) => (p.kind === kind ? Result.succeed(p.text) : Result.failVoid)),\n ).join(\"\")\n\nconst collectFunctionCalls = (\n parts: ReadonlyArray<ChunkPart>,\n): ReadonlyArray<Extract<ChunkPart, { kind: \"function_call\" }>> =>\n pipe(\n parts,\n Arr.filterMap((p) => (p.kind === \"function_call\" ? Result.succeed(p) : Result.failVoid)),\n )\n\nconst mergeUsage = (\n prev: Accumulator[\"usage\"],\n next: WireChunk[\"usageMetadata\"],\n): Accumulator[\"usage\"] =>\n next === undefined\n ? prev\n : {\n ...prev,\n ...(next.promptTokenCount !== undefined && { input_tokens: next.promptTokenCount }),\n ...(next.candidatesTokenCount !== undefined && {\n output_tokens: next.candidatesTokenCount,\n }),\n ...(next.totalTokenCount !== undefined && { total_tokens: next.totalTokenCount }),\n ...(next.cachedContentTokenCount !== undefined && {\n input_tokens_details: { cached_tokens: next.cachedContentTokenCount },\n }),\n ...(next.thoughtsTokenCount !== undefined && {\n output_tokens_details: { reasoning_tokens: next.thoughtsTokenCount },\n }),\n }\n\n/**\n * Synthesize a stable `call_id` for a function call. Gemini 3 provides one\n * via `functionCall.id`; older models do not, so we fall back to\n * `<name>_<index>` based on prior calls' position in the accumulator.\n */\nconst synthesizeCallId = (\n call: Extract<ChunkPart, { kind: \"function_call\" }>,\n priorCalls: ReadonlyArray<AccumulatedFunctionCall>,\n): string =>\n Option.match(call.id, {\n onSome: (id) => id,\n onNone: () => `${call.name}_${priorCalls.length}`,\n })\n\nconst chunkCallToAccumulated = (\n prior: ReadonlyArray<AccumulatedFunctionCall>,\n call: Extract<ChunkPart, { kind: \"function_call\" }>,\n): AccumulatedFunctionCall => ({\n callId: synthesizeCallId(call, prior),\n name: call.name,\n providerId: call.id,\n signature: call.signature,\n // `functionCallToChunkParts` already replaced null/undefined with `{}`,\n // so `call.args` is always a JSON-encodable value here.\n arguments: JSON.stringify(call.args),\n})\n\nconst appendFunctionCalls = (\n prior: ReadonlyArray<AccumulatedFunctionCall>,\n fromChunk: ReadonlyArray<Extract<ChunkPart, { kind: \"function_call\" }>>,\n): ReadonlyArray<AccumulatedFunctionCall> =>\n fromChunk.reduce<ReadonlyArray<AccumulatedFunctionCall>>(\n (acc, call) => [...acc, chunkCallToAccumulated(acc, call)],\n prior,\n )\n\nexport const ingestChunk = (acc: Accumulator, chunk: WireChunk): ChunkResult => {\n const parts = chunkParts(chunk)\n const finishReason = Option.fromNullishOr(chunk.candidates?.[0]?.finishReason)\n return {\n parts,\n finished: Option.isSome(finishReason),\n accumulator: {\n text: acc.text + sumStrings(parts, \"text\"),\n reasoning: acc.reasoning + sumStrings(parts, \"reasoning\"),\n functionCalls: appendFunctionCalls(acc.functionCalls, collectFunctionCalls(parts)),\n finishReason: Option.orElse(finishReason, () => acc.finishReason),\n usage: mergeUsage(acc.usage, chunk.usageMetadata),\n },\n }\n}\n\nconst reasoningItems = (acc: Accumulator): ReadonlyArray<HistoryItem> =>\n acc.reasoning.length > 0 ? [{ type: \"reasoning\", summary: acc.reasoning }] : []\n\nconst assistantMessageItems = (acc: Accumulator): ReadonlyArray<HistoryItem> =>\n acc.text.length === 0\n ? []\n : [\n {\n type: \"message\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: acc.text }],\n },\n ]\n\nconst functionCallItems = (acc: Accumulator): ReadonlyArray<HistoryItem> =>\n pipe(\n acc.functionCalls,\n Arr.map((c) => {\n const gemini = {\n ...(Option.isSome(c.providerId) && { id: c.providerId.value }),\n ...(Option.isSome(c.signature) && { thoughtSignature: c.signature.value }),\n }\n return {\n type: \"function_call\" as const,\n call_id: c.callId,\n name: c.name,\n arguments: c.arguments,\n ...(Object.keys(gemini).length > 0 && { providerData: { gemini } }),\n }\n }),\n )\n\nexport const accumulatorToTurn = (acc: Accumulator): Turn => ({\n stop_reason:\n acc.functionCalls.length > 0 ? (\"tool_calls\" as const) : finishReasonToStop(acc.finishReason),\n usage: { ...acc.usage },\n items: [...reasoningItems(acc), ...assistantMessageItems(acc), ...functionCallItems(acc)],\n})\n"],"mappings":";;;;;;;;;;;AAiBA,MAAM,WAAW,OAAO,OAAO;CAC7B,MAAM,OAAO;;;;;;CAMb,SAAS,OAAO,SAAS,OAAO,QAAQ;CACzC,CAAC;;;;;;;AAQF,MAAM,mBAAmB,OAAO,OAAO;CACrC,cAAc,OAAO,OAAO;EAC1B,IAAI,OAAO,SAAS,OAAO,OAAO;EAClC,MAAM,OAAO;EACb,MAAM,OAAO,SAAS,OAAO,QAAQ;EACtC,CAAC;CAGF,kBAAkB,OAAO,SAAS,OAAO,OAAO;CACjD,CAAC;AAEF,MAAM,OAAO,OAAO,MAAM,CAAC,UAAU,iBAAiB,CAAC;AAGvD,MAAM,UAAU,OAAO,OAAO;CAC5B,MAAM,OAAO,SAAS,OAAO,OAAO;CACpC,OAAO,OAAO,SAAS,OAAO,MAAM,KAAK,CAAC;CAC3C,CAAC;AAEF,MAAM,YAAY,OAAO,OAAO;CAC9B,SAAS,OAAO,SAAS,QAAQ;CACjC,cAAc,OAAO,SAAS,OAAO,OAAO;CAC5C,OAAO,OAAO,SAAS,OAAO,OAAO;CACtC,CAAC;AAEF,MAAM,gBAAgB,OAAO,OAAO;CAClC,kBAAkB,OAAO,SAAS,OAAO,OAAO;CAChD,sBAAsB,OAAO,SAAS,OAAO,OAAO;CACpD,iBAAiB,OAAO,SAAS,OAAO,OAAO;CAC/C,yBAAyB,OAAO,SAAS,OAAO,OAAO;CACvD,oBAAoB,OAAO,SAAS,OAAO,OAAO;CACnD,CAAC;AAEF,MAAa,YAAY,OAAO,OAAO;CACrC,YAAY,OAAO,SAAS,OAAO,MAAM,UAAU,CAAC;CACpD,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AE,MAAM;CAAa,SAAS,IAAI;CAAW,CAAC,GAAG,EAAE;AAEjF,MAAM,yBAAyB,QAC7B,IAAI,KAAK,WAAW,IAChB,EAAE,GACF,CACE;CACE,MAAM;CACN,MAAM;CACN,SAAS,CAAC;EAAE,MAAM;EAAe,MAAM,IAAI;EAAM,CAAC;CACnD,CACF;AAEP,MAAM,qBAAqB,QACzB,KACE,IAAI,eACJA,QAAI,KAAK,MAAM;CACb,MAAM,SAAS;EACb,GAAI,OAAO,OAAO,EAAE,WAAW,IAAI,EAAE,IAAI,EAAE,WAAW,OAAO;EAC7D,GAAI,OAAO,OAAO,EAAE,UAAU,IAAI,EAAE,kBAAkB,EAAE,UAAU,OAAO;EAC1E;AACD,QAAO;EACL,MAAM;EACN,SAAS,EAAE;EACX,MAAM,EAAE;EACR,WAAW,EAAE;EACb,GAAI,OAAO,KAAK,OAAO,CAAC,SAAS,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE;EACnE;EACD,CACH;AAEH,MAAa,qBAAqB,SAA4B;CAC5D,aACE,IAAI,cAAc,SAAS,IAAK,eAAyB,mBAAmB,IAAI,aAAa;CAC/F,OAAO,EAAE,GAAG,IAAI,OAAO;CACvB,OAAO;EAAC,GAAG,eAAe,IAAI;EAAE,GAAG,sBAAsB,IAAI;EAAE,GAAG,kBAAkB,IAAI;EAAC;CAC1F"}
1
+ {"version":3,"file":"codec.mjs","names":["Arr"],"sources":["../src/codec.ts"],"sourcesContent":["import { Array as Arr, Encoding, Match, Option, Result, Schema, pipe } from \"effect\"\nimport type {\n ContentBlock,\n ToolCall,\n InputImage,\n HistoryItem,\n Message,\n Annotation,\n} from \"@effect-uai/core/Items\"\nimport type { ToolDescriptor } from \"@effect-uai/core/Tool\"\nimport type { Turn } from \"@effect-uai/core/Turn\"\nimport type { CommonRequest } from \"@effect-uai/core/LanguageModel\"\n\n// ---------------------------------------------------------------------------\n// Wire schemas - the subset of Gemini's streamGenerateContent payload we\n// consume. Reference: https://ai.google.dev/api/generate-content\n// ---------------------------------------------------------------------------\n\nconst TextPart = Schema.Struct({\n text: Schema.String,\n /**\n * Gemini's flag for chain-of-thought parts. When `true`, the part is\n * reasoning trace, not the model's user-facing answer. Maps onto\n * `reasoning_delta { kind: \"trace\" }` in the canonical view.\n */\n thought: Schema.optional(Schema.Boolean),\n})\n\n/**\n * Gemini function-call part. Args are delivered as a whole JSON *object*\n * in a single chunk (Gemini does not stream tool-call args). On Gemini 3\n * the response also carries an `id` per call, which we echo back on the\n * corresponding `functionResponse`.\n */\nconst FunctionCallPart = Schema.Struct({\n functionCall: Schema.Struct({\n id: Schema.optional(Schema.String),\n name: Schema.String,\n args: Schema.optional(Schema.Unknown),\n }),\n // Gemini 3 thinking models attach an opaque signature to each function-call\n // part that must be replayed on the next request, or the call is rejected.\n thoughtSignature: Schema.optional(Schema.String),\n})\n\nconst Part = Schema.Union([TextPart, FunctionCallPart])\ntype WireFunctionCallPart = typeof FunctionCallPart.Type\n\nconst Content = Schema.Struct({\n role: Schema.optional(Schema.String),\n parts: Schema.optional(Schema.Array(Part)),\n})\n\n// Google grounding metadata. On a grounded response the candidate carries\n// `groundingChunks[].web.{uri,title}` - the structured form of the inline `[n]`\n// / trailing `**Sources:**` list the model renders into the answer text.\n// Decoded defensively (every field optional) as it is absent on ungrounded\n// turns. Shared with the Interactions deep-research surface via `codec.ts`.\nconst GroundingChunk = Schema.Struct({\n web: Schema.optional(\n Schema.NullOr(\n Schema.Struct({\n uri: Schema.optional(Schema.NullOr(Schema.String)),\n title: Schema.optional(Schema.NullOr(Schema.String)),\n }),\n ),\n ),\n})\nexport const GroundingMetadata = Schema.Struct({\n groundingChunks: Schema.optional(Schema.NullOr(Schema.Array(GroundingChunk))),\n})\nexport type GroundingMetadata = typeof GroundingMetadata.Type\n\n// Two citations are the same source when they point at the same url.\nconst sameUrlCitation = (a: Annotation, b: Annotation): boolean =>\n a.type === \"url_citation\" && b.type === \"url_citation\" && a.url === b.url\n\n// Grounding chunks → `url_citation` annotations, de-duped by url across every\n// metadata block passed. `web.uri` is a `grounding-api-redirect` URL and\n// `web.title` the bare domain; both are kept as-is (the redirect resolves to\n// the real page).\nexport const groundingToAnnotations = (\n ...metas: ReadonlyArray<GroundingMetadata | null | undefined>\n): ReadonlyArray<Annotation> =>\n pipe(\n metas,\n Arr.flatMap((meta) => meta?.groundingChunks ?? []),\n Arr.filterMap((chunk) =>\n chunk.web?.uri == null\n ? Result.failVoid\n : Result.succeed<Annotation>({\n type: \"url_citation\",\n url: chunk.web.uri,\n title: chunk.web.title ?? chunk.web.uri,\n }),\n ),\n Arr.dedupeWith(sameUrlCitation),\n )\n\nconst Candidate = Schema.Struct({\n content: Schema.optional(Content),\n groundingMetadata: Schema.optional(GroundingMetadata),\n finishReason: Schema.optional(Schema.String),\n index: Schema.optional(Schema.Number),\n})\n\nconst UsageMetadata = Schema.Struct({\n promptTokenCount: Schema.optional(Schema.Number),\n candidatesTokenCount: Schema.optional(Schema.Number),\n totalTokenCount: Schema.optional(Schema.Number),\n cachedContentTokenCount: Schema.optional(Schema.Number),\n thoughtsTokenCount: Schema.optional(Schema.Number),\n})\n\nexport const WireChunk = Schema.Struct({\n candidates: Schema.optional(Schema.Array(Candidate)),\n usageMetadata: Schema.optional(UsageMetadata),\n})\nexport type WireChunk = typeof WireChunk.Type\n\n// ---------------------------------------------------------------------------\n// History → request body\n// ---------------------------------------------------------------------------\n\ntype RequestPart =\n | { readonly text: string }\n | { readonly inlineData: { readonly mimeType: string; readonly data: string } }\n | {\n readonly functionCall: {\n readonly id?: string\n readonly name: string\n readonly args: unknown\n }\n readonly thoughtSignature?: string\n }\n | {\n readonly functionResponse: {\n readonly id?: string\n readonly name: string\n readonly response: Record<string, unknown>\n }\n }\n\ntype RequestContent = {\n readonly role: \"user\" | \"model\"\n readonly parts: ReadonlyArray<RequestPart>\n}\n\ntype RequestSystemInstruction = {\n readonly parts: ReadonlyArray<{ readonly text: string }>\n}\n\n/**\n * Gemini's tool declaration. A `tools[]` entry is either a function-declaration\n * block (translated from `ToolDescriptor`s) or one of the native hosted-tool\n * entries. The native entries are empty objects keyed camelCase per the REST\n * v1beta `Tool` object, and sit as siblings of the declarations in the same\n * `tools` array.\n */\nexport type RequestTool =\n | {\n readonly functionDeclarations: ReadonlyArray<{\n readonly name: string\n readonly description: string\n readonly parameters: Record<string, unknown>\n }>\n }\n | { readonly googleSearch: {} }\n | { readonly urlContext: {} }\n | { readonly codeExecution: {} }\n\ntype RequestToolConfig = {\n readonly functionCallingConfig: {\n readonly mode: \"AUTO\" | \"ANY\" | \"NONE\"\n readonly allowedFunctionNames?: ReadonlyArray<string>\n }\n}\n\nexport type ThinkingConfig = {\n readonly thinkingBudget: number\n}\n\nexport type GenerationConfig = {\n readonly temperature?: number\n readonly maxOutputTokens?: number\n readonly topP?: number\n readonly thinkingConfig?: ThinkingConfig\n /** Set together with `responseJsonSchema` to constrain output to JSON. */\n readonly responseMimeType?: string\n /** JSON Schema constraint on the output. */\n readonly responseJsonSchema?: Record<string, unknown>\n}\n\nexport type RequestBody = {\n readonly contents: ReadonlyArray<RequestContent>\n readonly systemInstruction?: RequestSystemInstruction\n readonly generationConfig?: GenerationConfig\n readonly tools?: ReadonlyArray<RequestTool>\n readonly toolConfig?: RequestToolConfig\n}\n\nconst blockText = Match.type<ContentBlock>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (b) => b.text,\n input_image: () => \"\",\n output_text: (b) => b.text,\n refusal: (b) => b.text,\n }),\n)\n\nconst messageText = (message: Message): string => message.content.map(blockText).join(\"\")\n\n/**\n * Gemini's `inlineData` form expects a base64 payload. URL-form images\n * would need to go through Gemini's Files API (upload then `fileData`\n * with the returned URI); pre-uploading isn't free, so we skip those for\n * now and document as a follow-up.\n */\nconst imageSourceToParts = Match.type<InputImage[\"source\"]>().pipe(\n Match.tag(\"url\", (): ReadonlyArray<RequestPart> => []),\n Match.tag(\n \"base64\",\n (s): ReadonlyArray<RequestPart> => [{ inlineData: { mimeType: s.mimeType, data: s.base64 } }],\n ),\n Match.tag(\n \"bytes\",\n (s): ReadonlyArray<RequestPart> => [\n { inlineData: { mimeType: s.mimeType, data: Encoding.encodeBase64(s.bytes) } },\n ],\n ),\n Match.exhaustive,\n)\n\nconst blockToParts = Match.type<ContentBlock>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (b): ReadonlyArray<RequestPart> => (b.text.length === 0 ? [] : [{ text: b.text }]),\n input_image: (b): ReadonlyArray<RequestPart> => imageSourceToParts(b.source),\n output_text: (b): ReadonlyArray<RequestPart> => (b.text.length === 0 ? [] : [{ text: b.text }]),\n // Refusals are assistant-side content; they don't round-trip into Gemini's\n // request body as parts. Skip.\n refusal: (): ReadonlyArray<RequestPart> => [],\n }),\n)\n\nconst messageToContent = (message: Message): Result.Result<RequestContent, void> => {\n const parts = pipe(message.content, Arr.flatMap(blockToParts))\n if (parts.length === 0) return Result.failVoid\n return Match.value(message.role).pipe(\n Match.when(\"user\", () => Result.succeed({ role: \"user\" as const, parts })),\n Match.when(\"assistant\", () => Result.succeed({ role: \"model\" as const, parts })),\n Match.when(\"system\", () => Result.failVoid),\n Match.exhaustive,\n )\n}\n\nconst systemMessageText = (message: Message): Result.Result<string, void> => {\n if (message.role !== \"system\") return Result.failVoid\n const text = messageText(message)\n return text.length === 0 ? Result.failVoid : Result.succeed(text)\n}\n\nconst allMessages = (history: ReadonlyArray<HistoryItem>): ReadonlyArray<Message> =>\n pipe(\n history,\n Arr.filterMap((item) => (item.type === \"message\" ? Result.succeed(item) : Result.failVoid)),\n )\n\n// ---------------------------------------------------------------------------\n// Function-call round-trip\n//\n// `ToolCall.arguments` and `ToolCallOutput.output` are JSON-encoded\n// strings; Gemini's `functionCall.args` and `functionResponse.response`\n// expect parsed JSON *objects*. Decode via Schema:\n// - object payload → use as-is\n// - scalar / array / malformed → wrap as `{ output: <raw string> }` so the\n// model still sees *some* response without crashing the request.\n// ---------------------------------------------------------------------------\n\nconst JsonObject = Schema.Record(Schema.String, Schema.Unknown)\nconst decodeJsonObject = Schema.decodeResult(Schema.fromJsonString(JsonObject))\n\nconst parsedJsonObject =\n (fallback: (raw: string) => Record<string, unknown>) =>\n (encoded: string): Record<string, unknown> =>\n pipe(\n decodeJsonObject(encoded),\n Result.match({\n onSuccess: (v) => v,\n onFailure: () => fallback(encoded),\n }),\n )\n\nconst parsedArgs = parsedJsonObject(() => ({}))\nconst parsedResponse = parsedJsonObject((raw) => ({ output: raw }))\n\n/**\n * `ToolCallOutput` only carries `call_id`; Gemini's `functionResponse`\n * requires the declared function `name`. Resolve the name by scanning prior\n * `function_call` items in the history for a matching `call_id`. If we\n * cannot resolve, fall back to `call_id` as the name - imperfect but\n * preserves stream shape so the model sees *some* response.\n */\nconst isFunctionCallItem = (item: HistoryItem): item is ToolCall => item.type === \"function_call\"\n\nconst nameForCallId = (\n history: ReadonlyArray<HistoryItem>,\n call_id: string,\n): Option.Option<string> =>\n pipe(\n history,\n Arr.findFirst((item): item is ToolCall => isFunctionCallItem(item) && item.call_id === call_id),\n Option.map((f) => f.name),\n )\n\n/**\n * Extract the Gemini-3 wire id and thought signature we stashed in\n * `providerData` on the way out. Schema-driven so the shape lives in one\n * place; failure or absence → `Option.none()`.\n */\nconst ProviderDataGemini = Schema.Struct({\n gemini: Schema.Struct({\n id: Schema.optional(Schema.String),\n thoughtSignature: Schema.optional(Schema.String),\n }),\n})\nconst decodeGemini = Schema.decodeUnknownResult(ProviderDataGemini)\n\nconst geminiField = (\n item: ToolCall,\n pick: (g: {\n readonly id?: string | undefined\n readonly thoughtSignature?: string | undefined\n }) => string | undefined,\n): Option.Option<string> =>\n pipe(\n decodeGemini(item.providerData),\n Result.match({\n onSuccess: (d) => Option.fromNullishOr(pick(d.gemini)),\n onFailure: () => Option.none<string>(),\n }),\n )\n\nconst providerIdFor = (item: ToolCall): Option.Option<string> => geminiField(item, (g) => g.id)\n\n// The originating call's Gemini id, looked up from history by our `call_id`.\n// Gemini 3 maps a `functionResponse` back to its call by this id, so parallel\n// calls to the same function are mis-paired if we drop it.\nconst providerIdForCallId = (\n history: ReadonlyArray<HistoryItem>,\n call_id: string,\n): Option.Option<string> =>\n pipe(\n history,\n Arr.findFirst((item): item is ToolCall => isFunctionCallItem(item) && item.call_id === call_id),\n Option.flatMap(providerIdFor),\n )\n\nconst signatureFor = (item: ToolCall): Option.Option<string> =>\n geminiField(item, (g) => g.thoughtSignature)\n\nconst itemToContent =\n (history: ReadonlyArray<HistoryItem>) =>\n (item: HistoryItem): Result.Result<RequestContent, void> =>\n Match.value(item).pipe(\n Match.discriminatorsExhaustive(\"type\")({\n message: messageToContent,\n function_call: (f) =>\n Result.succeed({\n role: \"model\" as const,\n parts: [\n {\n ...Option.match(signatureFor(f), {\n onSome: (thoughtSignature) => ({ thoughtSignature }),\n onNone: () => ({}),\n }),\n functionCall: {\n ...Option.match(providerIdFor(f), {\n onSome: (id) => ({ id }),\n onNone: () => ({}),\n }),\n name: f.name,\n args: parsedArgs(f.arguments),\n },\n },\n ],\n }),\n function_call_output: (o) =>\n Result.succeed({\n role: \"user\" as const,\n parts: [\n {\n functionResponse: {\n ...Option.match(providerIdForCallId(history, o.call_id), {\n onSome: (id) => ({ id }),\n onNone: () => ({}),\n }),\n name: Option.getOrElse(nameForCallId(history, o.call_id), () => o.call_id),\n response: parsedResponse(o.output),\n },\n },\n ],\n }),\n reasoning: () => Result.failVoid,\n }),\n )\n\n// ---------------------------------------------------------------------------\n// Tool descriptors → Gemini `functionDeclarations`. Gemini accepts only a\n// strict OpenAPI 3.0 subset for `parameters`; strip JSON-Schema keys it\n// rejects (`$schema`, `$ref`, `additionalProperties`, `oneOf`,\n// `definitions`).\n// ---------------------------------------------------------------------------\n\nconst UNSUPPORTED_SCHEMA_KEYS: ReadonlySet<string> = new Set([\n \"$schema\",\n \"$ref\",\n \"$defs\",\n \"definitions\",\n \"additionalProperties\",\n \"oneOf\",\n])\n\nconst sanitizeSchema = (schema: unknown): unknown => {\n if (Array.isArray(schema)) return schema.map(sanitizeSchema)\n if (schema === null || typeof schema !== \"object\") return schema\n return pipe(\n Object.entries(schema as Record<string, unknown>),\n Arr.filterMap(([k, v]) =>\n UNSUPPORTED_SCHEMA_KEYS.has(k)\n ? Result.failVoid\n : Result.succeed([k, sanitizeSchema(v)] as const),\n ),\n Object.fromEntries,\n )\n}\n\nconst toolDescriptorsToTools = (tools: ReadonlyArray<ToolDescriptor>): ReadonlyArray<RequestTool> =>\n tools.length === 0\n ? []\n : [\n {\n functionDeclarations: tools.map((t) => ({\n name: t.name,\n description: t.description,\n parameters: sanitizeSchema(t.inputSchema) as Record<string, unknown>,\n })),\n },\n ]\n\n/**\n * Map our cross-provider `toolChoice` onto Gemini's `functionCallingConfig`.\n * Gemini honours the same three modes plus a function allow-list, so the\n * choice is mapped, not dropped. `undefined` keeps the API default (`AUTO`).\n */\nconst toolChoiceToFunctionCallingConfig = (\n toolChoice: CommonRequest[\"toolChoice\"],\n): RequestToolConfig[\"functionCallingConfig\"] =>\n Match.value(toolChoice ?? \"auto\").pipe(\n Match.when(\"auto\", () => ({ mode: \"AUTO\" as const })),\n Match.when(\"required\", () => ({ mode: \"ANY\" as const })),\n Match.when(\"none\", () => ({ mode: \"NONE\" as const })),\n Match.orElse((tc) => ({ mode: \"ANY\" as const, allowedFunctionNames: [tc.name] })),\n )\n\n/**\n * URL-form images need Gemini's Files API (upload, then `fileData`); we\n * don't pre-upload, so such a part would otherwise vanish from the request.\n * The caller fails the request with `Unsupported` instead of silently\n * dropping the image.\n */\nexport const hasUrlImageSource = (history: ReadonlyArray<HistoryItem>): boolean =>\n history.some(\n (item) =>\n item.type === \"message\" &&\n item.content.some((b) => b.type === \"input_image\" && b.source._tag === \"url\"),\n )\n\nexport const buildRequestBody = (\n history: ReadonlyArray<HistoryItem>,\n generationConfig: Option.Option<GenerationConfig>,\n tools: ReadonlyArray<ToolDescriptor> = [],\n providerToolEntries: ReadonlyArray<RequestTool> = [],\n toolChoice: CommonRequest[\"toolChoice\"] = undefined,\n): RequestBody => {\n const systemTexts = pipe(allMessages(history), Arr.filterMap(systemMessageText))\n const contents = pipe(history, Arr.filterMap(itemToContent(history)))\n const functionTools = toolDescriptorsToTools(tools)\n const requestTools = [...functionTools, ...providerToolEntries]\n return {\n contents,\n ...(systemTexts.length > 0 && {\n systemInstruction: { parts: [{ text: systemTexts.join(\"\\n\") }] },\n }),\n ...Option.match(generationConfig, {\n onNone: () => ({}),\n onSome: (cfg) => ({ generationConfig: cfg }),\n }),\n ...(requestTools.length > 0 && { tools: requestTools }),\n // Only force a function-calling mode when there are function declarations;\n // a grounding-only request must keep the API default.\n ...(functionTools.length > 0 && {\n toolConfig: { functionCallingConfig: toolChoiceToFunctionCallingConfig(toolChoice) },\n }),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Stream-level state - accumulate chunk text + final usage/finish.\n//\n// `Accumulator` is immutable; `ingestChunk` returns a fresh one per chunk.\n// Drive it via `Stream.mapAccum` in the consumer.\n// ---------------------------------------------------------------------------\n\nconst finishReasonToStop = (reason: Option.Option<string>): Turn[\"stop_reason\"] =>\n Option.match(reason, {\n onNone: () => \"stop\" as const,\n onSome: (r) => (r === \"MAX_TOKENS\" ? (\"max_tokens\" as const) : (\"stop\" as const)),\n })\n\nexport type AccumulatedFunctionCall = {\n /** Synthesized id-or-name we surface as `call_id` on the canonical item. */\n readonly callId: string\n readonly name: string\n /** Wire id from Gemini 3, when present - echoed back on `functionResponse`. */\n readonly providerId: Option.Option<string>\n /** Thought signature from Gemini 3, replayed on the next request's part. */\n readonly signature: Option.Option<string>\n /** Args as JSON-encoded string, mirroring `Items.ToolCall.arguments`. */\n readonly arguments: string\n}\n\nexport type Accumulator = {\n readonly text: string\n readonly reasoning: string\n readonly functionCalls: ReadonlyArray<AccumulatedFunctionCall>\n /** Grounding citations, accumulated (de-duped by url) across chunks. */\n readonly annotations: ReadonlyArray<Annotation>\n readonly finishReason: Option.Option<string>\n readonly usage: {\n readonly input_tokens?: number\n readonly output_tokens?: number\n readonly total_tokens?: number\n readonly input_tokens_details?: { readonly cached_tokens?: number }\n readonly output_tokens_details?: { readonly reasoning_tokens?: number }\n }\n}\n\nexport const emptyAccumulator: Accumulator = {\n text: \"\",\n reasoning: \"\",\n functionCalls: [],\n annotations: [],\n finishReason: Option.none(),\n usage: {},\n}\n\n/**\n * One part's worth of streamable output. `text` and `reasoning` are\n * incremental string deltas; `function_call` arrives whole-in-one-chunk\n * (Gemini does not stream tool-call args).\n */\nexport type ChunkPart =\n | { readonly kind: \"text\"; readonly text: string }\n | { readonly kind: \"reasoning\"; readonly text: string }\n | {\n readonly kind: \"function_call\"\n readonly id: Option.Option<string>\n readonly signature: Option.Option<string>\n readonly name: string\n readonly args: unknown\n }\n\nexport type ChunkResult = {\n readonly accumulator: Accumulator\n readonly parts: ReadonlyArray<ChunkPart>\n readonly finished: boolean\n}\n\nconst isTextPart = (p: typeof Part.Type): p is typeof TextPart.Type => \"text\" in p\n\nconst textToChunkParts = (p: typeof TextPart.Type): ReadonlyArray<ChunkPart> =>\n p.text.length === 0 ? [] : [{ kind: p.thought === true ? \"reasoning\" : \"text\", text: p.text }]\n\nconst functionCallToChunkParts = (p: WireFunctionCallPart): ReadonlyArray<ChunkPart> => [\n {\n kind: \"function_call\",\n id: Option.fromNullishOr(p.functionCall.id),\n signature: Option.fromNullishOr(p.thoughtSignature),\n name: p.functionCall.name,\n args: p.functionCall.args ?? {},\n },\n]\n\nconst partToChunkParts = (p: typeof Part.Type): ReadonlyArray<ChunkPart> =>\n isTextPart(p) ? textToChunkParts(p) : functionCallToChunkParts(p)\n\nconst chunkParts = (chunk: WireChunk): ReadonlyArray<ChunkPart> =>\n pipe(chunk.candidates?.[0]?.content?.parts ?? [], Arr.flatMap(partToChunkParts))\n\nconst sumStrings = (parts: ReadonlyArray<ChunkPart>, kind: \"text\" | \"reasoning\"): string =>\n pipe(\n parts,\n Arr.filterMap((p) => (p.kind === kind ? Result.succeed(p.text) : Result.failVoid)),\n ).join(\"\")\n\nconst collectFunctionCalls = (\n parts: ReadonlyArray<ChunkPart>,\n): ReadonlyArray<Extract<ChunkPart, { kind: \"function_call\" }>> =>\n pipe(\n parts,\n Arr.filterMap((p) => (p.kind === \"function_call\" ? Result.succeed(p) : Result.failVoid)),\n )\n\nconst mergeUsage = (\n prev: Accumulator[\"usage\"],\n next: WireChunk[\"usageMetadata\"],\n): Accumulator[\"usage\"] =>\n next === undefined\n ? prev\n : {\n ...prev,\n ...(next.promptTokenCount !== undefined && { input_tokens: next.promptTokenCount }),\n ...(next.candidatesTokenCount !== undefined && {\n output_tokens: next.candidatesTokenCount,\n }),\n ...(next.totalTokenCount !== undefined && { total_tokens: next.totalTokenCount }),\n ...(next.cachedContentTokenCount !== undefined && {\n input_tokens_details: { cached_tokens: next.cachedContentTokenCount },\n }),\n ...(next.thoughtsTokenCount !== undefined && {\n output_tokens_details: { reasoning_tokens: next.thoughtsTokenCount },\n }),\n }\n\n/**\n * Synthesize a stable `call_id` for a function call. Gemini 3 provides one\n * via `functionCall.id`; older models do not, so we fall back to\n * `<name>_<index>` based on prior calls' position in the accumulator.\n */\nconst synthesizeCallId = (\n call: Extract<ChunkPart, { kind: \"function_call\" }>,\n priorCalls: ReadonlyArray<AccumulatedFunctionCall>,\n): string =>\n Option.match(call.id, {\n onSome: (id) => id,\n onNone: () => `${call.name}_${priorCalls.length}`,\n })\n\nconst chunkCallToAccumulated = (\n prior: ReadonlyArray<AccumulatedFunctionCall>,\n call: Extract<ChunkPart, { kind: \"function_call\" }>,\n): AccumulatedFunctionCall => ({\n callId: synthesizeCallId(call, prior),\n name: call.name,\n providerId: call.id,\n signature: call.signature,\n // `functionCallToChunkParts` already replaced null/undefined with `{}`,\n // so `call.args` is always a JSON-encodable value here.\n arguments: JSON.stringify(call.args),\n})\n\nconst appendFunctionCalls = (\n prior: ReadonlyArray<AccumulatedFunctionCall>,\n fromChunk: ReadonlyArray<Extract<ChunkPart, { kind: \"function_call\" }>>,\n): ReadonlyArray<AccumulatedFunctionCall> =>\n fromChunk.reduce<ReadonlyArray<AccumulatedFunctionCall>>(\n (acc, call) => [...acc, chunkCallToAccumulated(acc, call)],\n prior,\n )\n\n// Grounding usually arrives on the final chunk, but merge across chunks and\n// de-dupe by url so a mid-stream metadata block is not lost or double-counted.\nconst mergeAnnotations = (\n prev: ReadonlyArray<Annotation>,\n next: ReadonlyArray<Annotation>,\n): ReadonlyArray<Annotation> =>\n next.length === 0 ? prev : Arr.dedupeWith(Arr.appendAll(prev, next), sameUrlCitation)\n\nexport const ingestChunk = (acc: Accumulator, chunk: WireChunk): ChunkResult => {\n const parts = chunkParts(chunk)\n const finishReason = Option.fromNullishOr(chunk.candidates?.[0]?.finishReason)\n return {\n parts,\n finished: Option.isSome(finishReason),\n accumulator: {\n text: acc.text + sumStrings(parts, \"text\"),\n reasoning: acc.reasoning + sumStrings(parts, \"reasoning\"),\n functionCalls: appendFunctionCalls(acc.functionCalls, collectFunctionCalls(parts)),\n annotations: mergeAnnotations(\n acc.annotations,\n groundingToAnnotations(chunk.candidates?.[0]?.groundingMetadata),\n ),\n finishReason: Option.orElse(finishReason, () => acc.finishReason),\n usage: mergeUsage(acc.usage, chunk.usageMetadata),\n },\n }\n}\n\nconst reasoningItems = (acc: Accumulator): ReadonlyArray<HistoryItem> =>\n acc.reasoning.length > 0 ? [{ type: \"reasoning\", summary: acc.reasoning }] : []\n\nconst assistantMessageItems = (acc: Accumulator): ReadonlyArray<HistoryItem> =>\n acc.text.length === 0\n ? []\n : [\n {\n type: \"message\",\n role: \"assistant\",\n content: [\n {\n type: \"output_text\",\n text: acc.text,\n ...(acc.annotations.length > 0 && { annotations: acc.annotations }),\n },\n ],\n },\n ]\n\nconst functionCallItems = (acc: Accumulator): ReadonlyArray<HistoryItem> =>\n pipe(\n acc.functionCalls,\n Arr.map((c) => {\n const gemini = {\n ...(Option.isSome(c.providerId) && { id: c.providerId.value }),\n ...(Option.isSome(c.signature) && { thoughtSignature: c.signature.value }),\n }\n return {\n type: \"function_call\" as const,\n call_id: c.callId,\n name: c.name,\n arguments: c.arguments,\n ...(Object.keys(gemini).length > 0 && { providerData: { gemini } }),\n }\n }),\n )\n\nexport const accumulatorToTurn = (acc: Accumulator): Turn => ({\n stop_reason:\n acc.functionCalls.length > 0 ? (\"tool_calls\" as const) : finishReasonToStop(acc.finishReason),\n usage: { ...acc.usage },\n items: [...reasoningItems(acc), ...assistantMessageItems(acc), ...functionCallItems(acc)],\n})\n"],"mappings":";;;;;;;;;;;;;AAkBA,MAAM,WAAW,OAAO,OAAO;CAC7B,MAAM,OAAO;;;;;;CAMb,SAAS,OAAO,SAAS,OAAO,QAAQ;CACzC,CAAC;;;;;;;AAQF,MAAM,mBAAmB,OAAO,OAAO;CACrC,cAAc,OAAO,OAAO;EAC1B,IAAI,OAAO,SAAS,OAAO,OAAO;EAClC,MAAM,OAAO;EACb,MAAM,OAAO,SAAS,OAAO,QAAQ;EACtC,CAAC;CAGF,kBAAkB,OAAO,SAAS,OAAO,OAAO;CACjD,CAAC;AAEF,MAAM,OAAO,OAAO,MAAM,CAAC,UAAU,iBAAiB,CAAC;AAGvD,MAAM,UAAU,OAAO,OAAO;CAC5B,MAAM,OAAO,SAAS,OAAO,OAAO;CACpC,OAAO,OAAO,SAAS,OAAO,MAAM,KAAK,CAAC;CAC3C,CAAC;AAOF,MAAM,iBAAiB,OAAO,OAAO,EACnC,KAAK,OAAO,SACV,OAAO,OACL,OAAO,OAAO;CACZ,KAAK,OAAO,SAAS,OAAO,OAAO,OAAO,OAAO,CAAC;CAClD,OAAO,OAAO,SAAS,OAAO,OAAO,OAAO,OAAO,CAAC;CACrD,CAAC,CACH,CACF,EACF,CAAC;AACF,MAAa,oBAAoB,OAAO,OAAO,EAC7C,iBAAiB,OAAO,SAAS,OAAO,OAAO,OAAO,MAAM,eAAe,CAAC,CAAC,EAC9E,CAAC;AAIF,MAAM,mBAAmB,GAAe,MACtC,EAAE,SAAS,kBAAkB,EAAE,SAAS,kBAAkB,EAAE,QAAQ,EAAE;AAMxE,MAA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;CAAa,SAAS,IAAI;CAAW,CAAC,GAAG,EAAE;AAEjF,MAAM,yBAAyB,QAC7B,IAAI,KAAK,WAAW,IAChB,EAAE,GACF,CACE;CACE,MAAM;CACN,MAAM;CACN,SAAS,CACP;EACE,MAAM;EACN,MAAM,IAAI;EACV,GAAI,IAAI,YAAY,SAAS,KAAK,EAAE,aAAa,IAAI,aAAa;EACnE,CACF;CACF,CACF;AAEP,MAAM,qBAAqB,QACzB,KACE,IAAI,eACJA,QAAI,KAAK,MAAM;CACb,MAAM,SAAS;EACb,GAAI,OAAO,OAAO,EAAE,WAAW,IAAI,EAAE,IAAI,EAAE,WAAW,OAAO;EAC7D,GAAI,OAAO,OAAO,EAAE,UAAU,IAAI,EAAE,kBAAkB,EAAE,UAAU,OAAO;EAC1E;AACD,QAAO;EACL,MAAM;EACN,SAAS,EAAE;EACX,MAAM,EAAE;EACR,WAAW,EAAE;EACb,GAAI,OAAO,KAAK,OAAO,CAAC,SAAS,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE;EACnE;EACD,CACH;AAEH,MAAa,qBAAqB,SAA4B;CAC5D,aACE,IAAI,cAAc,SAAS,IAAK,eAAyB,mBAAmB,IAAI,aAAa;CAC/F,OAAO,EAAE,GAAG,IAAI,OAAO;CACvB,OAAO;EAAC,GAAG,eAAe,IAAI;EAAE,GAAG,sBAAsB,IAAI;EAAE,GAAG,kBAAkB,IAAI;EAAC;CAC1F"}
@@ -1,9 +1,10 @@
1
1
  import { codeExecutionTool, googleSearchTool, renderProviderTools } from "./GeminiTools.mjs";
2
- import { WireChunk, buildRequestBody } from "./codec.mjs";
2
+ import { WireChunk, accumulatorToTurn, buildRequestBody, emptyAccumulator, ingestChunk } from "./codec.mjs";
3
3
  import { i as it, n as globalExpect, r as describe } from "./dist-CWoAuwS9.mjs";
4
4
  import { Effect, Option, Result, Schema } from "effect";
5
5
  import * as Tool from "@effect-uai/core/Tool";
6
6
  import { descriptorsOf, providerToolsOf } from "@effect-uai/core/Tool";
7
+ import * as Turn$1 from "@effect-uai/core/Turn";
7
8
  //#region src/geminiTools.test.ts
8
9
  const localTool = Tool.make({
9
10
  name: "get_weather",
@@ -57,21 +58,39 @@ describe("Gemini provider tools", () => {
57
58
  }) }));
58
59
  globalExpect(Result.isFailure(result)).toBe(true);
59
60
  });
60
- it("decodes a grounded chunk without throwing (groundingMetadata is dropped)", () => {
61
- globalExpect(Schema.decodeUnknownSync(WireChunk)({ candidates: [{
61
+ it("maps groundingMetadata chunks to url_citation annotations on the turn", () => {
62
+ const chunk = Schema.decodeUnknownSync(WireChunk)({ candidates: [{
62
63
  content: {
63
64
  role: "model",
64
65
  parts: [{ text: "Grounded answer." }]
65
66
  },
66
67
  groundingMetadata: {
67
68
  webSearchQueries: ["effect ts"],
68
- groundingChunks: [{ web: {
69
- uri: "https://example.com",
70
- title: "Example"
71
- } }]
69
+ groundingChunks: [
70
+ { web: {
71
+ uri: "https://example.com",
72
+ title: "Example"
73
+ } },
74
+ { web: {
75
+ uri: "https://example.com",
76
+ title: "Example"
77
+ } },
78
+ { web: { uri: "https://effect.website" } }
79
+ ]
72
80
  },
73
81
  finishReason: "STOP"
74
- }] }).candidates?.[0]?.content?.parts?.[0]).toEqual({ text: "Grounded answer." });
82
+ }] });
83
+ globalExpect(chunk.candidates?.[0]?.content?.parts?.[0]).toEqual({ text: "Grounded answer." });
84
+ const turn = accumulatorToTurn(ingestChunk(emptyAccumulator, chunk).accumulator);
85
+ globalExpect(Turn$1.citations(turn)).toEqual([{
86
+ type: "url_citation",
87
+ url: "https://example.com",
88
+ title: "Example"
89
+ }, {
90
+ type: "url_citation",
91
+ url: "https://effect.website",
92
+ title: "https://effect.website"
93
+ }]);
75
94
  });
76
95
  });
77
96
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"geminiTools.test.mjs","names":["expect"],"sources":["../src/geminiTools.test.ts"],"sourcesContent":["import { Effect, Option, Result, Schema } from \"effect\"\nimport * as Tool from \"@effect-uai/core/Tool\"\nimport { descriptorsOf, providerToolsOf } from \"@effect-uai/core/Tool\"\nimport { describe, expect, it } from \"vitest\"\nimport { WireChunk, buildRequestBody } from \"./codec.js\"\nimport { codeExecutionTool, googleSearchTool, renderProviderTools } from \"./GeminiTools.js\"\n\nconst localTool = Tool.make({\n name: \"get_weather\",\n description: \"Look up the weather.\",\n inputSchema: Tool.fromEffectSchema(Schema.Struct({ city: Schema.String })),\n run: ({ city }) => Effect.succeed(`sunny in ${city}`),\n})\n\nconst build = (toolkit: Record<string, Tool.AnyTool>) => {\n const entries = Result.getOrThrow(renderProviderTools(providerToolsOf(toolkit)))\n return buildRequestBody([], Option.none(), descriptorsOf(toolkit), entries)\n}\n\ndescribe(\"Gemini provider tools\", () => {\n it(\"renders google_search to the native googleSearch entry\", () => {\n const body = build({ google_search: googleSearchTool })\n expect(body.tools).toEqual([{ googleSearch: {} }])\n })\n\n it(\"renders a mixed toolkit to both a functionDeclarations entry and the native entry\", () => {\n const body = build({ get_weather: localTool, code_execution: codeExecutionTool })\n expect(body.tools).toEqual([\n {\n functionDeclarations: [\n expect.objectContaining({ name: \"get_weather\", description: \"Look up the weather.\" }),\n ],\n },\n { codeExecution: {} },\n ])\n })\n\n it(\"omits toolConfig for a grounding-only request (no forced function-calling mode)\", () => {\n const body = build({ google_search: googleSearchTool })\n expect(body.toolConfig).toBeUndefined()\n })\n\n it(\"sets toolConfig when a function declaration is present\", () => {\n const body = build({ get_weather: localTool, google_search: googleSearchTool })\n expect(body.toolConfig).toEqual({ functionCallingConfig: { mode: \"AUTO\" } })\n })\n\n it(\"fails on a foreign provider tool\", () => {\n const foreign = Tool.provider({\n name: \"web_search\",\n description: \"Anthropic web search.\",\n inputSchema: Tool.noInput,\n provider: \"anthropic\",\n config: { type: \"web_search_20250305\" },\n })\n const result = renderProviderTools(providerToolsOf({ web_search: foreign }))\n expect(Result.isFailure(result)).toBe(true)\n })\n\n it(\"fails on an unrecognized config kind\", () => {\n const bogus = Tool.provider({\n name: \"mystery\",\n description: \"Unknown Gemini tool.\",\n inputSchema: Tool.noInput,\n provider: \"gemini\",\n config: { kind: \"telepathy\" },\n })\n const result = renderProviderTools(providerToolsOf({ mystery: bogus }))\n expect(Result.isFailure(result)).toBe(true)\n })\n\n it(\"decodes a grounded chunk without throwing (groundingMetadata is dropped)\", () => {\n const grounded = {\n candidates: [\n {\n content: { role: \"model\", parts: [{ text: \"Grounded answer.\" }] },\n groundingMetadata: {\n webSearchQueries: [\"effect ts\"],\n groundingChunks: [{ web: { uri: \"https://example.com\", title: \"Example\" } }],\n },\n finishReason: \"STOP\",\n },\n ],\n }\n const chunk = Schema.decodeUnknownSync(WireChunk)(grounded)\n expect(chunk.candidates?.[0]?.content?.parts?.[0]).toEqual({ text: \"Grounded answer.\" })\n })\n})\n"],"mappings":";;;;;;;AAOA,MAAM,YAAY,KAAK,KAAK;CAC1B,MAAM;CACN,aAAa;CACb,aAAa,KAAK,iBAAiB,OAAO,OAAO,EAAE,MAAM,OAAO,QAAQ,CAAC,CAAC;CAC1E,MAAM,EAAE,WAAW,OAAO,QAAQ,YAAY,OAAO;CACtD,CAAC;AAEF,MAAM,SAAS,YAA0C;CACvD,MAAM,UAAU,OAAO,WAAW,oBAAoB,gBAAgB,QAAQ,CAAC,CAAC;AAChF,QAAO,iBAAiB,EAAE,EAAE,OAAO,MAAM,EAAE,cAAc,QAAQ,EAAE,QAAQ;;AAG7E,SAAS,+BAA+B;AACtC,IAAG,gEAAgE;AAEjE,eADa,MAAM,EAAE,eAAe,kBAAkB,CAC3C,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,cAAc,EAAE,EAAE,CAAC,CAAC;GAClD;AAEF,IAAG,2FAA2F;AAE5F,eADa,MAAM;GAAE,aAAa;GAAW,gBAAgB;GAAmB,CACrE,CAAC,MAAM,CAAC,QAAQ,CACzB,EACE,sBAAsB,CACpBA,aAAO,iBAAiB;GAAE,MAAM;GAAe,aAAa;GAAwB,CAAC,CACtF,EACF,EACD,EAAE,eAAe,EAAE,EA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n"],"sources":["../src/geminiTools.test.ts"],"sourcesContent":["import { Effect, Option, Result, Schema } from \"effect\"\nimport * as Tool from \"@effect-uai/core/Tool\"\nimport { descriptorsOf, providerToolsOf } from \"@effect-uai/core/Tool\"\nimport * as Turn from \"@effect-uai/core/Turn\"\nimport { describe, expect, it } from \"vitest\"\nimport {\n WireChunk,\n accumulatorToTurn,\n buildRequestBody,\n emptyAccumulator,\n ingestChunk,\n} from \"./codec.js\"\nimport { codeExecutionTool, googleSearchTool, renderProviderTools } from \"./GeminiTools.js\"\n\nconst localTool = Tool.make({\n name: \"get_weather\",\n description: \"Look up the weather.\",\n inputSchema: Tool.fromEffectSchema(Schema.Struct({ city: Schema.String })),\n run: ({ city }) => Effect.succeed(`sunny in ${city}`),\n})\n\nconst build = (toolkit: Record<string, Tool.AnyTool>) => {\n const entries = Result.getOrThrow(renderProviderTools(providerToolsOf(toolkit)))\n return buildRequestBody([], Option.none(), descriptorsOf(toolkit), entries)\n}\n\ndescribe(\"Gemini provider tools\", () => {\n it(\"renders google_search to the native googleSearch entry\", () => {\n const body = build({ google_search: googleSearchTool })\n expect(body.tools).toEqual([{ googleSearch: {} }])\n })\n\n it(\"renders a mixed toolkit to both a functionDeclarations entry and the native entry\", () => {\n const body = build({ get_weather: localTool, code_execution: codeExecutionTool })\n expect(body.tools).toEqual([\n {\n functionDeclarations: [\n expect.objectContaining({ name: \"get_weather\", description: \"Look up the weather.\" }),\n ],\n },\n { codeExecution: {} },\n ])\n })\n\n it(\"omits toolConfig for a grounding-only request (no forced function-calling mode)\", () => {\n const body = build({ google_search: googleSearchTool })\n expect(body.toolConfig).toBeUndefined()\n })\n\n it(\"sets toolConfig when a function declaration is present\", () => {\n const body = build({ get_weather: localTool, google_search: googleSearchTool })\n expect(body.toolConfig).toEqual({ functionCallingConfig: { mode: \"AUTO\" } })\n })\n\n it(\"fails on a foreign provider tool\", () => {\n const foreign = Tool.provider({\n name: \"web_search\",\n description: \"Anthropic web search.\",\n inputSchema: Tool.noInput,\n provider: \"anthropic\",\n config: { type: \"web_search_20250305\" },\n })\n const result = renderProviderTools(providerToolsOf({ web_search: foreign }))\n expect(Result.isFailure(result)).toBe(true)\n })\n\n it(\"fails on an unrecognized config kind\", () => {\n const bogus = Tool.provider({\n name: \"mystery\",\n description: \"Unknown Gemini tool.\",\n inputSchema: Tool.noInput,\n provider: \"gemini\",\n config: { kind: \"telepathy\" },\n })\n const result = renderProviderTools(providerToolsOf({ mystery: bogus }))\n expect(Result.isFailure(result)).toBe(true)\n })\n\n it(\"maps groundingMetadata chunks to url_citation annotations on the turn\", () => {\n const grounded = {\n candidates: [\n {\n content: { role: \"model\", parts: [{ text: \"Grounded answer.\" }] },\n groundingMetadata: {\n webSearchQueries: [\"effect ts\"],\n groundingChunks: [\n { web: { uri: \"https://example.com\", title: \"Example\" } },\n // Duplicate uri (de-duped) and a bare-domain title fallback.\n { web: { uri: \"https://example.com\", title: \"Example\" } },\n { web: { uri: \"https://effect.website\" } },\n ],\n },\n finishReason: \"STOP\",\n },\n ],\n }\n const chunk = Schema.decodeUnknownSync(WireChunk)(grounded)\n expect(chunk.candidates?.[0]?.content?.parts?.[0]).toEqual({ text: \"Grounded answer.\" })\n\n const turn = accumulatorToTurn(ingestChunk(emptyAccumulator, chunk).accumulator)\n expect(Turn.citations(turn)).toEqual([\n { type: \"url_citation\", url: \"https://example.com\", title: \"Example\" },\n { type: \"url_citation\", url: \"https://effect.website\", title: \"https://effect.website\" },\n ])\n })\n})\n"],"mappings":";;;;;;;;AAcA,MAAM,YAAY,KAAK,KAAK;CAC1B,MAAM;CACN,aAAa;CACb,aAAa,KAAK,iBAAiB,OAAO,OAAO,EAAE,MAAM,OAAO,QAAQ,CAAC,CAAC;CAC1E,MAAM,EAAE,WAAW,OAAO,QAAQ,YAAY,OAAO;CACtD,CAAC;AAEF,MAAM,SAAS,YAA0C;CACvD,MAAM,UAAU,OAAO,WAAW,oBAAoB,gBAAgB,QAAQ,CAAC,CAAC;AAChF,QAAO,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3C;AAEF,IAAG,+EAA+E;EAkBhF,MAAM,QAAQ,OAAO,kBAAkB,UAAU,CAAC,EAhBhD,YAAY,CACV;GACE,SAAS;IAAE,MAAM;IAAS,OAAO,CAAC,EAAE,MAAM,oBAAoB,CAAC;IAAE;GACjE,mBAAmB;IACjB,kBAAkB,CAAC,YAAY;IAC/B,iBAAiB;KACf,EAAE,KAAK;MAAE,KAAK;MAAuB,OAAO;MAAW,EAAE;KAEzD,EAAE,KAAK;MAAE,KAAK;MAAuB,OAAO;MAAW,EAAE;KACzD,EAAE,KAAK,EAAE,KAAK,0BAA0B,EAAE;KAC3C;IACF;GACD,cAAc;GACf,CACF,EAEuD,CAAC;AAC3D,eAAO,MAAM,aAAa,IAAI,SAAS,QAAQ,GAAG,CAAC,QAAQ,EAAE,MAAM,oBAAoB,CAAC;EAExF,MAAM,OAAO,kBAAkB,YAAY,kBAAkB,MAAM,CAAC,YAAY;AAChF,eAAOC,OAAK,UAAU,KAAK,CAAC,CAAC,QAAQ,CACnC;GAAE,MAAM;GAAgB,KAAK;GAAuB,OAAO;GAAW,EACtE;GAAE,MAAM;GAAgB,KAAK;GAA0B,OAAO;GAA0B,CACzF,CAAC;GACF;EACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@effect-uai/google",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Google Gemini provider for @effect-uai/core.",
5
5
  "keywords": [
6
6
  "ai",
@@ -61,7 +61,7 @@
61
61
  "devDependencies": {
62
62
  "effect": "4.0.0-beta.94",
63
63
  "typescript": "^6.0.3",
64
- "@effect-uai/core": "0.11.0"
64
+ "@effect-uai/core": "0.12.0"
65
65
  },
66
66
  "peerDependencies": {
67
67
  "@effect-uai/core": ">=0.2.0 <1",
@@ -0,0 +1,80 @@
1
+ import { Schema } from "effect"
2
+ import * as Turn from "@effect-uai/core/Turn"
3
+ import { describe, expect, it } from "vitest"
4
+ import { WireInteraction, jobStateOf } from "./GoogleDeepResearch.js"
5
+
6
+ const decode = Schema.decodeUnknownSync(WireInteraction)
7
+
8
+ // Extract the `Turn` from a completed interaction the way the service does.
9
+ const turnOf = (raw: unknown): Turn.Turn => {
10
+ const state = jobStateOf(decode(raw))
11
+ if (state._tag !== "Succeeded") throw new Error(`expected Succeeded, got ${state._tag}`)
12
+ return state.result
13
+ }
14
+
15
+ describe("GoogleDeepResearch grounding", () => {
16
+ it("maps grounding chunks on a completed interaction to url_citation annotations", () => {
17
+ const turn = turnOf({
18
+ id: "int_1",
19
+ status: "completed",
20
+ outputs: [
21
+ {
22
+ type: "text",
23
+ text: "Report body [1][2].",
24
+ groundingMetadata: {
25
+ groundingChunks: [
26
+ {
27
+ web: {
28
+ uri: "https://vertexaisearch.cloud.google.com/grounding-api-redirect/abc",
29
+ title: "example.com",
30
+ },
31
+ },
32
+ {
33
+ web: { uri: "https://vertexaisearch.cloud.google.com/grounding-api-redirect/def" },
34
+ },
35
+ ],
36
+ },
37
+ },
38
+ ],
39
+ })
40
+ expect(Turn.assistantText(turn)).toBe("Report body [1][2].")
41
+ expect(Turn.citations(turn)).toEqual([
42
+ {
43
+ type: "url_citation",
44
+ url: "https://vertexaisearch.cloud.google.com/grounding-api-redirect/abc",
45
+ title: "example.com",
46
+ },
47
+ {
48
+ type: "url_citation",
49
+ url: "https://vertexaisearch.cloud.google.com/grounding-api-redirect/def",
50
+ title: "https://vertexaisearch.cloud.google.com/grounding-api-redirect/def",
51
+ },
52
+ ])
53
+ })
54
+
55
+ it("gathers and de-dupes grounding across interaction / output / step levels", () => {
56
+ const turn = turnOf({
57
+ id: "int_2",
58
+ status: "completed",
59
+ groundingMetadata: {
60
+ groundingChunks: [{ web: { uri: "https://a.example", title: "a" } }],
61
+ },
62
+ outputs: [{ type: "text", text: "Body." }],
63
+ steps: [
64
+ {
65
+ type: "research",
66
+ groundingMetadata: {
67
+ groundingChunks: [
68
+ { web: { uri: "https://a.example", title: "a" } },
69
+ { web: { uri: "https://b.example", title: "b" } },
70
+ ],
71
+ },
72
+ },
73
+ ],
74
+ })
75
+ expect(Turn.citations(turn).map((c) => c.type === "url_citation" && c.url)).toEqual([
76
+ "https://a.example",
77
+ "https://b.example",
78
+ ])
79
+ })
80
+ })