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 @@
1
+ {"version":3,"file":"google-DKsl1vVF.js","names":[],"sources":["../src/providers/google-wire.ts","../src/providers/google.ts"],"sourcesContent":["/**\n * The subset of the Gemini API (`v1beta` `generateContent` and `streamGenerateContent`) that EDA's\n * Google adapter sends and reads. Requests are built by EDA, so they are plain types; responses are\n * parsed with these schemas at the HTTP boundary. Unknown response fields (such as the `p` padding\n * on streamed chunks) are dropped by decoding.\n */\nimport * as Schema from \"effect/Schema\";\n\n/** `thinkingConfig.thinkingLevel` values the Gemini 4 models accept (`minimal` is rejected). */\nexport type GoogleThinkingLevel = \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\n/** `toolConfig.functionCallingConfig.mode`. */\nexport type GoogleFunctionCallingMode = \"AUTO\" | \"ANY\" | \"NONE\" | \"VALIDATED\";\n\n/** One request part. Exactly one data field is set; `thought` and `thoughtSignature` annotate it. */\nexport interface GoogleRequestPart {\n readonly text?: string;\n readonly thought?: boolean;\n readonly thoughtSignature?: string;\n readonly inlineData?: { readonly mimeType: string; readonly data: string };\n readonly fileData?: { readonly mimeType: string; readonly fileUri: string };\n readonly functionCall?: { readonly name: string; readonly args: unknown; readonly id?: string };\n readonly functionResponse?: {\n readonly name: string;\n readonly response: Readonly<Record<string, unknown>>;\n readonly id?: string;\n };\n}\n\n/** One turn of `contents`. Tool results go back in `user` turns. */\nexport interface GoogleContent {\n readonly role: \"user\" | \"model\";\n readonly parts: ReadonlyArray<GoogleRequestPart>;\n}\n\nexport interface GoogleFunctionDeclaration {\n readonly name: string;\n readonly description?: string;\n /** JSON Schema for the arguments object (mutually exclusive with OpenAPI `parameters`). */\n readonly parametersJsonSchema: unknown;\n}\n\nexport interface GoogleGenerationConfig {\n readonly maxOutputTokens?: number;\n readonly thinkingConfig?: {\n readonly thinkingLevel?: GoogleThinkingLevel;\n /** Return thought summaries as parts with `thought: true`. */\n readonly includeThoughts?: boolean;\n };\n readonly responseMimeType?: string;\n readonly responseJsonSchema?: unknown;\n}\n\nexport interface GoogleToolConfig {\n readonly functionCallingConfig?: {\n readonly mode?: GoogleFunctionCallingMode;\n readonly allowedFunctionNames?: ReadonlyArray<string>;\n };\n}\n\n/** `POST /v1beta/models/{model}:generateContent` (and `:streamGenerateContent`) body. */\nexport interface GoogleGenerateContentRequest {\n readonly systemInstruction?: { readonly parts: ReadonlyArray<{ readonly text: string }> };\n readonly tools?: ReadonlyArray<{\n readonly functionDeclarations: ReadonlyArray<GoogleFunctionDeclaration>;\n }>;\n readonly toolConfig?: GoogleToolConfig;\n readonly contents: ReadonlyArray<GoogleContent>;\n readonly generationConfig?: GoogleGenerationConfig;\n}\n\nconst ResponsePart = Schema.Struct({\n text: Schema.optionalKey(Schema.String),\n thought: Schema.optionalKey(Schema.Boolean),\n thoughtSignature: Schema.optionalKey(Schema.String),\n functionCall: Schema.optionalKey(\n Schema.Struct({\n name: Schema.String,\n args: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),\n id: Schema.optionalKey(Schema.String),\n }),\n ),\n});\nexport type GoogleResponsePart = typeof ResponsePart.Type;\n\nconst UsageMetadata = Schema.Struct({\n promptTokenCount: Schema.optionalKey(Schema.Number),\n /** Prompt tokens read from the implicit cache; a subset of `promptTokenCount`. */\n cachedContentTokenCount: Schema.optionalKey(Schema.Number),\n candidatesTokenCount: Schema.optionalKey(Schema.Number),\n /** Thinking tokens, billed as output and not part of `candidatesTokenCount`. */\n thoughtsTokenCount: Schema.optionalKey(Schema.Number),\n toolUsePromptTokenCount: Schema.optionalKey(Schema.Number),\n totalTokenCount: Schema.optionalKey(Schema.Number),\n});\nexport type GoogleUsageMetadata = typeof UsageMetadata.Type;\n\n/**\n * A full response, and also each streamed SSE chunk: chunks carry new parts only, and\n * `usageMetadata` cumulatively, so the last chunk's usage is final.\n */\nexport const GoogleGenerateContentResponse = Schema.Struct({\n candidates: Schema.optionalKey(\n Schema.Array(\n Schema.Struct({\n content: Schema.optionalKey(\n Schema.Struct({ parts: Schema.optionalKey(Schema.Array(ResponsePart)) }),\n ),\n finishReason: Schema.optionalKey(Schema.String),\n finishMessage: Schema.optionalKey(Schema.String),\n }),\n ),\n ),\n /** Set when the prompt itself was blocked; there are no candidates then. */\n promptFeedback: Schema.optionalKey(\n Schema.Struct({\n blockReason: Schema.optionalKey(Schema.String),\n blockReasonMessage: Schema.optionalKey(Schema.String),\n }),\n ),\n usageMetadata: Schema.optionalKey(UsageMetadata),\n modelVersion: Schema.optionalKey(Schema.String),\n responseId: Schema.optionalKey(Schema.String),\n});\nexport type GoogleGenerateContentResponse = typeof GoogleGenerateContentResponse.Type;\n\n/** Error body of a failed request, and of an error sent as an SSE event. */\nexport const GoogleErrorBody = Schema.Struct({\n error: Schema.Struct({\n code: Schema.optionalKey(Schema.Number),\n message: Schema.optionalKey(Schema.String),\n status: Schema.optionalKey(Schema.String),\n }),\n});\nexport type GoogleErrorBody = typeof GoogleErrorBody.Type;\n\n/** One streamed SSE `data` payload. */\nexport const GoogleStreamChunk = Schema.Union([GoogleErrorBody, GoogleGenerateContentResponse]);\n","/**\n * Google Gemini API provider for EDA: a client over EDA's provider transport and an Effect AI\n * `LanguageModel` for `generateContent` and `streamGenerateContent`.\n *\n * Thought signatures are kept per part. Response text, reasoning and tool-call parts carry\n * `metadata.google.thoughtSignature`, which EDA persists on the committed prompt part and replays\n * as `options.google.thoughtSignature`; the request puts it back on the same part. Gemini asks for\n * every signature back on exactly the part that carried it, and rejects a function call replayed\n * without its signature. A streamed answer usually ends with a signed empty text part, which EDA\n * keeps as an empty text part and replays as it came.\n */\nimport * as Arr from \"effect/Array\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as AiError from \"effect/ai/AiError\";\nimport * as IdGenerator from \"effect/ai/IdGenerator\";\nimport * as LanguageModel from \"effect/ai/LanguageModel\";\nimport * as Prompt from \"effect/ai/Prompt\";\nimport type * as Response from \"effect/ai/Response\";\nimport { addGenAIAnnotations } from \"effect/ai/Telemetry\";\nimport * as Tool from \"effect/ai/Tool\";\nimport * as Base64 from \"effect/encoding/Base64\";\nimport * as Sse from \"effect/encoding/Sse\";\nimport * as Headers from \"effect/http/Headers\";\nimport * as HttpBody from \"effect/http/HttpBody\";\nimport * as HttpClient from \"effect/http/HttpClient\";\nimport type * as HttpClientError from \"effect/http/HttpClientError\";\nimport * as HttpClientRequest from \"effect/http/HttpClientRequest\";\n\nimport {\n GoogleErrorBody,\n GoogleGenerateContentResponse,\n GoogleStreamChunk,\n type GoogleContent,\n type GoogleFunctionCallingMode,\n type GoogleFunctionDeclaration,\n type GoogleGenerateContentRequest,\n type GoogleRequestPart,\n type GoogleThinkingLevel,\n type GoogleToolConfig,\n type GoogleUsageMetadata,\n} from \"./google-wire\";\nimport { makeEDAProviderHttpClient } from \"./transport\";\n\n// =============================================================================\n// Config\n// =============================================================================\n\n/** Gemini request defaults for one resolved model (everything but the model id). */\nexport interface EDAGoogleModelConfig {\n readonly generationConfig?: {\n readonly maxOutputTokens?: number | undefined;\n readonly thinkingConfig?: {\n readonly thinkingLevel?: GoogleThinkingLevel | undefined;\n readonly includeThoughts?: boolean | undefined;\n };\n };\n readonly toolConfig?: {\n /** Used when the request lets the model choose (`toolChoice: \"auto\"`), in place of `AUTO`. */\n readonly functionCallingConfig?: { readonly mode?: GoogleFunctionCallingMode | undefined };\n };\n}\n\n/** Agent request policy for Gemini 4 models. */\nexport interface EDAGoogleAgentSettings {\n /** Thinking depth. Gemini 4 cannot disable thinking, so effort is the only control. */\n readonly effort: \"low\" | \"medium\" | \"high\";\n /** Output budget including thinking. Defaults to 65,536, the Gemini 4 per-request maximum. */\n readonly maxOutputTokens?: number | undefined;\n /** Stream thought summaries as reasoning parts. Defaults to `true`. */\n readonly includeThoughts?: boolean | undefined;\n}\n\n/**\n * Effort to `thinkingConfig.thinkingLevel`, one to one: `low` is `low`, `medium` is `medium`,\n * `high` is `high` (Gemini's default). Gemini's `xhigh` is not offered as an effort, so the three\n * efforts mean the same on every provider. `thinkingBudget` is deprecated and returns 400 next to\n * `thinkingLevel`, so it is never sent.\n */\nconst THINKING_LEVEL = {\n low: \"low\",\n medium: \"medium\",\n high: \"high\",\n} as const satisfies Record<EDAGoogleAgentSettings[\"effort\"], GoogleThinkingLevel>;\n\n/**\n * Model config for EDA agent sessions on Gemini 4. Effort maps to `thinkingLevel` one to one\n * (`low` → `low`, `medium` → `medium`, `high` → `high`; `xhigh` is not exposed), output defaults\n * to 65,536 tokens and thought summaries are on.\n */\nexport const googleAgentModelConfig = (settings: EDAGoogleAgentSettings): EDAGoogleModelConfig => ({\n generationConfig: {\n maxOutputTokens: settings.maxOutputTokens ?? 65_536,\n thinkingConfig: {\n thinkingLevel: THINKING_LEVEL[settings.effort],\n includeThoughts: settings.includeThoughts ?? true,\n },\n },\n});\n\n// =============================================================================\n// Client\n// =============================================================================\n\n/** Low-level Gemini API calls, with every failure mapped to `AiError`. */\nexport interface EDAGoogleClientService {\n readonly generateContent: (\n model: string,\n request: GoogleGenerateContentRequest,\n ) => Effect.Effect<GoogleGenerateContentResponse, AiError.AiError>;\n /** Server-sent chunks, each a full response holding only the parts generated since the last. */\n readonly streamGenerateContent: (\n model: string,\n request: GoogleGenerateContentRequest,\n ) => Stream.Stream<GoogleGenerateContentResponse, AiError.AiError>;\n}\n\n/** Gemini API client service. */\nexport class EDAGoogleClient extends Context.Service<EDAGoogleClient, EDAGoogleClientService>()(\n \"effect-durable-agent-cloudflare/EDAGoogleClient\",\n) {}\n\n/** Shared Gemini transport and client options. */\nexport interface EDAGoogleClientOptions {\n /** Cloudflare AI Gateway binding; requests go to its `google-ai-studio` provider. */\n readonly aiGateway?: AiGateway | undefined;\n /** Gemini API key, sent as `x-goog-api-key`. Optional only behind a gateway that stores one. */\n readonly apiKey?: string | undefined;\n /** Defaults to `https://generativelanguage.googleapis.com`. */\n readonly apiUrl?: string | undefined;\n}\n\nconst API_KEY_HEADER = \"x-goog-api-key\";\n\nconst withRedactedKey = Effect.updateService(\n Headers.CurrentRedactedNames,\n Arr.append(API_KEY_HEADER),\n);\n\n/** Gemini client layer over EDA's provider transport (Cloudflare AI Gateway or `fetch`). */\nexport const makeEDAGoogleClientLayer = (\n options: EDAGoogleClientOptions,\n): Layer.Layer<EDAGoogleClient> => {\n const apiKey = optionalNonEmptyString(options.apiKey);\n if (apiKey === undefined && options.aiGateway === undefined) {\n throw new Error(\n \"GEMINI_API_KEY is required unless Google traffic goes through a Cloudflare AI Gateway binding with a stored key.\",\n );\n }\n const http = makeEDAProviderHttpClient({ provider: \"google\", aiGateway: options.aiGateway }).pipe(\n HttpClient.mapRequest((request) => {\n const based = HttpClientRequest.prependUrl(\n request,\n options.apiUrl ?? \"https://generativelanguage.googleapis.com\",\n );\n return apiKey === undefined\n ? based\n : HttpClientRequest.setHeader(based, API_KEY_HEADER, apiKey);\n }),\n HttpClient.filterStatusOk,\n );\n const post = (model: string, method: string, request: GoogleGenerateContentRequest) =>\n HttpClientRequest.post(`/v1beta/models/${model}:${method}`, {\n body: HttpBody.jsonUnsafe(request),\n ...(method === \"streamGenerateContent\" ? { urlParams: { alt: \"sse\" } } : {}),\n });\n\n return Layer.succeed(EDAGoogleClient, {\n generateContent: (model, request) =>\n http.execute(post(model, \"generateContent\", request)).pipe(\n Effect.flatMap((response) => response.json),\n Effect.flatMap(Schema.decodeUnknownEffect(GoogleGenerateContentResponse)),\n Effect.catchTags({\n HttpClientError: (error) => mapHttpClientError(error, \"generateContent\"),\n SchemaError: (error) => Effect.fail(invalidResponse(error, \"generateContent\")),\n }),\n withRedactedKey,\n ),\n streamGenerateContent: (model, body) => {\n const request = post(model, \"streamGenerateContent\", body);\n return http.execute(request).pipe(\n Effect.map((response) => response.stream),\n Stream.unwrap,\n Stream.decodeText,\n Stream.pipeThroughChannel(Sse.decodeDataSchema(GoogleStreamChunk)),\n // A failure after the response started arrives as an error event.\n Stream.mapEffect(({ data }) =>\n \"error\" in data\n ? Effect.fail(\n AiError.make({\n module: \"EDAGoogleClient\",\n method: \"streamGenerateContent\",\n reason: statusReason({\n status: data.error.code ?? 500,\n body: data,\n http: undefined,\n request,\n }),\n }),\n )\n : Effect.succeed(data),\n ),\n Stream.catchTags({\n Retry: (error) => Stream.die(error),\n SseError: (error) =>\n Stream.fail(\n AiError.make({\n module: \"EDAGoogleClient\",\n method: \"streamGenerateContent\",\n reason: new AiError.InvalidResponseError({ description: error.message }),\n }),\n ),\n HttpClientError: (error) =>\n Stream.fromEffect(mapHttpClientError(error, \"streamGenerateContent\")),\n SchemaError: (error) => Stream.fail(invalidResponse(error, \"streamGenerateContent\")),\n }),\n Stream.updateService(Headers.CurrentRedactedNames, Arr.append(API_KEY_HEADER)),\n );\n },\n });\n};\n\n// =============================================================================\n// Errors\n// =============================================================================\n\nconst invalidResponse = (error: Schema.SchemaError, method: string): AiError.AiError =>\n AiError.make({\n module: \"EDAGoogleClient\",\n method,\n reason: AiError.InvalidResponseError.fromSchemaError(error),\n });\n\nconst mapHttpClientError = (\n error: HttpClientError.HttpClientError,\n method: string,\n): Effect.Effect<never, AiError.AiError> => {\n const reason = error.reason;\n switch (reason._tag) {\n case \"TransportError\":\n case \"EncodeError\":\n case \"InvalidUrlError\":\n return Effect.fail(\n AiError.make({\n module: \"EDAGoogleClient\",\n method,\n reason: new AiError.NetworkError({\n reason: reason._tag,\n method: reason.request.method,\n url: reason.request.url,\n description: reason.description,\n // The request (and its API key header) stays out of the error.\n cause: reason.cause,\n }),\n }),\n );\n case \"StatusCodeError\":\n return Effect.flatMap(\n Effect.orElseSucceed(reason.response.text, () => \"\"),\n (text) =>\n Effect.fail(\n AiError.make({\n module: \"EDAGoogleClient\",\n method,\n reason: statusReason({\n status: reason.response.status,\n body: Option.getOrUndefined(\n Schema.decodeUnknownOption(Schema.fromJsonString(GoogleErrorBody))(text),\n ),\n http: {\n response: {\n status: reason.response.status,\n headers: { ...reason.response.headers },\n },\n body: text,\n },\n request: reason.request,\n }),\n }),\n ),\n );\n case \"DecodeError\":\n case \"EmptyBodyError\":\n return Effect.fail(\n AiError.make({\n module: \"EDAGoogleClient\",\n method,\n reason: new AiError.InvalidOutputError({\n description: reason.description ?? \"Failed to read the Gemini response body\",\n }),\n }),\n );\n }\n};\n\n/** HTTP status to `AiError` reason, as the Anthropic adapter maps it. */\nconst statusReason = (params: {\n readonly status: number;\n readonly body: GoogleErrorBody | undefined;\n readonly http: typeof AiError.HttpContext.Type | undefined;\n readonly request: HttpClientRequest.HttpClientRequest;\n}): AiError.AiErrorReason => {\n const { status, http } = params;\n const message = params.body?.error.message;\n const metadata = { google: { status: params.body?.error.status ?? null } };\n const description = AiError.buildErrorDescription({\n status,\n message,\n method: params.request.method,\n url: params.request.url,\n errorType: params.body?.error.status,\n body: http?.body,\n });\n const context = { metadata, ...(http === undefined ? {} : { http }) };\n switch (status) {\n case 400:\n case 404:\n case 422:\n return new AiError.InvalidRequestError({ description, ...context });\n case 401:\n return new AiError.AuthenticationError({ kind: \"InvalidKey\", description, ...context });\n case 403:\n return new AiError.AuthenticationError({\n kind: \"InsufficientPermissions\",\n description,\n ...context,\n });\n case 429:\n return new AiError.RateLimitError(context);\n default:\n return status >= 500\n ? new AiError.InternalProviderError({ description: message ?? \"Server error\", ...context })\n : new AiError.UnknownError({ description: message, ...context });\n }\n};\n\nconst invalidInput = (method: string, description: string): AiError.AiError =>\n AiError.make({\n module: \"EDAGoogleLanguageModel\",\n method,\n reason: new AiError.InvalidUserInputError({ description }),\n });\n\n// =============================================================================\n// Language model\n// =============================================================================\n\n/** Gemini `LanguageModel` for one model id; requires {@link EDAGoogleClient}. */\nexport const makeEDAGoogleLanguageModel = (options: {\n readonly modelId: string;\n readonly config?: EDAGoogleModelConfig | undefined;\n}): Effect.Effect<LanguageModel.LanguageModel, never, EDAGoogleClient> =>\n Effect.gen(function* () {\n const client = yield* EDAGoogleClient;\n const config = options.config ?? {};\n const request = (provider: LanguageModel.ProviderOptions) =>\n makeRequest(provider, config).pipe(\n Effect.tap((body) => Effect.sync(() => annotateRequest(provider, options.modelId, body))),\n );\n return yield* LanguageModel.make({\n generateText: (provider) =>\n Effect.gen(function* () {\n const body = yield* request(provider);\n const response = yield* client.generateContent(options.modelId, body);\n const converter = yield* makeConverter;\n const parts = collapseStreamParts([\n ...(yield* converter.chunk(response)),\n ...converter.end(),\n ]);\n annotateResponse(provider, parts);\n return parts;\n }),\n streamText: (provider) =>\n request(provider).pipe(\n Effect.zip(makeConverter),\n Effect.map(([body, converter]) =>\n client.streamGenerateContent(options.modelId, body).pipe(\n Stream.mapEffect(converter.chunk),\n Stream.flattenIterable,\n Stream.concat(Stream.suspend(() => Stream.fromIterable(converter.end()))),\n Stream.tap((part) => Effect.sync(() => annotateResponse(provider, [part]))),\n ),\n ),\n Stream.unwrap,\n ),\n supportsSystemMessagesInHistory: Effect.succeed(false),\n });\n });\n\n// =============================================================================\n// Request\n// =============================================================================\n\nconst makeRequest = (\n provider: LanguageModel.ProviderOptions,\n config: EDAGoogleModelConfig,\n): Effect.Effect<GoogleGenerateContentRequest, AiError.AiError> =>\n Effect.gen(function* () {\n const tools = yield* prepareTools(provider, config);\n const { systemInstruction, contents } = yield* prepareContents(provider.prompt);\n const format = provider.responseFormat;\n return {\n ...tools,\n ...(systemInstruction === undefined ? {} : { systemInstruction }),\n contents,\n generationConfig: {\n ...config.generationConfig,\n ...(format.type === \"json\"\n ? {\n responseMimeType: \"application/json\",\n responseJsonSchema: Tool.getJsonSchemaFromSchema(format.schema),\n }\n : {}),\n },\n } satisfies GoogleGenerateContentRequest;\n });\n\n/**\n * Leading system messages become `systemInstruction`; the rest become `contents`, with assistant\n * messages as `model` turns and tool results as `functionResponse` parts in `user` turns. The\n * results of one step's calls share one turn, as Gemini expects for parallel calls. Every other\n * message keeps its own turn, so a request's contents always start with the previous request's\n * contents unchanged, which is the prefix Gemini's implicit cache matches.\n */\nconst prepareContents = (\n prompt: Prompt.Prompt,\n): Effect.Effect<\n {\n readonly systemInstruction: GoogleGenerateContentRequest[\"systemInstruction\"];\n readonly contents: ReadonlyArray<GoogleContent>;\n },\n AiError.AiError\n> =>\n Effect.gen(function* () {\n const system: Array<{ readonly text: string }> = [];\n const contents: Array<GoogleContent> = [];\n let results: Array<GoogleRequestPart> | undefined;\n for (const message of prompt.content) {\n if (message.role !== \"tool\") results = undefined;\n switch (message.role) {\n case \"system\":\n if (contents.length > 0) {\n return yield* invalidInput(\n \"prepareContents\",\n \"Gemini takes system messages only before the conversation.\",\n );\n }\n system.push({ text: message.content });\n break;\n case \"user\":\n contents.push({ role: \"user\", parts: message.content.map(userPart) });\n break;\n case \"assistant\": {\n const parts = message.content.flatMap(modelParts);\n if (parts.length > 0) contents.push({ role: \"model\", parts });\n break;\n }\n case \"tool\":\n if (results === undefined) {\n results = [];\n contents.push({ role: \"user\", parts: results });\n }\n results.push(...message.content.flatMap(toolResultParts));\n break;\n }\n }\n return {\n systemInstruction: system.length === 0 ? undefined : { parts: system },\n contents,\n };\n });\n\nconst userPart = (part: Prompt.UserMessagePart): GoogleRequestPart =>\n part.type === \"text\" ? { text: part.text } : filePart(part);\n\n/**\n * A file part as Gemini data. EDA stores file data as a string: bytes as a base64 `data:` URL and a\n * URL as its href. Bytes, base64 and every `data:` URL go inline, a `data:` URL with its decoded\n * payload and its own media type. A URL, as a `URL` or a string with a scheme (an https or Gemini\n * Files URI), goes as `fileData.fileUri`. Base64 has no `:`, so a scheme tells a URL from base64.\n */\nconst filePart = (part: Prompt.FilePart): GoogleRequestPart => {\n if (part.data instanceof Uint8Array) return inline(part.mediaType, Base64.encode(part.data));\n const value = part.data instanceof URL ? part.data.href : part.data;\n const dataUrl = parseDataUrl(value);\n if (dataUrl !== undefined) {\n return inline(dataUrl.mediaType === \"\" ? part.mediaType : dataUrl.mediaType, dataUrl.base64);\n }\n return URL_SCHEME.test(value)\n ? { fileData: { mimeType: geminiMediaType(part.mediaType), fileUri: value } }\n : inline(part.mediaType, value);\n};\n\nconst URL_SCHEME = /^[a-z][a-z\\d+.-]*:/i;\n\nconst inline = (mediaType: string, data: string): GoogleRequestPart => ({\n inlineData: { mimeType: geminiMediaType(mediaType), data },\n});\n\n/** `image/*`, an image of unknown type, goes as JPEG, as the Anthropic and OpenAI adapters send it. */\nconst geminiMediaType = (mediaType: string): string =>\n mediaType === \"image/*\" ? \"image/jpeg\" : mediaType;\n\n/**\n * A `data:` URL's media type (empty when it names none) and its payload as base64, decoded as the\n * Fetch standard's `data:` URL processor decodes it. The payload is percent-decoded. With\n * `;base64` it is base64 text, and without it the payload is the bytes themselves.\n */\nconst parseDataUrl = (\n value: string,\n): { readonly mediaType: string; readonly base64: string } | undefined => {\n // A URL's fragment is not part of its data; an encoded `%23` is.\n const match = DATA_URL.exec(value.split(\"#\", 1)[0] ?? \"\");\n if (match === null) return undefined;\n const [, header = \"\", payload = \"\"] = match;\n const mediaType = (header.split(\";\")[0] ?? \"\").trim().toLowerCase();\n return /;\\s*base64\\s*$/i.test(header)\n ? {\n mediaType,\n base64: payload\n .replace(/%([\\da-f]{2})/gi, (_, hex: string) =>\n String.fromCharCode(Number.parseInt(hex, 16)),\n )\n .replace(/[\\t\\n\\f\\r ]/g, \"\"),\n }\n : { mediaType, base64: Base64.encode(percentDecode(payload)) };\n};\n\nconst DATA_URL = /^data:([^,]*),(.*)$/is;\n\n/** Bytes of a percent-encoded string: `%XX` is that byte, and any other character its UTF-8. */\nconst percentDecode = (text: string): Uint8Array => {\n // Splitting on a captured `%XX` puts the escapes at the odd indexes.\n const chunks = text\n .split(/(%[\\da-f]{2})/i)\n .map((piece, index) =>\n index % 2 === 1\n ? Uint8Array.of(Number.parseInt(piece.slice(1), 16))\n : new TextEncoder().encode(piece),\n );\n const bytes = new Uint8Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0));\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n};\n\n/** An assistant part as the `model` part it came from, with its signature back on it. */\nconst modelParts = (part: Prompt.AssistantMessagePart): ReadonlyArray<GoogleRequestPart> => {\n const thoughtSignature = googleThoughtSignature(part.options);\n const signed = thoughtSignature === undefined ? {} : { thoughtSignature };\n switch (part.type) {\n case \"text\":\n return part.text.length === 0 && thoughtSignature === undefined\n ? []\n : [{ text: part.text, ...signed }];\n case \"reasoning\":\n return part.text.length === 0 && thoughtSignature === undefined\n ? []\n : [{ text: part.text, thought: true, ...signed }];\n case \"tool-call\":\n return [{ functionCall: { name: part.name, args: part.params, id: part.id }, ...signed }];\n case \"file\":\n return [filePart(part)];\n case \"tool-result\":\n case \"tool-approval-request\":\n // Provider-executed results and approvals have no Gemini request form; EDA stores neither.\n return [];\n }\n};\n\nconst toolResultParts = (part: Prompt.ToolMessagePart): ReadonlyArray<GoogleRequestPart> => {\n if (part.type !== \"tool-result\") return [];\n const output =\n part.modelOutput === undefined ? part.result : Prompt.toolModelOutputToText(part.modelOutput);\n return [\n {\n functionResponse: {\n name: part.name,\n id: part.id,\n // Gemini reads `output` as the function's result and `error` as its failure.\n response: part.isFailure ? { error: output } : { output },\n },\n },\n ];\n};\n\n/** The part's Gemini thought signature, if Gemini sent one. */\nconst googleThoughtSignature = (options: Prompt.ProviderOptions): string | undefined => {\n const google = options.google;\n return isRecord(google) && typeof google.thoughtSignature === \"string\"\n ? google.thoughtSignature\n : undefined;\n};\n\nconst prepareTools = (\n provider: LanguageModel.ProviderOptions,\n config: EDAGoogleModelConfig,\n): Effect.Effect<Pick<GoogleGenerateContentRequest, \"tools\" | \"toolConfig\">, AiError.AiError> =>\n Effect.gen(function* () {\n if (provider.tools.length === 0) return {};\n const functionDeclarations: Array<GoogleFunctionDeclaration> = [];\n for (const tool of provider.tools) {\n if (Tool.isProviderDefined(tool)) {\n return yield* invalidInput(\n \"prepareTools\",\n `Provider-defined tool ${tool.name} is not supported on Gemini.`,\n );\n }\n const parametersJsonSchema = yield* Effect.try({\n try: () => Tool.getJsonSchema(tool),\n catch: (error) =>\n AiError.make({\n module: \"EDAGoogleLanguageModel\",\n method: \"prepareTools\",\n reason: new AiError.UnsupportedSchemaError({\n description: `Tool ${tool.name} parameters: ${String(error)}`,\n }),\n }),\n });\n const description = Tool.getDescription(tool);\n functionDeclarations.push({\n name: tool.name,\n ...(description === undefined ? {} : { description }),\n parametersJsonSchema,\n });\n }\n return {\n tools: [{ functionDeclarations }],\n toolConfig: { functionCallingConfig: functionCalling(provider.toolChoice, config) },\n };\n });\n\nconst functionCalling = (\n choice: LanguageModel.ToolChoice<string>,\n config: EDAGoogleModelConfig,\n): NonNullable<GoogleToolConfig[\"functionCallingConfig\"]> => {\n const auto = config.toolConfig?.functionCallingConfig?.mode ?? \"AUTO\";\n if (choice === \"auto\") return { mode: auto };\n if (choice === \"none\") return { mode: \"NONE\" };\n if (choice === \"required\") return { mode: \"ANY\" };\n if (\"tool\" in choice) return { mode: \"ANY\", allowedFunctionNames: [choice.tool] };\n // `oneOf` already narrowed the declared tools.\n return choice.mode === \"required\"\n ? { mode: \"ANY\", allowedFunctionNames: choice.oneOf }\n : { mode: auto };\n};\n\n// =============================================================================\n// Response\n// =============================================================================\n\n/** The stream parts a Gemini response becomes. */\ntype StreamPart = Extract<\n Response.StreamPartEncoded,\n {\n readonly type:\n | \"response-metadata\"\n | \"text-start\"\n | \"text-delta\"\n | \"text-end\"\n | \"reasoning-start\"\n | \"reasoning-delta\"\n | \"reasoning-end\"\n | \"tool-params-start\"\n | \"tool-params-delta\"\n | \"tool-params-end\"\n | \"tool-call\"\n | \"finish\";\n }\n>;\n\ntype BlockKind = \"text\" | \"reasoning\";\n\nconst blockStart = (\n kind: BlockKind,\n id: string,\n metadata: Response.ProviderMetadata = {},\n): StreamPart =>\n kind === \"text\"\n ? { type: \"text-start\", id, metadata }\n : { type: \"reasoning-start\", id, metadata };\n\nconst blockDelta = (kind: BlockKind, id: string, delta: string): StreamPart =>\n kind === \"text\" ? { type: \"text-delta\", id, delta } : { type: \"reasoning-delta\", id, delta };\n\nconst blockEnd = (kind: BlockKind, id: string): StreamPart =>\n kind === \"text\" ? { type: \"text-end\", id } : { type: \"reasoning-end\", id };\n\n/**\n * Converts the chunks of one response into stream parts that replay as the parts Gemini sent.\n * Unsigned text parts of one kind (thought or answer) in a row are streamed pieces of one part and\n * form one block. A signed part is a block of its own whose start carries the signature, so the\n * signature replays on exactly that part, even an empty one. A function call closes the open\n * block, which keeps replayed parts in the order Gemini sent them. `finish` is emitted when the\n * response ends, with the last (cumulative) usage, and only if Gemini sent a finish reason.\n */\nconst makeConverter = Effect.gen(function* () {\n const ids = yield* IdGenerator.IdGenerator;\n let started = false;\n let open: { readonly kind: BlockKind; readonly id: string } | undefined;\n let blocks = 0;\n let toolCalls = false;\n let finishReason: string | undefined;\n let usage: GoogleUsageMetadata | undefined;\n\n const close = (out: Array<StreamPart>) => {\n if (open === undefined) return;\n out.push(blockEnd(open.kind, open.id));\n open = undefined;\n };\n\n const chunk = (response: GoogleGenerateContentResponse) =>\n Effect.gen(function* () {\n const blocked = response.promptFeedback?.blockReason;\n if (blocked !== undefined) {\n const message = response.promptFeedback?.blockReasonMessage;\n return yield* AiError.make({\n module: \"EDAGoogleLanguageModel\",\n method: \"convertResponse\",\n reason: new AiError.ContentPolicyError({\n description: `Gemini blocked the prompt (${blocked})${message === undefined ? \"\" : `: ${message}`}`,\n metadata: { google: { blockReason: blocked } },\n }),\n });\n }\n const out: Array<StreamPart> = [];\n if (!started) {\n started = true;\n out.push({\n type: \"response-metadata\",\n id: response.responseId,\n modelId: response.modelVersion,\n timestamp: DateTime.formatIso(yield* DateTime.now),\n });\n }\n usage = response.usageMetadata ?? usage;\n const candidate = response.candidates?.[0];\n const failure = finishFailure(candidate);\n if (failure !== undefined) return yield* failure;\n for (const part of candidate?.content?.parts ?? []) {\n const metadata =\n part.thoughtSignature === undefined\n ? {}\n : { metadata: { google: { thoughtSignature: part.thoughtSignature } } };\n if (part.functionCall !== undefined) {\n close(out);\n toolCalls = true;\n const id = part.functionCall.id ?? (yield* ids.generateId());\n const { name } = part.functionCall;\n const params = part.functionCall.args ?? {};\n out.push(\n { type: \"tool-params-start\", id, name },\n { type: \"tool-params-delta\", id, delta: JSON.stringify(params) },\n { type: \"tool-params-end\", id },\n { type: \"tool-call\", id, name, params, ...metadata },\n );\n continue;\n }\n if (\n part.text === undefined ||\n (part.text.length === 0 && part.thoughtSignature === undefined)\n ) {\n continue;\n }\n const kind = part.thought === true ? \"reasoning\" : \"text\";\n if (part.thoughtSignature === undefined) {\n if (open?.kind !== kind) {\n close(out);\n open = { kind, id: String(blocks++) };\n out.push(blockStart(kind, open.id));\n }\n out.push(blockDelta(kind, open.id, part.text));\n continue;\n }\n close(out);\n const id = String(blocks++);\n out.push(blockStart(kind, id, { google: { thoughtSignature: part.thoughtSignature } }));\n if (part.text.length > 0) out.push(blockDelta(kind, id, part.text));\n out.push(blockEnd(kind, id));\n }\n finishReason = candidate?.finishReason ?? finishReason;\n return out;\n });\n\n const end = (): ReadonlyArray<StreamPart> => {\n if (finishReason === undefined) return [];\n const out: Array<StreamPart> = [];\n close(out);\n out.push({\n type: \"finish\",\n reason: resolveFinishReason(finishReason, toolCalls),\n usage: makeUsage(usage),\n metadata: { google: { finishReason, usageMetadata: usage ?? null } },\n });\n return out;\n };\n\n return { chunk, end };\n});\n\n/**\n * Gemini usage as Effect AI usage. Input is the prompt plus tool-use prompt tokens, of which\n * `cachedContentTokenCount` came from the implicit cache. Gemini charges no cache writes. Output\n * is the answer (`candidatesTokenCount`) plus thinking (`thoughtsTokenCount`), both billed as\n * output.\n */\nconst makeUsage = (usage: GoogleUsageMetadata | undefined): Response.FinishPartEncoded[\"usage\"] => {\n if (usage === undefined) {\n return {\n inputTokens: {\n uncached: undefined,\n total: undefined,\n cacheRead: undefined,\n cacheWrite: undefined,\n },\n outputTokens: { total: undefined, text: undefined, reasoning: undefined },\n };\n }\n const input = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);\n const cached = usage.cachedContentTokenCount ?? 0;\n const text = usage.candidatesTokenCount ?? 0;\n const reasoning = usage.thoughtsTokenCount ?? 0;\n return {\n inputTokens: { total: input, uncached: input - cached, cacheRead: cached, cacheWrite: 0 },\n outputTokens: { total: text + reasoning, text, reasoning },\n };\n};\n\n/**\n * Gemini finish reasons that end a usable response, as the Anthropic and OpenAI adapters end\n * theirs: output limits are `length`, and safety and recitation filters are `content-filter`, as\n * Anthropic's `refusal` and OpenAI's `content_filter` are. A reason in neither table is `unknown`.\n */\nconst STOP_REASONS: Readonly<Record<string, Response.FinishReason>> = {\n STOP: \"stop\",\n MAX_TOKENS: \"length\",\n CONTINUATION: \"length\",\n SAFETY: \"content-filter\",\n RECITATION: \"content-filter\",\n LANGUAGE: \"content-filter\",\n BLOCKLIST: \"content-filter\",\n PROHIBITED_CONTENT: \"content-filter\",\n SPII: \"content-filter\",\n IMAGE_SAFETY: \"content-filter\",\n IMAGE_PROHIBITED_CONTENT: \"content-filter\",\n IMAGE_RECITATION: \"content-filter\",\n ESCALATION: \"content-filter\",\n OTHER: \"other\",\n IMAGE_OTHER: \"other\",\n NO_IMAGE: \"other\",\n FINISH_REASON_UNSPECIFIED: \"other\",\n};\n\ntype FailureContext = {\n readonly description: string;\n readonly metadata: { readonly google: Readonly<Record<string, string>> };\n};\n\n/**\n * Gemini finish reasons that say the response or the request is broken. Each fails the inference\n * with an `AiError`, as OpenAI's `response.failed` does, so EDA commits no tool call from it.\n */\nconst FAILURE_REASONS: Readonly<\n Record<string, (context: FailureContext) => AiError.AiErrorReason>\n> = {\n MALFORMED_FUNCTION_CALL: (context) => new AiError.InvalidOutputError(context),\n UNEXPECTED_TOOL_CALL: (context) => new AiError.InvalidOutputError(context),\n TOO_MANY_TOOL_CALLS: (context) => new AiError.InvalidOutputError(context),\n MALFORMED_RESPONSE: (context) => new AiError.InvalidOutputError(context),\n // The request left out a signature, which Gemini otherwise rejects with a 400.\n MISSING_THOUGHT_SIGNATURE: (context) => new AiError.InvalidRequestError(context),\n // The account is limited for Prohibited Use Policy violations; every request will stop.\n PUP_LIMITED_DISABLED: (context) => new AiError.ContentPolicyError(context),\n};\n\n/** The failure a candidate's finish reason is, keeping Gemini's `finishMessage`, if any. */\nconst finishFailure = (\n candidate: NonNullable<GoogleGenerateContentResponse[\"candidates\"]>[number] | undefined,\n): AiError.AiError | undefined => {\n const finishReason = candidate?.finishReason;\n const failure =\n finishReason !== undefined && Object.hasOwn(FAILURE_REASONS, finishReason)\n ? FAILURE_REASONS[finishReason]\n : undefined;\n if (finishReason === undefined || failure === undefined) return undefined;\n const finishMessage = candidate?.finishMessage;\n return AiError.make({\n module: \"EDAGoogleLanguageModel\",\n method: \"convertResponse\",\n reason: failure({\n description: `Gemini finished with ${finishReason}${finishMessage === undefined ? \"\" : `: ${finishMessage}`}`,\n metadata: {\n google: { finishReason, ...(finishMessage === undefined ? {} : { finishMessage }) },\n },\n }),\n });\n};\n\n/** Gemini finishes a function-call response with `STOP`; that is a `tool-calls` finish. */\nconst resolveFinishReason = (reason: string, toolCalls: boolean): Response.FinishReason => {\n if (reason === \"STOP\" && toolCalls) return \"tool-calls\";\n return (Object.hasOwn(STOP_REASONS, reason) ? STOP_REASONS[reason] : undefined) ?? \"unknown\";\n};\n\n/** Folds stream parts into the whole parts `generateText` returns. */\nconst collapseStreamParts = (parts: ReadonlyArray<StreamPart>): Array<Response.PartEncoded> => {\n const out: Array<Response.PartEncoded> = [];\n const blocks = new Map<string, { text: string; metadata: Response.ProviderMetadata }>();\n for (const part of parts) {\n switch (part.type) {\n case \"text-start\":\n case \"reasoning-start\":\n blocks.set(part.id, { text: \"\", metadata: part.metadata ?? {} });\n break;\n case \"text-delta\":\n case \"reasoning-delta\": {\n const block = blocks.get(part.id);\n if (block === undefined) break;\n block.text += part.delta;\n break;\n }\n case \"text-end\":\n case \"reasoning-end\": {\n const block = blocks.get(part.id);\n // A signed block is kept even when empty: its signature must be replayed.\n if (\n block === undefined ||\n (block.text.length === 0 && block.metadata.google === undefined)\n ) {\n break;\n }\n out.push({\n type: part.type === \"text-end\" ? \"text\" : \"reasoning\",\n text: block.text,\n metadata: block.metadata,\n });\n break;\n }\n case \"tool-params-start\":\n case \"tool-params-delta\":\n case \"tool-params-end\":\n break;\n case \"response-metadata\":\n case \"tool-call\":\n case \"finish\":\n out.push(part);\n break;\n }\n }\n return out;\n};\n\n// =============================================================================\n// Telemetry\n// =============================================================================\n\nconst annotateRequest = (\n provider: LanguageModel.ProviderOptions,\n model: string,\n request: GoogleGenerateContentRequest,\n) =>\n addGenAIAnnotations(provider.span, {\n provider: { name: \"gcp.gemini\" },\n operation: { name: \"chat\" },\n request: { model, maxTokens: request.generationConfig?.maxOutputTokens },\n });\n\nconst annotateResponse = (\n provider: LanguageModel.ProviderOptions,\n parts: ReadonlyArray<StreamPart | Response.PartEncoded>,\n) => {\n for (const part of parts) {\n if (part.type === \"response-metadata\") {\n addGenAIAnnotations(provider.span, { response: { id: part.id, model: part.modelId } });\n }\n if (part.type === \"finish\") {\n addGenAIAnnotations(provider.span, {\n response: { finishReasons: [part.reason] },\n usage: {\n inputTokens: part.usage.inputTokens.total,\n outputTokens: part.usage.outputTokens.total,\n },\n });\n }\n }\n};\n\nconst isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst optionalNonEmptyString = (value: string | undefined): string | undefined => {\n const trimmed = value?.trim();\n return trimmed === undefined || trimmed.length === 0 ? undefined : trimmed;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,MAAM,eAAe,OAAO,OAAO;CACjC,MAAM,OAAO,YAAY,OAAO,MAAM;CACtC,SAAS,OAAO,YAAY,OAAO,OAAO;CAC1C,kBAAkB,OAAO,YAAY,OAAO,MAAM;C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B;CAEF,OAAO;AACT;AAMA,MAAM,mBACJ,UACA,OACA,YAEA,oBAAoB,SAAS,MAAM;CACjC,UAAU,EAAE,MAAM,aAAa;CAC/B,WAAW,EAAE,MAAM,OAAO;CAC1B,SAAS;EAAE;EAAO,WAAW,QAAQ,kBAAkB;CAAgB;AACzE,CAAC;AAEH,MAAM,oBACJ,UACA,UACG;CACH,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,KAAK,SAAS,qBAChB,oBAAoB,SAAS,MAAM,EAAE,UAAU;GAAE,IAAI,KAAK;GAAI,OAAO,KAAK;EAAQ,EAAE,CAAC;EAEvF,IAAI,KAAK,SAAS,UAChB,oBAAoB,SAAS,MAAM;GACjC,UAAU,EAAE,eAAe,CAAC,KAAK,MAAM,EAAE;GACzC,OAAO;IACL,aAAa,KAAK,MAAM,YAAY;IACpC,cAAc,KAAK,MAAM,aAAa;GACxC;EACF,CAAC;CAEL;AACF;AAEA,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,MAAM,0BAA0B,UAAkD;CAChF,MAAM,UAAU,OAAO,KAAK;CAC5B,OAAO,YAAY,KAAA,KAAa,QAAQ,WAAW,IAAI,KAAA,IAAY;AACrE"}
@@ -0,0 +1,178 @@
1
+ import * as Layer from "effect/Layer";
2
+ import * as Context from "effect/Context";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Schema from "effect/Schema";
5
+ import * as Stream from "effect/Stream";
6
+ import * as AiError from "effect/ai/AiError";
7
+ import * as LanguageModel from "effect/ai/LanguageModel";
8
+ //#region src/providers/google-wire.d.ts
9
+ /** `thinkingConfig.thinkingLevel` values the Gemini 4 models accept (`minimal` is rejected). */
10
+ type GoogleThinkingLevel = "low" | "medium" | "high" | "xhigh";
11
+ /** `toolConfig.functionCallingConfig.mode`. */
12
+ type GoogleFunctionCallingMode = "AUTO" | "ANY" | "NONE" | "VALIDATED";
13
+ /** One request part. Exactly one data field is set; `thought` and `thoughtSignature` annotate it. */
14
+ interface GoogleRequestPart {
15
+ readonly text?: string;
16
+ readonly thought?: boolean;
17
+ readonly thoughtSignature?: string;
18
+ readonly inlineData?: {
19
+ readonly mimeType: string;
20
+ readonly data: string;
21
+ };
22
+ readonly fileData?: {
23
+ readonly mimeType: string;
24
+ readonly fileUri: string;
25
+ };
26
+ readonly functionCall?: {
27
+ readonly name: string;
28
+ readonly args: unknown;
29
+ readonly id?: string;
30
+ };
31
+ readonly functionResponse?: {
32
+ readonly name: string;
33
+ readonly response: Readonly<Record<string, unknown>>;
34
+ readonly id?: string;
35
+ };
36
+ }
37
+ /** One turn of `contents`. Tool results go back in `user` turns. */
38
+ interface GoogleContent {
39
+ readonly role: "user" | "model";
40
+ readonly parts: ReadonlyArray<GoogleRequestPart>;
41
+ }
42
+ interface GoogleFunctionDeclaration {
43
+ readonly name: string;
44
+ readonly description?: string;
45
+ /** JSON Schema for the arguments object (mutually exclusive with OpenAPI `parameters`). */
46
+ readonly parametersJsonSchema: unknown;
47
+ }
48
+ interface GoogleGenerationConfig {
49
+ readonly maxOutputTokens?: number;
50
+ readonly thinkingConfig?: {
51
+ readonly thinkingLevel?: GoogleThinkingLevel;
52
+ /** Return thought summaries as parts with `thought: true`. */
53
+ readonly includeThoughts?: boolean;
54
+ };
55
+ readonly responseMimeType?: string;
56
+ readonly responseJsonSchema?: unknown;
57
+ }
58
+ interface GoogleToolConfig {
59
+ readonly functionCallingConfig?: {
60
+ readonly mode?: GoogleFunctionCallingMode;
61
+ readonly allowedFunctionNames?: ReadonlyArray<string>;
62
+ };
63
+ }
64
+ /** `POST /v1beta/models/{model}:generateContent` (and `:streamGenerateContent`) body. */
65
+ interface GoogleGenerateContentRequest {
66
+ readonly systemInstruction?: {
67
+ readonly parts: ReadonlyArray<{
68
+ readonly text: string;
69
+ }>;
70
+ };
71
+ readonly tools?: ReadonlyArray<{
72
+ readonly functionDeclarations: ReadonlyArray<GoogleFunctionDeclaration>;
73
+ }>;
74
+ readonly toolConfig?: GoogleToolConfig;
75
+ readonly contents: ReadonlyArray<GoogleContent>;
76
+ readonly generationConfig?: GoogleGenerationConfig;
77
+ }
78
+ /**
79
+ * A full response, and also each streamed SSE chunk: chunks carry new parts only, and
80
+ * `usageMetadata` cumulatively, so the last chunk's usage is final.
81
+ */
82
+ declare const GoogleGenerateContentResponse: Schema.Struct<{
83
+ readonly candidates: Schema.optionalKey<Schema.$Array<Schema.Struct<{
84
+ readonly content: Schema.optionalKey<Schema.Struct<{
85
+ readonly parts: Schema.optionalKey<Schema.$Array<Schema.Struct<{
86
+ readonly text: Schema.optionalKey<Schema.String>;
87
+ readonly thought: Schema.optionalKey<Schema.Boolean>;
88
+ readonly thoughtSignature: Schema.optionalKey<Schema.String>;
89
+ readonly functionCall: Schema.optionalKey<Schema.Struct<{
90
+ readonly name: Schema.String;
91
+ readonly args: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Unknown>>;
92
+ readonly id: Schema.optionalKey<Schema.String>;
93
+ }>>;
94
+ }>>>;
95
+ }>>;
96
+ readonly finishReason: Schema.optionalKey<Schema.String>;
97
+ readonly finishMessage: Schema.optionalKey<Schema.String>;
98
+ }>>>;
99
+ /** Set when the prompt itself was blocked; there are no candidates then. */
100
+ readonly promptFeedback: Schema.optionalKey<Schema.Struct<{
101
+ readonly blockReason: Schema.optionalKey<Schema.String>;
102
+ readonly blockReasonMessage: Schema.optionalKey<Schema.String>;
103
+ }>>;
104
+ readonly usageMetadata: Schema.optionalKey<Schema.Struct<{
105
+ readonly promptTokenCount: Schema.optionalKey<Schema.Number>;
106
+ /** Prompt tokens read from the implicit cache; a subset of `promptTokenCount`. */
107
+ readonly cachedContentTokenCount: Schema.optionalKey<Schema.Number>;
108
+ readonly candidatesTokenCount: Schema.optionalKey<Schema.Number>;
109
+ /** Thinking tokens, billed as output and not part of `candidatesTokenCount`. */
110
+ readonly thoughtsTokenCount: Schema.optionalKey<Schema.Number>;
111
+ readonly toolUsePromptTokenCount: Schema.optionalKey<Schema.Number>;
112
+ readonly totalTokenCount: Schema.optionalKey<Schema.Number>;
113
+ }>>;
114
+ readonly modelVersion: Schema.optionalKey<Schema.String>;
115
+ readonly responseId: Schema.optionalKey<Schema.String>;
116
+ }>;
117
+ type GoogleGenerateContentResponse = typeof GoogleGenerateContentResponse.Type;
118
+ //#endregion
119
+ //#region src/providers/google.d.ts
120
+ /** Gemini request defaults for one resolved model (everything but the model id). */
121
+ interface EDAGoogleModelConfig {
122
+ readonly generationConfig?: {
123
+ readonly maxOutputTokens?: number | undefined;
124
+ readonly thinkingConfig?: {
125
+ readonly thinkingLevel?: GoogleThinkingLevel | undefined;
126
+ readonly includeThoughts?: boolean | undefined;
127
+ };
128
+ };
129
+ readonly toolConfig?: {
130
+ /** Used when the request lets the model choose (`toolChoice: "auto"`), in place of `AUTO`. */
131
+ readonly functionCallingConfig?: {
132
+ readonly mode?: GoogleFunctionCallingMode | undefined;
133
+ };
134
+ };
135
+ }
136
+ /** Agent request policy for Gemini 4 models. */
137
+ interface EDAGoogleAgentSettings {
138
+ /** Thinking depth. Gemini 4 cannot disable thinking, so effort is the only control. */
139
+ readonly effort: "low" | "medium" | "high";
140
+ /** Output budget including thinking. Defaults to 65,536, the Gemini 4 per-request maximum. */
141
+ readonly maxOutputTokens?: number | undefined;
142
+ /** Stream thought summaries as reasoning parts. Defaults to `true`. */
143
+ readonly includeThoughts?: boolean | undefined;
144
+ }
145
+ /**
146
+ * Model config for EDA agent sessions on Gemini 4. Effort maps to `thinkingLevel` one to one
147
+ * (`low` → `low`, `medium` → `medium`, `high` → `high`; `xhigh` is not exposed), output defaults
148
+ * to 65,536 tokens and thought summaries are on.
149
+ */
150
+ declare const googleAgentModelConfig: (settings: EDAGoogleAgentSettings) => EDAGoogleModelConfig;
151
+ /** Low-level Gemini API calls, with every failure mapped to `AiError`. */
152
+ interface EDAGoogleClientService {
153
+ readonly generateContent: (model: string, request: GoogleGenerateContentRequest) => Effect.Effect<GoogleGenerateContentResponse, AiError.AiError>;
154
+ /** Server-sent chunks, each a full response holding only the parts generated since the last. */
155
+ readonly streamGenerateContent: (model: string, request: GoogleGenerateContentRequest) => Stream.Stream<GoogleGenerateContentResponse, AiError.AiError>;
156
+ }
157
+ declare const EDAGoogleClient_base: Context.ServiceClass<EDAGoogleClient, "effect-durable-agent-cloudflare/EDAGoogleClient", EDAGoogleClientService>;
158
+ /** Gemini API client service. */
159
+ declare class EDAGoogleClient extends EDAGoogleClient_base {}
160
+ /** Shared Gemini transport and client options. */
161
+ interface EDAGoogleClientOptions {
162
+ /** Cloudflare AI Gateway binding; requests go to its `google-ai-studio` provider. */
163
+ readonly aiGateway?: AiGateway | undefined;
164
+ /** Gemini API key, sent as `x-goog-api-key`. Optional only behind a gateway that stores one. */
165
+ readonly apiKey?: string | undefined;
166
+ /** Defaults to `https://generativelanguage.googleapis.com`. */
167
+ readonly apiUrl?: string | undefined;
168
+ }
169
+ /** Gemini client layer over EDA's provider transport (Cloudflare AI Gateway or `fetch`). */
170
+ declare const makeEDAGoogleClientLayer: (options: EDAGoogleClientOptions) => Layer.Layer<EDAGoogleClient>;
171
+ /** Gemini `LanguageModel` for one model id; requires {@link EDAGoogleClient}. */
172
+ declare const makeEDAGoogleLanguageModel: (options: {
173
+ readonly modelId: string;
174
+ readonly config?: EDAGoogleModelConfig | undefined;
175
+ }) => Effect.Effect<LanguageModel.LanguageModel, never, EDAGoogleClient>;
176
+ //#endregion
177
+ export { EDAGoogleModelConfig as a, makeEDAGoogleLanguageModel as c, EDAGoogleClientService as i, EDAGoogleClient as n, googleAgentModelConfig as o, EDAGoogleClientOptions as r, makeEDAGoogleClientLayer as s, EDAGoogleAgentSettings as t };
178
+ //# sourceMappingURL=google-Dja9VEPg.d.ts.map
@@ -0,0 +1,2 @@
1
+ import { a as EDAGoogleModelConfig, c as makeEDAGoogleLanguageModel, i as EDAGoogleClientService, n as EDAGoogleClient, o as googleAgentModelConfig, r as EDAGoogleClientOptions, s as makeEDAGoogleClientLayer, t as EDAGoogleAgentSettings } from "./google-Dja9VEPg.js";
2
+ export { EDAGoogleAgentSettings, EDAGoogleClient, EDAGoogleClientOptions, EDAGoogleClientService, EDAGoogleModelConfig, googleAgentModelConfig, makeEDAGoogleClientLayer, makeEDAGoogleLanguageModel };
package/dist/google.js ADDED
@@ -0,0 +1,2 @@
1
+ import { i as makeEDAGoogleLanguageModel, n as googleAgentModelConfig, r as makeEDAGoogleClientLayer, t as EDAGoogleClient } from "./google-DKsl1vVF.js";
2
+ export { EDAGoogleClient, googleAgentModelConfig, makeEDAGoogleClientLayer, makeEDAGoogleLanguageModel };
package/dist/openai.js CHANGED
@@ -1,4 +1,4 @@
1
- import { r as makeEDAProviderHttpClient } from "./transport-BzgK07l4.js";
1
+ import { r as makeEDAProviderHttpClient } from "./transport-D8197izA.js";
2
2
  import * as Layer from "effect/Layer";
3
3
  import * as Redacted from "effect/Redacted";
4
4
  import * as HttpClient from "effect/http/HttpClient";
@@ -1,5 +1,6 @@
1
1
  import { EDAOpenAiModelConfig } from "./openai.js";
2
2
  import { EDAAnthropicClientOptions, EDAAnthropicModelConfig, prepareEDAAnthropicPrompt } from "./anthropic.js";
3
+ import { a as EDAGoogleModelConfig, r as EDAGoogleClientOptions } from "./google-Dja9VEPg.js";
3
4
  import * as Layer from "effect/Layer";
4
5
  import { ModelSelectionPayload } from "effect-durable-agent/types/events";
5
6
  import { CompactionExecutor } from "effect-durable-agent/services/compaction";
@@ -14,6 +15,10 @@ type EDAResolvedModel = {
14
15
  readonly provider: "anthropic";
15
16
  readonly modelId: string;
16
17
  readonly config: EDAAnthropicModelConfig;
18
+ } | {
19
+ readonly provider: "google";
20
+ readonly modelId: string;
21
+ readonly config: EDAGoogleModelConfig;
17
22
  };
18
23
  /** Clients for every provider a host serves; a session runs on the one its selection names. */
19
24
  interface EDAMultiProviderModelResolverOptions {
@@ -23,12 +28,14 @@ interface EDAMultiProviderModelResolverOptions {
23
28
  readonly apiUrl?: string | undefined;
24
29
  };
25
30
  readonly anthropic?: EDAAnthropicClientOptions;
31
+ readonly google?: EDAGoogleClientOptions;
26
32
  /** Host policy: validate the recorded selection and choose request settings. Throw to reject. */
27
33
  readonly resolve: (selection: ModelSelectionPayload | undefined) => EDAResolvedModel;
28
34
  }
29
35
  /**
30
36
  * Resolves each durable selection to the provider it names, sharing one client per provider for
31
- * the runtime lifetime, and prepares prompts in that provider's cache and compaction shape.
37
+ * the runtime lifetime, and prepares prompts in that provider's cache and compaction shape,
38
+ * without the parts that hold only another provider's state.
32
39
  */
33
40
  declare const makeEDAMultiProviderModelResolverLayer: (options: EDAMultiProviderModelResolverOptions) => Layer.Layer<ModelResolver>;
34
41
  /** Options for provider-native compaction. */
@@ -45,9 +52,11 @@ interface EDANativeCompactionOptions {
45
52
  * Compacts with the session provider's own endpoint: OpenAI `/responses/compact`, Anthropic
46
53
  * on-demand compaction (`compact-2026-09-04`). Each call carries the exact earlier request prompt,
47
54
  * so it reads the conversation from the provider cache, and the returned native items replace the
48
- * summarized history on later requests. Other providers fall back to a prompt-prefix summary.
55
+ * summarized history on later requests. Providers without one (Google, and any selection EDA does
56
+ * not know) summarize with `promptPrefixSummaryCompactionExecutor`, which re-sends the same
57
+ * earlier prompt with the summary request appended.
49
58
  */
50
59
  declare const makeEDANativeCompactionExecutorLayer: (options?: EDANativeCompactionOptions) => Layer.Layer<CompactionExecutor>;
51
60
  //#endregion
52
- export { type EDAAnthropicModelConfig, EDAMultiProviderModelResolverOptions, EDANativeCompactionOptions, type EDAOpenAiModelConfig, EDAResolvedModel, makeEDAMultiProviderModelResolverLayer, makeEDANativeCompactionExecutorLayer, prepareEDAAnthropicPrompt };
61
+ export { type EDAAnthropicModelConfig, type EDAGoogleModelConfig, EDAMultiProviderModelResolverOptions, EDANativeCompactionOptions, type EDAOpenAiModelConfig, EDAResolvedModel, makeEDAMultiProviderModelResolverLayer, makeEDANativeCompactionExecutorLayer, prepareEDAAnthropicPrompt };
53
62
  //# sourceMappingURL=providers.d.ts.map
package/dist/providers.js CHANGED
@@ -1,6 +1,7 @@
1
- import { a as withBeta, i as prepareNativeCompaction, n as EDAProviderRequestOverride, t as ANTHROPIC_COMPACTION_BETA } from "./transport-BzgK07l4.js";
1
+ import { a as withBeta, i as prepareNativeCompaction, n as EDAProviderRequestOverride, o as withoutOtherProvidersState, t as ANTHROPIC_COMPACTION_BETA } from "./transport-D8197izA.js";
2
2
  import { makeEDAAnthropicClientLayer, prepareEDAAnthropicPrompt } from "./anthropic.js";
3
3
  import { makeEDAOpenAiClientLayer } from "./openai.js";
4
+ import { i as makeEDAGoogleLanguageModel, r as makeEDAGoogleClientLayer, t as EDAGoogleClient } from "./google-DKsl1vVF.js";
4
5
  import { AnthropicClient, AnthropicLanguageModel } from "@effect/ai-anthropic";
5
6
  import { nativeCompactionSummaryMessage } from "effect-durable-agent/services/prompt-projector";
6
7
  import * as Layer from "effect/Layer";
@@ -12,33 +13,70 @@ import { OpenAiClient, OpenAiLanguageModel } from "@effect/ai-openai";
12
13
  import { ModelResolver } from "effect-durable-agent/services/model-resolver";
13
14
  import { generateTextOfferingTools } from "effect-durable-agent/services/model-call";
14
15
  //#region src/providers/providers.ts
16
+ const PROVIDERS = {
17
+ openai: {
18
+ name: "OpenAI",
19
+ connect: (options) => {
20
+ const layer = makeEDAOpenAiClientLayer(options);
21
+ return Effect.map(OpenAiClient.OpenAiClient.pipe(Effect.provide(layer)), (client) => (resolved) => OpenAiLanguageModel.make({
22
+ model: resolved.modelId,
23
+ config: resolved.config
24
+ }).pipe(Effect.provideService(OpenAiClient.OpenAiClient, client)));
25
+ },
26
+ preparePrompt: (prompt) => prepareNativeCompaction("openai", prompt),
27
+ compact: (input) => openAiCompaction(input)
28
+ },
29
+ anthropic: {
30
+ name: "Anthropic",
31
+ connect: (options) => {
32
+ const layer = makeEDAAnthropicClientLayer(options);
33
+ return Effect.map(AnthropicClient.AnthropicClient.pipe(Effect.provide(layer)), (client) => (resolved) => AnthropicLanguageModel.make({
34
+ model: resolved.modelId,
35
+ config: resolved.config
36
+ }).pipe(Effect.provideService(AnthropicClient.AnthropicClient, client)));
37
+ },
38
+ preparePrompt: prepareEDAAnthropicPrompt,
39
+ compact: (input, options) => anthropicCompaction(input, options)
40
+ },
41
+ google: {
42
+ name: "Google",
43
+ connect: (options) => {
44
+ const layer = makeEDAGoogleClientLayer(options);
45
+ return Effect.map(EDAGoogleClient.pipe(Effect.provide(layer)), (client) => (resolved) => makeEDAGoogleLanguageModel({
46
+ modelId: resolved.modelId,
47
+ config: resolved.config
48
+ }).pipe(Effect.provideService(EDAGoogleClient, client)));
49
+ },
50
+ preparePrompt: (prompt) => prompt,
51
+ compact: void 0
52
+ }
53
+ };
54
+ const isProvider = (provider) => provider !== void 0 && Object.hasOwn(PROVIDERS, provider);
55
+ const connect = (provider, options) => options === void 0 ? Effect.succeed(void 0) : PROVIDERS[provider].connect(options);
56
+ const makeModel = (makers, provider, resolved) => {
57
+ const make = makers[provider];
58
+ return make === void 0 ? Effect.die(/* @__PURE__ */ new Error(`No ${PROVIDERS[provider].name} client is configured.`)) : make(resolved);
59
+ };
15
60
  /**
16
61
  * Resolves each durable selection to the provider it names, sharing one client per provider for
17
- * the runtime lifetime, and prepares prompts in that provider's cache and compaction shape.
62
+ * the runtime lifetime, and prepares prompts in that provider's cache and compaction shape,
63
+ * without the parts that hold only another provider's state.
18
64
  */
19
65
  const makeEDAMultiProviderModelResolverLayer = (options) => {
20
- const openAiClient = options.openai === void 0 ? void 0 : makeEDAOpenAiClientLayer(options.openai);
21
- const anthropicClient = options.anthropic === void 0 ? void 0 : makeEDAAnthropicClientLayer(options.anthropic);
66
+ const clients = {
67
+ openai: connect("openai", options.openai),
68
+ anthropic: connect("anthropic", options.anthropic),
69
+ google: connect("google", options.google)
70
+ };
22
71
  return Layer.effect(ModelResolver, Effect.gen(function* () {
23
- const openAi = openAiClient === void 0 ? void 0 : yield* OpenAiClient.OpenAiClient.pipe(Effect.provide(openAiClient));
24
- const anthropic = anthropicClient === void 0 ? void 0 : yield* AnthropicClient.AnthropicClient.pipe(Effect.provide(anthropicClient));
72
+ const makers = yield* Effect.all(clients);
25
73
  return {
26
74
  resolve: Effect.fn("MultiProviderModelResolver.resolve")(function* (selection) {
27
75
  const resolved = options.resolve(selection);
28
- if (resolved.provider === "anthropic") {
29
- if (anthropic === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("No Anthropic client is configured."));
30
- return yield* AnthropicLanguageModel.make({
31
- model: resolved.modelId,
32
- config: resolved.config
33
- }).pipe(Effect.provideService(AnthropicClient.AnthropicClient, anthropic));
34
- }
35
- if (openAi === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("No OpenAI client is configured."));
36
- return yield* OpenAiLanguageModel.make({
37
- model: resolved.modelId,
38
- config: resolved.config
39
- }).pipe(Effect.provideService(OpenAiClient.OpenAiClient, openAi));
76
+ if (selection !== void 0 && resolved.provider !== selection.provider) return yield* Effect.die(/* @__PURE__ */ new Error(`A ${selection.provider} selection resolved to ${resolved.provider}; a selection must resolve to the provider it names.`));
77
+ return yield* makeModel(makers, resolved.provider, resolved);
40
78
  }),
41
- preparePrompt: (selection, prompt) => selection?.provider === "anthropic" ? prepareEDAAnthropicPrompt(prompt) : selection?.provider === "openai" ? prepareNativeCompaction("openai", prompt) : prompt
79
+ preparePrompt: (selection, prompt) => isProvider(selection?.provider) ? PROVIDERS[selection.provider].preparePrompt(withoutOtherProvidersState(selection.provider, prompt)) : prompt
42
80
  };
43
81
  }));
44
82
  };
@@ -46,18 +84,18 @@ const makeEDAMultiProviderModelResolverLayer = (options) => {
46
84
  * Compacts with the session provider's own endpoint: OpenAI `/responses/compact`, Anthropic
47
85
  * on-demand compaction (`compact-2026-09-04`). Each call carries the exact earlier request prompt,
48
86
  * so it reads the conversation from the provider cache, and the returned native items replace the
49
- * summarized history on later requests. Other providers fall back to a prompt-prefix summary.
87
+ * summarized history on later requests. Providers without one (Google, and any selection EDA does
88
+ * not know) summarize with `promptPrefixSummaryCompactionExecutor`, which re-sends the same
89
+ * earlier prompt with the summary request appended.
50
90
  */
51
91
  const makeEDANativeCompactionExecutorLayer = (options = {}) => Layer.effect(CompactionExecutor, Effect.gen(function* () {
52
92
  const fallback = yield* CompactionExecutor.pipe(Effect.provide(promptPrefixSummaryCompactionExecutor()));
53
93
  return {
54
94
  id: CompactionExecutorId.make("provider-native"),
55
95
  execute: (input) => {
56
- switch (input.state.modelSelection?.provider) {
57
- case "anthropic": return anthropicCompaction(input, options);
58
- case "openai": return openAiCompaction(input);
59
- default: return fallback.execute(input);
60
- }
96
+ const provider = input.state.modelSelection?.provider;
97
+ const compact = isProvider(provider) ? PROVIDERS[provider].compact : void 0;
98
+ return compact === void 0 ? fallback.execute(input) : compact(input, options);
61
99
  }
62
100
  };
63
101
  }));