@effect-uai/google 0.10.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/Gemini.d.mts +11 -2
- package/dist/Gemini.d.mts.map +1 -1
- package/dist/Gemini.mjs +18 -6
- package/dist/Gemini.mjs.map +1 -1
- package/dist/GeminiEmbedding.mjs +1 -1
- package/dist/GeminiEmbedding.mjs.map +1 -1
- package/dist/GeminiSynthesizer.d.mts.map +1 -1
- package/dist/GeminiSynthesizer.mjs +2 -2
- package/dist/GeminiSynthesizer.mjs.map +1 -1
- package/dist/GeminiSynthesizer.test.mjs +1 -1
- package/dist/GeminiTools.d.mts +48 -0
- package/dist/GeminiTools.d.mts.map +1 -0
- package/dist/GeminiTools.mjs +64 -0
- package/dist/GeminiTools.mjs.map +1 -0
- package/dist/GoogleDeepResearch.d.mts +122 -0
- package/dist/GoogleDeepResearch.d.mts.map +1 -0
- package/dist/GoogleDeepResearch.mjs +320 -0
- package/dist/GoogleDeepResearch.mjs.map +1 -0
- package/dist/GoogleDeepResearch.test.d.mts +1 -0
- package/dist/GoogleDeepResearch.test.mjs +66 -0
- package/dist/GoogleDeepResearch.test.mjs.map +1 -0
- package/dist/LyriaGenerator.mjs +1 -1
- package/dist/LyriaGenerator.mjs.map +1 -1
- package/dist/LyriaGenerator.test.mjs +1 -1
- package/dist/codec.d.mts +38 -6
- package/dist/codec.d.mts.map +1 -1
- package/dist/codec.mjs +30 -8
- package/dist/codec.mjs.map +1 -1
- package/dist/{dist-DMsg8YLb.mjs → dist-CWoAuwS9.mjs} +7 -7
- package/dist/{dist-DMsg8YLb.mjs.map → dist-CWoAuwS9.mjs.map} +1 -1
- package/dist/geminiSpeechCodec.test.mjs +1 -1
- package/dist/geminiTools.test.d.mts +1 -0
- package/dist/geminiTools.test.mjs +99 -0
- package/dist/geminiTools.test.mjs.map +1 -0
- package/dist/index.d.mts +4 -2
- package/dist/index.mjs +3 -1
- package/dist/models.d.mts +11 -1
- package/dist/models.d.mts.map +1 -1
- package/package.json +8 -4
- package/src/Gemini.ts +21 -3
- package/src/GeminiEmbedding.ts +1 -1
- package/src/GeminiSynthesizer.ts +4 -2
- package/src/GeminiTools.ts +95 -0
- package/src/GoogleDeepResearch.test.ts +80 -0
- package/src/GoogleDeepResearch.ts +545 -0
- package/src/LyriaGenerator.ts +1 -1
- package/src/codec.ts +114 -12
- package/src/geminiTools.test.ts +106 -0
- package/src/index.ts +2 -0
- package/src/models.ts +15 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LyriaGenerator.mjs","names":[],"sources":["../src/LyriaGenerator.ts"],"sourcesContent":["import {\n Context,\n Duration,\n Effect,\n Encoding,\n Layer,\n Match,\n Redacted,\n Result,\n Schema,\n Stream,\n} from \"effect\"\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport type { AudioChunk, AudioFormat } from \"@effect-uai/core/Audio\"\nimport { warnDroppedWhen } from \"@effect-uai/core/Capabilities\"\nimport type {\n CommonGenerateMusicRequest,\n CommonStreamGenerateMusicRequest,\n GenerateResult,\n MusicResult,\n MusicSessionInput,\n MusicStreamEvent,\n} from \"@effect-uai/core/Music\"\nimport { singleVariant } from \"@effect-uai/core/Music\"\nimport { MusicGenerator, type MusicGeneratorService } from \"@effect-uai/core/MusicGenerator\"\nimport type { LyriaModel } from \"./models.js\"\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Lyria-typed generate request. Narrows `model` to `LyriaModel`.\n *\n * Lyria 3 sync `generateContent` has no structured wire fields for\n * `lyrics` / `duration` / `seed` / `instrumental` / `bpm` / `scale` /\n * etc. Those fields on the Common request are logged as\n * dropped-bucket-2 hints; the adapter never rewrites or augments the\n * caller's prompt on their behalf. If you want lyrics or vocal\n * suppression, include them in your `prompt` text yourself.\n *\n * Output format: only `audio/mp3` and `audio/wav` are accepted; other\n * containers fail `Unsupported`. The Clip model variant is fixed at\n * `audio/mp3`.\n */\nexport type LyriaGenerateRequest = Omit<CommonGenerateMusicRequest, \"model\"> & {\n readonly model: LyriaModel\n}\n\nexport type LyriaGeneratorService = {\n readonly generate: (\n request: LyriaGenerateRequest,\n ) => Effect.Effect<GenerateResult, AiError.AiError>\n readonly streamGeneration: (\n request: LyriaGenerateRequest,\n ) => Stream.Stream<AudioChunk, AiError.AiError>\n readonly streamGenerationFrom: <E, R>(\n input: Stream.Stream<MusicSessionInput, E, R>,\n request: CommonStreamGenerateMusicRequest,\n ) => Stream.Stream<MusicStreamEvent, AiError.AiError | E, R>\n}\n\nexport class LyriaGenerator extends Context.Service<LyriaGenerator, LyriaGeneratorService>()(\n \"@betalyra/effect-uai/providers/google/LyriaGenerator\",\n) {}\n\nexport type Config = {\n readonly apiKey: Redacted.Redacted\n readonly baseUrl?: string\n}\n\n// ---------------------------------------------------------------------------\n// Codec: AudioFormat → Lyria mimeType\n// ---------------------------------------------------------------------------\n\nexport type LyriaResponseMimeType = \"audio/mp3\" | \"audio/wav\"\n\nexport const containerToMimeType: (\n container: AudioFormat[\"container\"],\n) => Effect.Effect<LyriaResponseMimeType, AiError.AiError> = Match.type<\n AudioFormat[\"container\"]\n>().pipe(\n Match.when(\"mp3\", () => Effect.succeed<LyriaResponseMimeType>(\"audio/mp3\")),\n Match.when(\"wav\", () => Effect.succeed<LyriaResponseMimeType>(\"audio/wav\")),\n Match.whenOr(\"ogg\", \"opus\", \"flac\", \"aac\", \"webm\", \"raw\", (c) =>\n Effect.fail(\n new AiError.Unsupported({\n provider: \"lyria\",\n capability: \"outputFormat\",\n reason: `Lyria 3 only produces audio/mp3 or audio/wav; ${c} is not available. Use container: \"mp3\" or \"wav\".`,\n }),\n ),\n ),\n Match.exhaustive,\n)\n\n/**\n * Is this a Lyria 3 Clip model variant? Clip is fixed at 30 s MP3, it\n * does not accept a `responseFormat` on `generationConfig` (the live\n * API rejects unknown fields). Pro accepts the documented\n * `responseFormat` knob.\n */\nconst isClipModel = (model: string): boolean => model.includes(\"clip\")\n\nexport const realizedFormat: (mime: LyriaResponseMimeType) => AudioFormat =\n Match.type<LyriaResponseMimeType>().pipe(\n Match.when(\n \"audio/mp3\",\n (): AudioFormat => ({ container: \"mp3\", encoding: \"mp3\", sampleRate: 44100, channels: 2 }),\n ),\n Match.when(\n \"audio/wav\",\n (): AudioFormat => ({\n container: \"wav\",\n encoding: \"pcm_s16le\",\n sampleRate: 44100,\n channels: 2,\n }),\n ),\n Match.exhaustive,\n )\n\n// ---------------------------------------------------------------------------\n// Bucket-2 warn-and-drop for Common fields Lyria 3 can't honor\n// ---------------------------------------------------------------------------\n\n/**\n * Warn (don't fail) when the caller passed Common fields Lyria 3 has\n * no wire field for. Bucket-2 per capabilities policy: provider has\n * no structured interpretation; the output is still valid music, just\n * less aligned with the caller's hint. We never embed these into the\n * prompt on the caller's behalf, prompt construction is the\n * developer's job.\n */\nconst warnDroppedHints = (request: LyriaGenerateRequest): Effect.Effect<void> =>\n Effect.all(\n [\n warnDroppedWhen(request.lyrics, {\n provider: \"lyria\",\n capability: \"lyrics\",\n field: \"lyrics\",\n reason:\n \"Lyria 3 sync has no `lyrics` wire field. If you want vocals to follow specific lyrics, embed them in your prompt yourself (e.g. with `[Verse]` / `[Chorus]` tags).\",\n }),\n warnDroppedWhen(\n request.duration !== undefined ? Duration.toMillis(request.duration) : undefined,\n {\n provider: \"lyria\",\n capability: \"duration\",\n field: \"duration\",\n reason:\n \"Lyria 3 clip is fixed at 30 s; pro derives duration from prompt content. There is no wire field for duration. If you want to steer length, mention it in your prompt.\",\n },\n ),\n warnDroppedWhen(request.seed, {\n provider: \"lyria\",\n capability: \"seed\",\n field: \"seed\",\n reason:\n \"Lyria 3 (Gemini surface) does not expose a seed parameter. Output is non-deterministic across identical prompts. Use Lyria 2 (Vertex) for seeded generation.\",\n }),\n ],\n { discard: true },\n )\n\n// ---------------------------------------------------------------------------\n// Wire response schema\n// ---------------------------------------------------------------------------\n\nconst InlineData = Schema.Struct({\n mimeType: Schema.optional(Schema.String),\n data: Schema.String,\n})\n\nconst Part = Schema.Struct({\n text: Schema.optional(Schema.String),\n inlineData: Schema.optional(InlineData),\n})\n\nconst Content = Schema.Struct({\n parts: Schema.optional(Schema.Array(Part)),\n})\n\nconst Candidate = Schema.Struct({\n content: Schema.optional(Content),\n})\n\nconst Wire = Schema.Struct({\n candidates: Schema.optional(Schema.Array(Candidate)),\n})\n\nconst decodeWire = Schema.decodeUnknownEffect(Wire)\n\n// ---------------------------------------------------------------------------\n// HTTP plumbing\n// ---------------------------------------------------------------------------\n\nconst baseUrl = (cfg: Config): string =>\n cfg.baseUrl ?? \"https://generativelanguage.googleapis.com/v1beta\"\n\nconst transportFailure = (cause: unknown): AiError.AiError =>\n new AiError.Unavailable({ provider: \"lyria\", raw: cause })\n\nconst httpStatusError: (status: number, body: string) => AiError.AiError = (status, body) =>\n Match.value(status).pipe(\n Match.when(\n 429,\n (): AiError.AiError => new AiError.RateLimited({ provider: \"lyria\", raw: body }),\n ),\n Match.whenOr(\n 408,\n 504,\n (): AiError.AiError => new AiError.Timeout({ provider: \"lyria\", raw: body }),\n ),\n Match.when(\n 401,\n (): AiError.AiError =>\n new AiError.AuthFailed({ provider: \"lyria\", subtype: \"auth\", raw: body }),\n ),\n Match.when(\n 403,\n (): AiError.AiError =>\n new AiError.AuthFailed({ provider: \"lyria\", subtype: \"permission\", raw: body }),\n ),\n Match.when(\n 402,\n (): AiError.AiError =>\n new AiError.AuthFailed({ provider: \"lyria\", subtype: \"billing\", raw: body }),\n ),\n Match.when(\n (n) => n >= 500,\n (n): AiError.AiError => new AiError.Unavailable({ provider: \"lyria\", status: n, raw: body }),\n ),\n Match.orElse(\n (): AiError.AiError => new AiError.InvalidRequest({ provider: \"lyria\", raw: body }),\n ),\n )\n\nconst decodeBase64ToBytes = (b64: string): Effect.Effect<Uint8Array, AiError.AiError> =>\n Result.match(Encoding.decodeBase64(b64), {\n onSuccess: Effect.succeed,\n onFailure: (cause) =>\n Effect.fail(new AiError.InvalidRequest({ provider: \"lyria\", param: \"audio\", raw: cause })),\n })\n\n/**\n * Find the first inline-data audio part and the concatenated text parts\n * from a Wire response.\n */\nconst extractParts = (\n wire: typeof Wire.Type,\n): { readonly inline?: typeof InlineData.Type; readonly text?: string } => {\n const allParts = (wire.candidates ?? []).flatMap((c) => c.content?.parts ?? [])\n const inline = allParts.find((p) => p.inlineData !== undefined)?.inlineData\n const textParts = allParts.flatMap((p) => (p.text !== undefined ? [p.text] : []))\n const text = textParts.length === 0 ? undefined : textParts.join(\"\\n\")\n return {\n ...(inline !== undefined && { inline }),\n ...(text !== undefined && { text }),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Service implementation\n// ---------------------------------------------------------------------------\n\nconst generateImpl =\n (cfg: Config) =>\n (\n request: LyriaGenerateRequest,\n ): Effect.Effect<GenerateResult, AiError.AiError, HttpClient.HttpClient> =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const requestedContainer = (request.outputFormat?.container ??\n \"mp3\") satisfies AudioFormat[\"container\"]\n const requestedMime = yield* containerToMimeType(requestedContainer)\n // lyria-3-clip-preview has no `responseFormat` wire field and always\n // emits mp3, so there is no format to send and no 400 to surface. Rather\n // than keep a per-model table that rejects `wav`, report the format the\n // model actually produces (mp3) so the result is never mislabeled.\n // lyria-3-pro honours the requested container.\n const mimeType = isClipModel(request.model) ? (\"audio/mp3\" as const) : requestedMime\n yield* warnDroppedHints(request)\n const body = isClipModel(request.model)\n ? { contents: [{ parts: [{ text: request.prompt }] }] }\n : {\n contents: [{ parts: [{ text: request.prompt }] }],\n generationConfig: {\n responseModalities: [\"AUDIO\", \"TEXT\"],\n responseFormat: { audio: { mimeType } },\n },\n }\n const httpRequest = HttpClientRequest.post(\n `${baseUrl(cfg)}/models/${request.model}:generateContent`,\n ).pipe(\n HttpClientRequest.setHeader(\"x-goog-api-key\", Redacted.value(cfg.apiKey)),\n HttpClientRequest.bodyJsonUnsafe(body),\n )\n const response = yield* client.execute(httpRequest).pipe(Effect.mapError(transportFailure))\n if (response.status >= 400) {\n const text = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"))\n return yield* httpStatusError(response.status, text)\n }\n const json = yield* response.json.pipe(Effect.mapError(transportFailure))\n const wire = yield* decodeWire(json).pipe(\n Effect.mapError(\n (cause): AiError.AiError =>\n new AiError.GenerationFailed({ provider: \"lyria\", raw: cause }),\n ),\n )\n const { inline, text } = extractParts(wire)\n if (inline === undefined) {\n return yield* new AiError.GenerationFailed({\n provider: \"lyria\",\n raw: {\n message: \"Lyria response had no inlineData audio part.\",\n hint: \"Likely a prompt-filter rejection. Lyria filters references to real artists / copyrighted song lyrics. Rephrase with descriptive style language instead of artist names.\",\n textParts: text,\n response: json,\n },\n })\n }\n const bytes = yield* decodeBase64ToBytes(inline.data)\n const result: MusicResult = {\n audio: { format: realizedFormat(mimeType), bytes },\n provider: \"lyria\",\n ...(text !== undefined && { lyrics: text }),\n watermark: \"synthid\",\n }\n return singleVariant(result)\n })\n\nconst streamGenerationImpl =\n (cfg: Config) =>\n (\n request: LyriaGenerateRequest,\n ): Stream.Stream<AudioChunk, AiError.AiError, HttpClient.HttpClient> =>\n Stream.unwrap(\n Effect.map(generateImpl(cfg)(request), (result) =>\n Stream.succeed<AudioChunk>({ bytes: result.primary.audio.bytes }),\n ),\n )\n\n/**\n * Lyria 3 sync has no bidirectional session at the wire level, that's\n * Lyria RealTime (separate Layer). The provider Layer here also does\n * NOT register `MusicInteractiveSession`, so callers using\n * `MusicGenerator.streamGenerationFrom` against only this Layer get a\n * compile-time error before this runtime fallback ever fires.\n */\nconst streamGenerationFromUnsupported = <E, R>(\n _input: Stream.Stream<MusicSessionInput, E, R>,\n _request: CommonStreamGenerateMusicRequest,\n): Stream.Stream<MusicStreamEvent, AiError.AiError | E, R> => {\n const fail: Stream.Stream<MusicStreamEvent, AiError.AiError | E, R> = Stream.fail(\n new AiError.Unsupported({\n provider: \"lyria\",\n capability: \"streamGenerationFrom\",\n reason:\n \"Lyria 3 sync does not support bidirectional sessions. Use the Lyria RealTime Layer (WebSocket BidiGenerateMusic) for interactive mid-session prompts.\",\n }),\n )\n return fail\n}\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\nexport const make = (\n cfg: Config,\n): Effect.Effect<LyriaGeneratorService, never, HttpClient.HttpClient> =>\n Effect.map(HttpClient.HttpClient.asEffect(), (client) => ({\n generate: (request) =>\n generateImpl(cfg)(request).pipe(Effect.provideService(HttpClient.HttpClient, client)),\n streamGeneration: (request) =>\n streamGenerationImpl(cfg)(request).pipe(Stream.provideService(HttpClient.HttpClient, client)),\n streamGenerationFrom: streamGenerationFromUnsupported,\n }))\n\n/**\n * Layer that registers both the provider-specific `LyriaGenerator` tag\n * and the generic `MusicGenerator` tag.\n *\n * Does NOT register the `MusicInteractiveSession` capability marker,\n * Lyria 3 sync has no bidirectional session at the wire level. Code\n * calling `MusicGenerator.streamGenerationFrom` will fail to typecheck\n * against this Layer alone, which is the intended UX.\n */\nexport const layer = (\n cfg: Config,\n): Layer.Layer<LyriaGenerator | MusicGenerator, never, HttpClient.HttpClient> =>\n Layer.merge(\n Layer.effect(LyriaGenerator, make(cfg)),\n Layer.effect(\n MusicGenerator,\n Effect.map(\n make(cfg),\n (s): MusicGeneratorService => ({\n generate: (req: CommonGenerateMusicRequest) =>\n s.generate({ ...req, model: req.model as LyriaModel }),\n streamGeneration: (req: CommonStreamGenerateMusicRequest) =>\n s.streamGeneration({ ...req, model: req.model as LyriaModel }),\n streamGenerationFrom: s.streamGenerationFrom,\n }),\n ),\n ),\n )\n"],"mappings":";;;;;;;;;;;;;;;AA+DA,IAAa,iBAAb,cAAoC,QAAQ,SAAgD,CAC1F,uDACD,CAAC;AAaF,MAAa,sBAEgD,MAAM,MAEhE,CAAC,KACF,MAAM,KAAK,aAAa,OAAO,QAA+B,YAAY,CAAC,EAC3E,MAAM,KAAK,aAAa,OAAO,QAA+B,YAA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vB,EAAE;;;;;;;;;;AAWL,MAAa,SACX,QAEA,MAAM,MACJ,MAAM,OAAO,gBAAgB,KAAK,IAAI,CAAC,EACvC,MAAM,OACJ,gBACA,OAAO,IACL,KAAK,IAAI,GACR,OAA8B;CAC7B,WAAW,QACT,EAAE,SAAS;EAAE,GAAG;EAAK,OAAO,IAAI;EAAqB,CAAC;CACxD,mBAAmB,QACjB,EAAE,iBAAiB;EAAE,GAAG;EAAK,OAAO,IAAI;EAAqB,CAAC;CAChE,sBAAsB,EAAE;CACzB,EACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"LyriaGenerator.mjs","names":[],"sources":["../src/LyriaGenerator.ts"],"sourcesContent":["import {\n Context,\n Duration,\n Effect,\n Encoding,\n Layer,\n Match,\n Redacted,\n Result,\n Schema,\n Stream,\n} from \"effect\"\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport type { AudioChunk, AudioFormat } from \"@effect-uai/core/Audio\"\nimport { warnDroppedWhen } from \"@effect-uai/core/Capabilities\"\nimport type {\n CommonGenerateMusicRequest,\n CommonStreamGenerateMusicRequest,\n GenerateResult,\n MusicResult,\n MusicSessionInput,\n MusicStreamEvent,\n} from \"@effect-uai/core/Music\"\nimport { singleVariant } from \"@effect-uai/core/Music\"\nimport { MusicGenerator, type MusicGeneratorService } from \"@effect-uai/core/MusicGenerator\"\nimport type { LyriaModel } from \"./models.js\"\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Lyria-typed generate request. Narrows `model` to `LyriaModel`.\n *\n * Lyria 3 sync `generateContent` has no structured wire fields for\n * `lyrics` / `duration` / `seed` / `instrumental` / `bpm` / `scale` /\n * etc. Those fields on the Common request are logged as\n * dropped-bucket-2 hints; the adapter never rewrites or augments the\n * caller's prompt on their behalf. If you want lyrics or vocal\n * suppression, include them in your `prompt` text yourself.\n *\n * Output format: only `audio/mp3` and `audio/wav` are accepted; other\n * containers fail `Unsupported`. The Clip model variant is fixed at\n * `audio/mp3`.\n */\nexport type LyriaGenerateRequest = Omit<CommonGenerateMusicRequest, \"model\"> & {\n readonly model: LyriaModel\n}\n\nexport type LyriaGeneratorService = {\n readonly generate: (\n request: LyriaGenerateRequest,\n ) => Effect.Effect<GenerateResult, AiError.AiError>\n readonly streamGeneration: (\n request: LyriaGenerateRequest,\n ) => Stream.Stream<AudioChunk, AiError.AiError>\n readonly streamGenerationFrom: <E, R>(\n input: Stream.Stream<MusicSessionInput, E, R>,\n request: CommonStreamGenerateMusicRequest,\n ) => Stream.Stream<MusicStreamEvent, AiError.AiError | E, R>\n}\n\nexport class LyriaGenerator extends Context.Service<LyriaGenerator, LyriaGeneratorService>()(\n \"@betalyra/effect-uai/providers/google/LyriaGenerator\",\n) {}\n\nexport type Config = {\n readonly apiKey: Redacted.Redacted\n readonly baseUrl?: string\n}\n\n// ---------------------------------------------------------------------------\n// Codec: AudioFormat → Lyria mimeType\n// ---------------------------------------------------------------------------\n\nexport type LyriaResponseMimeType = \"audio/mp3\" | \"audio/wav\"\n\nexport const containerToMimeType: (\n container: AudioFormat[\"container\"],\n) => Effect.Effect<LyriaResponseMimeType, AiError.AiError> = Match.type<\n AudioFormat[\"container\"]\n>().pipe(\n Match.when(\"mp3\", () => Effect.succeed<LyriaResponseMimeType>(\"audio/mp3\")),\n Match.when(\"wav\", () => Effect.succeed<LyriaResponseMimeType>(\"audio/wav\")),\n Match.whenOr(\"ogg\", \"opus\", \"flac\", \"aac\", \"webm\", \"raw\", (c) =>\n Effect.fail(\n new AiError.Unsupported({\n provider: \"lyria\",\n capability: \"outputFormat\",\n reason: `Lyria 3 only produces audio/mp3 or audio/wav; ${c} is not available. Use container: \"mp3\" or \"wav\".`,\n }),\n ),\n ),\n Match.exhaustive,\n)\n\n/**\n * Is this a Lyria 3 Clip model variant? Clip is fixed at 30 s MP3, it\n * does not accept a `responseFormat` on `generationConfig` (the live\n * API rejects unknown fields). Pro accepts the documented\n * `responseFormat` knob.\n */\nconst isClipModel = (model: string): boolean => model.includes(\"clip\")\n\nexport const realizedFormat: (mime: LyriaResponseMimeType) => AudioFormat =\n Match.type<LyriaResponseMimeType>().pipe(\n Match.when(\n \"audio/mp3\",\n (): AudioFormat => ({ container: \"mp3\", encoding: \"mp3\", sampleRate: 44100, channels: 2 }),\n ),\n Match.when(\n \"audio/wav\",\n (): AudioFormat => ({\n container: \"wav\",\n encoding: \"pcm_s16le\",\n sampleRate: 44100,\n channels: 2,\n }),\n ),\n Match.exhaustive,\n )\n\n// ---------------------------------------------------------------------------\n// Bucket-2 warn-and-drop for Common fields Lyria 3 can't honor\n// ---------------------------------------------------------------------------\n\n/**\n * Warn (don't fail) when the caller passed Common fields Lyria 3 has\n * no wire field for. Bucket-2 per capabilities policy: provider has\n * no structured interpretation; the output is still valid music, just\n * less aligned with the caller's hint. We never embed these into the\n * prompt on the caller's behalf, prompt construction is the\n * developer's job.\n */\nconst warnDroppedHints = (request: LyriaGenerateRequest): Effect.Effect<void> =>\n Effect.all(\n [\n warnDroppedWhen(request.lyrics, {\n provider: \"lyria\",\n capability: \"lyrics\",\n field: \"lyrics\",\n reason:\n \"Lyria 3 sync has no `lyrics` wire field. If you want vocals to follow specific lyrics, embed them in your prompt yourself (e.g. with `[Verse]` / `[Chorus]` tags).\",\n }),\n warnDroppedWhen(\n request.duration !== undefined ? Duration.toMillis(request.duration) : undefined,\n {\n provider: \"lyria\",\n capability: \"duration\",\n field: \"duration\",\n reason:\n \"Lyria 3 clip is fixed at 30 s; pro derives duration from prompt content. There is no wire field for duration. If you want to steer length, mention it in your prompt.\",\n },\n ),\n warnDroppedWhen(request.seed, {\n provider: \"lyria\",\n capability: \"seed\",\n field: \"seed\",\n reason:\n \"Lyria 3 (Gemini surface) does not expose a seed parameter. Output is non-deterministic across identical prompts. Use Lyria 2 (Vertex) for seeded generation.\",\n }),\n ],\n { discard: true },\n )\n\n// ---------------------------------------------------------------------------\n// Wire response schema\n// ---------------------------------------------------------------------------\n\nconst InlineData = Schema.Struct({\n mimeType: Schema.optional(Schema.String),\n data: Schema.String,\n})\n\nconst Part = Schema.Struct({\n text: Schema.optional(Schema.String),\n inlineData: Schema.optional(InlineData),\n})\n\nconst Content = Schema.Struct({\n parts: Schema.optional(Schema.Array(Part)),\n})\n\nconst Candidate = Schema.Struct({\n content: Schema.optional(Content),\n})\n\nconst Wire = Schema.Struct({\n candidates: Schema.optional(Schema.Array(Candidate)),\n})\n\nconst decodeWire = Schema.decodeUnknownEffect(Wire)\n\n// ---------------------------------------------------------------------------\n// HTTP plumbing\n// ---------------------------------------------------------------------------\n\nconst baseUrl = (cfg: Config): string =>\n cfg.baseUrl ?? \"https://generativelanguage.googleapis.com/v1beta\"\n\nconst transportFailure = (cause: unknown): AiError.AiError =>\n new AiError.Unavailable({ provider: \"lyria\", raw: cause })\n\nconst httpStatusError: (status: number, body: string) => AiError.AiError = (status, body) =>\n Match.value(status).pipe(\n Match.when(\n 429,\n (): AiError.AiError => new AiError.RateLimited({ provider: \"lyria\", raw: body }),\n ),\n Match.whenOr(\n 408,\n 504,\n (): AiError.AiError => new AiError.Timeout({ provider: \"lyria\", raw: body }),\n ),\n Match.when(\n 401,\n (): AiError.AiError =>\n new AiError.AuthFailed({ provider: \"lyria\", subtype: \"auth\", raw: body }),\n ),\n Match.when(\n 403,\n (): AiError.AiError =>\n new AiError.AuthFailed({ provider: \"lyria\", subtype: \"permission\", raw: body }),\n ),\n Match.when(\n 402,\n (): AiError.AiError =>\n new AiError.AuthFailed({ provider: \"lyria\", subtype: \"billing\", raw: body }),\n ),\n Match.when(\n (n) => n >= 500,\n (n): AiError.AiError => new AiError.Unavailable({ provider: \"lyria\", status: n, raw: body }),\n ),\n Match.orElse(\n (): AiError.AiError => new AiError.InvalidRequest({ provider: \"lyria\", raw: body }),\n ),\n )\n\nconst decodeBase64ToBytes = (b64: string): Effect.Effect<Uint8Array, AiError.AiError> =>\n Result.match(Encoding.decodeBase64(b64), {\n onSuccess: Effect.succeed,\n onFailure: (cause) =>\n Effect.fail(new AiError.InvalidRequest({ provider: \"lyria\", param: \"audio\", raw: cause })),\n })\n\n/**\n * Find the first inline-data audio part and the concatenated text parts\n * from a Wire response.\n */\nconst extractParts = (\n wire: typeof Wire.Type,\n): { readonly inline?: typeof InlineData.Type; readonly text?: string } => {\n const allParts = (wire.candidates ?? []).flatMap((c) => c.content?.parts ?? [])\n const inline = allParts.find((p) => p.inlineData !== undefined)?.inlineData\n const textParts = allParts.flatMap((p) => (p.text !== undefined ? [p.text] : []))\n const text = textParts.length === 0 ? undefined : textParts.join(\"\\n\")\n return {\n ...(inline !== undefined && { inline }),\n ...(text !== undefined && { text }),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Service implementation\n// ---------------------------------------------------------------------------\n\nconst generateImpl =\n (cfg: Config) =>\n (\n request: LyriaGenerateRequest,\n ): Effect.Effect<GenerateResult, AiError.AiError, HttpClient.HttpClient> =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const requestedContainer = (request.outputFormat?.container ??\n \"mp3\") satisfies AudioFormat[\"container\"]\n const requestedMime = yield* containerToMimeType(requestedContainer)\n // lyria-3-clip-preview has no `responseFormat` wire field and always\n // emits mp3, so there is no format to send and no 400 to surface. Rather\n // than keep a per-model table that rejects `wav`, report the format the\n // model actually produces (mp3) so the result is never mislabeled.\n // lyria-3-pro honours the requested container.\n const mimeType = isClipModel(request.model) ? (\"audio/mp3\" as const) : requestedMime\n yield* warnDroppedHints(request)\n const body = isClipModel(request.model)\n ? { contents: [{ parts: [{ text: request.prompt }] }] }\n : {\n contents: [{ parts: [{ text: request.prompt }] }],\n generationConfig: {\n responseModalities: [\"AUDIO\", \"TEXT\"],\n responseFormat: { audio: { mimeType } },\n },\n }\n const httpRequest = HttpClientRequest.post(\n `${baseUrl(cfg)}/models/${request.model}:generateContent`,\n ).pipe(\n HttpClientRequest.setHeader(\"x-goog-api-key\", Redacted.value(cfg.apiKey)),\n HttpClientRequest.bodyJsonUnsafe(body),\n )\n const response = yield* client.execute(httpRequest).pipe(Effect.mapError(transportFailure))\n if (response.status >= 400) {\n const text = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"))\n return yield* httpStatusError(response.status, text)\n }\n const json = yield* response.json.pipe(Effect.mapError(transportFailure))\n const wire = yield* decodeWire(json).pipe(\n Effect.mapError(\n (cause): AiError.AiError =>\n new AiError.GenerationFailed({ provider: \"lyria\", raw: cause }),\n ),\n )\n const { inline, text } = extractParts(wire)\n if (inline === undefined) {\n return yield* new AiError.GenerationFailed({\n provider: \"lyria\",\n raw: {\n message: \"Lyria response had no inlineData audio part.\",\n hint: \"Likely a prompt-filter rejection. Lyria filters references to real artists / copyrighted song lyrics. Rephrase with descriptive style language instead of artist names.\",\n textParts: text,\n response: json,\n },\n })\n }\n const bytes = yield* decodeBase64ToBytes(inline.data)\n const result: MusicResult = {\n audio: { format: realizedFormat(mimeType), bytes },\n provider: \"lyria\",\n ...(text !== undefined && { lyrics: text }),\n watermark: \"synthid\",\n }\n return singleVariant(result)\n })\n\nconst streamGenerationImpl =\n (cfg: Config) =>\n (\n request: LyriaGenerateRequest,\n ): Stream.Stream<AudioChunk, AiError.AiError, HttpClient.HttpClient> =>\n Stream.unwrap(\n Effect.map(generateImpl(cfg)(request), (result) =>\n Stream.succeed<AudioChunk>({ bytes: result.primary.audio.bytes }),\n ),\n )\n\n/**\n * Lyria 3 sync has no bidirectional session at the wire level, that's\n * Lyria RealTime (separate Layer). The provider Layer here also does\n * NOT register `MusicInteractiveSession`, so callers using\n * `MusicGenerator.streamGenerationFrom` against only this Layer get a\n * compile-time error before this runtime fallback ever fires.\n */\nconst streamGenerationFromUnsupported = <E, R>(\n _input: Stream.Stream<MusicSessionInput, E, R>,\n _request: CommonStreamGenerateMusicRequest,\n): Stream.Stream<MusicStreamEvent, AiError.AiError | E, R> => {\n const fail: Stream.Stream<MusicStreamEvent, AiError.AiError | E, R> = Stream.fail(\n new AiError.Unsupported({\n provider: \"lyria\",\n capability: \"streamGenerationFrom\",\n reason:\n \"Lyria 3 sync does not support bidirectional sessions. Use the Lyria RealTime Layer (WebSocket BidiGenerateMusic) for interactive mid-session prompts.\",\n }),\n )\n return fail\n}\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\nexport const make = (\n cfg: Config,\n): Effect.Effect<LyriaGeneratorService, never, HttpClient.HttpClient> =>\n Effect.map(HttpClient.HttpClient, (client) => ({\n generate: (request) =>\n generateImpl(cfg)(request).pipe(Effect.provideService(HttpClient.HttpClient, client)),\n streamGeneration: (request) =>\n streamGenerationImpl(cfg)(request).pipe(Stream.provideService(HttpClient.HttpClient, client)),\n streamGenerationFrom: streamGenerationFromUnsupported,\n }))\n\n/**\n * Layer that registers both the provider-specific `LyriaGenerator` tag\n * and the generic `MusicGenerator` tag.\n *\n * Does NOT register the `MusicInteractiveSession` capability marker,\n * Lyria 3 sync has no bidirectional session at the wire level. Code\n * calling `MusicGenerator.streamGenerationFrom` will fail to typecheck\n * against this Layer alone, which is the intended UX.\n */\nexport const layer = (\n cfg: Config,\n): Layer.Layer<LyriaGenerator | MusicGenerator, never, HttpClient.HttpClient> =>\n Layer.merge(\n Layer.effect(LyriaGenerator, make(cfg)),\n Layer.effect(\n MusicGenerator,\n Effect.map(\n make(cfg),\n (s): MusicGeneratorService => ({\n generate: (req: CommonGenerateMusicRequest) =>\n s.generate({ ...req, model: req.model as LyriaModel }),\n streamGeneration: (req: CommonStreamGenerateMusicRequest) =>\n s.streamGeneration({ ...req, model: req.model as LyriaModel }),\n streamGenerationFrom: s.streamGenerationFrom,\n }),\n ),\n ),\n )\n"],"mappings":";;;;;;;;;;;;;;;AA+DA,IAAa,iBAAb,cAAoC,QAAQ,SAAgD,CAC1F,uDACD,CAAC;AAaF,MAAa,sBAEgD,MAAM,MAEhE,CAAC,KACF,MAAM,KAAK,aAAa,OAAO,QAA+B,YAAY,CAAC,EAC3E,MAAM,KAAK,aAAa,OAAO,QAA+B,Y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;;;;;;;;;;AAWL,MAAa,SACX,QAEA,MAAM,MACJ,MAAM,OAAO,gBAAgB,KAAK,IAAI,CAAC,EACvC,MAAM,OACJ,gBACA,OAAO,IACL,KAAK,IAAI,GACR,OAA8B;CAC7B,WAAW,QACT,EAAE,SAAS;EAAE,GAAG;EAAK,OAAO,IAAI;EAAqB,CAAC;CACxD,mBAAmB,QACjB,EAAE,iBAAiB;EAAE,GAAG;EAAK,OAAO,IAAI;EAAqB,CAAC;CAChE,sBAAsB,EAAE;CACzB,EACF,CACF,CACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as it, n as globalExpect, r as describe, t as import_dist } from "./dist-
|
|
1
|
+
import { i as it, n as globalExpect, r as describe, t as import_dist } from "./dist-CWoAuwS9.mjs";
|
|
2
2
|
import { LyriaGenerator, containerToMimeType, layer, realizedFormat } from "./LyriaGenerator.mjs";
|
|
3
3
|
import { Duration, Effect, Layer, Redacted, Stream } from "effect";
|
|
4
4
|
import { FetchHttpClient } from "effect/unstable/http";
|
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, 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
|
};
|
|
@@ -70,13 +89,25 @@ type RequestSystemInstruction = {
|
|
|
70
89
|
readonly text: string;
|
|
71
90
|
}>;
|
|
72
91
|
};
|
|
73
|
-
/**
|
|
92
|
+
/**
|
|
93
|
+
* Gemini's tool declaration. A `tools[]` entry is either a function-declaration
|
|
94
|
+
* block (translated from `ToolDescriptor`s) or one of the native hosted-tool
|
|
95
|
+
* entries. The native entries are empty objects keyed camelCase per the REST
|
|
96
|
+
* v1beta `Tool` object, and sit as siblings of the declarations in the same
|
|
97
|
+
* `tools` array.
|
|
98
|
+
*/
|
|
74
99
|
type RequestTool = {
|
|
75
100
|
readonly functionDeclarations: ReadonlyArray<{
|
|
76
101
|
readonly name: string;
|
|
77
102
|
readonly description: string;
|
|
78
103
|
readonly parameters: Record<string, unknown>;
|
|
79
104
|
}>;
|
|
105
|
+
} | {
|
|
106
|
+
readonly googleSearch: {};
|
|
107
|
+
} | {
|
|
108
|
+
readonly urlContext: {};
|
|
109
|
+
} | {
|
|
110
|
+
readonly codeExecution: {};
|
|
80
111
|
};
|
|
81
112
|
type RequestToolConfig = {
|
|
82
113
|
readonly functionCallingConfig: {
|
|
@@ -109,7 +140,7 @@ type RequestBody = {
|
|
|
109
140
|
* dropping the image.
|
|
110
141
|
*/
|
|
111
142
|
declare const hasUrlImageSource: (history: ReadonlyArray<HistoryItem>) => boolean;
|
|
112
|
-
declare const buildRequestBody: (history: ReadonlyArray<HistoryItem>, generationConfig: Option.Option<GenerationConfig>, tools?: ReadonlyArray<ToolDescriptor>, toolChoice?: CommonRequest["toolChoice"]) => RequestBody;
|
|
143
|
+
declare const buildRequestBody: (history: ReadonlyArray<HistoryItem>, generationConfig: Option.Option<GenerationConfig>, tools?: ReadonlyArray<ToolDescriptor>, providerToolEntries?: ReadonlyArray<RequestTool>, toolChoice?: CommonRequest["toolChoice"]) => RequestBody;
|
|
113
144
|
type AccumulatedFunctionCall = {
|
|
114
145
|
/** Synthesized id-or-name we surface as `call_id` on the canonical item. */readonly callId: string;
|
|
115
146
|
readonly name: string; /** Wire id from Gemini 3, when present - echoed back on `functionResponse`. */
|
|
@@ -120,7 +151,8 @@ type AccumulatedFunctionCall = {
|
|
|
120
151
|
type Accumulator = {
|
|
121
152
|
readonly text: string;
|
|
122
153
|
readonly reasoning: string;
|
|
123
|
-
readonly functionCalls: ReadonlyArray<AccumulatedFunctionCall>;
|
|
154
|
+
readonly functionCalls: ReadonlyArray<AccumulatedFunctionCall>; /** Grounding citations, accumulated (de-duped by url) across chunks. */
|
|
155
|
+
readonly annotations: ReadonlyArray<Annotation>;
|
|
124
156
|
readonly finishReason: Option.Option<string>;
|
|
125
157
|
readonly usage: {
|
|
126
158
|
readonly input_tokens?: number;
|
|
@@ -161,5 +193,5 @@ type ChunkResult = {
|
|
|
161
193
|
declare const ingestChunk: (acc: Accumulator, chunk: WireChunk) => ChunkResult;
|
|
162
194
|
declare const accumulatorToTurn: (acc: Accumulator) => Turn;
|
|
163
195
|
//#endregion
|
|
164
|
-
export { AccumulatedFunctionCall, Accumulator, ChunkPart, ChunkResult, GenerationConfig, RequestBody, 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 };
|
|
165
197
|
//# sourceMappingURL=codec.d.mts.map
|
package/dist/codec.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codec.d.mts","names":[],"sources":["../src/codec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AAA;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
|
} }]
|
|
@@ -191,10 +210,11 @@ const toolChoiceToFunctionCallingConfig = (toolChoice) => Match.value(toolChoice
|
|
|
191
210
|
* dropping the image.
|
|
192
211
|
*/
|
|
193
212
|
const hasUrlImageSource = (history) => history.some((item) => item.type === "message" && item.content.some((b) => b.type === "input_image" && b.source._tag === "url"));
|
|
194
|
-
const buildRequestBody = (history, generationConfig, tools = [], toolChoice = void 0) => {
|
|
213
|
+
const buildRequestBody = (history, generationConfig, tools = [], providerToolEntries = [], toolChoice = void 0) => {
|
|
195
214
|
const systemTexts = pipe(allMessages(history), Array$1.filterMap(systemMessageText));
|
|
196
215
|
const contents = pipe(history, Array$1.filterMap(itemToContent(history)));
|
|
197
|
-
const
|
|
216
|
+
const functionTools = toolDescriptorsToTools(tools);
|
|
217
|
+
const requestTools = [...functionTools, ...providerToolEntries];
|
|
198
218
|
return {
|
|
199
219
|
contents,
|
|
200
220
|
...systemTexts.length > 0 && { systemInstruction: { parts: [{ text: systemTexts.join("\n") }] } },
|
|
@@ -202,10 +222,8 @@ const buildRequestBody = (history, generationConfig, tools = [], toolChoice = vo
|
|
|
202
222
|
onNone: () => ({}),
|
|
203
223
|
onSome: (cfg) => ({ generationConfig: cfg })
|
|
204
224
|
}),
|
|
205
|
-
...requestTools.length > 0 && {
|
|
206
|
-
|
|
207
|
-
toolConfig: { functionCallingConfig: toolChoiceToFunctionCallingConfig(toolChoice) }
|
|
208
|
-
}
|
|
225
|
+
...requestTools.length > 0 && { tools: requestTools },
|
|
226
|
+
...functionTools.length > 0 && { toolConfig: { functionCallingConfig: toolChoiceToFunctionCallingConfig(toolChoice) } }
|
|
209
227
|
};
|
|
210
228
|
};
|
|
211
229
|
const finishReasonToStop = (reason) => Option.match(reason, {
|
|
@@ -216,6 +234,7 @@ const emptyAccumulator = {
|
|
|
216
234
|
text: "",
|
|
217
235
|
reasoning: "",
|
|
218
236
|
functionCalls: [],
|
|
237
|
+
annotations: [],
|
|
219
238
|
finishReason: Option.none(),
|
|
220
239
|
usage: {}
|
|
221
240
|
};
|
|
@@ -260,6 +279,7 @@ const chunkCallToAccumulated = (prior, call) => ({
|
|
|
260
279
|
arguments: JSON.stringify(call.args)
|
|
261
280
|
});
|
|
262
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);
|
|
263
283
|
const ingestChunk = (acc, chunk) => {
|
|
264
284
|
const parts = chunkParts(chunk);
|
|
265
285
|
const finishReason = Option.fromNullishOr(chunk.candidates?.[0]?.finishReason);
|
|
@@ -270,6 +290,7 @@ const ingestChunk = (acc, chunk) => {
|
|
|
270
290
|
text: acc.text + sumStrings(parts, "text"),
|
|
271
291
|
reasoning: acc.reasoning + sumStrings(parts, "reasoning"),
|
|
272
292
|
functionCalls: appendFunctionCalls(acc.functionCalls, collectFunctionCalls(parts)),
|
|
293
|
+
annotations: mergeAnnotations(acc.annotations, groundingToAnnotations(chunk.candidates?.[0]?.groundingMetadata)),
|
|
273
294
|
finishReason: Option.orElse(finishReason, () => acc.finishReason),
|
|
274
295
|
usage: mergeUsage(acc.usage, chunk.usageMetadata)
|
|
275
296
|
}
|
|
@@ -284,7 +305,8 @@ const assistantMessageItems = (acc) => acc.text.length === 0 ? [] : [{
|
|
|
284
305
|
role: "assistant",
|
|
285
306
|
content: [{
|
|
286
307
|
type: "output_text",
|
|
287
|
-
text: acc.text
|
|
308
|
+
text: acc.text,
|
|
309
|
+
...acc.annotations.length > 0 && { annotations: acc.annotations }
|
|
288
310
|
}]
|
|
289
311
|
}];
|
|
290
312
|
const functionCallItems = (acc) => pipe(acc.functionCalls, Array$1.map((c) => {
|
|
@@ -310,6 +332,6 @@ const accumulatorToTurn = (acc) => ({
|
|
|
310
332
|
]
|
|
311
333
|
});
|
|
312
334
|
//#endregion
|
|
313
|
-
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 };
|
|
314
336
|
|
|
315
337
|
//# sourceMappingURL=codec.mjs.map
|
package/dist/codec.mjs.map
CHANGED
|
@@ -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/** Gemini's tool declaration. We translate one `ToolDescriptor` per entry. */\ntype RequestTool = {\n readonly functionDeclarations: ReadonlyArray<{\n readonly name: string\n readonly description: string\n readonly parameters: Record<string, unknown>\n }>\n}\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 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 requestTools = toolDescriptorsToTools(tools)\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 && {\n tools: requestTools,\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,eAAe,OAAO,SAAS,cAAc;CAC9C,CAAC;AAyEF,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;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,MAAa,0BACX,GAAG,UAEH,KACE,OACAA,QAAI,SAAS,SAAS,MAAM,mBAAmB,EAAE,CAAC,EAClDA,QAAI,WAAW,UACb,MAAM,KAAK,OAAO,OACd,OAAO,WACP,OAAO,QAAoB;CACz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ACE,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"}
|
|
@@ -5107,7 +5107,7 @@ function manageArtifactAttachment(attachment) {
|
|
|
5107
5107
|
if (attachment.body != null) attachment.bodyEncoding ??= "base64";
|
|
5108
5108
|
}
|
|
5109
5109
|
//#endregion
|
|
5110
|
-
//#region ../../../node_modules/.pnpm/vitest@4.1.5_@types+node@25.6.0_vite@7.3.2_@types+node@25.6.0_jiti@2.6.1_lightningcss@1.32.0_tsx@4.21.0_yaml@2.
|
|
5110
|
+
//#region ../../../node_modules/.pnpm/vitest@4.1.5_@types+node@25.6.0_vite@7.3.2_@types+node@25.6.0_jiti@2.6.1_lightningcss@1.32.0_tsx@4.21.0_yaml@2.9.0_/node_modules/vitest/dist/chunks/utils.BX5Fg8C4.js
|
|
5111
5111
|
const NAME_WORKER_STATE = "__vitest_worker__";
|
|
5112
5112
|
function getWorkerState() {
|
|
5113
5113
|
const workerState = globalThis[NAME_WORKER_STATE];
|
|
@@ -9986,10 +9986,10 @@ function offsetToLineNumber(source, offset) {
|
|
|
9986
9986
|
return line + 1;
|
|
9987
9987
|
}
|
|
9988
9988
|
//#endregion
|
|
9989
|
-
//#region ../../../node_modules/.pnpm/vitest@4.1.5_@types+node@25.6.0_vite@7.3.2_@types+node@25.6.0_jiti@2.6.1_lightningcss@1.32.0_tsx@4.21.0_yaml@2.
|
|
9989
|
+
//#region ../../../node_modules/.pnpm/vitest@4.1.5_@types+node@25.6.0_vite@7.3.2_@types+node@25.6.0_jiti@2.6.1_lightningcss@1.32.0_tsx@4.21.0_yaml@2.9.0_/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.js
|
|
9990
9990
|
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
|
|
9991
9991
|
//#endregion
|
|
9992
|
-
//#region ../../../node_modules/.pnpm/vitest@4.1.5_@types+node@25.6.0_vite@7.3.2_@types+node@25.6.0_jiti@2.6.1_lightningcss@1.32.0_tsx@4.21.0_yaml@2.
|
|
9992
|
+
//#region ../../../node_modules/.pnpm/vitest@4.1.5_@types+node@25.6.0_vite@7.3.2_@types+node@25.6.0_jiti@2.6.1_lightningcss@1.32.0_tsx@4.21.0_yaml@2.9.0_/node_modules/vitest/dist/chunks/rpc.MzXet3jl.js
|
|
9993
9993
|
const RealDate = Date;
|
|
9994
9994
|
let now = null;
|
|
9995
9995
|
var MockDate = class MockDate extends RealDate {
|
|
@@ -10952,7 +10952,7 @@ function raceWith(promise, other) {
|
|
|
10952
10952
|
}))]);
|
|
10953
10953
|
}
|
|
10954
10954
|
//#endregion
|
|
10955
|
-
//#region ../../../node_modules/.pnpm/vitest@4.1.5_@types+node@25.6.0_vite@7.3.2_@types+node@25.6.0_jiti@2.6.1_lightningcss@1.32.0_tsx@4.21.0_yaml@2.
|
|
10955
|
+
//#region ../../../node_modules/.pnpm/vitest@4.1.5_@types+node@25.6.0_vite@7.3.2_@types+node@25.6.0_jiti@2.6.1_lightningcss@1.32.0_tsx@4.21.0_yaml@2.9.0_/node_modules/vitest/dist/chunks/test.DNmyFkvJ.js
|
|
10956
10956
|
var fakeTimersSrc = {};
|
|
10957
10957
|
var global$1;
|
|
10958
10958
|
var hasRequiredGlobal;
|
|
@@ -13629,7 +13629,7 @@ Object.defineProperty(globalThis, GLOBAL_EXPECT, {
|
|
|
13629
13629
|
configurable: true
|
|
13630
13630
|
});
|
|
13631
13631
|
//#endregion
|
|
13632
|
-
//#region ../../../node_modules/.pnpm/vite@7.3.2_@types+node@25.6.0_jiti@2.6.1_lightningcss@1.32.0_tsx@4.21.0_yaml@2.
|
|
13632
|
+
//#region ../../../node_modules/.pnpm/vite@7.3.2_@types+node@25.6.0_jiti@2.6.1_lightningcss@1.32.0_tsx@4.21.0_yaml@2.9.0/node_modules/vite/dist/node/module-runner.js
|
|
13633
13633
|
let SOURCEMAPPING_URL = "sourceMa";
|
|
13634
13634
|
SOURCEMAPPING_URL += "ppingURL";
|
|
13635
13635
|
typeof process < "u" && process.platform;
|
|
@@ -13677,7 +13677,7 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
13677
13677
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13678
13678
|
}));
|
|
13679
13679
|
//#endregion
|
|
13680
|
-
//#region ../../../node_modules/.pnpm/vitest@4.1.5_@types+node@25.6.0_vite@7.3.2_@types+node@25.6.0_jiti@2.6.1_lightningcss@1.32.0_tsx@4.21.0_yaml@2.
|
|
13680
|
+
//#region ../../../node_modules/.pnpm/vitest@4.1.5_@types+node@25.6.0_vite@7.3.2_@types+node@25.6.0_jiti@2.6.1_lightningcss@1.32.0_tsx@4.21.0_yaml@2.9.0_/node_modules/vitest/dist/index.js
|
|
13681
13681
|
var import_dist = (/* @__PURE__ */ __commonJSMin(((exports) => {
|
|
13682
13682
|
var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
|
|
13683
13683
|
if (k2 === void 0) k2 = k;
|
|
@@ -13779,4 +13779,4 @@ var import_dist = (/* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
13779
13779
|
//#endregion
|
|
13780
13780
|
export { it as i, globalExpect as n, describe as r, import_dist as t };
|
|
13781
13781
|
|
|
13782
|
-
//# sourceMappingURL=dist-
|
|
13782
|
+
//# sourceMappingURL=dist-CWoAuwS9.mjs.map
|