effect-durable-agent-cloudflare 0.4.0 → 0.5.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.
@@ -0,0 +1,782 @@
1
+ import { r as makeEDAProviderHttpClient } from "./transport-D8197izA.js";
2
+ import * as Layer from "effect/Layer";
3
+ import * as Prompt from "effect/ai/Prompt";
4
+ import * as HttpClient from "effect/http/HttpClient";
5
+ import * as Context from "effect/Context";
6
+ import * as Effect from "effect/Effect";
7
+ import * as HttpBody from "effect/http/HttpBody";
8
+ import * as Schema from "effect/Schema";
9
+ import * as Option from "effect/Option";
10
+ import * as Stream from "effect/Stream";
11
+ import * as Arr from "effect/Array";
12
+ import * as DateTime from "effect/DateTime";
13
+ import * as AiError from "effect/ai/AiError";
14
+ import * as IdGenerator from "effect/ai/IdGenerator";
15
+ import * as LanguageModel from "effect/ai/LanguageModel";
16
+ import { addGenAIAnnotations } from "effect/ai/Telemetry";
17
+ import * as Tool from "effect/ai/Tool";
18
+ import * as Base64 from "effect/encoding/Base64";
19
+ import * as Sse from "effect/encoding/Sse";
20
+ import * as Headers from "effect/http/Headers";
21
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
22
+ //#region src/providers/google-wire.ts
23
+ /**
24
+ * The subset of the Gemini API (`v1beta` `generateContent` and `streamGenerateContent`) that EDA's
25
+ * Google adapter sends and reads. Requests are built by EDA, so they are plain types; responses are
26
+ * parsed with these schemas at the HTTP boundary. Unknown response fields (such as the `p` padding
27
+ * on streamed chunks) are dropped by decoding.
28
+ */
29
+ const ResponsePart = Schema.Struct({
30
+ text: Schema.optionalKey(Schema.String),
31
+ thought: Schema.optionalKey(Schema.Boolean),
32
+ thoughtSignature: Schema.optionalKey(Schema.String),
33
+ functionCall: Schema.optionalKey(Schema.Struct({
34
+ name: Schema.String,
35
+ args: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),
36
+ id: Schema.optionalKey(Schema.String)
37
+ }))
38
+ });
39
+ const UsageMetadata = Schema.Struct({
40
+ promptTokenCount: Schema.optionalKey(Schema.Number),
41
+ /** Prompt tokens read from the implicit cache; a subset of `promptTokenCount`. */
42
+ cachedContentTokenCount: Schema.optionalKey(Schema.Number),
43
+ candidatesTokenCount: Schema.optionalKey(Schema.Number),
44
+ /** Thinking tokens, billed as output and not part of `candidatesTokenCount`. */
45
+ thoughtsTokenCount: Schema.optionalKey(Schema.Number),
46
+ toolUsePromptTokenCount: Schema.optionalKey(Schema.Number),
47
+ totalTokenCount: Schema.optionalKey(Schema.Number)
48
+ });
49
+ /**
50
+ * A full response, and also each streamed SSE chunk: chunks carry new parts only, and
51
+ * `usageMetadata` cumulatively, so the last chunk's usage is final.
52
+ */
53
+ const GoogleGenerateContentResponse = Schema.Struct({
54
+ candidates: Schema.optionalKey(Schema.Array(Schema.Struct({
55
+ content: Schema.optionalKey(Schema.Struct({ parts: Schema.optionalKey(Schema.Array(ResponsePart)) })),
56
+ finishReason: Schema.optionalKey(Schema.String),
57
+ finishMessage: Schema.optionalKey(Schema.String)
58
+ }))),
59
+ /** Set when the prompt itself was blocked; there are no candidates then. */
60
+ promptFeedback: Schema.optionalKey(Schema.Struct({
61
+ blockReason: Schema.optionalKey(Schema.String),
62
+ blockReasonMessage: Schema.optionalKey(Schema.String)
63
+ })),
64
+ usageMetadata: Schema.optionalKey(UsageMetadata),
65
+ modelVersion: Schema.optionalKey(Schema.String),
66
+ responseId: Schema.optionalKey(Schema.String)
67
+ });
68
+ /** Error body of a failed request, and of an error sent as an SSE event. */
69
+ const GoogleErrorBody = Schema.Struct({ error: Schema.Struct({
70
+ code: Schema.optionalKey(Schema.Number),
71
+ message: Schema.optionalKey(Schema.String),
72
+ status: Schema.optionalKey(Schema.String)
73
+ }) });
74
+ /** One streamed SSE `data` payload. */
75
+ const GoogleStreamChunk = Schema.Union([GoogleErrorBody, GoogleGenerateContentResponse]);
76
+ //#endregion
77
+ //#region src/providers/google.ts
78
+ /**
79
+ * Google Gemini API provider for EDA: a client over EDA's provider transport and an Effect AI
80
+ * `LanguageModel` for `generateContent` and `streamGenerateContent`.
81
+ *
82
+ * Thought signatures are kept per part. Response text, reasoning and tool-call parts carry
83
+ * `metadata.google.thoughtSignature`, which EDA persists on the committed prompt part and replays
84
+ * as `options.google.thoughtSignature`; the request puts it back on the same part. Gemini asks for
85
+ * every signature back on exactly the part that carried it, and rejects a function call replayed
86
+ * without its signature. A streamed answer usually ends with a signed empty text part, which EDA
87
+ * keeps as an empty text part and replays as it came.
88
+ */
89
+ /**
90
+ * Effort to `thinkingConfig.thinkingLevel`, one to one: `low` is `low`, `medium` is `medium`,
91
+ * `high` is `high` (Gemini's default). Gemini's `xhigh` is not offered as an effort, so the three
92
+ * efforts mean the same on every provider. `thinkingBudget` is deprecated and returns 400 next to
93
+ * `thinkingLevel`, so it is never sent.
94
+ */
95
+ const THINKING_LEVEL = {
96
+ low: "low",
97
+ medium: "medium",
98
+ high: "high"
99
+ };
100
+ /**
101
+ * Model config for EDA agent sessions on Gemini 4. Effort maps to `thinkingLevel` one to one
102
+ * (`low` → `low`, `medium` → `medium`, `high` → `high`; `xhigh` is not exposed), output defaults
103
+ * to 65,536 tokens and thought summaries are on.
104
+ */
105
+ const googleAgentModelConfig = (settings) => ({ generationConfig: {
106
+ maxOutputTokens: settings.maxOutputTokens ?? 65536,
107
+ thinkingConfig: {
108
+ thinkingLevel: THINKING_LEVEL[settings.effort],
109
+ includeThoughts: settings.includeThoughts ?? true
110
+ }
111
+ } });
112
+ /** Gemini API client service. */
113
+ var EDAGoogleClient = class extends Context.Service()("effect-durable-agent-cloudflare/EDAGoogleClient") {};
114
+ const API_KEY_HEADER = "x-goog-api-key";
115
+ const withRedactedKey = Effect.updateService(Headers.CurrentRedactedNames, Arr.append(API_KEY_HEADER));
116
+ /** Gemini client layer over EDA's provider transport (Cloudflare AI Gateway or `fetch`). */
117
+ const makeEDAGoogleClientLayer = (options) => {
118
+ const apiKey = optionalNonEmptyString(options.apiKey);
119
+ if (apiKey === void 0 && options.aiGateway === void 0) throw new Error("GEMINI_API_KEY is required unless Google traffic goes through a Cloudflare AI Gateway binding with a stored key.");
120
+ const http = makeEDAProviderHttpClient({
121
+ provider: "google",
122
+ aiGateway: options.aiGateway
123
+ }).pipe(HttpClient.mapRequest((request) => {
124
+ const based = HttpClientRequest.prependUrl(request, options.apiUrl ?? "https://generativelanguage.googleapis.com");
125
+ return apiKey === void 0 ? based : HttpClientRequest.setHeader(based, API_KEY_HEADER, apiKey);
126
+ }), HttpClient.filterStatusOk);
127
+ const post = (model, method, request) => HttpClientRequest.post(`/v1beta/models/${model}:${method}`, {
128
+ body: HttpBody.jsonUnsafe(request),
129
+ ...method === "streamGenerateContent" ? { urlParams: { alt: "sse" } } : {}
130
+ });
131
+ return Layer.succeed(EDAGoogleClient, {
132
+ generateContent: (model, request) => http.execute(post(model, "generateContent", request)).pipe(Effect.flatMap((response) => response.json), Effect.flatMap(Schema.decodeUnknownEffect(GoogleGenerateContentResponse)), Effect.catchTags({
133
+ HttpClientError: (error) => mapHttpClientError(error, "generateContent"),
134
+ SchemaError: (error) => Effect.fail(invalidResponse(error, "generateContent"))
135
+ }), withRedactedKey),
136
+ streamGenerateContent: (model, body) => {
137
+ const request = post(model, "streamGenerateContent", body);
138
+ return http.execute(request).pipe(Effect.map((response) => response.stream), Stream.unwrap, Stream.decodeText, Stream.pipeThroughChannel(Sse.decodeDataSchema(GoogleStreamChunk)), Stream.mapEffect(({ data }) => "error" in data ? Effect.fail(AiError.make({
139
+ module: "EDAGoogleClient",
140
+ method: "streamGenerateContent",
141
+ reason: statusReason({
142
+ status: data.error.code ?? 500,
143
+ body: data,
144
+ http: void 0,
145
+ request
146
+ })
147
+ })) : Effect.succeed(data)), Stream.catchTags({
148
+ Retry: (error) => Stream.die(error),
149
+ SseError: (error) => Stream.fail(AiError.make({
150
+ module: "EDAGoogleClient",
151
+ method: "streamGenerateContent",
152
+ reason: new AiError.InvalidResponseError({ description: error.message })
153
+ })),
154
+ HttpClientError: (error) => Stream.fromEffect(mapHttpClientError(error, "streamGenerateContent")),
155
+ SchemaError: (error) => Stream.fail(invalidResponse(error, "streamGenerateContent"))
156
+ }), Stream.updateService(Headers.CurrentRedactedNames, Arr.append(API_KEY_HEADER)));
157
+ }
158
+ });
159
+ };
160
+ const invalidResponse = (error, method) => AiError.make({
161
+ module: "EDAGoogleClient",
162
+ method,
163
+ reason: AiError.InvalidResponseError.fromSchemaError(error)
164
+ });
165
+ const mapHttpClientError = (error, method) => {
166
+ const reason = error.reason;
167
+ switch (reason._tag) {
168
+ case "TransportError":
169
+ case "EncodeError":
170
+ case "InvalidUrlError": return Effect.fail(AiError.make({
171
+ module: "EDAGoogleClient",
172
+ method,
173
+ reason: new AiError.NetworkError({
174
+ reason: reason._tag,
175
+ method: reason.request.method,
176
+ url: reason.request.url,
177
+ description: reason.description,
178
+ cause: reason.cause
179
+ })
180
+ }));
181
+ case "StatusCodeError": return Effect.flatMap(Effect.orElseSucceed(reason.response.text, () => ""), (text) => Effect.fail(AiError.make({
182
+ module: "EDAGoogleClient",
183
+ method,
184
+ reason: statusReason({
185
+ status: reason.response.status,
186
+ body: Option.getOrUndefined(Schema.decodeUnknownOption(Schema.fromJsonString(GoogleErrorBody))(text)),
187
+ http: {
188
+ response: {
189
+ status: reason.response.status,
190
+ headers: { ...reason.response.headers }
191
+ },
192
+ body: text
193
+ },
194
+ request: reason.request
195
+ })
196
+ })));
197
+ case "DecodeError":
198
+ case "EmptyBodyError": return Effect.fail(AiError.make({
199
+ module: "EDAGoogleClient",
200
+ method,
201
+ reason: new AiError.InvalidOutputError({ description: reason.description ?? "Failed to read the Gemini response body" })
202
+ }));
203
+ }
204
+ };
205
+ /** HTTP status to `AiError` reason, as the Anthropic adapter maps it. */
206
+ const statusReason = (params) => {
207
+ const { status, http } = params;
208
+ const message = params.body?.error.message;
209
+ const metadata = { google: { status: params.body?.error.status ?? null } };
210
+ const description = AiError.buildErrorDescription({
211
+ status,
212
+ message,
213
+ method: params.request.method,
214
+ url: params.request.url,
215
+ errorType: params.body?.error.status,
216
+ body: http?.body
217
+ });
218
+ const context = {
219
+ metadata,
220
+ ...http === void 0 ? {} : { http }
221
+ };
222
+ switch (status) {
223
+ case 400:
224
+ case 404:
225
+ case 422: return new AiError.InvalidRequestError({
226
+ description,
227
+ ...context
228
+ });
229
+ case 401: return new AiError.AuthenticationError({
230
+ kind: "InvalidKey",
231
+ description,
232
+ ...context
233
+ });
234
+ case 403: return new AiError.AuthenticationError({
235
+ kind: "InsufficientPermissions",
236
+ description,
237
+ ...context
238
+ });
239
+ case 429: return new AiError.RateLimitError(context);
240
+ default: return status >= 500 ? new AiError.InternalProviderError({
241
+ description: message ?? "Server error",
242
+ ...context
243
+ }) : new AiError.UnknownError({
244
+ description: message,
245
+ ...context
246
+ });
247
+ }
248
+ };
249
+ const invalidInput = (method, description) => AiError.make({
250
+ module: "EDAGoogleLanguageModel",
251
+ method,
252
+ reason: new AiError.InvalidUserInputError({ description })
253
+ });
254
+ /** Gemini `LanguageModel` for one model id; requires {@link EDAGoogleClient}. */
255
+ const makeEDAGoogleLanguageModel = (options) => Effect.gen(function* () {
256
+ const client = yield* EDAGoogleClient;
257
+ const config = options.config ?? {};
258
+ const request = (provider) => makeRequest(provider, config).pipe(Effect.tap((body) => Effect.sync(() => annotateRequest(provider, options.modelId, body))));
259
+ return yield* LanguageModel.make({
260
+ generateText: (provider) => Effect.gen(function* () {
261
+ const body = yield* request(provider);
262
+ const response = yield* client.generateContent(options.modelId, body);
263
+ const converter = yield* makeConverter;
264
+ const parts = collapseStreamParts([...yield* converter.chunk(response), ...converter.end()]);
265
+ annotateResponse(provider, parts);
266
+ return parts;
267
+ }),
268
+ streamText: (provider) => request(provider).pipe(Effect.zip(makeConverter), Effect.map(([body, converter]) => client.streamGenerateContent(options.modelId, body).pipe(Stream.mapEffect(converter.chunk), Stream.flattenIterable, Stream.concat(Stream.suspend(() => Stream.fromIterable(converter.end()))), Stream.tap((part) => Effect.sync(() => annotateResponse(provider, [part]))))), Stream.unwrap),
269
+ supportsSystemMessagesInHistory: Effect.succeed(false)
270
+ });
271
+ });
272
+ const makeRequest = (provider, config) => Effect.gen(function* () {
273
+ const tools = yield* prepareTools(provider, config);
274
+ const { systemInstruction, contents } = yield* prepareContents(provider.prompt);
275
+ const format = provider.responseFormat;
276
+ return {
277
+ ...tools,
278
+ ...systemInstruction === void 0 ? {} : { systemInstruction },
279
+ contents,
280
+ generationConfig: {
281
+ ...config.generationConfig,
282
+ ...format.type === "json" ? {
283
+ responseMimeType: "application/json",
284
+ responseJsonSchema: Tool.getJsonSchemaFromSchema(format.schema)
285
+ } : {}
286
+ }
287
+ };
288
+ });
289
+ /**
290
+ * Leading system messages become `systemInstruction`; the rest become `contents`, with assistant
291
+ * messages as `model` turns and tool results as `functionResponse` parts in `user` turns. The
292
+ * results of one step's calls share one turn, as Gemini expects for parallel calls. Every other
293
+ * message keeps its own turn, so a request's contents always start with the previous request's
294
+ * contents unchanged, which is the prefix Gemini's implicit cache matches.
295
+ */
296
+ const prepareContents = (prompt) => Effect.gen(function* () {
297
+ const system = [];
298
+ const contents = [];
299
+ let results;
300
+ for (const message of prompt.content) {
301
+ if (message.role !== "tool") results = void 0;
302
+ switch (message.role) {
303
+ case "system":
304
+ if (contents.length > 0) return yield* invalidInput("prepareContents", "Gemini takes system messages only before the conversation.");
305
+ system.push({ text: message.content });
306
+ break;
307
+ case "user":
308
+ contents.push({
309
+ role: "user",
310
+ parts: message.content.map(userPart)
311
+ });
312
+ break;
313
+ case "assistant": {
314
+ const parts = message.content.flatMap(modelParts);
315
+ if (parts.length > 0) contents.push({
316
+ role: "model",
317
+ parts
318
+ });
319
+ break;
320
+ }
321
+ case "tool":
322
+ if (results === void 0) {
323
+ results = [];
324
+ contents.push({
325
+ role: "user",
326
+ parts: results
327
+ });
328
+ }
329
+ results.push(...message.content.flatMap(toolResultParts));
330
+ }
331
+ }
332
+ return {
333
+ systemInstruction: system.length === 0 ? void 0 : { parts: system },
334
+ contents
335
+ };
336
+ });
337
+ const userPart = (part) => part.type === "text" ? { text: part.text } : filePart(part);
338
+ /**
339
+ * A file part as Gemini data. EDA stores file data as a string: bytes as a base64 `data:` URL and a
340
+ * URL as its href. Bytes, base64 and every `data:` URL go inline, a `data:` URL with its decoded
341
+ * payload and its own media type. A URL, as a `URL` or a string with a scheme (an https or Gemini
342
+ * Files URI), goes as `fileData.fileUri`. Base64 has no `:`, so a scheme tells a URL from base64.
343
+ */
344
+ const filePart = (part) => {
345
+ if (part.data instanceof Uint8Array) return inline(part.mediaType, Base64.encode(part.data));
346
+ const value = part.data instanceof URL ? part.data.href : part.data;
347
+ const dataUrl = parseDataUrl(value);
348
+ if (dataUrl !== void 0) return inline(dataUrl.mediaType === "" ? part.mediaType : dataUrl.mediaType, dataUrl.base64);
349
+ return URL_SCHEME.test(value) ? { fileData: {
350
+ mimeType: geminiMediaType(part.mediaType),
351
+ fileUri: value
352
+ } } : inline(part.mediaType, value);
353
+ };
354
+ const URL_SCHEME = /^[a-z][a-z\d+.-]*:/i;
355
+ const inline = (mediaType, data) => ({ inlineData: {
356
+ mimeType: geminiMediaType(mediaType),
357
+ data
358
+ } });
359
+ /** `image/*`, an image of unknown type, goes as JPEG, as the Anthropic and OpenAI adapters send it. */
360
+ const geminiMediaType = (mediaType) => mediaType === "image/*" ? "image/jpeg" : mediaType;
361
+ /**
362
+ * A `data:` URL's media type (empty when it names none) and its payload as base64, decoded as the
363
+ * Fetch standard's `data:` URL processor decodes it. The payload is percent-decoded. With
364
+ * `;base64` it is base64 text, and without it the payload is the bytes themselves.
365
+ */
366
+ const parseDataUrl = (value) => {
367
+ const match = DATA_URL.exec(value.split("#", 1)[0] ?? "");
368
+ if (match === null) return void 0;
369
+ const [, header = "", payload = ""] = match;
370
+ const mediaType = (header.split(";")[0] ?? "").trim().toLowerCase();
371
+ return /;\s*base64\s*$/i.test(header) ? {
372
+ mediaType,
373
+ base64: payload.replace(/%([\da-f]{2})/gi, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))).replace(/[\t\n\f\r ]/g, "")
374
+ } : {
375
+ mediaType,
376
+ base64: Base64.encode(percentDecode(payload))
377
+ };
378
+ };
379
+ const DATA_URL = /^data:([^,]*),(.*)$/is;
380
+ /** Bytes of a percent-encoded string: `%XX` is that byte, and any other character its UTF-8. */
381
+ const percentDecode = (text) => {
382
+ const chunks = text.split(/(%[\da-f]{2})/i).map((piece, index) => index % 2 === 1 ? Uint8Array.of(Number.parseInt(piece.slice(1), 16)) : new TextEncoder().encode(piece));
383
+ const bytes = new Uint8Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0));
384
+ let offset = 0;
385
+ for (const chunk of chunks) {
386
+ bytes.set(chunk, offset);
387
+ offset += chunk.length;
388
+ }
389
+ return bytes;
390
+ };
391
+ /** An assistant part as the `model` part it came from, with its signature back on it. */
392
+ const modelParts = (part) => {
393
+ const thoughtSignature = googleThoughtSignature(part.options);
394
+ const signed = thoughtSignature === void 0 ? {} : { thoughtSignature };
395
+ switch (part.type) {
396
+ case "text": return part.text.length === 0 && thoughtSignature === void 0 ? [] : [{
397
+ text: part.text,
398
+ ...signed
399
+ }];
400
+ case "reasoning": return part.text.length === 0 && thoughtSignature === void 0 ? [] : [{
401
+ text: part.text,
402
+ thought: true,
403
+ ...signed
404
+ }];
405
+ case "tool-call": return [{
406
+ functionCall: {
407
+ name: part.name,
408
+ args: part.params,
409
+ id: part.id
410
+ },
411
+ ...signed
412
+ }];
413
+ case "file": return [filePart(part)];
414
+ case "tool-result":
415
+ case "tool-approval-request": return [];
416
+ }
417
+ };
418
+ const toolResultParts = (part) => {
419
+ if (part.type !== "tool-result") return [];
420
+ const output = part.modelOutput === void 0 ? part.result : Prompt.toolModelOutputToText(part.modelOutput);
421
+ return [{ functionResponse: {
422
+ name: part.name,
423
+ id: part.id,
424
+ response: part.isFailure ? { error: output } : { output }
425
+ } }];
426
+ };
427
+ /** The part's Gemini thought signature, if Gemini sent one. */
428
+ const googleThoughtSignature = (options) => {
429
+ const google = options.google;
430
+ return isRecord(google) && typeof google.thoughtSignature === "string" ? google.thoughtSignature : void 0;
431
+ };
432
+ const prepareTools = (provider, config) => Effect.gen(function* () {
433
+ if (provider.tools.length === 0) return {};
434
+ const functionDeclarations = [];
435
+ for (const tool of provider.tools) {
436
+ if (Tool.isProviderDefined(tool)) return yield* invalidInput("prepareTools", `Provider-defined tool ${tool.name} is not supported on Gemini.`);
437
+ const parametersJsonSchema = yield* Effect.try({
438
+ try: () => Tool.getJsonSchema(tool),
439
+ catch: (error) => AiError.make({
440
+ module: "EDAGoogleLanguageModel",
441
+ method: "prepareTools",
442
+ reason: new AiError.UnsupportedSchemaError({ description: `Tool ${tool.name} parameters: ${String(error)}` })
443
+ })
444
+ });
445
+ const description = Tool.getDescription(tool);
446
+ functionDeclarations.push({
447
+ name: tool.name,
448
+ ...description === void 0 ? {} : { description },
449
+ parametersJsonSchema
450
+ });
451
+ }
452
+ return {
453
+ tools: [{ functionDeclarations }],
454
+ toolConfig: { functionCallingConfig: functionCalling(provider.toolChoice, config) }
455
+ };
456
+ });
457
+ const functionCalling = (choice, config) => {
458
+ const auto = config.toolConfig?.functionCallingConfig?.mode ?? "AUTO";
459
+ if (choice === "auto") return { mode: auto };
460
+ if (choice === "none") return { mode: "NONE" };
461
+ if (choice === "required") return { mode: "ANY" };
462
+ if ("tool" in choice) return {
463
+ mode: "ANY",
464
+ allowedFunctionNames: [choice.tool]
465
+ };
466
+ return choice.mode === "required" ? {
467
+ mode: "ANY",
468
+ allowedFunctionNames: choice.oneOf
469
+ } : { mode: auto };
470
+ };
471
+ const blockStart = (kind, id, metadata = {}) => kind === "text" ? {
472
+ type: "text-start",
473
+ id,
474
+ metadata
475
+ } : {
476
+ type: "reasoning-start",
477
+ id,
478
+ metadata
479
+ };
480
+ const blockDelta = (kind, id, delta) => kind === "text" ? {
481
+ type: "text-delta",
482
+ id,
483
+ delta
484
+ } : {
485
+ type: "reasoning-delta",
486
+ id,
487
+ delta
488
+ };
489
+ const blockEnd = (kind, id) => kind === "text" ? {
490
+ type: "text-end",
491
+ id
492
+ } : {
493
+ type: "reasoning-end",
494
+ id
495
+ };
496
+ /**
497
+ * Converts the chunks of one response into stream parts that replay as the parts Gemini sent.
498
+ * Unsigned text parts of one kind (thought or answer) in a row are streamed pieces of one part and
499
+ * form one block. A signed part is a block of its own whose start carries the signature, so the
500
+ * signature replays on exactly that part, even an empty one. A function call closes the open
501
+ * block, which keeps replayed parts in the order Gemini sent them. `finish` is emitted when the
502
+ * response ends, with the last (cumulative) usage, and only if Gemini sent a finish reason.
503
+ */
504
+ const makeConverter = Effect.gen(function* () {
505
+ const ids = yield* IdGenerator.IdGenerator;
506
+ let started = false;
507
+ let open;
508
+ let blocks = 0;
509
+ let toolCalls = false;
510
+ let finishReason;
511
+ let usage;
512
+ const close = (out) => {
513
+ if (open === void 0) return;
514
+ out.push(blockEnd(open.kind, open.id));
515
+ open = void 0;
516
+ };
517
+ const chunk = (response) => Effect.gen(function* () {
518
+ const blocked = response.promptFeedback?.blockReason;
519
+ if (blocked !== void 0) {
520
+ const message = response.promptFeedback?.blockReasonMessage;
521
+ return yield* AiError.make({
522
+ module: "EDAGoogleLanguageModel",
523
+ method: "convertResponse",
524
+ reason: new AiError.ContentPolicyError({
525
+ description: `Gemini blocked the prompt (${blocked})${message === void 0 ? "" : `: ${message}`}`,
526
+ metadata: { google: { blockReason: blocked } }
527
+ })
528
+ });
529
+ }
530
+ const out = [];
531
+ if (!started) {
532
+ started = true;
533
+ out.push({
534
+ type: "response-metadata",
535
+ id: response.responseId,
536
+ modelId: response.modelVersion,
537
+ timestamp: DateTime.formatIso(yield* DateTime.now)
538
+ });
539
+ }
540
+ usage = response.usageMetadata ?? usage;
541
+ const candidate = response.candidates?.[0];
542
+ const failure = finishFailure(candidate);
543
+ if (failure !== void 0) return yield* failure;
544
+ for (const part of candidate?.content?.parts ?? []) {
545
+ const metadata = part.thoughtSignature === void 0 ? {} : { metadata: { google: { thoughtSignature: part.thoughtSignature } } };
546
+ if (part.functionCall !== void 0) {
547
+ close(out);
548
+ toolCalls = true;
549
+ const id = part.functionCall.id ?? (yield* ids.generateId());
550
+ const { name } = part.functionCall;
551
+ const params = part.functionCall.args ?? {};
552
+ out.push({
553
+ type: "tool-params-start",
554
+ id,
555
+ name
556
+ }, {
557
+ type: "tool-params-delta",
558
+ id,
559
+ delta: JSON.stringify(params)
560
+ }, {
561
+ type: "tool-params-end",
562
+ id
563
+ }, {
564
+ type: "tool-call",
565
+ id,
566
+ name,
567
+ params,
568
+ ...metadata
569
+ });
570
+ continue;
571
+ }
572
+ if (part.text === void 0 || part.text.length === 0 && part.thoughtSignature === void 0) continue;
573
+ const kind = part.thought === true ? "reasoning" : "text";
574
+ if (part.thoughtSignature === void 0) {
575
+ if (open?.kind !== kind) {
576
+ close(out);
577
+ open = {
578
+ kind,
579
+ id: String(blocks++)
580
+ };
581
+ out.push(blockStart(kind, open.id));
582
+ }
583
+ out.push(blockDelta(kind, open.id, part.text));
584
+ continue;
585
+ }
586
+ close(out);
587
+ const id = String(blocks++);
588
+ out.push(blockStart(kind, id, { google: { thoughtSignature: part.thoughtSignature } }));
589
+ if (part.text.length > 0) out.push(blockDelta(kind, id, part.text));
590
+ out.push(blockEnd(kind, id));
591
+ }
592
+ finishReason = candidate?.finishReason ?? finishReason;
593
+ return out;
594
+ });
595
+ const end = () => {
596
+ if (finishReason === void 0) return [];
597
+ const out = [];
598
+ close(out);
599
+ out.push({
600
+ type: "finish",
601
+ reason: resolveFinishReason(finishReason, toolCalls),
602
+ usage: makeUsage(usage),
603
+ metadata: { google: {
604
+ finishReason,
605
+ usageMetadata: usage ?? null
606
+ } }
607
+ });
608
+ return out;
609
+ };
610
+ return {
611
+ chunk,
612
+ end
613
+ };
614
+ });
615
+ /**
616
+ * Gemini usage as Effect AI usage. Input is the prompt plus tool-use prompt tokens, of which
617
+ * `cachedContentTokenCount` came from the implicit cache. Gemini charges no cache writes. Output
618
+ * is the answer (`candidatesTokenCount`) plus thinking (`thoughtsTokenCount`), both billed as
619
+ * output.
620
+ */
621
+ const makeUsage = (usage) => {
622
+ if (usage === void 0) return {
623
+ inputTokens: {
624
+ uncached: void 0,
625
+ total: void 0,
626
+ cacheRead: void 0,
627
+ cacheWrite: void 0
628
+ },
629
+ outputTokens: {
630
+ total: void 0,
631
+ text: void 0,
632
+ reasoning: void 0
633
+ }
634
+ };
635
+ const input = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
636
+ const cached = usage.cachedContentTokenCount ?? 0;
637
+ const text = usage.candidatesTokenCount ?? 0;
638
+ const reasoning = usage.thoughtsTokenCount ?? 0;
639
+ return {
640
+ inputTokens: {
641
+ total: input,
642
+ uncached: input - cached,
643
+ cacheRead: cached,
644
+ cacheWrite: 0
645
+ },
646
+ outputTokens: {
647
+ total: text + reasoning,
648
+ text,
649
+ reasoning
650
+ }
651
+ };
652
+ };
653
+ /**
654
+ * Gemini finish reasons that end a usable response, as the Anthropic and OpenAI adapters end
655
+ * theirs: output limits are `length`, and safety and recitation filters are `content-filter`, as
656
+ * Anthropic's `refusal` and OpenAI's `content_filter` are. A reason in neither table is `unknown`.
657
+ */
658
+ const STOP_REASONS = {
659
+ STOP: "stop",
660
+ MAX_TOKENS: "length",
661
+ CONTINUATION: "length",
662
+ SAFETY: "content-filter",
663
+ RECITATION: "content-filter",
664
+ LANGUAGE: "content-filter",
665
+ BLOCKLIST: "content-filter",
666
+ PROHIBITED_CONTENT: "content-filter",
667
+ SPII: "content-filter",
668
+ IMAGE_SAFETY: "content-filter",
669
+ IMAGE_PROHIBITED_CONTENT: "content-filter",
670
+ IMAGE_RECITATION: "content-filter",
671
+ ESCALATION: "content-filter",
672
+ OTHER: "other",
673
+ IMAGE_OTHER: "other",
674
+ NO_IMAGE: "other",
675
+ FINISH_REASON_UNSPECIFIED: "other"
676
+ };
677
+ /**
678
+ * Gemini finish reasons that say the response or the request is broken. Each fails the inference
679
+ * with an `AiError`, as OpenAI's `response.failed` does, so EDA commits no tool call from it.
680
+ */
681
+ const FAILURE_REASONS = {
682
+ MALFORMED_FUNCTION_CALL: (context) => new AiError.InvalidOutputError(context),
683
+ UNEXPECTED_TOOL_CALL: (context) => new AiError.InvalidOutputError(context),
684
+ TOO_MANY_TOOL_CALLS: (context) => new AiError.InvalidOutputError(context),
685
+ MALFORMED_RESPONSE: (context) => new AiError.InvalidOutputError(context),
686
+ MISSING_THOUGHT_SIGNATURE: (context) => new AiError.InvalidRequestError(context),
687
+ PUP_LIMITED_DISABLED: (context) => new AiError.ContentPolicyError(context)
688
+ };
689
+ /** The failure a candidate's finish reason is, keeping Gemini's `finishMessage`, if any. */
690
+ const finishFailure = (candidate) => {
691
+ const finishReason = candidate?.finishReason;
692
+ const failure = finishReason !== void 0 && Object.hasOwn(FAILURE_REASONS, finishReason) ? FAILURE_REASONS[finishReason] : void 0;
693
+ if (finishReason === void 0 || failure === void 0) return void 0;
694
+ const finishMessage = candidate?.finishMessage;
695
+ return AiError.make({
696
+ module: "EDAGoogleLanguageModel",
697
+ method: "convertResponse",
698
+ reason: failure({
699
+ description: `Gemini finished with ${finishReason}${finishMessage === void 0 ? "" : `: ${finishMessage}`}`,
700
+ metadata: { google: {
701
+ finishReason,
702
+ ...finishMessage === void 0 ? {} : { finishMessage }
703
+ } }
704
+ })
705
+ });
706
+ };
707
+ /** Gemini finishes a function-call response with `STOP`; that is a `tool-calls` finish. */
708
+ const resolveFinishReason = (reason, toolCalls) => {
709
+ if (reason === "STOP" && toolCalls) return "tool-calls";
710
+ return (Object.hasOwn(STOP_REASONS, reason) ? STOP_REASONS[reason] : void 0) ?? "unknown";
711
+ };
712
+ /** Folds stream parts into the whole parts `generateText` returns. */
713
+ const collapseStreamParts = (parts) => {
714
+ const out = [];
715
+ const blocks = /* @__PURE__ */ new Map();
716
+ for (const part of parts) switch (part.type) {
717
+ case "text-start":
718
+ case "reasoning-start":
719
+ blocks.set(part.id, {
720
+ text: "",
721
+ metadata: part.metadata ?? {}
722
+ });
723
+ break;
724
+ case "text-delta":
725
+ case "reasoning-delta": {
726
+ const block = blocks.get(part.id);
727
+ if (block === void 0) break;
728
+ block.text += part.delta;
729
+ break;
730
+ }
731
+ case "text-end":
732
+ case "reasoning-end": {
733
+ const block = blocks.get(part.id);
734
+ if (block === void 0 || block.text.length === 0 && block.metadata.google === void 0) break;
735
+ out.push({
736
+ type: part.type === "text-end" ? "text" : "reasoning",
737
+ text: block.text,
738
+ metadata: block.metadata
739
+ });
740
+ break;
741
+ }
742
+ case "tool-params-start":
743
+ case "tool-params-delta":
744
+ case "tool-params-end": break;
745
+ case "response-metadata":
746
+ case "tool-call":
747
+ case "finish": out.push(part);
748
+ }
749
+ return out;
750
+ };
751
+ const annotateRequest = (provider, model, request) => addGenAIAnnotations(provider.span, {
752
+ provider: { name: "gcp.gemini" },
753
+ operation: { name: "chat" },
754
+ request: {
755
+ model,
756
+ maxTokens: request.generationConfig?.maxOutputTokens
757
+ }
758
+ });
759
+ const annotateResponse = (provider, parts) => {
760
+ for (const part of parts) {
761
+ if (part.type === "response-metadata") addGenAIAnnotations(provider.span, { response: {
762
+ id: part.id,
763
+ model: part.modelId
764
+ } });
765
+ if (part.type === "finish") addGenAIAnnotations(provider.span, {
766
+ response: { finishReasons: [part.reason] },
767
+ usage: {
768
+ inputTokens: part.usage.inputTokens.total,
769
+ outputTokens: part.usage.outputTokens.total
770
+ }
771
+ });
772
+ }
773
+ };
774
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
775
+ const optionalNonEmptyString = (value) => {
776
+ const trimmed = value?.trim();
777
+ return trimmed === void 0 || trimmed.length === 0 ? void 0 : trimmed;
778
+ };
779
+ //#endregion
780
+ export { makeEDAGoogleLanguageModel as i, googleAgentModelConfig as n, makeEDAGoogleClientLayer as r, EDAGoogleClient as t };
781
+
782
+ //# sourceMappingURL=google-DKsl1vVF.js.map