@alvin0/ai-agent-sdk-provider-gemini 0.1.0 → 0.1.1

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 CHANGED
@@ -13,3 +13,9 @@ Interactions endpoint at `/v1beta/interactions` and does not use
13
13
  Credentials are always injected. This package never reads `.env`, environment
14
14
  variables, or files; a Node host may opt into `envCredential()` from
15
15
  `@alvin0/ai-agent-sdk-auth-node`.
16
+
17
+ Unknown models now default to a conservative 200,000-token operating context.
18
+ Verified Pro model policies stay at 200,000 to avoid the higher long-context price
19
+ tier; verified Flash policies can use 1,000,000. Set `models[].contextWindow` to
20
+ override, or `defaultContextWindow` at provider level. See the
21
+ [context policy guide](../../web-documents/en/09-providers/index.md).
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import { ComposableModelProviderPlugin, CredentialInput, ModelTarget } from "@alvin0/ai-agent-sdk-core/provider";
2
- import { CredentialSource, HttpModelAdapter, ProviderCatalogModel, ProviderRequestLogger } from "@alvin0/ai-agent-sdk-provider-http";
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";
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
+ import { EmbeddingAdapter } from "@alvin0/ai-agent-sdk-core/embedding";
5
6
  //#region src/adapter.d.ts
6
7
  /** Google Gemini API v1beta base. The protocol appends only `/interactions`. */
7
8
  declare const GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
@@ -11,7 +12,7 @@ interface GeminiAdapterOptions {
11
12
  apiKey: GeminiCredential;
12
13
  /** Endpoint base; defaults to {@link GEMINI_BASE_URL}. */
13
14
  baseUrl?: string;
14
- /** Advisory catalog. No model ids are built in, so the list cannot become stale. */
15
+ /** Advisory catalog; built-in context policies do not advertise model availability. */
15
16
  models?: readonly ProviderCatalogModel[];
16
17
  /** Whether Google may retain interactions. Defaults to false. */
17
18
  store?: boolean;
@@ -46,5 +47,66 @@ declare function geminiPlugin(options: GeminiProviderOptions): ComposableModelPr
46
47
  };
47
48
  declare function geminiPlugin(options: GeminiPluginOptions): ModelProviderPlugin;
48
49
  //#endregion
49
- export { GEMINI_BASE_URL, type GeminiAdapterOptions, type GeminiCredential, type GeminiInteractionsDialect, type GeminiPluginOptions, type GeminiProviderOptions, geminiAdapter, geminiInteractionsProtocol, geminiPlugin };
50
+ //#region src/embedding.d.ts
51
+ /** Google Generative Language API v1beta base; the adapter appends the model path. */
52
+ declare const GEMINI_EMBEDDING_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
53
+ /**
54
+ * The Gemini embedding generations this package declares.
55
+ *
56
+ * Unlike the generation catalog, an embedding catalog entry cannot be omitted
57
+ * entirely: `compatibilityIdentity` is a claim about an embedding space that only
58
+ * the route can make, and Requirement 14.6 puts that claim on this adapter. The
59
+ * identity names the GENERATION, so `gemini-embedding-001` and a future
60
+ * `gemini-embedding-2` are detected as incompatible even at equal width. Pass
61
+ * `models` to override or extend this list.
62
+ */
63
+ declare const GEMINI_EMBEDDING_MODELS: readonly EmbeddingCatalogModel[];
64
+ /** Configuration for {@link geminiEmbeddingAdapter} and {@link geminiEmbeddingPlugin}. */
65
+ interface GeminiEmbeddingProviderOptions {
66
+ /** Injected key or credential source; universal packages never read the environment. */
67
+ readonly apiKey: CredentialInput;
68
+ /** Endpoint base; defaults to {@link GEMINI_EMBEDDING_BASE_URL}. */
69
+ readonly baseUrl?: string;
70
+ /** Plugin id; defaults to `'gemini-embedding'`. */
71
+ readonly id?: string;
72
+ /** Routes the plugin claims; defaults to `[id]`. */
73
+ readonly routes?: readonly string[];
74
+ /** Default model for the claimed route. */
75
+ readonly defaultModel?: string | ModelTarget;
76
+ /** Declared embedding catalog; defaults to {@link GEMINI_EMBEDDING_MODELS}. */
77
+ readonly models?: readonly EmbeddingCatalogModel[];
78
+ /** Permit cleartext HTTP explicitly, for a trusted local endpoint only. */
79
+ readonly allowInsecureHttp?: boolean;
80
+ readonly requestTimeoutMs?: number;
81
+ readonly maxRequestBytes?: number;
82
+ readonly maxResponseBytes?: number;
83
+ readonly maxResponseChunks?: number;
84
+ readonly maxErrorBodyBytes?: number;
85
+ readonly requestLoggerTimeoutMs?: number;
86
+ readonly retryPolicy?: RetryPolicyConfig;
87
+ readonly fetch?: typeof globalThis.fetch;
88
+ }
89
+ /**
90
+ * Create the Gemini embedding adapter.
91
+ *
92
+ * No I/O happens here: the credential is resolved per operation, not at
93
+ * construction.
94
+ * @param options - route configuration.
95
+ * @returns an adapter registrable under any number of routes.
96
+ */
97
+ declare function geminiEmbeddingAdapter(options: GeminiEmbeddingProviderOptions): EmbeddingAdapter;
98
+ /**
99
+ * Create the Gemini `Embedding_Provider_Plugin`.
100
+ *
101
+ * Its `kind` is `'embedding-provider-plugin'`, so a generation host never
102
+ * mistakes it for {@link geminiPlugin} and neither plugin needs a version bump
103
+ * because of the other (Requirement 11.1).
104
+ * @param options - route configuration.
105
+ * @returns an inert plugin; registration happens during runtime activation.
106
+ */
107
+ declare function geminiEmbeddingPlugin(options: GeminiEmbeddingProviderOptions): ComposableEmbeddingProviderPlugin & {
108
+ readonly family: 'gemini';
109
+ };
110
+ //#endregion
111
+ export { GEMINI_BASE_URL, GEMINI_EMBEDDING_BASE_URL, GEMINI_EMBEDDING_MODELS, type GeminiAdapterOptions, type GeminiCredential, type GeminiEmbeddingProviderOptions, type GeminiInteractionsDialect, type GeminiPluginOptions, type GeminiProviderOptions, geminiAdapter, geminiEmbeddingAdapter, geminiEmbeddingPlugin, geminiInteractionsProtocol, geminiPlugin };
50
112
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/adapter.ts"],"mappings":";;;;;;cAuBa;KAED,mBAAmB;UAEd;;EAEf,QAAQ;;EAER;;EAEA,kBAAkB;;EAElB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,cAAc;EACd,gBAAgB;EAChB,eAAe,WAAW;;iBAGZ,cAAc,SAAS,uBAAuB;UAoB7C,4BAA4B;;WAElC;;UAGM,8BAA8B,KAAK;WACzC,wBAAwB;WACxB,QAAQ;WACR;WACA;;iBAGK,aACd,SAAS,wBACR;WAA2C;;iBAC9B,aAAa,SAAS,sBAAsB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/adapter.ts","../src/embedding.ts"],"mappings":";;;;;;;cAwBa;KAED,mBAAmB;UAEd;;EAEf,QAAQ;;EAER;;EAEA,kBAAkB;;EAElB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,cAAc;EACd,gBAAgB;EAChB,eAAe,WAAW;;iBAGZ,cAAc,SAAS,uBAAuB;UAqB7C,4BAA4B;;WAElC;;UAGM,8BAA8B,KAAK;WACzC,wBAAwB;WACxB,QAAQ;WACR;WACA;;iBAGK,aACd,SAAS,wBACR;WAA2C;;iBAC9B,aAAa,SAAS,sBAAsB;;;;cCb/C;;;;;;;;;;;cA6CA,kCAAkC;;UAe9B;;WAEN,QAAQ;;WAER;;WAEA;;WAEA;;WAEA,wBAAwB;;WAExB,kBAAkB;;WAElB;WACA;WACA;WACA;WACA;WACA;WACA;WACA,cAAc;WACd,eAAe,WAAW;;;;;;;;;;iBA0OrB,uBACd,SAAS,iCACR;;;;;;;;;;iBAaa,sBACd,SAAS,iCACR;WAA+C"}
package/dist/index.js CHANGED
@@ -1,13 +1,32 @@
1
- import { defineModelProviderPlugin } from "@alvin0/ai-agent-sdk-core/provider";
2
- import { createHttpProvider, createRuntimeHttpProvider } from "@alvin0/ai-agent-sdk-provider-http";
1
+ import { defineEmbeddingProviderPlugin, defineModelProviderPlugin } from "@alvin0/ai-agent-sdk-core/provider";
2
+ import { captureTransportConnection, createHttpProvider, createModelContextPolicy, createRuntimeHttpProvider, embeddingCatalogModelInfo, 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
+ import { assertUsableApiKey, resolveRetryPolicy } from "@alvin0/ai-agent-sdk-core";
5
+ import { EMBEDDING_ERROR_CODES, EmbeddingAdapter, EmbeddingError, defaultEmbeddingProfile, deriveSpaceId, resolveBatchLimits, validateBatchResult } from "@alvin0/ai-agent-sdk-core/embedding";
4
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
5
23
  //#region src/adapter.ts
6
24
  /** Google Gemini API v1beta base. The protocol appends only `/interactions`. */
7
25
  const GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
8
26
  function geminiAdapter(options) {
9
27
  return createHttpProvider({
10
28
  displayName: "Gemini",
29
+ describeModel: geminiContextPolicy(options),
11
30
  protocol: geminiInteractionsProtocol$1,
12
31
  baseUrl: options.baseUrl ?? "https://generativelanguage.googleapis.com/v1beta",
13
32
  auth: {
@@ -19,7 +38,7 @@ function geminiAdapter(options) {
19
38
  dialect: dialectOf(options),
20
39
  ...options.models === void 0 ? {} : { models: options.models },
21
40
  defaultMaxTokens: options.defaultMaxTokens ?? 8192,
22
- defaultContextWindow: options.defaultContextWindow ?? 1e6,
41
+ defaultContextWindow: options.defaultContextWindow ?? 2e5,
23
42
  ...options.streamIdleTimeoutMs === void 0 ? {} : { streamIdleTimeoutMs: options.streamIdleTimeoutMs },
24
43
  ...transportLimits(options),
25
44
  ...options.retryPolicy === void 0 ? {} : { retryPolicy: options.retryPolicy },
@@ -57,6 +76,7 @@ function legacyGeminiPlugin(options) {
57
76
  }
58
77
  function createRuntimeGeminiAdapter(options) {
59
78
  return createRuntimeHttpProvider({
79
+ describeModel: geminiContextPolicy(options),
60
80
  displayName: "Gemini",
61
81
  protocol: geminiInteractionsProtocol$1,
62
82
  baseUrl: options.baseUrl ?? "https://generativelanguage.googleapis.com/v1beta",
@@ -69,7 +89,7 @@ function createRuntimeGeminiAdapter(options) {
69
89
  dialect: dialectOf(options),
70
90
  ...options.models === void 0 ? {} : { models: options.models },
71
91
  defaultMaxTokens: options.defaultMaxTokens ?? 8192,
72
- defaultContextWindow: options.defaultContextWindow ?? 1e6,
92
+ defaultContextWindow: options.defaultContextWindow ?? 2e5,
73
93
  ...options.streamIdleTimeoutMs === void 0 ? {} : { streamIdleTimeoutMs: options.streamIdleTimeoutMs },
74
94
  ...transportLimits(options),
75
95
  ...options.retryPolicy === void 0 ? {} : { retryPolicy: options.retryPolicy },
@@ -109,5 +129,406 @@ function transportLimits(options) {
109
129
  }
110
130
 
111
131
  //#endregion
112
- export { GEMINI_BASE_URL, geminiAdapter, geminiInteractionsProtocol, geminiPlugin };
132
+ //#region src/embedding.ts
133
+ /**
134
+ * `Gemini_Embedding_Adapter`: Gemini's `batchEmbedContents` endpoint expressed as
135
+ * an `Embedding_Adapter`.
136
+ *
137
+ * Deliberately separate from `./adapter.ts`: nothing here imports
138
+ * `geminiInteractionsProtocol`, and nothing there imports this module. Generation
139
+ * and embedding share the same credential shape and the same HTTP transport, and
140
+ * that is all they share — a request vocabulary in common would be the conflation
141
+ * Requirement 14.2 rules out.
142
+ *
143
+ * Three Gemini specifics shape this file, and each one is stated rather than
144
+ * inferred:
145
+ *
146
+ * - **Purpose is a wire parameter.** `taskType` exists, so `purpose` translates
147
+ * into it — but only when the route DECLARES that mechanism. A route that
148
+ * declares nothing gets the text sent verbatim and no invented parameter
149
+ * (Requirement 7.3).
150
+ * - **A narrower vector is a model mechanism plus a recorded step.**
151
+ * `outputDimensionality` asks the model for a narrower vector; Gemini
152
+ * documents that a narrower vector is no longer unit-length, so the profile
153
+ * declares `postProcessing: { kind: 'l2-renormalize', revision: '1' }` and this
154
+ * adapter performs exactly that step. Nothing here slices or pads a vector
155
+ * (Requirement 9.8).
156
+ * - **Mapping is positional.** `batchEmbedContents` returns
157
+ * `{ embeddings: [{ values }] }` with no index, so the index is assigned by
158
+ * this adapter from request order, and the count is checked rather than
159
+ * assumed.
160
+ *
161
+ * @module ai-agent-sdk/providers/gemini/embedding
162
+ */
163
+ /** Google Generative Language API v1beta base; the adapter appends the model path. */
164
+ const GEMINI_EMBEDDING_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
165
+ /** Name used in every diagnostic this module raises. */
166
+ const DISPLAY_NAME = "Gemini";
167
+ /** Header layer the JSON pipeline owns for this route. */
168
+ const TRANSPORT_HEADERS = Object.freeze({
169
+ "content-type": "application/json",
170
+ accept: "application/json"
171
+ });
172
+ /** Revision of the `l2-renormalize` step this adapter performs. */
173
+ const POST_PROCESSING_REVISION = "1";
174
+ /** Applied when neither the caller nor the catalog says otherwise. */
175
+ const DEFAULT_RECIPE_REVISION = "1";
176
+ /** The one mapping from this SDK's purpose vocabulary to Gemini's `taskType`. */
177
+ const TASK_TYPES = Object.freeze({
178
+ "retrieval-query": "RETRIEVAL_QUERY",
179
+ "retrieval-document": "RETRIEVAL_DOCUMENT"
180
+ });
181
+ const NEVER_ABORTED_SIGNAL = new AbortController().signal;
182
+ const NULL_LOGGER = Object.freeze({
183
+ child: () => NULL_LOGGER,
184
+ trace: () => void 0,
185
+ debug: () => void 0,
186
+ info: () => void 0,
187
+ warn: () => void 0,
188
+ error: () => void 0,
189
+ fatal: () => void 0
190
+ });
191
+ /**
192
+ * The Gemini embedding generations this package declares.
193
+ *
194
+ * Unlike the generation catalog, an embedding catalog entry cannot be omitted
195
+ * entirely: `compatibilityIdentity` is a claim about an embedding space that only
196
+ * the route can make, and Requirement 14.6 puts that claim on this adapter. The
197
+ * identity names the GENERATION, so `gemini-embedding-001` and a future
198
+ * `gemini-embedding-2` are detected as incompatible even at equal width. Pass
199
+ * `models` to override or extend this list.
200
+ */
201
+ const GEMINI_EMBEDDING_MODELS = Object.freeze([Object.freeze({
202
+ id: "gemini-embedding-001",
203
+ name: "Gemini Embedding 001",
204
+ description: "Gemini text embedding with selectable output dimensionality.",
205
+ dimensions: Object.freeze([
206
+ 3072,
207
+ 1536,
208
+ 768
209
+ ]),
210
+ defaultDimensions: 3072,
211
+ maxInputTokens: 2048,
212
+ maxBatchItems: 100,
213
+ purposeHandling: Object.freeze({
214
+ kind: "wire-parameter",
215
+ parameter: "taskType"
216
+ }),
217
+ compatibilityIdentity: "google:gemini-embedding-001"
218
+ })]);
219
+ /**
220
+ * The Gemini `batchEmbedContents` adapter.
221
+ *
222
+ * Every metadata method takes the route key, so one instance serves every route
223
+ * the plugin claims. Connection facts are captured once per operation in
224
+ * {@link prepareEmbeddingCall}, which is what keeps a credential from travelling
225
+ * to a URL from a different configuration generation.
226
+ */
227
+ var GeminiEmbeddingAdapter = class extends EmbeddingAdapter {
228
+ #options;
229
+ #models;
230
+ #retryPolicy;
231
+ constructor(options) {
232
+ super();
233
+ this.#options = Object.freeze({ ...options });
234
+ this.#models = Object.freeze([...options.models ?? GEMINI_EMBEDDING_MODELS]);
235
+ this.#retryPolicy = resolveRetryPolicy(options.retryPolicy, "retryPolicy");
236
+ }
237
+ providerInfo(provider) {
238
+ return {
239
+ id: provider,
240
+ name: DISPLAY_NAME
241
+ };
242
+ }
243
+ providerRetryPolicy(_provider) {
244
+ return this.#retryPolicy;
245
+ }
246
+ listEmbeddingModels(provider, _signal) {
247
+ return Promise.resolve(Object.freeze(this.#models.map((model) => embeddingCatalogModelInfo(provider, model))));
248
+ }
249
+ resolveEmbeddingModel(provider, model, _signal) {
250
+ return Promise.resolve(resolvedEmbeddingCatalogModelInfo(provider, model, this.#models));
251
+ }
252
+ /**
253
+ * Declare the real Gemini profile instead of accepting the generic default.
254
+ *
255
+ * Two statements the default cannot make: the compatibility identity is the
256
+ * route's declaration about a GENERATION, and asking for a narrower vector adds
257
+ * a recorded `l2-renormalize` step which this adapter then actually performs.
258
+ */
259
+ embeddingProfile(model, request) {
260
+ const base = defaultEmbeddingProfile(model, request);
261
+ const postProcessing = postProcessingFor(model, base.dimensions);
262
+ return Object.freeze({
263
+ ...base,
264
+ compatibilityIdentity: model.compatibilityIdentity.state === "supported" ? model.compatibilityIdentity.value : `google:${model.id}`,
265
+ normalization: postProcessing !== void 0 ? "unit-l2" : model.normalization.state === "supported" ? model.normalization.value : "unknown",
266
+ documentRecipeRevision: request.documentRecipeRevision ?? DEFAULT_RECIPE_REVISION,
267
+ queryRecipeRevision: request.queryRecipeRevision ?? DEFAULT_RECIPE_REVISION,
268
+ ...postProcessing === void 0 ? {} : { postProcessing }
269
+ });
270
+ }
271
+ /**
272
+ * Capture the endpoint, the credential and the catalog together, once.
273
+ *
274
+ * The connection is read here and never re-read per batch, so every batch of
275
+ * one `Logical_Call` goes out through the same generation of configuration
276
+ * that its dimensions were checked against.
277
+ */
278
+ async prepareEmbeddingCall(provider, model, options, signal, context) {
279
+ const resolved = await this.resolveEmbeddingModel(provider, model, signal);
280
+ const profile = this.embeddingProfile(resolved, options);
281
+ const connection = await this.#connect(signal, context);
282
+ return Object.freeze({
283
+ model: resolved,
284
+ profile,
285
+ spaceId: deriveSpaceId(profile),
286
+ limits: resolveBatchLimits(resolved, options.limits),
287
+ embedBatch: (batch, invocation = context) => this.#dispatch(connection, resolved, profile, batch, invocation)
288
+ });
289
+ }
290
+ /**
291
+ * Perform exactly one `batchEmbedContents` request.
292
+ *
293
+ * Usable directly, in which case the catalog and connection are resolved for
294
+ * this batch alone; `prepareEmbeddingCall` is the path that binds one snapshot
295
+ * to a whole logical call.
296
+ */
297
+ async embedBatch(batch, context) {
298
+ const resolved = await this.resolveEmbeddingModel(batch.provider, batch.model, batch.signal);
299
+ const profile = this.embeddingProfile(resolved, { ...batch.dimensions === void 0 ? {} : { dimensions: batch.dimensions } });
300
+ const connection = await this.#connect(batch.signal, context);
301
+ return await this.#dispatch(connection, resolved, profile, batch, context);
302
+ }
303
+ /** Resolve the credential and bounds into one frozen snapshot. */
304
+ async #connect(signal, context) {
305
+ const options = this.#options;
306
+ const apiKey = assertUsableApiKey(await resolveCredential(options.apiKey, signal, context), DISPLAY_NAME, "the `apiKey` option");
307
+ return captureTransportConnection({
308
+ baseUrl: options.baseUrl ?? "https://generativelanguage.googleapis.com/v1beta",
309
+ headers: Object.freeze({ "x-goog-api-key": apiKey }),
310
+ models: this.#models,
311
+ retryPolicy: this.#retryPolicy,
312
+ ...options.allowInsecureHttp === void 0 ? {} : { allowInsecureHttp: options.allowInsecureHttp },
313
+ ...options.requestTimeoutMs === void 0 ? {} : { requestTimeoutMs: options.requestTimeoutMs },
314
+ ...options.maxRequestBytes === void 0 ? {} : { maxRequestBytes: options.maxRequestBytes },
315
+ ...options.maxResponseBytes === void 0 ? {} : { maxResponseBytes: options.maxResponseBytes },
316
+ ...options.maxResponseChunks === void 0 ? {} : { maxResponseChunks: options.maxResponseChunks },
317
+ ...options.maxErrorBodyBytes === void 0 ? {} : { maxErrorBodyBytes: options.maxErrorBodyBytes },
318
+ ...options.requestLoggerTimeoutMs === void 0 ? {} : { requestLoggerTimeoutMs: options.requestLoggerTimeoutMs },
319
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch }
320
+ }, TRANSPORT_HEADERS);
321
+ }
322
+ /** One `Provider_Attempt`: build the body, send it, decode the response. */
323
+ async #dispatch(connection, model, profile, batch, context) {
324
+ if (batch.truncation === "allow") throw new EmbeddingError("Gemini batchEmbedContents exposes no truncation parameter", EMBEDDING_ERROR_CODES.TRUNCATION_UNSUPPORTED, {
325
+ provider: batch.provider,
326
+ model: batch.model
327
+ });
328
+ const modelId = bareModelId(batch.model);
329
+ const body = { requests: batch.items.map((item) => embedRequest(item, model, batch, modelId)) };
330
+ const encoded = JSON.stringify(body);
331
+ return decodeBatch(batch, profile, await transportJson({
332
+ connection,
333
+ displayName: DISPLAY_NAME,
334
+ provider: batch.provider,
335
+ model: batch.model,
336
+ path: `/models/${encodeURIComponent(modelId)}:batchEmbedContents`,
337
+ accept: "application/json",
338
+ body: {
339
+ value: body,
340
+ encoded,
341
+ bytes: new TextEncoder().encode(encoded).length
342
+ },
343
+ ...batch.signal === void 0 ? {} : { signal: batch.signal },
344
+ ...context === void 0 ? {} : { context }
345
+ }, (session, payload) => Object.freeze({
346
+ payload,
347
+ ...session.providerRequestId === void 0 ? {} : { providerRequestId: session.providerRequestId }
348
+ })));
349
+ }
350
+ };
351
+ /**
352
+ * Create the Gemini embedding adapter.
353
+ *
354
+ * No I/O happens here: the credential is resolved per operation, not at
355
+ * construction.
356
+ * @param options - route configuration.
357
+ * @returns an adapter registrable under any number of routes.
358
+ */
359
+ function geminiEmbeddingAdapter(options) {
360
+ return new GeminiEmbeddingAdapter(options);
361
+ }
362
+ /**
363
+ * Create the Gemini `Embedding_Provider_Plugin`.
364
+ *
365
+ * Its `kind` is `'embedding-provider-plugin'`, so a generation host never
366
+ * mistakes it for {@link geminiPlugin} and neither plugin needs a version bump
367
+ * because of the other (Requirement 11.1).
368
+ * @param options - route configuration.
369
+ * @returns an inert plugin; registration happens during runtime activation.
370
+ */
371
+ function geminiEmbeddingPlugin(options) {
372
+ const id = options.id ?? "gemini-embedding";
373
+ const routes = Object.freeze([...options.routes ?? [id]]);
374
+ const adapter = geminiEmbeddingAdapter(options);
375
+ return defineEmbeddingProviderPlugin({
376
+ id,
377
+ family: "gemini",
378
+ displayName: DISPLAY_NAME,
379
+ routes,
380
+ ...defaultModelTarget(options.defaultModel, routes),
381
+ setup(registrar) {
382
+ const remove = registrar.registerEmbeddingAdapter(adapter);
383
+ return () => {
384
+ remove();
385
+ };
386
+ }
387
+ });
388
+ }
389
+ /** Resolve a literal key or a credential source, without caching the secret. */
390
+ async function resolveCredential(apiKey, signal, context) {
391
+ if (typeof apiKey === "string") return apiKey;
392
+ return await apiKey.resolve({
393
+ signal: signal ?? NEVER_ABORTED_SIGNAL,
394
+ logger: context?.logger ?? NULL_LOGGER
395
+ });
396
+ }
397
+ /** Accept both `gemini-embedding-001` and the `models/`-prefixed resource name. */
398
+ function bareModelId(model) {
399
+ return model.startsWith("models/") ? model.slice(7) : model;
400
+ }
401
+ /**
402
+ * Build one request element.
403
+ *
404
+ * `taskType` appears only when the route DECLARES a wire parameter for purpose,
405
+ * and it is spelled with the declared parameter name. A route that declares
406
+ * nothing gets the text verbatim — an undeclared parameter would be this adapter
407
+ * inventing a mechanism (Requirement 7.3).
408
+ */
409
+ function embedRequest(item, model, batch, modelId) {
410
+ const purposeHandling = model.purposeHandling;
411
+ const wireParameter = purposeHandling.state === "supported" && purposeHandling.value.kind === "wire-parameter" ? purposeHandling.value.parameter : void 0;
412
+ const width = outputDimensionality(model, batch);
413
+ return {
414
+ model: `models/${modelId}`,
415
+ content: { parts: item.contentParts.map((part) => ({ text: part.text })) },
416
+ ...wireParameter === void 0 ? {} : { [wireParameter]: TASK_TYPES[batch.purpose] },
417
+ ...width === void 0 ? {} : { outputDimensionality: width }
418
+ };
419
+ }
420
+ /**
421
+ * `outputDimensionality` travels only when the route declares selectable widths.
422
+ *
423
+ * With an `unknown` declaration there is nothing saying the parameter exists, and
424
+ * sending it anyway would make a capability claim on the route's behalf
425
+ * (Requirement 14.4).
426
+ */
427
+ function outputDimensionality(model, batch) {
428
+ if (batch.dimensions === void 0) return void 0;
429
+ return model.dimensions.state === "supported" ? batch.dimensions : void 0;
430
+ }
431
+ /**
432
+ * The recorded step a narrower-than-native vector needs.
433
+ *
434
+ * Gemini documents that only the native width comes back unit-length, so a
435
+ * narrower request declares `l2-renormalize` in the profile and this adapter
436
+ * performs exactly that. It is NOT a slice or a pad: the model produced the
437
+ * narrower vector itself (Requirement 9.8).
438
+ */
439
+ function postProcessingFor(model, dimensions) {
440
+ if (model.defaultDimensions.state !== "supported") return void 0;
441
+ const native = model.defaultDimensions.value;
442
+ if (dimensions <= 0 || dimensions >= native) return void 0;
443
+ return Object.freeze({
444
+ kind: "l2-renormalize",
445
+ revision: POST_PROCESSING_REVISION
446
+ });
447
+ }
448
+ /**
449
+ * Turn one response into vectors, positionally, with the count checked.
450
+ *
451
+ * Order: structural shape, then count, then the SHARED
452
+ * {@link validateBatchResult} — so the same malformed response yields the same
453
+ * code here as it does for any other provider — and only then the recorded
454
+ * post-processing step.
455
+ */
456
+ function decodeBatch(batch, profile, received) {
457
+ const embeddings = readEmbeddings(batch, received.payload);
458
+ if (embeddings.length !== batch.items.length) throw new EmbeddingError(`Gemini returned ${embeddings.length} embeddings for ${batch.items.length} inputs`, EMBEDDING_ERROR_CODES.VECTOR_COUNT_MISMATCH, {
459
+ provider: batch.provider,
460
+ model: batch.model
461
+ });
462
+ const vectors = embeddings.map((embedding, position) => Object.freeze({
463
+ index: batch.items[position].index,
464
+ values: readValues(batch, embedding, batch.items[position].index)
465
+ }));
466
+ const raw = Object.freeze({
467
+ vectors: Object.freeze(vectors),
468
+ ...received.providerRequestId === void 0 ? {} : { providerRequestId: received.providerRequestId }
469
+ });
470
+ validateBatchResult(batch, raw);
471
+ return applyPostProcessing(raw, profile);
472
+ }
473
+ /** Read `embeddings[]`, refusing any other shape rather than guessing at it. */
474
+ function readEmbeddings(batch, payload) {
475
+ if (typeof payload !== "object" || payload === null) throw malformed(batch, "Gemini response is not a JSON object");
476
+ const embeddings = Reflect.get(payload, "embeddings");
477
+ if (!Array.isArray(embeddings)) throw malformed(batch, "Gemini response carries no embeddings array");
478
+ return embeddings;
479
+ }
480
+ /** Read one `values[]`, leaving every number exactly as the provider sent it. */
481
+ function readValues(batch, embedding, index) {
482
+ if (typeof embedding !== "object" || embedding === null) throw malformed(batch, "Gemini embedding entry is not an object", index);
483
+ const values = Reflect.get(embedding, "values");
484
+ if (!Array.isArray(values)) throw malformed(batch, "Gemini embedding entry carries no values array", index);
485
+ return Object.freeze([...values]);
486
+ }
487
+ /** One place the structural-failure code is spelled. */
488
+ function malformed(batch, message, index) {
489
+ return new EmbeddingError(message, EMBEDDING_ERROR_CODES.RESPONSE_MALFORMED, {
490
+ provider: batch.provider,
491
+ model: batch.model,
492
+ ...index === void 0 ? {} : { itemIndexes: [index] }
493
+ });
494
+ }
495
+ /**
496
+ * Perform the step the profile declares, and nothing else.
497
+ *
498
+ * A profile with no `postProcessing` returns the provider's values untouched, so
499
+ * the vectors a caller receives are faithful to what came back (Property 22). A
500
+ * zero vector has no direction to preserve, so it is passed through rather than
501
+ * turned into `NaN`.
502
+ */
503
+ function applyPostProcessing(result, profile) {
504
+ if (profile.postProcessing?.kind !== "l2-renormalize") return result;
505
+ return Object.freeze({
506
+ ...result,
507
+ vectors: Object.freeze(result.vectors.map((vector) => Object.freeze({
508
+ ...vector,
509
+ values: l2Renormalize(vector.values)
510
+ })))
511
+ });
512
+ }
513
+ /** Scale a vector to unit L2 length. */
514
+ function l2Renormalize(values) {
515
+ let sum = 0;
516
+ for (const value of values) sum += value * value;
517
+ const norm = Math.sqrt(sum);
518
+ if (!Number.isFinite(norm) || norm === 0) return values;
519
+ return Object.freeze(values.map((value) => value / norm));
520
+ }
521
+ /** A string default model needs exactly one route to belong to. */
522
+ function defaultModelTarget(value, routes) {
523
+ if (value === void 0) return {};
524
+ if (typeof value !== "string") return { defaultModel: value };
525
+ if (routes.length !== 1) throw new TypeError("A string defaultModel requires exactly one Gemini embedding route");
526
+ return { defaultModel: Object.freeze({
527
+ provider: routes[0],
528
+ id: value
529
+ }) };
530
+ }
531
+
532
+ //#endregion
533
+ export { GEMINI_BASE_URL, GEMINI_EMBEDDING_BASE_URL, GEMINI_EMBEDDING_MODELS, geminiAdapter, geminiEmbeddingAdapter, geminiEmbeddingPlugin, geminiInteractionsProtocol, geminiPlugin };
113
534
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["geminiInteractionsProtocol"],"sources":["../src/adapter.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 HttpModelAdapter,\n ProviderCatalogModel,\n ProviderRequestLogger,\n} from '@alvin0/ai-agent-sdk-provider-http'\nimport {\n createHttpProvider,\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 /** Advisory catalog. No model ids are built in, so the list cannot become stale. */\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 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 ?? 1_000_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 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 ?? 1_000_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.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"],"mappings":";;;;;;AAuBA,MAAa,kBAAkB;AA6B/B,SAAgB,cAAc,SAAiD;CAC7E,OAAO,mBAAmB;EACxB,aAAa;EACb,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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AAqB,SAAY,CAAC,IAAI,EAAE,kBAAkB,QAAQ,iBAAiB;EAC/F,GAAI,QAAQ,sBAAsB,SAAY,CAAC,IAAI,EAAE,mBAAmB,QAAQ,kBAAkB;EAClG,GAAI,QAAQ,2BAA2B,SAAY,CAAC,IAAI,EAAE,wBAAwB,QAAQ,uBAAuB;EACjH,GAAI,QAAQ,UAAU,SAAY,CAAC,IAAI,EAAE,OAAO,QAAQ,MAAM;CAChE;AACF"}
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 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 /** 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.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 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 /** 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 #models: readonly EmbeddingCatalogModel[]\n readonly #retryPolicy: ResolvedRetryPolicy\n\n constructor(options: GeminiEmbeddingProviderOptions) {\n super()\n this.#options = Object.freeze({ ...options })\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 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({ '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;;;;;ACSA,MAAa,kBAAkB;AA6B/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;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,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"}
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "name": "alvin0 - chaulamdinhai",
5
5
  "email": "chaulamdinhai@gmail.com"
6
6
  },
7
- "version": "0.1.0",
7
+ "version": "0.1.1",
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.0",
42
- "@alvin0/ai-agent-sdk-protocol-gemini-interactions": "^0.1.0"
41
+ "@alvin0/ai-agent-sdk-provider-http": "^0.1.1",
42
+ "@alvin0/ai-agent-sdk-protocol-gemini-interactions": "^0.1.1"
43
43
  },
44
44
  "peerDependencies": {
45
- "@alvin0/ai-agent-sdk-core": "^0.1.0"
45
+ "@alvin0/ai-agent-sdk-core": "^0.1.1"
46
46
  },
47
47
  "devDependencies": {
48
- "@alvin0/ai-agent-sdk-core": "^0.1.0",
49
- "@alvin0/ai-agent-sdk-testkit": "^0.1.0",
48
+ "@alvin0/ai-agent-sdk-core": "^0.1.1",
49
+ "@alvin0/ai-agent-sdk-testkit": "^0.1.1",
50
50
  "@arethetypeswrong/cli": "0.18.5",
51
51
  "playwright": "1.62.1",
52
52
  "publint": "0.3.24",
@@ -67,6 +67,7 @@
67
67
  "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true});require('node:fs').rmSync('artifacts',{recursive:true,force:true})\"",
68
68
  "typecheck": "tsc --noEmit",
69
69
  "test": "vitest run --config vitest.config.ts",
70
+ "test:integration": "vitest run --config vitest.integration.config.ts",
70
71
  "pack": "pnpm pack --pack-destination artifacts",
71
72
  "test:pack": "node ../../scripts/test-packed-provider.mts provider-gemini",
72
73
  "check:publint": "publint",