@alvin0/ai-agent-sdk-provider-gemini 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -8
- package/dist/index.d.ts +31 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +50 -45
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -6,9 +6,15 @@ Compatible gateways can configure `baseUrl`, `models`, `fetch`, and `headers`
|
|
|
6
6
|
(a string record or synchronous function returning one per operation).
|
|
7
7
|
Generation uses Interactions; embedding uses batchEmbedContents.
|
|
8
8
|
The embedding adapter/plugin also supports custom headers.
|
|
9
|
-
Header names are case-insensitive
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
Header names are case-insensitive. A `headers` entry overrides what the SDK
|
|
10
|
+
would otherwise send for that name (`accept`, `content-type`, `user-agent`) —
|
|
11
|
+
only a connection-level name `fetch` itself forbids (`host`, `content-length`,
|
|
12
|
+
…) or a credential-shaped name (must go through `apiKey`/`authHeader` instead,
|
|
13
|
+
so it can be redacted in logs) stays rejected. Supply credentials with
|
|
14
|
+
`apiKey`, or `authHeader: 'bearer'` when a gateway in front of Gemini expects
|
|
15
|
+
`Authorization: Bearer` instead of this API's own `x-goog-api-key`. Static
|
|
16
|
+
records are copied; prepared embedding calls keep the same header snapshot
|
|
17
|
+
across all batches.
|
|
12
18
|
Trusted local HTTP gateways require `allowInsecureHttp: true`.
|
|
13
19
|
|
|
14
20
|
```sh
|
|
@@ -23,8 +29,36 @@ Credentials are always injected. This package never reads `.env`, environment
|
|
|
23
29
|
variables, or files; a Node host may opt into `envCredential()` from
|
|
24
30
|
`@alvin0/ai-agent-sdk-auth-node`.
|
|
25
31
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
32
|
+
An uncatalogued model defaults to the SDK's own 200,000-token operating
|
|
33
|
+
context — this package no longer hardcodes per-vendor context windows (Pro vs.
|
|
34
|
+
Flash, etc.), so a model with a larger real window (Flash's 1,000,000, for
|
|
35
|
+
example) needs it declared explicitly. Set `models: [{ id, contextWindow }]`
|
|
36
|
+
to override per model, or `defaultContextWindow` at the route level; both take
|
|
37
|
+
precedence over the SDK default and over `createAgentRuntime({ defaults })`.
|
|
38
|
+
|
|
39
|
+
## Prompt caching
|
|
40
|
+
|
|
41
|
+
Gemini Interactions uses implicit prompt caching automatically for supported
|
|
42
|
+
models, in both stateless requests (the SDK resends history) and stateful
|
|
43
|
+
`previous_interaction_id` flows. There is no OpenAI-style cache-key field to
|
|
44
|
+
send, and Interactions does not accept the explicit `cached_content` resources
|
|
45
|
+
from the legacy `generateContent` API. Keep stable instructions, tools, and
|
|
46
|
+
history at the front of the request to improve prefix matches. Cache hits are
|
|
47
|
+
reported as `cacheReadTokens` from Gemini's `usage.total_cached_tokens`.
|
|
48
|
+
|
|
49
|
+
This provider currently uses the stateless Interactions shape. Its `store`
|
|
50
|
+
option controls provider-side interaction retention; it is not a prompt-cache
|
|
51
|
+
toggle.
|
|
52
|
+
|
|
53
|
+
## Connecting a compatible endpoint
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
import { envCredential } from '@alvin0/ai-agent-sdk-auth-node'
|
|
57
|
+
|
|
58
|
+
geminiPlugin({
|
|
59
|
+
id: 'ai-studio',
|
|
60
|
+
apiKey: envCredential('GEMINI_API_KEY'),
|
|
61
|
+
// path / query override the request path and add query-string parameters,
|
|
62
|
+
// the same way as the other two providers in this SDK.
|
|
63
|
+
})
|
|
64
|
+
```
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ComposableEmbeddingProviderPlugin, ComposableModelProviderPlugin, CredentialInput, ModelTarget } from "@alvin0/ai-agent-sdk-core/provider";
|
|
2
|
-
import { CredentialSource, EmbeddingCatalogModel, HttpModelAdapter, ProviderCatalogModel, ProviderRequestLogger } from "@alvin0/ai-agent-sdk-provider-http";
|
|
2
|
+
import { CredentialSource, EmbeddingCatalogModel, HeaderContext, HttpModelAdapter, ProviderCatalogModel, ProviderRequestLogger, ProviderResponseLogger, RequestContext } from "@alvin0/ai-agent-sdk-provider-http";
|
|
3
3
|
import { GeminiInteractionsDialect, geminiInteractionsProtocol } from "@alvin0/ai-agent-sdk-protocol-gemini-interactions";
|
|
4
4
|
import { ModelProviderPlugin, RetryPolicyConfig } from "@alvin0/ai-agent-sdk-core";
|
|
5
5
|
import { EmbeddingAdapter } from "@alvin0/ai-agent-sdk-core/embedding";
|
|
@@ -12,14 +12,41 @@ interface GeminiAdapterOptions {
|
|
|
12
12
|
apiKey: GeminiCredential;
|
|
13
13
|
/** Endpoint base; defaults to {@link GEMINI_BASE_URL}. */
|
|
14
14
|
baseUrl?: string;
|
|
15
|
+
/**
|
|
16
|
+
* Name this endpoint uses in diagnostics and error messages. Defaults to
|
|
17
|
+
* `'Gemini'`; set it to the real vendor name when pointing this provider at a
|
|
18
|
+
* compatible gateway, so a rejection names who rejected it.
|
|
19
|
+
*/
|
|
20
|
+
displayName?: string;
|
|
15
21
|
/** Extra endpoint headers, captured once per operation. Reserved names and collisions fail. */
|
|
16
|
-
headers?: Readonly<Record<string, string>> | (() => Readonly<Record<string, string>>);
|
|
22
|
+
headers?: Readonly<Record<string, string>> | ((ctx: HeaderContext) => Readonly<Record<string, string>>);
|
|
17
23
|
/** Permit cleartext HTTP explicitly for trusted local gateways. */
|
|
18
24
|
allowInsecureHttp?: boolean;
|
|
25
|
+
/** Override the request path this protocol would otherwise pick (e.g. a gateway deployment path). */
|
|
26
|
+
path?: string;
|
|
27
|
+
/** Extra query-string parameters, or a resolver for them. Never for secrets. */
|
|
28
|
+
query?: Readonly<Record<string, string>> | (() => Readonly<Record<string, string>>);
|
|
29
|
+
/**
|
|
30
|
+
* Fields to deep-merge into the serialized body. The caller's value always
|
|
31
|
+
* wins, even over a field the SDK set. A `null` value deletes the field.
|
|
32
|
+
*/
|
|
33
|
+
body?: Readonly<Record<string, unknown>>;
|
|
34
|
+
/** Last-resort hook with full authority over the body, run after `body` is merged in. */
|
|
35
|
+
transformRequest?: (body: unknown, ctx: RequestContext) => unknown;
|
|
19
36
|
/** Advisory catalog; built-in context policies do not advertise model availability. */
|
|
20
37
|
models?: readonly ProviderCatalogModel[];
|
|
21
|
-
/**
|
|
38
|
+
/**
|
|
39
|
+
* Whether Google may retain interactions. Defaults to false.
|
|
40
|
+
*
|
|
41
|
+
* This is not a prompt-cache switch: Interactions performs implicit prefix
|
|
42
|
+
* caching automatically for supported models and exposes no cache-key field.
|
|
43
|
+
*/
|
|
22
44
|
store?: boolean;
|
|
45
|
+
/**
|
|
46
|
+
* How the API key travels. Defaults to `'x-goog-api-key'`, this API's own
|
|
47
|
+
* header — but a gateway sitting in front of it may expect Bearer instead.
|
|
48
|
+
*/
|
|
49
|
+
authHeader?: 'x-goog-api-key' | 'bearer';
|
|
23
50
|
defaultMaxTokens?: number;
|
|
24
51
|
defaultContextWindow?: number;
|
|
25
52
|
streamIdleTimeoutMs?: number;
|
|
@@ -33,6 +60,7 @@ interface GeminiAdapterOptions {
|
|
|
33
60
|
requestLoggerTimeoutMs?: number;
|
|
34
61
|
retryPolicy?: RetryPolicyConfig;
|
|
35
62
|
requestLogger?: ProviderRequestLogger;
|
|
63
|
+
responseLogger?: ProviderResponseLogger;
|
|
36
64
|
fetch?: typeof globalThis.fetch;
|
|
37
65
|
}
|
|
38
66
|
declare function geminiAdapter(options: GeminiAdapterOptions): HttpModelAdapter;
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/adapter.ts","../src/embedding.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/adapter.ts","../src/embedding.ts"],"mappings":";;;;;;;cA2Ba;KAED,mBAAmB;UAEd;;EAEf,QAAQ;;EAER;;;;;;EAMA;;EAEA,UAAU,SAAS,4BAA4B,KAAK,kBAAkB,SAAS;;EAE/E;;EAEA;;EAEA,QAAQ,SAAS,iCAAiC,SAAS;;;;;EAK3D,OAAO,SAAS;;EAEhB,oBAAoB,eAAe,KAAK;;EAExC,kBAAkB;;;;;;;EAOlB;;;;;EAKA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,cAAc;EACd,gBAAgB;EAChB,iBAAiB;EACjB,eAAe,WAAW;;iBAGZ,cAAc,SAAS,uBAAuB;UAkB7C,4BAA4B;;WAElC;;UAGM,8BAA8B,KAAK;WACzC,wBAAwB;WACxB,QAAQ;WACR;WACA;;iBAGK,aACd,SAAS,wBACR;WAA2C;;iBAC9B,aAAa,SAAS,sBAAsB;;;;cC3C/C;;;;;;;;;;;cA6CA,kCAAkC;;UAe9B;;WAEN,QAAQ;;WAER,UAAU,SAAS,iCAAiC,SAAS;;WAE7D;;WAEA;;WAEA;;WAEA,wBAAwB;;WAExB,kBAAkB;;WAElB;WACA;WACA;WACA;WACA;WACA;WACA;WACA,cAAc;WACd,eAAe,WAAW;;;;;;;;;;iBAkPrB,uBACd,SAAS,iCACR;;;;;;;;;;iBAaa,sBACd,SAAS,iCACR;WAA+C"}
|
package/dist/index.js
CHANGED
|
@@ -1,48 +1,27 @@
|
|
|
1
1
|
import { defineEmbeddingProviderPlugin, defineModelProviderPlugin } from "@alvin0/ai-agent-sdk-core/provider";
|
|
2
|
-
import { captureTransportConnection, createHttpProvider,
|
|
2
|
+
import { captureTransportConnection, createHttpProvider, createRuntimeHttpProvider, embeddingCatalogModelInfo, endpointHeaders, resolvedEmbeddingCatalogModelInfo, transportJson } from "@alvin0/ai-agent-sdk-provider-http";
|
|
3
3
|
import { geminiInteractionsProtocol, geminiInteractionsProtocol as geminiInteractionsProtocol$1 } from "@alvin0/ai-agent-sdk-protocol-gemini-interactions";
|
|
4
4
|
import { assertUsableApiKey, resolveRetryPolicy } from "@alvin0/ai-agent-sdk-core";
|
|
5
5
|
import { EMBEDDING_ERROR_CODES, EmbeddingAdapter, EmbeddingError, defaultEmbeddingProfile, deriveSpaceId, resolveBatchLimits, validateBatchResult } from "@alvin0/ai-agent-sdk-core/embedding";
|
|
6
6
|
|
|
7
|
-
//#region src/context-policy.ts
|
|
8
|
-
const PRO = {
|
|
9
|
-
defaultContextWindow: 2e5,
|
|
10
|
-
standardPriceInputTokens: 2e5
|
|
11
|
-
};
|
|
12
|
-
function geminiContextPolicy(options) {
|
|
13
|
-
return createModelContextPolicy(options.baseUrl === void 0 || options.baseUrl.replace(/\/$/, "") === "https://generativelanguage.googleapis.com/v1beta" ? {
|
|
14
|
-
"gemini-3.1-pro-preview": PRO,
|
|
15
|
-
"gemini-3.1-pro-preview-customtools": PRO,
|
|
16
|
-
"gemini-2.5-pro": PRO,
|
|
17
|
-
"gemini-2.5-flash": { defaultContextWindow: 1e6 },
|
|
18
|
-
"gemini-3-flash-preview": { defaultContextWindow: 1e6 }
|
|
19
|
-
} : {}, options.models, options.defaultContextWindow);
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
//#endregion
|
|
23
7
|
//#region src/adapter.ts
|
|
24
8
|
/** Google Gemini API v1beta base. The protocol appends only `/interactions`. */
|
|
25
9
|
const GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
|
|
26
10
|
function geminiAdapter(options) {
|
|
27
11
|
return createHttpProvider({
|
|
28
|
-
displayName: "Gemini",
|
|
29
|
-
describeModel: geminiContextPolicy(options),
|
|
12
|
+
displayName: options.displayName ?? "Gemini",
|
|
30
13
|
protocol: geminiInteractionsProtocol$1,
|
|
31
14
|
baseUrl: options.baseUrl ?? "https://generativelanguage.googleapis.com/v1beta",
|
|
32
|
-
auth:
|
|
33
|
-
kind: "header",
|
|
34
|
-
name: "x-goog-api-key",
|
|
35
|
-
value: options.apiKey,
|
|
36
|
-
label: "the `apiKey` option"
|
|
37
|
-
},
|
|
15
|
+
auth: authOf(options),
|
|
38
16
|
dialect: dialectOf(options),
|
|
39
17
|
...options.models === void 0 ? {} : { models: options.models },
|
|
40
|
-
defaultMaxTokens: options.defaultMaxTokens
|
|
41
|
-
defaultContextWindow: options.defaultContextWindow
|
|
18
|
+
...options.defaultMaxTokens === void 0 ? {} : { defaultMaxTokens: options.defaultMaxTokens },
|
|
19
|
+
...options.defaultContextWindow === void 0 ? {} : { defaultContextWindow: options.defaultContextWindow },
|
|
42
20
|
...options.streamIdleTimeoutMs === void 0 ? {} : { streamIdleTimeoutMs: options.streamIdleTimeoutMs },
|
|
43
21
|
...transportLimits(options),
|
|
44
22
|
...options.retryPolicy === void 0 ? {} : { retryPolicy: options.retryPolicy },
|
|
45
|
-
...options.requestLogger === void 0 ? {} : { requestLogger: options.requestLogger }
|
|
23
|
+
...options.requestLogger === void 0 ? {} : { requestLogger: options.requestLogger },
|
|
24
|
+
...options.responseLogger === void 0 ? {} : { responseLogger: options.responseLogger }
|
|
46
25
|
});
|
|
47
26
|
}
|
|
48
27
|
function geminiPlugin(options) {
|
|
@@ -52,7 +31,7 @@ function geminiPlugin(options) {
|
|
|
52
31
|
return defineModelProviderPlugin({
|
|
53
32
|
id,
|
|
54
33
|
family: "gemini",
|
|
55
|
-
displayName: "Gemini",
|
|
34
|
+
displayName: options.displayName ?? "Gemini",
|
|
56
35
|
routes,
|
|
57
36
|
...runtimeDefaultModel(options.defaultModel, routes),
|
|
58
37
|
setup(registrar) {
|
|
@@ -68,7 +47,7 @@ function legacyGeminiPlugin(options) {
|
|
|
68
47
|
const adapter = geminiAdapter(options);
|
|
69
48
|
return Object.freeze({
|
|
70
49
|
id: "gemini",
|
|
71
|
-
displayName: "Gemini",
|
|
50
|
+
displayName: options.displayName ?? "Gemini",
|
|
72
51
|
setup(registrar) {
|
|
73
52
|
registrar.registerAdapter(routes, adapter);
|
|
74
53
|
}
|
|
@@ -76,29 +55,47 @@ function legacyGeminiPlugin(options) {
|
|
|
76
55
|
}
|
|
77
56
|
function createRuntimeGeminiAdapter(options) {
|
|
78
57
|
return createRuntimeHttpProvider({
|
|
79
|
-
|
|
80
|
-
displayName: "Gemini",
|
|
58
|
+
displayName: options.displayName ?? "Gemini",
|
|
81
59
|
protocol: geminiInteractionsProtocol$1,
|
|
82
60
|
baseUrl: options.baseUrl ?? "https://generativelanguage.googleapis.com/v1beta",
|
|
83
|
-
auth:
|
|
84
|
-
kind: "header",
|
|
85
|
-
name: "x-goog-api-key",
|
|
86
|
-
value: options.apiKey,
|
|
87
|
-
label: "the `apiKey` option"
|
|
88
|
-
},
|
|
61
|
+
auth: authOf(options),
|
|
89
62
|
dialect: dialectOf(options),
|
|
90
63
|
...options.models === void 0 ? {} : { models: options.models },
|
|
91
|
-
defaultMaxTokens: options.defaultMaxTokens
|
|
92
|
-
defaultContextWindow: options.defaultContextWindow
|
|
64
|
+
...options.defaultMaxTokens === void 0 ? {} : { defaultMaxTokens: options.defaultMaxTokens },
|
|
65
|
+
...options.defaultContextWindow === void 0 ? {} : { defaultContextWindow: options.defaultContextWindow },
|
|
93
66
|
...options.streamIdleTimeoutMs === void 0 ? {} : { streamIdleTimeoutMs: options.streamIdleTimeoutMs },
|
|
94
67
|
...transportLimits(options),
|
|
95
68
|
...options.retryPolicy === void 0 ? {} : { retryPolicy: options.retryPolicy },
|
|
96
|
-
...options.requestLogger === void 0 ? {} : { requestLogger: options.requestLogger }
|
|
69
|
+
...options.requestLogger === void 0 ? {} : { requestLogger: options.requestLogger },
|
|
70
|
+
...options.responseLogger === void 0 ? {} : { responseLogger: options.responseLogger }
|
|
97
71
|
});
|
|
98
72
|
}
|
|
99
73
|
function dialectOf(options) {
|
|
100
74
|
return options.store === void 0 ? {} : { store: options.store };
|
|
101
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* This API's own header is `x-goog-api-key`, unlike most others' `authorization:
|
|
78
|
+
* Bearer` — but a gateway sitting in front of it may expect Bearer instead.
|
|
79
|
+
*/
|
|
80
|
+
/**
|
|
81
|
+
* Generic over the credential type on purpose: the two call sites accept
|
|
82
|
+
* DIFFERENT ones — the legacy adapter takes {@link GeminiCredential}
|
|
83
|
+
* (`provider-http`'s string-or-resolver), the composable one takes core's
|
|
84
|
+
* broader `CredentialInput`. A non-generic parameter union would widen
|
|
85
|
+
* `apiKey` to the union of both and fit neither target scheme.
|
|
86
|
+
*/
|
|
87
|
+
function authOf(options) {
|
|
88
|
+
return options.authHeader === "bearer" ? {
|
|
89
|
+
kind: "bearer",
|
|
90
|
+
token: options.apiKey,
|
|
91
|
+
label: "the `apiKey` option"
|
|
92
|
+
} : {
|
|
93
|
+
kind: "header",
|
|
94
|
+
name: "x-goog-api-key",
|
|
95
|
+
value: options.apiKey,
|
|
96
|
+
label: "the `apiKey` option"
|
|
97
|
+
};
|
|
98
|
+
}
|
|
102
99
|
function usesRuntimeComposition(options) {
|
|
103
100
|
if ("id" in options || "defaultModel" in options) return true;
|
|
104
101
|
if (typeof options.apiKey === "object" && options.apiKey !== null) return true;
|
|
@@ -118,6 +115,10 @@ function transportLimits(options) {
|
|
|
118
115
|
return {
|
|
119
116
|
...options.allowInsecureHttp === void 0 ? {} : { allowInsecureHttp: options.allowInsecureHttp },
|
|
120
117
|
headers: endpointHeaders(options.headers),
|
|
118
|
+
...options.path === void 0 ? {} : { path: options.path },
|
|
119
|
+
...options.query === void 0 ? {} : { query: options.query },
|
|
120
|
+
...options.body === void 0 ? {} : { body: options.body },
|
|
121
|
+
...options.transformRequest === void 0 ? {} : { transformRequest: options.transformRequest },
|
|
121
122
|
...options.requestTimeoutMs === void 0 ? {} : { requestTimeoutMs: options.requestTimeoutMs },
|
|
122
123
|
...options.maxRequestBytes === void 0 ? {} : { maxRequestBytes: options.maxRequestBytes },
|
|
123
124
|
...options.maxResponseBytes === void 0 ? {} : { maxResponseBytes: options.maxResponseBytes },
|
|
@@ -282,7 +283,7 @@ var GeminiEmbeddingAdapter = class extends EmbeddingAdapter {
|
|
|
282
283
|
async prepareEmbeddingCall(provider, model, options, signal, context) {
|
|
283
284
|
const resolved = await this.resolveEmbeddingModel(provider, model, signal);
|
|
284
285
|
const profile = this.embeddingProfile(resolved, options);
|
|
285
|
-
const connection = await this.#connect(signal, context);
|
|
286
|
+
const connection = await this.#connect(provider, signal, context);
|
|
286
287
|
return Object.freeze({
|
|
287
288
|
model: resolved,
|
|
288
289
|
profile,
|
|
@@ -301,13 +302,17 @@ var GeminiEmbeddingAdapter = class extends EmbeddingAdapter {
|
|
|
301
302
|
async embedBatch(batch, context) {
|
|
302
303
|
const resolved = await this.resolveEmbeddingModel(batch.provider, batch.model, batch.signal);
|
|
303
304
|
const profile = this.embeddingProfile(resolved, { ...batch.dimensions === void 0 ? {} : { dimensions: batch.dimensions } });
|
|
304
|
-
const connection = await this.#connect(batch.signal, context);
|
|
305
|
+
const connection = await this.#connect(batch.provider, batch.signal, context);
|
|
305
306
|
return await this.#dispatch(connection, resolved, profile, batch, context);
|
|
306
307
|
}
|
|
307
308
|
/** Resolve the credential and bounds into one frozen snapshot. */
|
|
308
|
-
async #connect(signal, context) {
|
|
309
|
+
async #connect(provider, signal, context) {
|
|
309
310
|
const options = this.#options;
|
|
310
|
-
const extraHeaders = this.#headers(
|
|
311
|
+
const extraHeaders = this.#headers({
|
|
312
|
+
provider,
|
|
313
|
+
...context?.agentId === void 0 ? {} : { agentId: context.agentId },
|
|
314
|
+
...signal === void 0 ? {} : { signal }
|
|
315
|
+
});
|
|
311
316
|
const apiKey = assertUsableApiKey(await resolveCredential(options.apiKey, signal, context), DISPLAY_NAME, "the `apiKey` option");
|
|
312
317
|
return captureTransportConnection({
|
|
313
318
|
baseUrl: options.baseUrl ?? "https://generativelanguage.googleapis.com/v1beta",
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["geminiInteractionsProtocol"],"sources":["../src/context-policy.ts","../src/adapter.ts","../src/embedding.ts"],"sourcesContent":["import { createModelContextPolicy } from '@alvin0/ai-agent-sdk-provider-http'\nimport type { ModelContextPolicyOptions } from '@alvin0/ai-agent-sdk-provider-http'\n\n// Verified 2026-09-13: https://ai.google.dev/gemini-api/docs/pricing\n// Google publishes separate input/output limits; do not invent a combined ceiling.\nconst PRO = { defaultContextWindow: 200_000, standardPriceInputTokens: 200_000 }\nexport function geminiContextPolicy(options: ModelContextPolicyOptions) {\n return createModelContextPolicy(\n options.baseUrl === undefined || options.baseUrl.replace(/\\/$/, '') === 'https://generativelanguage.googleapis.com/v1beta'\n ? {\n 'gemini-3.1-pro-preview': PRO, 'gemini-3.1-pro-preview-customtools': PRO, 'gemini-2.5-pro': PRO,\n 'gemini-2.5-flash': { defaultContextWindow: 1_000_000 },\n 'gemini-3-flash-preview': { defaultContextWindow: 1_000_000 },\n }\n : {}, options.models, options.defaultContextWindow)\n}\n","import type { ModelProviderPlugin, ModelProviderRegistrar, RetryPolicyConfig } from '@alvin0/ai-agent-sdk-core'\nimport {\n defineModelProviderPlugin,\n type ComposableModelProviderPlugin,\n type CredentialInput,\n type ModelTarget,\n} from '@alvin0/ai-agent-sdk-core/provider'\nimport type {\n HttpModelAdapter,\n ProviderCatalogModel,\n ProviderRequestLogger,\n} from '@alvin0/ai-agent-sdk-provider-http'\nimport {\n createHttpProvider,\n endpointHeaders,\n createRuntimeHttpProvider,\n type CredentialSource,\n} from '@alvin0/ai-agent-sdk-provider-http'\nimport {\n geminiInteractionsProtocol,\n type GeminiInteractionsDialect,\n} from '@alvin0/ai-agent-sdk-protocol-gemini-interactions'\nimport { geminiContextPolicy } from './context-policy.ts'\n\n/** Google Gemini API v1beta base. The protocol appends only `/interactions`. */\nexport const GEMINI_BASE_URL = 'https://generativelanguage.googleapis.com/v1beta'\n\nexport type GeminiCredential = CredentialSource\n\nexport interface GeminiAdapterOptions {\n /** Injected API key or resolver. Universal packages never read environment variables. */\n apiKey: GeminiCredential\n /** Endpoint base; defaults to {@link GEMINI_BASE_URL}. */\n baseUrl?: string\n /** Extra endpoint headers, captured once per operation. Reserved names and collisions fail. */\n headers?: Readonly<Record<string, string>> | (() => Readonly<Record<string, string>>)\n /** Permit cleartext HTTP explicitly for trusted local gateways. */\n allowInsecureHttp?: boolean\n /** Advisory catalog; built-in context policies do not advertise model availability. */\n models?: readonly ProviderCatalogModel[]\n /** Whether Google may retain interactions. Defaults to false. */\n store?: boolean\n defaultMaxTokens?: number\n defaultContextWindow?: number\n streamIdleTimeoutMs?: number\n requestTimeoutMs?: number\n maxRequestBytes?: number\n maxResponseBytes?: number\n maxResponseChunks?: number\n maxSseEvents?: number\n maxSseEventChars?: number\n maxErrorBodyBytes?: number\n requestLoggerTimeoutMs?: number\n retryPolicy?: RetryPolicyConfig\n requestLogger?: ProviderRequestLogger\n fetch?: typeof globalThis.fetch\n}\n\nexport function geminiAdapter(options: GeminiAdapterOptions): HttpModelAdapter {\n return createHttpProvider({\n displayName: 'Gemini',\n describeModel: geminiContextPolicy(options),\n protocol: geminiInteractionsProtocol,\n baseUrl: options.baseUrl ?? GEMINI_BASE_URL,\n auth: {\n kind: 'header', name: 'x-goog-api-key', value: options.apiKey,\n label: 'the `apiKey` option',\n },\n dialect: dialectOf(options),\n ...(options.models === undefined ? {} : { models: options.models }),\n defaultMaxTokens: options.defaultMaxTokens ?? 8_192,\n defaultContextWindow: options.defaultContextWindow ?? 200_000,\n ...(options.streamIdleTimeoutMs === undefined ? {} : { streamIdleTimeoutMs: options.streamIdleTimeoutMs }),\n ...transportLimits(options),\n ...(options.retryPolicy === undefined ? {} : { retryPolicy: options.retryPolicy }),\n ...(options.requestLogger === undefined ? {} : { requestLogger: options.requestLogger }),\n })\n}\n\nexport interface GeminiPluginOptions extends GeminiAdapterOptions {\n /** Registry routes installed by the plugin. Defaults to `['gemini']`. */\n readonly routes?: readonly string[]\n}\n\nexport interface GeminiProviderOptions extends Omit<GeminiAdapterOptions, 'apiKey'> {\n readonly defaultModel?: string | ModelTarget\n readonly apiKey: CredentialInput\n readonly id?: string\n readonly routes?: readonly string[]\n}\n\nexport function geminiPlugin(\n options: GeminiProviderOptions,\n): ComposableModelProviderPlugin & { readonly family: 'gemini' }\nexport function geminiPlugin(options: GeminiPluginOptions): ModelProviderPlugin\nexport function geminiPlugin(\n options: GeminiProviderOptions | GeminiPluginOptions,\n): ModelProviderPlugin | (ComposableModelProviderPlugin & { readonly family: 'gemini' }) {\n if (!usesRuntimeComposition(options)) return legacyGeminiPlugin(options)\n const id = options.id ?? 'gemini'\n const routes = Object.freeze([...(options.routes ?? [id])])\n return defineModelProviderPlugin({\n id,\n family: 'gemini',\n displayName: 'Gemini',\n routes,\n ...runtimeDefaultModel(options.defaultModel, routes),\n setup(registrar) {\n const remove = registrar.registerAdapter(createRuntimeGeminiAdapter(options))\n return () => { remove(); return undefined }\n },\n }) as ComposableModelProviderPlugin & { readonly family: 'gemini' }\n}\n\nfunction legacyGeminiPlugin(options: GeminiPluginOptions): ModelProviderPlugin {\n const routes = Object.freeze([...(options.routes ?? ['gemini'])])\n const adapter = geminiAdapter(options)\n return Object.freeze({\n id: 'gemini',\n displayName: 'Gemini',\n setup(registrar: ModelProviderRegistrar) {\n registrar.registerAdapter(routes, adapter)\n },\n })\n}\n\nfunction createRuntimeGeminiAdapter(options: GeminiProviderOptions): HttpModelAdapter {\n return createRuntimeHttpProvider({\n describeModel: geminiContextPolicy(options),\n displayName: 'Gemini',\n protocol: geminiInteractionsProtocol,\n baseUrl: options.baseUrl ?? GEMINI_BASE_URL,\n auth: {\n kind: 'header', name: 'x-goog-api-key', value: options.apiKey,\n label: 'the `apiKey` option',\n },\n dialect: dialectOf(options),\n ...(options.models === undefined ? {} : { models: options.models }),\n defaultMaxTokens: options.defaultMaxTokens ?? 8_192,\n defaultContextWindow: options.defaultContextWindow ?? 200_000,\n ...(options.streamIdleTimeoutMs === undefined ? {} : { streamIdleTimeoutMs: options.streamIdleTimeoutMs }),\n ...transportLimits(options),\n ...(options.retryPolicy === undefined ? {} : { retryPolicy: options.retryPolicy }),\n ...(options.requestLogger === undefined ? {} : { requestLogger: options.requestLogger }),\n })\n}\n\nfunction dialectOf(options: Pick<GeminiAdapterOptions, 'store'>): Partial<GeminiInteractionsDialect> {\n return options.store === undefined ? {} : { store: options.store }\n}\n\nfunction usesRuntimeComposition(\n options: GeminiProviderOptions | GeminiPluginOptions,\n): options is GeminiProviderOptions {\n if ('id' in options || 'defaultModel' in options) return true\n if (typeof options.apiKey === 'object' && options.apiKey !== null) return true\n if (typeof options.apiKey !== 'function') return true\n // Node's envCredential keeps a backwards-compatible callable surface while\n // also carrying the versioned CredentialSource marker used by composition.\n return 'kind' in options.apiKey && options.apiKey.kind === 'credential-source'\n}\n\nfunction runtimeDefaultModel(\n value: string | ModelTarget | undefined,\n routes: readonly string[],\n): { readonly defaultModel?: ModelTarget } {\n if (value === undefined) return {}\n if (typeof value !== 'string') return { defaultModel: value }\n if (routes.length !== 1) throw new TypeError('A string defaultModel requires exactly one Gemini route')\n return { defaultModel: Object.freeze({ provider: routes[0]!, id: value }) }\n}\n\nfunction transportLimits(options: GeminiAdapterOptions | GeminiProviderOptions) {\n return {\n ...(options.allowInsecureHttp === undefined ? {} : { allowInsecureHttp: options.allowInsecureHttp }),\n headers: endpointHeaders(options.headers),\n ...(options.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: options.requestTimeoutMs }),\n ...(options.maxRequestBytes === undefined ? {} : { maxRequestBytes: options.maxRequestBytes }),\n ...(options.maxResponseBytes === undefined ? {} : { maxResponseBytes: options.maxResponseBytes }),\n ...(options.maxResponseChunks === undefined ? {} : { maxResponseChunks: options.maxResponseChunks }),\n ...(options.maxSseEvents === undefined ? {} : { maxSseEvents: options.maxSseEvents }),\n ...(options.maxSseEventChars === undefined ? {} : { maxSseEventChars: options.maxSseEventChars }),\n ...(options.maxErrorBodyBytes === undefined ? {} : { maxErrorBodyBytes: options.maxErrorBodyBytes }),\n ...(options.requestLoggerTimeoutMs === undefined ? {} : { requestLoggerTimeoutMs: options.requestLoggerTimeoutMs }),\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n }\n}\n","/**\n * `Gemini_Embedding_Adapter`: Gemini's `batchEmbedContents` endpoint expressed as\n * an `Embedding_Adapter`.\n *\n * Deliberately separate from `./adapter.ts`: nothing here imports\n * `geminiInteractionsProtocol`, and nothing there imports this module. Generation\n * and embedding share the same credential shape and the same HTTP transport, and\n * that is all they share — a request vocabulary in common would be the conflation\n * Requirement 14.2 rules out.\n *\n * Three Gemini specifics shape this file, and each one is stated rather than\n * inferred:\n *\n * - **Purpose is a wire parameter.** `taskType` exists, so `purpose` translates\n * into it — but only when the route DECLARES that mechanism. A route that\n * declares nothing gets the text sent verbatim and no invented parameter\n * (Requirement 7.3).\n * - **A narrower vector is a model mechanism plus a recorded step.**\n * `outputDimensionality` asks the model for a narrower vector; Gemini\n * documents that a narrower vector is no longer unit-length, so the profile\n * declares `postProcessing: { kind: 'l2-renormalize', revision: '1' }` and this\n * adapter performs exactly that step. Nothing here slices or pads a vector\n * (Requirement 9.8).\n * - **Mapping is positional.** `batchEmbedContents` returns\n * `{ embeddings: [{ values }] }` with no index, so the index is assigned by\n * this adapter from request order, and the count is checked rather than\n * assumed.\n *\n * @module ai-agent-sdk/providers/gemini/embedding\n */\n\nimport {\n assertUsableApiKey,\n resolveRetryPolicy,\n type ModelInvocationContext,\n type ProviderInfo,\n type ResolvedRetryPolicy,\n type RetryPolicyConfig,\n type SdkLogger,\n} from '@alvin0/ai-agent-sdk-core'\nimport {\n EMBEDDING_ERROR_CODES,\n EmbeddingAdapter,\n EmbeddingError,\n defaultEmbeddingProfile,\n deriveSpaceId,\n resolveBatchLimits,\n validateBatchResult,\n type EmbeddingBatchRequest,\n type EmbeddingBatchResult,\n type EmbeddingModelInfo,\n type EmbeddingPostProcessing,\n type EmbeddingProfile,\n type EmbeddingProfileInput,\n type EmbeddingPurpose,\n type EmbeddingVector,\n type PrepareEmbeddingOptions,\n type PreparedEmbeddingCall,\n type ResolvedEmbeddingModelInfo,\n} from '@alvin0/ai-agent-sdk-core/embedding'\nimport {\n defineEmbeddingProviderPlugin,\n type ComposableEmbeddingProviderPlugin,\n type CredentialInput,\n type ModelTarget,\n} from '@alvin0/ai-agent-sdk-core/provider'\nimport {\n captureTransportConnection,\n endpointHeaders,\n embeddingCatalogModelInfo,\n resolvedEmbeddingCatalogModelInfo,\n transportJson,\n type EmbeddingCatalogModel,\n type EmbeddingHttpConnection,\n} from '@alvin0/ai-agent-sdk-provider-http'\n\n/** Google Generative Language API v1beta base; the adapter appends the model path. */\nexport const GEMINI_EMBEDDING_BASE_URL = 'https://generativelanguage.googleapis.com/v1beta'\n\n/** Name used in every diagnostic this module raises. */\nconst DISPLAY_NAME = 'Gemini'\n\n/** Header layer the JSON pipeline owns for this route. */\nconst TRANSPORT_HEADERS = Object.freeze({\n 'content-type': 'application/json',\n accept: 'application/json',\n})\n\n/** Revision of the `l2-renormalize` step this adapter performs. */\nconst POST_PROCESSING_REVISION = '1'\n\n/** Applied when neither the caller nor the catalog says otherwise. */\nconst DEFAULT_RECIPE_REVISION = '1'\n\n/** The one mapping from this SDK's purpose vocabulary to Gemini's `taskType`. */\nconst TASK_TYPES: Readonly<Record<EmbeddingPurpose, string>> = Object.freeze({\n 'retrieval-query': 'RETRIEVAL_QUERY',\n 'retrieval-document': 'RETRIEVAL_DOCUMENT',\n})\n\nconst NEVER_ABORTED_SIGNAL = new AbortController().signal\n\nconst NULL_LOGGER: SdkLogger = Object.freeze({\n child: () => NULL_LOGGER,\n trace: () => undefined,\n debug: () => undefined,\n info: () => undefined,\n warn: () => undefined,\n error: () => undefined,\n fatal: () => undefined,\n})\n\n/**\n * The Gemini embedding generations this package declares.\n *\n * Unlike the generation catalog, an embedding catalog entry cannot be omitted\n * entirely: `compatibilityIdentity` is a claim about an embedding space that only\n * the route can make, and Requirement 14.6 puts that claim on this adapter. The\n * identity names the GENERATION, so `gemini-embedding-001` and a future\n * `gemini-embedding-2` are detected as incompatible even at equal width. Pass\n * `models` to override or extend this list.\n */\nexport const GEMINI_EMBEDDING_MODELS: readonly EmbeddingCatalogModel[] = Object.freeze([\n Object.freeze({\n id: 'gemini-embedding-001',\n name: 'Gemini Embedding 001',\n description: 'Gemini text embedding with selectable output dimensionality.',\n dimensions: Object.freeze([3072, 1536, 768]),\n defaultDimensions: 3072,\n maxInputTokens: 2048,\n maxBatchItems: 100,\n purposeHandling: Object.freeze({ kind: 'wire-parameter' as const, parameter: 'taskType' }),\n compatibilityIdentity: 'google:gemini-embedding-001',\n }),\n])\n\n/** Configuration for {@link geminiEmbeddingAdapter} and {@link geminiEmbeddingPlugin}. */\nexport interface GeminiEmbeddingProviderOptions {\n /** Injected key or credential source; universal packages never read the environment. */\n readonly apiKey: CredentialInput\n /** Extra endpoint headers, captured once per logical call; reserved names fail. */\n readonly headers?: Readonly<Record<string, string>> | (() => Readonly<Record<string, string>>)\n /** Endpoint base; defaults to {@link GEMINI_EMBEDDING_BASE_URL}. */\n readonly baseUrl?: string\n /** Plugin id; defaults to `'gemini-embedding'`. */\n readonly id?: string\n /** Routes the plugin claims; defaults to `[id]`. */\n readonly routes?: readonly string[]\n /** Default model for the claimed route. */\n readonly defaultModel?: string | ModelTarget\n /** Declared embedding catalog; defaults to {@link GEMINI_EMBEDDING_MODELS}. */\n readonly models?: readonly EmbeddingCatalogModel[]\n /** Permit cleartext HTTP explicitly, for a trusted local endpoint only. */\n readonly allowInsecureHttp?: boolean\n readonly requestTimeoutMs?: number\n readonly maxRequestBytes?: number\n readonly maxResponseBytes?: number\n readonly maxResponseChunks?: number\n readonly maxErrorBodyBytes?: number\n readonly requestLoggerTimeoutMs?: number\n readonly retryPolicy?: RetryPolicyConfig\n readonly fetch?: typeof globalThis.fetch\n}\n\n/** What the JSON pipeline hands back: the parsed body plus its correlation id. */\ninterface GeminiEmbedResponse {\n readonly payload: unknown\n readonly providerRequestId?: string\n}\n\n/** One request element of Gemini's `batchEmbedContents` body. */\ninterface GeminiEmbedRequest {\n readonly model: string\n readonly content: { readonly parts: readonly { readonly text: string }[] }\n readonly outputDimensionality?: number\n readonly [parameter: string]: unknown\n}\n\n/**\n * The Gemini `batchEmbedContents` adapter.\n *\n * Every metadata method takes the route key, so one instance serves every route\n * the plugin claims. Connection facts are captured once per operation in\n * {@link prepareEmbeddingCall}, which is what keeps a credential from travelling\n * to a URL from a different configuration generation.\n */\nclass GeminiEmbeddingAdapter extends EmbeddingAdapter {\n readonly #options: GeminiEmbeddingProviderOptions\n readonly #headers: () => Readonly<Record<string, string>>\n readonly #models: readonly EmbeddingCatalogModel[]\n readonly #retryPolicy: ResolvedRetryPolicy\n\n constructor(options: GeminiEmbeddingProviderOptions) {\n super()\n this.#options = Object.freeze({ ...options })\n this.#headers = endpointHeaders(options.headers)\n this.#models = Object.freeze([...(options.models ?? GEMINI_EMBEDDING_MODELS)])\n this.#retryPolicy = resolveRetryPolicy(options.retryPolicy, 'retryPolicy')\n }\n\n override providerInfo(provider: string): ProviderInfo {\n return { id: provider, name: DISPLAY_NAME }\n }\n\n override providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined {\n return this.#retryPolicy\n }\n\n override listEmbeddingModels(\n provider: string,\n _signal?: AbortSignal,\n ): Promise<readonly EmbeddingModelInfo[]> {\n return Promise.resolve(Object.freeze(\n this.#models.map(model => embeddingCatalogModelInfo(provider, model)),\n ))\n }\n\n override resolveEmbeddingModel(\n provider: string,\n model: string,\n _signal?: AbortSignal,\n ): Promise<ResolvedEmbeddingModelInfo> {\n return Promise.resolve(resolvedEmbeddingCatalogModelInfo(provider, model, this.#models))\n }\n\n /**\n * Declare the real Gemini profile instead of accepting the generic default.\n *\n * Two statements the default cannot make: the compatibility identity is the\n * route's declaration about a GENERATION, and asking for a narrower vector adds\n * a recorded `l2-renormalize` step which this adapter then actually performs.\n */\n override embeddingProfile(\n model: ResolvedEmbeddingModelInfo,\n request: EmbeddingProfileInput,\n ): EmbeddingProfile {\n const base = defaultEmbeddingProfile(model, request)\n const postProcessing = postProcessingFor(model, base.dimensions)\n return Object.freeze({\n ...base,\n compatibilityIdentity: model.compatibilityIdentity.state === 'supported'\n ? model.compatibilityIdentity.value\n : `google:${model.id}`,\n // Truthful either way: `unit-l2` only where this adapter normalizes, and\n // otherwise whatever the route declared — never inferred from the width.\n normalization: postProcessing !== undefined\n ? 'unit-l2'\n : model.normalization.state === 'supported'\n ? model.normalization.value\n : 'unknown',\n documentRecipeRevision: request.documentRecipeRevision ?? DEFAULT_RECIPE_REVISION,\n queryRecipeRevision: request.queryRecipeRevision ?? DEFAULT_RECIPE_REVISION,\n ...(postProcessing === undefined ? {} : { postProcessing }),\n })\n }\n\n /**\n * Capture the endpoint, the credential and the catalog together, once.\n *\n * The connection is read here and never re-read per batch, so every batch of\n * one `Logical_Call` goes out through the same generation of configuration\n * that its dimensions were checked against.\n */\n override async prepareEmbeddingCall(\n provider: string,\n model: string,\n options: PrepareEmbeddingOptions,\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n ): Promise<PreparedEmbeddingCall> {\n const resolved = await this.resolveEmbeddingModel(provider, model, signal)\n const profile = this.embeddingProfile(resolved, options)\n const connection = await this.#connect(signal, context)\n return Object.freeze({\n model: resolved,\n profile,\n spaceId: deriveSpaceId(profile),\n limits: resolveBatchLimits(resolved, options.limits),\n embedBatch: (batch: EmbeddingBatchRequest, invocation = context) =>\n this.#dispatch(connection, resolved, profile, batch, invocation),\n })\n }\n\n /**\n * Perform exactly one `batchEmbedContents` request.\n *\n * Usable directly, in which case the catalog and connection are resolved for\n * this batch alone; `prepareEmbeddingCall` is the path that binds one snapshot\n * to a whole logical call.\n */\n override async embedBatch(\n batch: EmbeddingBatchRequest,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingBatchResult> {\n const resolved = await this.resolveEmbeddingModel(batch.provider, batch.model, batch.signal)\n const profile = this.embeddingProfile(resolved, {\n ...(batch.dimensions === undefined ? {} : { dimensions: batch.dimensions }),\n })\n const connection = await this.#connect(batch.signal, context)\n return await this.#dispatch(connection, resolved, profile, batch, context)\n }\n\n /** Resolve the credential and bounds into one frozen snapshot. */\n async #connect(\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingHttpConnection> {\n const options = this.#options\n const extraHeaders = this.#headers()\n const apiKey = assertUsableApiKey(\n await resolveCredential(options.apiKey, signal, context),\n DISPLAY_NAME,\n 'the `apiKey` option',\n )\n // Attribution headers are merged by the transport, so no embedding adapter\n // can forget them (Requirement 14.7).\n return captureTransportConnection<EmbeddingHttpConnection>({\n baseUrl: options.baseUrl ?? GEMINI_EMBEDDING_BASE_URL,\n headers: Object.freeze({ ...extraHeaders, 'x-goog-api-key': apiKey }),\n models: this.#models,\n retryPolicy: this.#retryPolicy,\n ...(options.allowInsecureHttp === undefined\n ? {}\n : { allowInsecureHttp: options.allowInsecureHttp }),\n ...(options.requestTimeoutMs === undefined\n ? {}\n : { requestTimeoutMs: options.requestTimeoutMs }),\n ...(options.maxRequestBytes === undefined ? {} : { maxRequestBytes: options.maxRequestBytes }),\n ...(options.maxResponseBytes === undefined\n ? {}\n : { maxResponseBytes: options.maxResponseBytes }),\n ...(options.maxResponseChunks === undefined\n ? {}\n : { maxResponseChunks: options.maxResponseChunks }),\n ...(options.maxErrorBodyBytes === undefined\n ? {}\n : { maxErrorBodyBytes: options.maxErrorBodyBytes }),\n ...(options.requestLoggerTimeoutMs === undefined\n ? {}\n : { requestLoggerTimeoutMs: options.requestLoggerTimeoutMs }),\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n }, TRANSPORT_HEADERS)\n }\n\n /** One `Provider_Attempt`: build the body, send it, decode the response. */\n async #dispatch(\n connection: EmbeddingHttpConnection,\n model: ResolvedEmbeddingModelInfo,\n profile: EmbeddingProfile,\n batch: EmbeddingBatchRequest,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingBatchResult> {\n if (batch.truncation === 'allow') {\n throw new EmbeddingError(\n 'Gemini batchEmbedContents exposes no truncation parameter',\n EMBEDDING_ERROR_CODES.TRUNCATION_UNSUPPORTED,\n { provider: batch.provider, model: batch.model },\n )\n }\n const modelId = bareModelId(batch.model)\n const body = { requests: batch.items.map(item => embedRequest(item, model, batch, modelId)) }\n const encoded = JSON.stringify(body)\n // The transport chain owns transport failures and normalizes anything thrown\n // inside `decode` into a ModelError, which would flatten this adapter's\n // embedding codes. So `decode` only extracts the payload, and contract\n // validation runs here, where an EmbeddingError reaches the caller intact.\n const received = await transportJson({\n connection,\n displayName: DISPLAY_NAME,\n provider: batch.provider,\n model: batch.model,\n path: `/models/${encodeURIComponent(modelId)}:batchEmbedContents`,\n accept: 'application/json',\n body: {\n value: body,\n encoded,\n bytes: new TextEncoder().encode(encoded).length,\n },\n ...(batch.signal === undefined ? {} : { signal: batch.signal }),\n ...(context === undefined ? {} : { context }),\n }, (session, payload) => Object.freeze({\n payload,\n ...(session.providerRequestId === undefined\n ? {}\n : { providerRequestId: session.providerRequestId }),\n }))\n return decodeBatch(batch, profile, received)\n }\n}\n\n/**\n * Create the Gemini embedding adapter.\n *\n * No I/O happens here: the credential is resolved per operation, not at\n * construction.\n * @param options - route configuration.\n * @returns an adapter registrable under any number of routes.\n */\nexport function geminiEmbeddingAdapter(\n options: GeminiEmbeddingProviderOptions,\n): EmbeddingAdapter {\n return new GeminiEmbeddingAdapter(options)\n}\n\n/**\n * Create the Gemini `Embedding_Provider_Plugin`.\n *\n * Its `kind` is `'embedding-provider-plugin'`, so a generation host never\n * mistakes it for {@link geminiPlugin} and neither plugin needs a version bump\n * because of the other (Requirement 11.1).\n * @param options - route configuration.\n * @returns an inert plugin; registration happens during runtime activation.\n */\nexport function geminiEmbeddingPlugin(\n options: GeminiEmbeddingProviderOptions,\n): ComposableEmbeddingProviderPlugin & { readonly family: 'gemini' } {\n const id = options.id ?? 'gemini-embedding'\n const routes = Object.freeze([...(options.routes ?? [id])])\n const adapter = geminiEmbeddingAdapter(options)\n return defineEmbeddingProviderPlugin({\n id,\n family: 'gemini',\n displayName: DISPLAY_NAME,\n routes,\n ...defaultModelTarget(options.defaultModel, routes),\n setup(registrar) {\n const remove = registrar.registerEmbeddingAdapter(adapter)\n return () => {\n remove()\n return undefined\n }\n },\n }) as ComposableEmbeddingProviderPlugin & { readonly family: 'gemini' }\n}\n\n/** Resolve a literal key or a credential source, without caching the secret. */\nasync function resolveCredential(\n apiKey: CredentialInput,\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n): Promise<string> {\n if (typeof apiKey === 'string') return apiKey\n return await apiKey.resolve({\n signal: signal ?? NEVER_ABORTED_SIGNAL,\n logger: context?.logger ?? NULL_LOGGER,\n })\n}\n\n/** Accept both `gemini-embedding-001` and the `models/`-prefixed resource name. */\nfunction bareModelId(model: string): string {\n return model.startsWith('models/') ? model.slice('models/'.length) : model\n}\n\n/**\n * Build one request element.\n *\n * `taskType` appears only when the route DECLARES a wire parameter for purpose,\n * and it is spelled with the declared parameter name. A route that declares\n * nothing gets the text verbatim — an undeclared parameter would be this adapter\n * inventing a mechanism (Requirement 7.3).\n */\nfunction embedRequest(\n item: EmbeddingBatchRequest['items'][number],\n model: ResolvedEmbeddingModelInfo,\n batch: EmbeddingBatchRequest,\n modelId: string,\n): GeminiEmbedRequest {\n const purposeHandling = model.purposeHandling\n const wireParameter = purposeHandling.state === 'supported'\n && purposeHandling.value.kind === 'wire-parameter'\n ? purposeHandling.value.parameter\n : undefined\n const width = outputDimensionality(model, batch)\n return {\n model: `models/${modelId}`,\n content: {\n parts: item.contentParts.map(part => ({ text: part.text })),\n },\n ...(wireParameter === undefined ? {} : { [wireParameter]: TASK_TYPES[batch.purpose] }),\n ...(width === undefined ? {} : { outputDimensionality: width }),\n }\n}\n\n/**\n * `outputDimensionality` travels only when the route declares selectable widths.\n *\n * With an `unknown` declaration there is nothing saying the parameter exists, and\n * sending it anyway would make a capability claim on the route's behalf\n * (Requirement 14.4).\n */\nfunction outputDimensionality(\n model: ResolvedEmbeddingModelInfo,\n batch: EmbeddingBatchRequest,\n): number | undefined {\n if (batch.dimensions === undefined) return undefined\n return model.dimensions.state === 'supported' ? batch.dimensions : undefined\n}\n\n/**\n * The recorded step a narrower-than-native vector needs.\n *\n * Gemini documents that only the native width comes back unit-length, so a\n * narrower request declares `l2-renormalize` in the profile and this adapter\n * performs exactly that. It is NOT a slice or a pad: the model produced the\n * narrower vector itself (Requirement 9.8).\n */\nfunction postProcessingFor(\n model: ResolvedEmbeddingModelInfo,\n dimensions: number,\n): EmbeddingPostProcessing | undefined {\n if (model.defaultDimensions.state !== 'supported') return undefined\n const native = model.defaultDimensions.value\n if (dimensions <= 0 || dimensions >= native) return undefined\n return Object.freeze({ kind: 'l2-renormalize' as const, revision: POST_PROCESSING_REVISION })\n}\n\n/**\n * Turn one response into vectors, positionally, with the count checked.\n *\n * Order: structural shape, then count, then the SHARED\n * {@link validateBatchResult} — so the same malformed response yields the same\n * code here as it does for any other provider — and only then the recorded\n * post-processing step.\n */\nfunction decodeBatch(\n batch: EmbeddingBatchRequest,\n profile: EmbeddingProfile,\n received: GeminiEmbedResponse,\n): EmbeddingBatchResult {\n const embeddings = readEmbeddings(batch, received.payload)\n if (embeddings.length !== batch.items.length) {\n throw new EmbeddingError(\n `Gemini returned ${embeddings.length} embeddings for ${batch.items.length} inputs`,\n EMBEDDING_ERROR_CODES.VECTOR_COUNT_MISMATCH,\n { provider: batch.provider, model: batch.model },\n )\n }\n // Positional mapping: the response carries no index, so the index comes from\n // request order — which is only sound because the length was just checked.\n const vectors = embeddings.map((embedding, position) => Object.freeze<EmbeddingVector>({\n index: batch.items[position]!.index,\n values: readValues(batch, embedding, batch.items[position]!.index),\n }))\n const raw: EmbeddingBatchResult = Object.freeze({\n vectors: Object.freeze(vectors),\n ...(received.providerRequestId === undefined\n ? {}\n : { providerRequestId: received.providerRequestId }),\n })\n validateBatchResult(batch, raw)\n // `batchEmbedContents` reports no usage at all, so no `usage` field is set on\n // the result — not an empty object and not a zero. The absence is what the\n // runtime aggregator reads to report `status: 'missing'` plus a\n // `usage-unreported` warning, and stating it here as well would double the\n // warning for one batch (Requirement 16.2).\n return applyPostProcessing(raw, profile)\n}\n\n/** Read `embeddings[]`, refusing any other shape rather than guessing at it. */\nfunction readEmbeddings(batch: EmbeddingBatchRequest, payload: unknown): readonly unknown[] {\n if (typeof payload !== 'object' || payload === null) {\n throw malformed(batch, 'Gemini response is not a JSON object')\n }\n const embeddings = Reflect.get(payload, 'embeddings')\n if (!Array.isArray(embeddings)) {\n throw malformed(batch, 'Gemini response carries no embeddings array')\n }\n return embeddings as readonly unknown[]\n}\n\n/** Read one `values[]`, leaving every number exactly as the provider sent it. */\nfunction readValues(\n batch: EmbeddingBatchRequest,\n embedding: unknown,\n index: number,\n): readonly number[] {\n if (typeof embedding !== 'object' || embedding === null) {\n throw malformed(batch, 'Gemini embedding entry is not an object', index)\n }\n const values = Reflect.get(embedding, 'values')\n if (!Array.isArray(values)) {\n throw malformed(batch, 'Gemini embedding entry carries no values array', index)\n }\n return Object.freeze([...values as readonly number[]])\n}\n\n/** One place the structural-failure code is spelled. */\nfunction malformed(\n batch: EmbeddingBatchRequest,\n message: string,\n index?: number,\n): EmbeddingError {\n return new EmbeddingError(message, EMBEDDING_ERROR_CODES.RESPONSE_MALFORMED, {\n provider: batch.provider,\n model: batch.model,\n ...(index === undefined ? {} : { itemIndexes: [index] }),\n })\n}\n\n/**\n * Perform the step the profile declares, and nothing else.\n *\n * A profile with no `postProcessing` returns the provider's values untouched, so\n * the vectors a caller receives are faithful to what came back (Property 22). A\n * zero vector has no direction to preserve, so it is passed through rather than\n * turned into `NaN`.\n */\nfunction applyPostProcessing(\n result: EmbeddingBatchResult,\n profile: EmbeddingProfile,\n): EmbeddingBatchResult {\n if (profile.postProcessing?.kind !== 'l2-renormalize') return result\n return Object.freeze({\n ...result,\n vectors: Object.freeze(result.vectors.map(vector => Object.freeze<EmbeddingVector>({\n ...vector,\n values: l2Renormalize(vector.values),\n }))),\n })\n}\n\n/** Scale a vector to unit L2 length. */\nfunction l2Renormalize(values: readonly number[]): readonly number[] {\n let sum = 0\n for (const value of values) sum += value * value\n const norm = Math.sqrt(sum)\n if (!Number.isFinite(norm) || norm === 0) return values\n return Object.freeze(values.map(value => value / norm))\n}\n\n/** A string default model needs exactly one route to belong to. */\nfunction defaultModelTarget(\n value: string | ModelTarget | undefined,\n routes: readonly string[],\n): { readonly defaultModel?: ModelTarget } {\n if (value === undefined) return {}\n if (typeof value !== 'string') return { defaultModel: value }\n if (routes.length !== 1) {\n throw new TypeError('A string defaultModel requires exactly one Gemini embedding route')\n }\n return { defaultModel: Object.freeze({ provider: routes[0]!, id: value }) }\n}\n"],"mappings":";;;;;;;AAKA,MAAM,MAAM;CAAE,sBAAsB;CAAS,0BAA0B;AAAQ;AAC/E,SAAgB,oBAAoB,SAAoC;CACtE,OAAO,yBACL,QAAQ,YAAY,UAAa,QAAQ,QAAQ,QAAQ,OAAO,EAAE,MAAM,qDACpE;EACE,0BAA0B;EAAK,sCAAsC;EAAK,kBAAkB;EAC5F,oBAAoB,EAAE,sBAAsB,IAAU;EACtD,0BAA0B,EAAE,sBAAsB,IAAU;CAC9D,IACA,CAAC,GAAG,QAAQ,QAAQ,QAAQ,oBAAoB;AACxD;;;;;ACUA,MAAa,kBAAkB;AAiC/B,SAAgB,cAAc,SAAiD;CAC7E,OAAO,mBAAmB;EACxB,aAAa;EACb,eAAe,oBAAoB,OAAO;EAC1C,UAAUA;EACV,SAAS,QAAQ;EACjB,MAAM;GACJ,MAAM;GAAU,MAAM;GAAkB,OAAO,QAAQ;GACvD,OAAO;EACT;EACA,SAAS,UAAU,OAAO;EAC1B,GAAI,QAAQ,WAAW,SAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;EACjE,kBAAkB,QAAQ,oBAAoB;EAC9C,sBAAsB,QAAQ,wBAAwB;EACtD,GAAI,QAAQ,wBAAwB,SAAY,CAAC,IAAI,EAAE,qBAAqB,QAAQ,oBAAoB;EACxG,GAAG,gBAAgB,OAAO;EAC1B,GAAI,QAAQ,gBAAgB,SAAY,CAAC,IAAI,EAAE,aAAa,QAAQ,YAAY;EAChF,GAAI,QAAQ,kBAAkB,SAAY,CAAC,IAAI,EAAE,eAAe,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AA2B,CAAC;AACvD;;AAGA,SAAS,UACP,OACA,SACA,OACgB;CAChB,OAAO,IAAI,eAAe,SAAS,sBAAsB,oBAAoB;EAC3E,UAAU,MAAM;EAChB,OAAO,MAAM;EACb,GAAI,UAAU,SAAY,CAAC,IAAI,EAAE,aAAa,CAAC,KAAK,EAAE;CACxD,CAAC;AACH;;;;;;;;;AAUA,SAAS,oBACP,QACA,SACsB;CACtB,IAAI,QAAQ,gBAAgB,SAAS,kBAAkB,OAAO;CAC9D,OAAO,OAAO,OAAO;EACnB,GAAG;EACH,SAAS,OAAO,OAAO,OAAO,QAAQ,KAAI,WAAU,OAAO,OAAwB;GACjF,GAAG;GACH,QAAQ,cAAc,OAAO,MAAM;EACrC,CAAC,CAAC,CAAC;CACL,CAAC;AACH;;AAGA,SAAS,cAAc,QAA8C;CACnE,IAAI,MAAM;CACV,KAAK,MAAM,SAAS,QAAQ,OAAO,QAAQ;CAC3C,MAAM,OAAO,KAAK,KAAK,GAAG;CAC1B,IAAI,CAAC,OAAO,SAAS,IAAI,KAAK,SAAS,GAAG,OAAO;CACjD,OAAO,OAAO,OAAO,OAAO,KAAI,UAAS,QAAQ,IAAI,CAAC;AACxD;;AAGA,SAAS,mBACP,OACA,QACyC;CACzC,IAAI,UAAU,QAAW,OAAO,CAAC;CACjC,IAAI,OAAO,UAAU,UAAU,OAAO,EAAE,cAAc,MAAM;CAC5D,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,UAAU,mEAAmE;CAEzF,OAAO,EAAE,cAAc,OAAO,OAAO;EAAE,UAAU,OAAO;EAAK,IAAI;CAAM,CAAC,EAAE;AAC5E"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["geminiInteractionsProtocol"],"sources":["../src/adapter.ts","../src/embedding.ts"],"sourcesContent":["import type { ModelProviderPlugin, ModelProviderRegistrar, RetryPolicyConfig } from '@alvin0/ai-agent-sdk-core'\nimport {\n defineModelProviderPlugin,\n type ComposableModelProviderPlugin,\n type CredentialInput,\n type ModelTarget,\n} from '@alvin0/ai-agent-sdk-core/provider'\nimport type {\n HeaderContext,\n HttpModelAdapter,\n ProviderCatalogModel,\n ProviderRequestLogger,\n ProviderResponseLogger,\n RequestContext,\n} from '@alvin0/ai-agent-sdk-provider-http'\nimport {\n createHttpProvider,\n endpointHeaders,\n createRuntimeHttpProvider,\n type CredentialSource,\n} from '@alvin0/ai-agent-sdk-provider-http'\nimport {\n geminiInteractionsProtocol,\n type GeminiInteractionsDialect,\n} from '@alvin0/ai-agent-sdk-protocol-gemini-interactions'\n\n/** Google Gemini API v1beta base. The protocol appends only `/interactions`. */\nexport const GEMINI_BASE_URL = 'https://generativelanguage.googleapis.com/v1beta'\n\nexport type GeminiCredential = CredentialSource\n\nexport interface GeminiAdapterOptions {\n /** Injected API key or resolver. Universal packages never read environment variables. */\n apiKey: GeminiCredential\n /** Endpoint base; defaults to {@link GEMINI_BASE_URL}. */\n baseUrl?: string\n /**\n * Name this endpoint uses in diagnostics and error messages. Defaults to\n * `'Gemini'`; set it to the real vendor name when pointing this provider at a\n * compatible gateway, so a rejection names who rejected it.\n */\n displayName?: string\n /** Extra endpoint headers, captured once per operation. Reserved names and collisions fail. */\n headers?: Readonly<Record<string, string>> | ((ctx: HeaderContext) => Readonly<Record<string, string>>)\n /** Permit cleartext HTTP explicitly for trusted local gateways. */\n allowInsecureHttp?: boolean\n /** Override the request path this protocol would otherwise pick (e.g. a gateway deployment path). */\n path?: string\n /** Extra query-string parameters, or a resolver for them. Never for secrets. */\n query?: Readonly<Record<string, string>> | (() => Readonly<Record<string, string>>)\n /**\n * Fields to deep-merge into the serialized body. The caller's value always\n * wins, even over a field the SDK set. A `null` value deletes the field.\n */\n body?: Readonly<Record<string, unknown>>\n /** Last-resort hook with full authority over the body, run after `body` is merged in. */\n transformRequest?: (body: unknown, ctx: RequestContext) => unknown\n /** Advisory catalog; built-in context policies do not advertise model availability. */\n models?: readonly ProviderCatalogModel[]\n /**\n * Whether Google may retain interactions. Defaults to false.\n *\n * This is not a prompt-cache switch: Interactions performs implicit prefix\n * caching automatically for supported models and exposes no cache-key field.\n */\n store?: boolean\n /**\n * How the API key travels. Defaults to `'x-goog-api-key'`, this API's own\n * header — but a gateway sitting in front of it may expect Bearer instead.\n */\n authHeader?: 'x-goog-api-key' | 'bearer'\n defaultMaxTokens?: number\n defaultContextWindow?: number\n streamIdleTimeoutMs?: number\n requestTimeoutMs?: number\n maxRequestBytes?: number\n maxResponseBytes?: number\n maxResponseChunks?: number\n maxSseEvents?: number\n maxSseEventChars?: number\n maxErrorBodyBytes?: number\n requestLoggerTimeoutMs?: number\n retryPolicy?: RetryPolicyConfig\n requestLogger?: ProviderRequestLogger\n responseLogger?: ProviderResponseLogger\n fetch?: typeof globalThis.fetch\n}\n\nexport function geminiAdapter(options: GeminiAdapterOptions): HttpModelAdapter {\n return createHttpProvider({\n displayName: options.displayName ?? 'Gemini',\n protocol: geminiInteractionsProtocol,\n baseUrl: options.baseUrl ?? GEMINI_BASE_URL,\n auth: authOf(options),\n dialect: dialectOf(options),\n ...(options.models === undefined ? {} : { models: options.models }),\n ...(options.defaultMaxTokens === undefined ? {} : { defaultMaxTokens: options.defaultMaxTokens }),\n ...(options.defaultContextWindow === undefined ? {} : { defaultContextWindow: options.defaultContextWindow }),\n ...(options.streamIdleTimeoutMs === undefined ? {} : { streamIdleTimeoutMs: options.streamIdleTimeoutMs }),\n ...transportLimits(options),\n ...(options.retryPolicy === undefined ? {} : { retryPolicy: options.retryPolicy }),\n ...(options.requestLogger === undefined ? {} : { requestLogger: options.requestLogger }),\n ...(options.responseLogger === undefined ? {} : { responseLogger: options.responseLogger }),\n })\n}\n\nexport interface GeminiPluginOptions extends GeminiAdapterOptions {\n /** Registry routes installed by the plugin. Defaults to `['gemini']`. */\n readonly routes?: readonly string[]\n}\n\nexport interface GeminiProviderOptions extends Omit<GeminiAdapterOptions, 'apiKey'> {\n readonly defaultModel?: string | ModelTarget\n readonly apiKey: CredentialInput\n readonly id?: string\n readonly routes?: readonly string[]\n}\n\nexport function geminiPlugin(\n options: GeminiProviderOptions,\n): ComposableModelProviderPlugin & { readonly family: 'gemini' }\nexport function geminiPlugin(options: GeminiPluginOptions): ModelProviderPlugin\nexport function geminiPlugin(\n options: GeminiProviderOptions | GeminiPluginOptions,\n): ModelProviderPlugin | (ComposableModelProviderPlugin & { readonly family: 'gemini' }) {\n if (!usesRuntimeComposition(options)) return legacyGeminiPlugin(options)\n const id = options.id ?? 'gemini'\n const routes = Object.freeze([...(options.routes ?? [id])])\n return defineModelProviderPlugin({\n id,\n family: 'gemini',\n displayName: options.displayName ?? 'Gemini',\n routes,\n ...runtimeDefaultModel(options.defaultModel, routes),\n setup(registrar) {\n const remove = registrar.registerAdapter(createRuntimeGeminiAdapter(options))\n return () => { remove(); return undefined }\n },\n }) as ComposableModelProviderPlugin & { readonly family: 'gemini' }\n}\n\nfunction legacyGeminiPlugin(options: GeminiPluginOptions): ModelProviderPlugin {\n const routes = Object.freeze([...(options.routes ?? ['gemini'])])\n const adapter = geminiAdapter(options)\n return Object.freeze({\n id: 'gemini',\n displayName: options.displayName ?? 'Gemini',\n setup(registrar: ModelProviderRegistrar) {\n registrar.registerAdapter(routes, adapter)\n },\n })\n}\n\nfunction createRuntimeGeminiAdapter(options: GeminiProviderOptions): HttpModelAdapter {\n return createRuntimeHttpProvider({\n displayName: options.displayName ?? 'Gemini',\n protocol: geminiInteractionsProtocol,\n baseUrl: options.baseUrl ?? GEMINI_BASE_URL,\n auth: authOf(options),\n dialect: dialectOf(options),\n ...(options.models === undefined ? {} : { models: options.models }),\n ...(options.defaultMaxTokens === undefined ? {} : { defaultMaxTokens: options.defaultMaxTokens }),\n ...(options.defaultContextWindow === undefined ? {} : { defaultContextWindow: options.defaultContextWindow }),\n ...(options.streamIdleTimeoutMs === undefined ? {} : { streamIdleTimeoutMs: options.streamIdleTimeoutMs }),\n ...transportLimits(options),\n ...(options.retryPolicy === undefined ? {} : { retryPolicy: options.retryPolicy }),\n ...(options.requestLogger === undefined ? {} : { requestLogger: options.requestLogger }),\n ...(options.responseLogger === undefined ? {} : { responseLogger: options.responseLogger }),\n })\n}\n\nfunction dialectOf(options: Pick<GeminiAdapterOptions, 'store'>): Partial<GeminiInteractionsDialect> {\n return options.store === undefined ? {} : { store: options.store }\n}\n\n/**\n * This API's own header is `x-goog-api-key`, unlike most others' `authorization:\n * Bearer` — but a gateway sitting in front of it may expect Bearer instead.\n */\n/**\n * Generic over the credential type on purpose: the two call sites accept\n * DIFFERENT ones — the legacy adapter takes {@link GeminiCredential}\n * (`provider-http`'s string-or-resolver), the composable one takes core's\n * broader `CredentialInput`. A non-generic parameter union would widen\n * `apiKey` to the union of both and fit neither target scheme.\n */\nfunction authOf<Credential>(options: {\n readonly authHeader?: 'x-goog-api-key' | 'bearer'\n readonly apiKey: Credential\n}) {\n return options.authHeader === 'bearer'\n ? { kind: 'bearer' as const, token: options.apiKey, label: 'the `apiKey` option' }\n : { kind: 'header' as const, name: 'x-goog-api-key', value: options.apiKey, label: 'the `apiKey` option' }\n}\n\nfunction usesRuntimeComposition(\n options: GeminiProviderOptions | GeminiPluginOptions,\n): options is GeminiProviderOptions {\n if ('id' in options || 'defaultModel' in options) return true\n if (typeof options.apiKey === 'object' && options.apiKey !== null) return true\n if (typeof options.apiKey !== 'function') return true\n // Node's envCredential keeps a backwards-compatible callable surface while\n // also carrying the versioned CredentialSource marker used by composition.\n return 'kind' in options.apiKey && options.apiKey.kind === 'credential-source'\n}\n\nfunction runtimeDefaultModel(\n value: string | ModelTarget | undefined,\n routes: readonly string[],\n): { readonly defaultModel?: ModelTarget } {\n if (value === undefined) return {}\n if (typeof value !== 'string') return { defaultModel: value }\n if (routes.length !== 1) throw new TypeError('A string defaultModel requires exactly one Gemini route')\n return { defaultModel: Object.freeze({ provider: routes[0]!, id: value }) }\n}\n\nfunction transportLimits(options: GeminiAdapterOptions | GeminiProviderOptions) {\n return {\n ...(options.allowInsecureHttp === undefined ? {} : { allowInsecureHttp: options.allowInsecureHttp }),\n headers: endpointHeaders(options.headers),\n ...(options.path === undefined ? {} : { path: options.path }),\n ...(options.query === undefined ? {} : { query: options.query }),\n ...(options.body === undefined ? {} : { body: options.body }),\n ...(options.transformRequest === undefined ? {} : { transformRequest: options.transformRequest }),\n ...(options.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: options.requestTimeoutMs }),\n ...(options.maxRequestBytes === undefined ? {} : { maxRequestBytes: options.maxRequestBytes }),\n ...(options.maxResponseBytes === undefined ? {} : { maxResponseBytes: options.maxResponseBytes }),\n ...(options.maxResponseChunks === undefined ? {} : { maxResponseChunks: options.maxResponseChunks }),\n ...(options.maxSseEvents === undefined ? {} : { maxSseEvents: options.maxSseEvents }),\n ...(options.maxSseEventChars === undefined ? {} : { maxSseEventChars: options.maxSseEventChars }),\n ...(options.maxErrorBodyBytes === undefined ? {} : { maxErrorBodyBytes: options.maxErrorBodyBytes }),\n ...(options.requestLoggerTimeoutMs === undefined ? {} : { requestLoggerTimeoutMs: options.requestLoggerTimeoutMs }),\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n }\n}\n","/**\n * `Gemini_Embedding_Adapter`: Gemini's `batchEmbedContents` endpoint expressed as\n * an `Embedding_Adapter`.\n *\n * Deliberately separate from `./adapter.ts`: nothing here imports\n * `geminiInteractionsProtocol`, and nothing there imports this module. Generation\n * and embedding share the same credential shape and the same HTTP transport, and\n * that is all they share — a request vocabulary in common would be the conflation\n * Requirement 14.2 rules out.\n *\n * Three Gemini specifics shape this file, and each one is stated rather than\n * inferred:\n *\n * - **Purpose is a wire parameter.** `taskType` exists, so `purpose` translates\n * into it — but only when the route DECLARES that mechanism. A route that\n * declares nothing gets the text sent verbatim and no invented parameter\n * (Requirement 7.3).\n * - **A narrower vector is a model mechanism plus a recorded step.**\n * `outputDimensionality` asks the model for a narrower vector; Gemini\n * documents that a narrower vector is no longer unit-length, so the profile\n * declares `postProcessing: { kind: 'l2-renormalize', revision: '1' }` and this\n * adapter performs exactly that step. Nothing here slices or pads a vector\n * (Requirement 9.8).\n * - **Mapping is positional.** `batchEmbedContents` returns\n * `{ embeddings: [{ values }] }` with no index, so the index is assigned by\n * this adapter from request order, and the count is checked rather than\n * assumed.\n *\n * @module ai-agent-sdk/providers/gemini/embedding\n */\n\nimport {\n assertUsableApiKey,\n resolveRetryPolicy,\n type ModelInvocationContext,\n type ProviderInfo,\n type ResolvedRetryPolicy,\n type RetryPolicyConfig,\n type SdkLogger,\n} from '@alvin0/ai-agent-sdk-core'\nimport {\n EMBEDDING_ERROR_CODES,\n EmbeddingAdapter,\n EmbeddingError,\n defaultEmbeddingProfile,\n deriveSpaceId,\n resolveBatchLimits,\n validateBatchResult,\n type EmbeddingBatchRequest,\n type EmbeddingBatchResult,\n type EmbeddingModelInfo,\n type EmbeddingPostProcessing,\n type EmbeddingProfile,\n type EmbeddingProfileInput,\n type EmbeddingPurpose,\n type EmbeddingVector,\n type PrepareEmbeddingOptions,\n type PreparedEmbeddingCall,\n type ResolvedEmbeddingModelInfo,\n} from '@alvin0/ai-agent-sdk-core/embedding'\nimport {\n defineEmbeddingProviderPlugin,\n type ComposableEmbeddingProviderPlugin,\n type CredentialInput,\n type ModelTarget,\n} from '@alvin0/ai-agent-sdk-core/provider'\nimport {\n captureTransportConnection,\n endpointHeaders,\n embeddingCatalogModelInfo,\n resolvedEmbeddingCatalogModelInfo,\n transportJson,\n type EmbeddingCatalogModel,\n type EmbeddingHttpConnection,\n type HeaderContext,\n} from '@alvin0/ai-agent-sdk-provider-http'\n\n/** Google Generative Language API v1beta base; the adapter appends the model path. */\nexport const GEMINI_EMBEDDING_BASE_URL = 'https://generativelanguage.googleapis.com/v1beta'\n\n/** Name used in every diagnostic this module raises. */\nconst DISPLAY_NAME = 'Gemini'\n\n/** Header layer the JSON pipeline owns for this route. */\nconst TRANSPORT_HEADERS = Object.freeze({\n 'content-type': 'application/json',\n accept: 'application/json',\n})\n\n/** Revision of the `l2-renormalize` step this adapter performs. */\nconst POST_PROCESSING_REVISION = '1'\n\n/** Applied when neither the caller nor the catalog says otherwise. */\nconst DEFAULT_RECIPE_REVISION = '1'\n\n/** The one mapping from this SDK's purpose vocabulary to Gemini's `taskType`. */\nconst TASK_TYPES: Readonly<Record<EmbeddingPurpose, string>> = Object.freeze({\n 'retrieval-query': 'RETRIEVAL_QUERY',\n 'retrieval-document': 'RETRIEVAL_DOCUMENT',\n})\n\nconst NEVER_ABORTED_SIGNAL = new AbortController().signal\n\nconst NULL_LOGGER: SdkLogger = Object.freeze({\n child: () => NULL_LOGGER,\n trace: () => undefined,\n debug: () => undefined,\n info: () => undefined,\n warn: () => undefined,\n error: () => undefined,\n fatal: () => undefined,\n})\n\n/**\n * The Gemini embedding generations this package declares.\n *\n * Unlike the generation catalog, an embedding catalog entry cannot be omitted\n * entirely: `compatibilityIdentity` is a claim about an embedding space that only\n * the route can make, and Requirement 14.6 puts that claim on this adapter. The\n * identity names the GENERATION, so `gemini-embedding-001` and a future\n * `gemini-embedding-2` are detected as incompatible even at equal width. Pass\n * `models` to override or extend this list.\n */\nexport const GEMINI_EMBEDDING_MODELS: readonly EmbeddingCatalogModel[] = Object.freeze([\n Object.freeze({\n id: 'gemini-embedding-001',\n name: 'Gemini Embedding 001',\n description: 'Gemini text embedding with selectable output dimensionality.',\n dimensions: Object.freeze([3072, 1536, 768]),\n defaultDimensions: 3072,\n maxInputTokens: 2048,\n maxBatchItems: 100,\n purposeHandling: Object.freeze({ kind: 'wire-parameter' as const, parameter: 'taskType' }),\n compatibilityIdentity: 'google:gemini-embedding-001',\n }),\n])\n\n/** Configuration for {@link geminiEmbeddingAdapter} and {@link geminiEmbeddingPlugin}. */\nexport interface GeminiEmbeddingProviderOptions {\n /** Injected key or credential source; universal packages never read the environment. */\n readonly apiKey: CredentialInput\n /** Extra endpoint headers, captured once per logical call; reserved names fail. */\n readonly headers?: Readonly<Record<string, string>> | (() => Readonly<Record<string, string>>)\n /** Endpoint base; defaults to {@link GEMINI_EMBEDDING_BASE_URL}. */\n readonly baseUrl?: string\n /** Plugin id; defaults to `'gemini-embedding'`. */\n readonly id?: string\n /** Routes the plugin claims; defaults to `[id]`. */\n readonly routes?: readonly string[]\n /** Default model for the claimed route. */\n readonly defaultModel?: string | ModelTarget\n /** Declared embedding catalog; defaults to {@link GEMINI_EMBEDDING_MODELS}. */\n readonly models?: readonly EmbeddingCatalogModel[]\n /** Permit cleartext HTTP explicitly, for a trusted local endpoint only. */\n readonly allowInsecureHttp?: boolean\n readonly requestTimeoutMs?: number\n readonly maxRequestBytes?: number\n readonly maxResponseBytes?: number\n readonly maxResponseChunks?: number\n readonly maxErrorBodyBytes?: number\n readonly requestLoggerTimeoutMs?: number\n readonly retryPolicy?: RetryPolicyConfig\n readonly fetch?: typeof globalThis.fetch\n}\n\n/** What the JSON pipeline hands back: the parsed body plus its correlation id. */\ninterface GeminiEmbedResponse {\n readonly payload: unknown\n readonly providerRequestId?: string\n}\n\n/** One request element of Gemini's `batchEmbedContents` body. */\ninterface GeminiEmbedRequest {\n readonly model: string\n readonly content: { readonly parts: readonly { readonly text: string }[] }\n readonly outputDimensionality?: number\n readonly [parameter: string]: unknown\n}\n\n/**\n * The Gemini `batchEmbedContents` adapter.\n *\n * Every metadata method takes the route key, so one instance serves every route\n * the plugin claims. Connection facts are captured once per operation in\n * {@link prepareEmbeddingCall}, which is what keeps a credential from travelling\n * to a URL from a different configuration generation.\n */\nclass GeminiEmbeddingAdapter extends EmbeddingAdapter {\n readonly #options: GeminiEmbeddingProviderOptions\n readonly #headers: (ctx: HeaderContext) => Readonly<Record<string, string>>\n readonly #models: readonly EmbeddingCatalogModel[]\n readonly #retryPolicy: ResolvedRetryPolicy\n\n constructor(options: GeminiEmbeddingProviderOptions) {\n super()\n this.#options = Object.freeze({ ...options })\n this.#headers = endpointHeaders(options.headers)\n this.#models = Object.freeze([...(options.models ?? GEMINI_EMBEDDING_MODELS)])\n this.#retryPolicy = resolveRetryPolicy(options.retryPolicy, 'retryPolicy')\n }\n\n override providerInfo(provider: string): ProviderInfo {\n return { id: provider, name: DISPLAY_NAME }\n }\n\n override providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined {\n return this.#retryPolicy\n }\n\n override listEmbeddingModels(\n provider: string,\n _signal?: AbortSignal,\n ): Promise<readonly EmbeddingModelInfo[]> {\n return Promise.resolve(Object.freeze(\n this.#models.map(model => embeddingCatalogModelInfo(provider, model)),\n ))\n }\n\n override resolveEmbeddingModel(\n provider: string,\n model: string,\n _signal?: AbortSignal,\n ): Promise<ResolvedEmbeddingModelInfo> {\n return Promise.resolve(resolvedEmbeddingCatalogModelInfo(provider, model, this.#models))\n }\n\n /**\n * Declare the real Gemini profile instead of accepting the generic default.\n *\n * Two statements the default cannot make: the compatibility identity is the\n * route's declaration about a GENERATION, and asking for a narrower vector adds\n * a recorded `l2-renormalize` step which this adapter then actually performs.\n */\n override embeddingProfile(\n model: ResolvedEmbeddingModelInfo,\n request: EmbeddingProfileInput,\n ): EmbeddingProfile {\n const base = defaultEmbeddingProfile(model, request)\n const postProcessing = postProcessingFor(model, base.dimensions)\n return Object.freeze({\n ...base,\n compatibilityIdentity: model.compatibilityIdentity.state === 'supported'\n ? model.compatibilityIdentity.value\n : `google:${model.id}`,\n // Truthful either way: `unit-l2` only where this adapter normalizes, and\n // otherwise whatever the route declared — never inferred from the width.\n normalization: postProcessing !== undefined\n ? 'unit-l2'\n : model.normalization.state === 'supported'\n ? model.normalization.value\n : 'unknown',\n documentRecipeRevision: request.documentRecipeRevision ?? DEFAULT_RECIPE_REVISION,\n queryRecipeRevision: request.queryRecipeRevision ?? DEFAULT_RECIPE_REVISION,\n ...(postProcessing === undefined ? {} : { postProcessing }),\n })\n }\n\n /**\n * Capture the endpoint, the credential and the catalog together, once.\n *\n * The connection is read here and never re-read per batch, so every batch of\n * one `Logical_Call` goes out through the same generation of configuration\n * that its dimensions were checked against.\n */\n override async prepareEmbeddingCall(\n provider: string,\n model: string,\n options: PrepareEmbeddingOptions,\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n ): Promise<PreparedEmbeddingCall> {\n const resolved = await this.resolveEmbeddingModel(provider, model, signal)\n const profile = this.embeddingProfile(resolved, options)\n const connection = await this.#connect(provider, signal, context)\n return Object.freeze({\n model: resolved,\n profile,\n spaceId: deriveSpaceId(profile),\n limits: resolveBatchLimits(resolved, options.limits),\n embedBatch: (batch: EmbeddingBatchRequest, invocation = context) =>\n this.#dispatch(connection, resolved, profile, batch, invocation),\n })\n }\n\n /**\n * Perform exactly one `batchEmbedContents` request.\n *\n * Usable directly, in which case the catalog and connection are resolved for\n * this batch alone; `prepareEmbeddingCall` is the path that binds one snapshot\n * to a whole logical call.\n */\n override async embedBatch(\n batch: EmbeddingBatchRequest,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingBatchResult> {\n const resolved = await this.resolveEmbeddingModel(batch.provider, batch.model, batch.signal)\n const profile = this.embeddingProfile(resolved, {\n ...(batch.dimensions === undefined ? {} : { dimensions: batch.dimensions }),\n })\n const connection = await this.#connect(batch.provider, batch.signal, context)\n return await this.#dispatch(connection, resolved, profile, batch, context)\n }\n\n /** Resolve the credential and bounds into one frozen snapshot. */\n async #connect(\n provider: string,\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingHttpConnection> {\n const options = this.#options\n const extraHeaders = this.#headers({\n provider,\n ...(context?.agentId === undefined ? {} : { agentId: context.agentId }),\n ...(signal === undefined ? {} : { signal }),\n })\n const apiKey = assertUsableApiKey(\n await resolveCredential(options.apiKey, signal, context),\n DISPLAY_NAME,\n 'the `apiKey` option',\n )\n // Attribution headers are merged by the transport, so no embedding adapter\n // can forget them (Requirement 14.7).\n return captureTransportConnection<EmbeddingHttpConnection>({\n baseUrl: options.baseUrl ?? GEMINI_EMBEDDING_BASE_URL,\n headers: Object.freeze({ ...extraHeaders, 'x-goog-api-key': apiKey }),\n models: this.#models,\n retryPolicy: this.#retryPolicy,\n ...(options.allowInsecureHttp === undefined\n ? {}\n : { allowInsecureHttp: options.allowInsecureHttp }),\n ...(options.requestTimeoutMs === undefined\n ? {}\n : { requestTimeoutMs: options.requestTimeoutMs }),\n ...(options.maxRequestBytes === undefined ? {} : { maxRequestBytes: options.maxRequestBytes }),\n ...(options.maxResponseBytes === undefined\n ? {}\n : { maxResponseBytes: options.maxResponseBytes }),\n ...(options.maxResponseChunks === undefined\n ? {}\n : { maxResponseChunks: options.maxResponseChunks }),\n ...(options.maxErrorBodyBytes === undefined\n ? {}\n : { maxErrorBodyBytes: options.maxErrorBodyBytes }),\n ...(options.requestLoggerTimeoutMs === undefined\n ? {}\n : { requestLoggerTimeoutMs: options.requestLoggerTimeoutMs }),\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n }, TRANSPORT_HEADERS)\n }\n\n /** One `Provider_Attempt`: build the body, send it, decode the response. */\n async #dispatch(\n connection: EmbeddingHttpConnection,\n model: ResolvedEmbeddingModelInfo,\n profile: EmbeddingProfile,\n batch: EmbeddingBatchRequest,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingBatchResult> {\n if (batch.truncation === 'allow') {\n throw new EmbeddingError(\n 'Gemini batchEmbedContents exposes no truncation parameter',\n EMBEDDING_ERROR_CODES.TRUNCATION_UNSUPPORTED,\n { provider: batch.provider, model: batch.model },\n )\n }\n const modelId = bareModelId(batch.model)\n const body = { requests: batch.items.map(item => embedRequest(item, model, batch, modelId)) }\n const encoded = JSON.stringify(body)\n // The transport chain owns transport failures and normalizes anything thrown\n // inside `decode` into a ModelError, which would flatten this adapter's\n // embedding codes. So `decode` only extracts the payload, and contract\n // validation runs here, where an EmbeddingError reaches the caller intact.\n const received = await transportJson({\n connection,\n displayName: DISPLAY_NAME,\n provider: batch.provider,\n model: batch.model,\n path: `/models/${encodeURIComponent(modelId)}:batchEmbedContents`,\n accept: 'application/json',\n body: {\n value: body,\n encoded,\n bytes: new TextEncoder().encode(encoded).length,\n },\n ...(batch.signal === undefined ? {} : { signal: batch.signal }),\n ...(context === undefined ? {} : { context }),\n }, (session, payload) => Object.freeze({\n payload,\n ...(session.providerRequestId === undefined\n ? {}\n : { providerRequestId: session.providerRequestId }),\n }))\n return decodeBatch(batch, profile, received)\n }\n}\n\n/**\n * Create the Gemini embedding adapter.\n *\n * No I/O happens here: the credential is resolved per operation, not at\n * construction.\n * @param options - route configuration.\n * @returns an adapter registrable under any number of routes.\n */\nexport function geminiEmbeddingAdapter(\n options: GeminiEmbeddingProviderOptions,\n): EmbeddingAdapter {\n return new GeminiEmbeddingAdapter(options)\n}\n\n/**\n * Create the Gemini `Embedding_Provider_Plugin`.\n *\n * Its `kind` is `'embedding-provider-plugin'`, so a generation host never\n * mistakes it for {@link geminiPlugin} and neither plugin needs a version bump\n * because of the other (Requirement 11.1).\n * @param options - route configuration.\n * @returns an inert plugin; registration happens during runtime activation.\n */\nexport function geminiEmbeddingPlugin(\n options: GeminiEmbeddingProviderOptions,\n): ComposableEmbeddingProviderPlugin & { readonly family: 'gemini' } {\n const id = options.id ?? 'gemini-embedding'\n const routes = Object.freeze([...(options.routes ?? [id])])\n const adapter = geminiEmbeddingAdapter(options)\n return defineEmbeddingProviderPlugin({\n id,\n family: 'gemini',\n displayName: DISPLAY_NAME,\n routes,\n ...defaultModelTarget(options.defaultModel, routes),\n setup(registrar) {\n const remove = registrar.registerEmbeddingAdapter(adapter)\n return () => {\n remove()\n return undefined\n }\n },\n }) as ComposableEmbeddingProviderPlugin & { readonly family: 'gemini' }\n}\n\n/** Resolve a literal key or a credential source, without caching the secret. */\nasync function resolveCredential(\n apiKey: CredentialInput,\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n): Promise<string> {\n if (typeof apiKey === 'string') return apiKey\n return await apiKey.resolve({\n signal: signal ?? NEVER_ABORTED_SIGNAL,\n logger: context?.logger ?? NULL_LOGGER,\n })\n}\n\n/** Accept both `gemini-embedding-001` and the `models/`-prefixed resource name. */\nfunction bareModelId(model: string): string {\n return model.startsWith('models/') ? model.slice('models/'.length) : model\n}\n\n/**\n * Build one request element.\n *\n * `taskType` appears only when the route DECLARES a wire parameter for purpose,\n * and it is spelled with the declared parameter name. A route that declares\n * nothing gets the text verbatim — an undeclared parameter would be this adapter\n * inventing a mechanism (Requirement 7.3).\n */\nfunction embedRequest(\n item: EmbeddingBatchRequest['items'][number],\n model: ResolvedEmbeddingModelInfo,\n batch: EmbeddingBatchRequest,\n modelId: string,\n): GeminiEmbedRequest {\n const purposeHandling = model.purposeHandling\n const wireParameter = purposeHandling.state === 'supported'\n && purposeHandling.value.kind === 'wire-parameter'\n ? purposeHandling.value.parameter\n : undefined\n const width = outputDimensionality(model, batch)\n return {\n model: `models/${modelId}`,\n content: {\n parts: item.contentParts.map(part => ({ text: part.text })),\n },\n ...(wireParameter === undefined ? {} : { [wireParameter]: TASK_TYPES[batch.purpose] }),\n ...(width === undefined ? {} : { outputDimensionality: width }),\n }\n}\n\n/**\n * `outputDimensionality` travels only when the route declares selectable widths.\n *\n * With an `unknown` declaration there is nothing saying the parameter exists, and\n * sending it anyway would make a capability claim on the route's behalf\n * (Requirement 14.4).\n */\nfunction outputDimensionality(\n model: ResolvedEmbeddingModelInfo,\n batch: EmbeddingBatchRequest,\n): number | undefined {\n if (batch.dimensions === undefined) return undefined\n return model.dimensions.state === 'supported' ? batch.dimensions : undefined\n}\n\n/**\n * The recorded step a narrower-than-native vector needs.\n *\n * Gemini documents that only the native width comes back unit-length, so a\n * narrower request declares `l2-renormalize` in the profile and this adapter\n * performs exactly that. It is NOT a slice or a pad: the model produced the\n * narrower vector itself (Requirement 9.8).\n */\nfunction postProcessingFor(\n model: ResolvedEmbeddingModelInfo,\n dimensions: number,\n): EmbeddingPostProcessing | undefined {\n if (model.defaultDimensions.state !== 'supported') return undefined\n const native = model.defaultDimensions.value\n if (dimensions <= 0 || dimensions >= native) return undefined\n return Object.freeze({ kind: 'l2-renormalize' as const, revision: POST_PROCESSING_REVISION })\n}\n\n/**\n * Turn one response into vectors, positionally, with the count checked.\n *\n * Order: structural shape, then count, then the SHARED\n * {@link validateBatchResult} — so the same malformed response yields the same\n * code here as it does for any other provider — and only then the recorded\n * post-processing step.\n */\nfunction decodeBatch(\n batch: EmbeddingBatchRequest,\n profile: EmbeddingProfile,\n received: GeminiEmbedResponse,\n): EmbeddingBatchResult {\n const embeddings = readEmbeddings(batch, received.payload)\n if (embeddings.length !== batch.items.length) {\n throw new EmbeddingError(\n `Gemini returned ${embeddings.length} embeddings for ${batch.items.length} inputs`,\n EMBEDDING_ERROR_CODES.VECTOR_COUNT_MISMATCH,\n { provider: batch.provider, model: batch.model },\n )\n }\n // Positional mapping: the response carries no index, so the index comes from\n // request order — which is only sound because the length was just checked.\n const vectors = embeddings.map((embedding, position) => Object.freeze<EmbeddingVector>({\n index: batch.items[position]!.index,\n values: readValues(batch, embedding, batch.items[position]!.index),\n }))\n const raw: EmbeddingBatchResult = Object.freeze({\n vectors: Object.freeze(vectors),\n ...(received.providerRequestId === undefined\n ? {}\n : { providerRequestId: received.providerRequestId }),\n })\n validateBatchResult(batch, raw)\n // `batchEmbedContents` reports no usage at all, so no `usage` field is set on\n // the result — not an empty object and not a zero. The absence is what the\n // runtime aggregator reads to report `status: 'missing'` plus a\n // `usage-unreported` warning, and stating it here as well would double the\n // warning for one batch (Requirement 16.2).\n return applyPostProcessing(raw, profile)\n}\n\n/** Read `embeddings[]`, refusing any other shape rather than guessing at it. */\nfunction readEmbeddings(batch: EmbeddingBatchRequest, payload: unknown): readonly unknown[] {\n if (typeof payload !== 'object' || payload === null) {\n throw malformed(batch, 'Gemini response is not a JSON object')\n }\n const embeddings = Reflect.get(payload, 'embeddings')\n if (!Array.isArray(embeddings)) {\n throw malformed(batch, 'Gemini response carries no embeddings array')\n }\n return embeddings as readonly unknown[]\n}\n\n/** Read one `values[]`, leaving every number exactly as the provider sent it. */\nfunction readValues(\n batch: EmbeddingBatchRequest,\n embedding: unknown,\n index: number,\n): readonly number[] {\n if (typeof embedding !== 'object' || embedding === null) {\n throw malformed(batch, 'Gemini embedding entry is not an object', index)\n }\n const values = Reflect.get(embedding, 'values')\n if (!Array.isArray(values)) {\n throw malformed(batch, 'Gemini embedding entry carries no values array', index)\n }\n return Object.freeze([...values as readonly number[]])\n}\n\n/** One place the structural-failure code is spelled. */\nfunction malformed(\n batch: EmbeddingBatchRequest,\n message: string,\n index?: number,\n): EmbeddingError {\n return new EmbeddingError(message, EMBEDDING_ERROR_CODES.RESPONSE_MALFORMED, {\n provider: batch.provider,\n model: batch.model,\n ...(index === undefined ? {} : { itemIndexes: [index] }),\n })\n}\n\n/**\n * Perform the step the profile declares, and nothing else.\n *\n * A profile with no `postProcessing` returns the provider's values untouched, so\n * the vectors a caller receives are faithful to what came back (Property 22). A\n * zero vector has no direction to preserve, so it is passed through rather than\n * turned into `NaN`.\n */\nfunction applyPostProcessing(\n result: EmbeddingBatchResult,\n profile: EmbeddingProfile,\n): EmbeddingBatchResult {\n if (profile.postProcessing?.kind !== 'l2-renormalize') return result\n return Object.freeze({\n ...result,\n vectors: Object.freeze(result.vectors.map(vector => Object.freeze<EmbeddingVector>({\n ...vector,\n values: l2Renormalize(vector.values),\n }))),\n })\n}\n\n/** Scale a vector to unit L2 length. */\nfunction l2Renormalize(values: readonly number[]): readonly number[] {\n let sum = 0\n for (const value of values) sum += value * value\n const norm = Math.sqrt(sum)\n if (!Number.isFinite(norm) || norm === 0) return values\n return Object.freeze(values.map(value => value / norm))\n}\n\n/** A string default model needs exactly one route to belong to. */\nfunction defaultModelTarget(\n value: string | ModelTarget | undefined,\n routes: readonly string[],\n): { readonly defaultModel?: ModelTarget } {\n if (value === undefined) return {}\n if (typeof value !== 'string') return { defaultModel: value }\n if (routes.length !== 1) {\n throw new TypeError('A string defaultModel requires exactly one Gemini embedding route')\n }\n return { defaultModel: Object.freeze({ provider: routes[0]!, id: value }) }\n}\n"],"mappings":";;;;;;;;AA2BA,MAAa,kBAAkB;AA6D/B,SAAgB,cAAc,SAAiD;CAC7E,OAAO,mBAAmB;EACxB,aAAa,QAAQ,eAAe;EACpC,UAAUA;EACV,SAAS,Q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5
|
"email": "chaulamdinhai@gmail.com"
|
|
6
6
|
},
|
|
7
|
-
"version": "0.1.
|
|
7
|
+
"version": "0.1.4",
|
|
8
8
|
"description": "Universal Gemini Interactions adapter and provider plugin for ai-agent-sdk",
|
|
9
9
|
"license": "MIT",
|
|
10
10
|
"repository": {
|
|
@@ -38,15 +38,15 @@
|
|
|
38
38
|
"provenance": true
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"@alvin0/ai-agent-sdk-provider-http": "^0.1.
|
|
42
|
-
"@alvin0/ai-agent-sdk-protocol-gemini-interactions": "^0.1.
|
|
41
|
+
"@alvin0/ai-agent-sdk-provider-http": "^0.1.4",
|
|
42
|
+
"@alvin0/ai-agent-sdk-protocol-gemini-interactions": "^0.1.4"
|
|
43
43
|
},
|
|
44
44
|
"peerDependencies": {
|
|
45
|
-
"@alvin0/ai-agent-sdk-core": "^0.1.
|
|
45
|
+
"@alvin0/ai-agent-sdk-core": "^0.1.4"
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
|
-
"@alvin0/ai-agent-sdk-core": "^0.1.
|
|
49
|
-
"@alvin0/ai-agent-sdk-testkit": "^0.1.
|
|
48
|
+
"@alvin0/ai-agent-sdk-core": "^0.1.4",
|
|
49
|
+
"@alvin0/ai-agent-sdk-testkit": "^0.1.4",
|
|
50
50
|
"@arethetypeswrong/cli": "0.18.5",
|
|
51
51
|
"playwright": "1.62.1",
|
|
52
52
|
"publint": "0.3.24",
|