@alvin0/ai-agent-sdk-provider-gemini 0.1.10 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -83,20 +83,7 @@ declare function geminiPlugin(options: GeminiProviderOptions): ComposableModelPr
83
83
  };
84
84
  declare function geminiPlugin(options: GeminiPluginOptions): ModelProviderPlugin;
85
85
  //#endregion
86
- //#region src/embedding.d.ts
87
- /** Google Generative Language API v1beta base; the adapter appends the model path. */
88
- declare const GEMINI_EMBEDDING_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
89
- /**
90
- * The Gemini embedding generations this package declares.
91
- *
92
- * Unlike the generation catalog, an embedding catalog entry cannot be omitted
93
- * entirely: `compatibilityIdentity` is a claim about an embedding space that only
94
- * the route can make, and Requirement 14.6 puts that claim on this adapter. The
95
- * identity names the GENERATION, so `gemini-embedding-001` and a future
96
- * `gemini-embedding-2` are detected as incompatible even at equal width. Pass
97
- * `models` to override or extend this list.
98
- */
99
- declare const GEMINI_EMBEDDING_MODELS: readonly EmbeddingCatalogModel[];
86
+ //#region src/embedding-types.d.ts
100
87
  /** Configuration for {@link geminiEmbeddingAdapter} and {@link geminiEmbeddingPlugin}. */
101
88
  interface GeminiEmbeddingProviderOptions {
102
89
  /** Injected key or credential source; universal packages never read the environment. */
@@ -124,6 +111,21 @@ interface GeminiEmbeddingProviderOptions {
124
111
  readonly retryPolicy?: RetryPolicyConfig;
125
112
  readonly fetch?: typeof globalThis.fetch;
126
113
  }
114
+ //#endregion
115
+ //#region src/embedding.d.ts
116
+ /** Google Generative Language API v1beta base; the adapter appends the model path. */
117
+ declare const GEMINI_EMBEDDING_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
118
+ /**
119
+ * The Gemini embedding generations this package declares.
120
+ *
121
+ * Unlike the generation catalog, an embedding catalog entry cannot be omitted
122
+ * entirely: `compatibilityIdentity` is a claim about an embedding space that only
123
+ * the route can make, and Requirement 14.6 puts that claim on this adapter. The
124
+ * identity names the GENERATION, so `gemini-embedding-001` and a future
125
+ * `gemini-embedding-2` are detected as incompatible even at equal width. Pass
126
+ * `models` to override or extend this list.
127
+ */
128
+ declare const GEMINI_EMBEDDING_MODELS: readonly EmbeddingCatalogModel[];
127
129
  /**
128
130
  * Create the Gemini embedding adapter.
129
131
  *
@@ -1 +1 @@
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;;;;;EAKA,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;;;;cC/C/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"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/adapter.ts","../src/embedding-types.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;;;;;EAKA,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;;;;UCjH3C;;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;;;;;cCwCxB;;;;;;;;;;;cAqBA,kCAAkC;;;;;;;;;iBAwN/B,uBACd,SAAS,iCACR;;;;;;;;;;iBAaa,sBACd,SAAS,iCACR;WAA+C"}
package/dist/index.js CHANGED
@@ -115,16 +115,199 @@ function transportLimits(options) {
115
115
  return {
116
116
  ...options.allowInsecureHttp === void 0 ? {} : { allowInsecureHttp: options.allowInsecureHttp },
117
117
  headers: endpointHeaders(options.headers),
118
+ ...requestOverrides(options),
119
+ ...options.requestTimeoutMs === void 0 ? {} : { requestTimeoutMs: options.requestTimeoutMs },
120
+ ...options.maxRequestBytes === void 0 ? {} : { maxRequestBytes: options.maxRequestBytes },
121
+ ...options.maxResponseBytes === void 0 ? {} : { maxResponseBytes: options.maxResponseBytes },
122
+ ...options.maxResponseChunks === void 0 ? {} : { maxResponseChunks: options.maxResponseChunks },
123
+ ...options.maxSseEvents === void 0 ? {} : { maxSseEvents: options.maxSseEvents },
124
+ ...options.maxSseEventChars === void 0 ? {} : { maxSseEventChars: options.maxSseEventChars },
125
+ ...options.maxErrorBodyBytes === void 0 ? {} : { maxErrorBodyBytes: options.maxErrorBodyBytes },
126
+ ...options.requestLoggerTimeoutMs === void 0 ? {} : { requestLoggerTimeoutMs: options.requestLoggerTimeoutMs }
127
+ };
128
+ }
129
+ function requestOverrides(options) {
130
+ return {
131
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch },
118
132
  ...options.path === void 0 ? {} : { path: options.path },
119
133
  ...options.query === void 0 ? {} : { query: options.query },
120
134
  ...options.body === void 0 ? {} : { body: options.body },
121
- ...options.transformRequest === void 0 ? {} : { transformRequest: options.transformRequest },
135
+ ...options.transformRequest === void 0 ? {} : { transformRequest: options.transformRequest }
136
+ };
137
+ }
138
+
139
+ //#endregion
140
+ //#region src/embedding-support.ts
141
+ /** Revision of the `l2-renormalize` step this adapter performs. */
142
+ const POST_PROCESSING_REVISION = "1";
143
+ /** The one mapping from this SDK's purpose vocabulary to Gemini's `taskType`. */
144
+ const TASK_TYPES = Object.freeze({
145
+ "retrieval-query": "RETRIEVAL_QUERY",
146
+ "retrieval-document": "RETRIEVAL_DOCUMENT"
147
+ });
148
+ const NEVER_ABORTED_SIGNAL = new AbortController().signal;
149
+ const NULL_LOGGER = Object.freeze({
150
+ child: () => NULL_LOGGER,
151
+ trace: () => void 0,
152
+ debug: () => void 0,
153
+ info: () => void 0,
154
+ warn: () => void 0,
155
+ error: () => void 0,
156
+ fatal: () => void 0
157
+ });
158
+ /** Resolve a literal key or a credential source, without caching the secret. */
159
+ async function resolveCredential(apiKey, signal, context) {
160
+ if (typeof apiKey === "string") return apiKey;
161
+ return await apiKey.resolve({
162
+ signal: signal ?? NEVER_ABORTED_SIGNAL,
163
+ logger: context?.logger ?? NULL_LOGGER
164
+ });
165
+ }
166
+ /** Accept both `gemini-embedding-001` and the `models/`-prefixed resource name. */
167
+ function bareModelId(model) {
168
+ return model.startsWith("models/") ? model.slice(7) : model;
169
+ }
170
+ /**
171
+ * Build one request element.
172
+ *
173
+ * `taskType` appears only when the route DECLARES a wire parameter for purpose,
174
+ * and it is spelled with the declared parameter name. A route that declares
175
+ * nothing gets the text verbatim — an undeclared parameter would be this adapter
176
+ * inventing a mechanism (Requirement 7.3).
177
+ */
178
+ function embedRequest(item, model, batch, modelId) {
179
+ const purposeHandling = model.purposeHandling;
180
+ const wireParameter = purposeHandling.state === "supported" && purposeHandling.value.kind === "wire-parameter" ? purposeHandling.value.parameter : void 0;
181
+ const width = outputDimensionality(model, batch);
182
+ return {
183
+ model: `models/${modelId}`,
184
+ content: { parts: item.contentParts.map((part) => ({ text: part.text })) },
185
+ ...wireParameter === void 0 ? {} : { [wireParameter]: TASK_TYPES[batch.purpose] },
186
+ ...width === void 0 ? {} : { outputDimensionality: width }
187
+ };
188
+ }
189
+ /**
190
+ * `outputDimensionality` travels only when the route declares selectable widths.
191
+ *
192
+ * With an `unknown` declaration there is nothing saying the parameter exists, and
193
+ * sending it anyway would make a capability claim on the route's behalf
194
+ * (Requirement 14.4).
195
+ */
196
+ function outputDimensionality(model, batch) {
197
+ if (batch.dimensions === void 0) return void 0;
198
+ return model.dimensions.state === "supported" ? batch.dimensions : void 0;
199
+ }
200
+ /**
201
+ * The recorded step a narrower-than-native vector needs.
202
+ *
203
+ * Gemini documents that only the native width comes back unit-length, so a
204
+ * narrower request declares `l2-renormalize` in the profile and this adapter
205
+ * performs exactly that. It is NOT a slice or a pad: the model produced the
206
+ * narrower vector itself (Requirement 9.8).
207
+ */
208
+ function postProcessingFor(model, dimensions) {
209
+ if (model.defaultDimensions.state !== "supported") return void 0;
210
+ const native = model.defaultDimensions.value;
211
+ if (dimensions <= 0 || dimensions >= native) return void 0;
212
+ return Object.freeze({
213
+ kind: "l2-renormalize",
214
+ revision: POST_PROCESSING_REVISION
215
+ });
216
+ }
217
+ /**
218
+ * Turn one response into vectors, positionally, with the count checked.
219
+ *
220
+ * Order: structural shape, then count, then the SHARED
221
+ * {@link validateBatchResult} — so the same malformed response yields the same
222
+ * code here as it does for any other provider — and only then the recorded
223
+ * post-processing step.
224
+ */
225
+ function decodeBatch(batch, profile, received) {
226
+ const embeddings = readEmbeddings(batch, received.payload);
227
+ 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, {
228
+ provider: batch.provider,
229
+ model: batch.model
230
+ });
231
+ const vectors = embeddings.map((embedding, position) => Object.freeze({
232
+ index: batch.items[position].index,
233
+ values: readValues(batch, embedding, batch.items[position].index)
234
+ }));
235
+ const raw = Object.freeze({
236
+ vectors: Object.freeze(vectors),
237
+ ...received.providerRequestId === void 0 ? {} : { providerRequestId: received.providerRequestId }
238
+ });
239
+ validateBatchResult(batch, raw);
240
+ return applyPostProcessing(raw, profile);
241
+ }
242
+ /** Read `embeddings[]`, refusing any other shape rather than guessing at it. */
243
+ function readEmbeddings(batch, payload) {
244
+ if (typeof payload !== "object" || payload === null) throw malformed(batch, "Gemini response is not a JSON object");
245
+ const embeddings = Reflect.get(payload, "embeddings");
246
+ if (!Array.isArray(embeddings)) throw malformed(batch, "Gemini response carries no embeddings array");
247
+ return embeddings;
248
+ }
249
+ /** Read one `values[]`, leaving every number exactly as the provider sent it. */
250
+ function readValues(batch, embedding, index) {
251
+ if (typeof embedding !== "object" || embedding === null) throw malformed(batch, "Gemini embedding entry is not an object", index);
252
+ const values = Reflect.get(embedding, "values");
253
+ if (!Array.isArray(values)) throw malformed(batch, "Gemini embedding entry carries no values array", index);
254
+ return Object.freeze([...values]);
255
+ }
256
+ /** One place the structural-failure code is spelled. */
257
+ function malformed(batch, message, index) {
258
+ return new EmbeddingError(message, EMBEDDING_ERROR_CODES.RESPONSE_MALFORMED, {
259
+ provider: batch.provider,
260
+ model: batch.model,
261
+ ...index === void 0 ? {} : { itemIndexes: [index] }
262
+ });
263
+ }
264
+ /**
265
+ * Perform the step the profile declares, and nothing else.
266
+ *
267
+ * A profile with no `postProcessing` returns the provider's values untouched, so
268
+ * the vectors a caller receives are faithful to what came back (Property 22). A
269
+ * zero vector has no direction to preserve, so it is passed through rather than
270
+ * turned into `NaN`.
271
+ */
272
+ function applyPostProcessing(result, profile) {
273
+ if (profile.postProcessing?.kind !== "l2-renormalize") return result;
274
+ return Object.freeze({
275
+ ...result,
276
+ vectors: Object.freeze(result.vectors.map((vector) => Object.freeze({
277
+ ...vector,
278
+ values: l2Renormalize(vector.values)
279
+ })))
280
+ });
281
+ }
282
+ /** Scale a vector to unit L2 length. */
283
+ function l2Renormalize(values) {
284
+ let sum = 0;
285
+ for (const value of values) sum += value * value;
286
+ const norm = Math.sqrt(sum);
287
+ if (!Number.isFinite(norm) || norm === 0) return values;
288
+ return Object.freeze(values.map((value) => value / norm));
289
+ }
290
+ /** A string default model needs exactly one route to belong to. */
291
+ function defaultModelTarget(value, routes) {
292
+ if (value === void 0) return {};
293
+ if (typeof value !== "string") return { defaultModel: value };
294
+ if (routes.length !== 1) throw new TypeError("A string defaultModel requires exactly one Gemini embedding route");
295
+ return { defaultModel: Object.freeze({
296
+ provider: routes[0],
297
+ id: value
298
+ }) };
299
+ }
300
+ function profileNormalization(model, postProcessing) {
301
+ if (postProcessing !== void 0) return "unit-l2";
302
+ return model.normalization.state === "supported" ? model.normalization.value : "unknown";
303
+ }
304
+ function embeddingTransportOptions(options) {
305
+ return {
306
+ ...options.allowInsecureHttp === void 0 ? {} : { allowInsecureHttp: options.allowInsecureHttp },
122
307
  ...options.requestTimeoutMs === void 0 ? {} : { requestTimeoutMs: options.requestTimeoutMs },
123
308
  ...options.maxRequestBytes === void 0 ? {} : { maxRequestBytes: options.maxRequestBytes },
124
309
  ...options.maxResponseBytes === void 0 ? {} : { maxResponseBytes: options.maxResponseBytes },
125
310
  ...options.maxResponseChunks === void 0 ? {} : { maxResponseChunks: options.maxResponseChunks },
126
- ...options.maxSseEvents === void 0 ? {} : { maxSseEvents: options.maxSseEvents },
127
- ...options.maxSseEventChars === void 0 ? {} : { maxSseEventChars: options.maxSseEventChars },
128
311
  ...options.maxErrorBodyBytes === void 0 ? {} : { maxErrorBodyBytes: options.maxErrorBodyBytes },
129
312
  ...options.requestLoggerTimeoutMs === void 0 ? {} : { requestLoggerTimeoutMs: options.requestLoggerTimeoutMs },
130
313
  ...options.fetch === void 0 ? {} : { fetch: options.fetch }
@@ -172,25 +355,6 @@ const TRANSPORT_HEADERS = Object.freeze({
172
355
  "content-type": "application/json",
173
356
  accept: "application/json"
174
357
  });
175
- /** Revision of the `l2-renormalize` step this adapter performs. */
176
- const POST_PROCESSING_REVISION = "1";
177
- /** Applied when neither the caller nor the catalog says otherwise. */
178
- const DEFAULT_RECIPE_REVISION = "1";
179
- /** The one mapping from this SDK's purpose vocabulary to Gemini's `taskType`. */
180
- const TASK_TYPES = Object.freeze({
181
- "retrieval-query": "RETRIEVAL_QUERY",
182
- "retrieval-document": "RETRIEVAL_DOCUMENT"
183
- });
184
- const NEVER_ABORTED_SIGNAL = new AbortController().signal;
185
- const NULL_LOGGER = Object.freeze({
186
- child: () => NULL_LOGGER,
187
- trace: () => void 0,
188
- debug: () => void 0,
189
- info: () => void 0,
190
- warn: () => void 0,
191
- error: () => void 0,
192
- fatal: () => void 0
193
- });
194
358
  /**
195
359
  * The Gemini embedding generations this package declares.
196
360
  *
@@ -267,9 +431,9 @@ var GeminiEmbeddingAdapter = class extends EmbeddingAdapter {
267
431
  return Object.freeze({
268
432
  ...base,
269
433
  compatibilityIdentity: model.compatibilityIdentity.state === "supported" ? model.compatibilityIdentity.value : `google:${model.id}`,
270
- normalization: postProcessing !== void 0 ? "unit-l2" : model.normalization.state === "supported" ? model.normalization.value : "unknown",
271
- documentRecipeRevision: request.documentRecipeRevision ?? DEFAULT_RECIPE_REVISION,
272
- queryRecipeRevision: request.queryRecipeRevision ?? DEFAULT_RECIPE_REVISION,
434
+ normalization: profileNormalization(model, postProcessing),
435
+ documentRecipeRevision: request.documentRecipeRevision ?? "1",
436
+ queryRecipeRevision: request.queryRecipeRevision ?? "1",
273
437
  ...postProcessing === void 0 ? {} : { postProcessing }
274
438
  });
275
439
  }
@@ -280,7 +444,8 @@ var GeminiEmbeddingAdapter = class extends EmbeddingAdapter {
280
444
  * one `Logical_Call` goes out through the same generation of configuration
281
445
  * that its dimensions were checked against.
282
446
  */
283
- async prepareEmbeddingCall(provider, model, options, signal, context) {
447
+ async prepareEmbeddingCall(provider, model, options, ...invocation) {
448
+ const [signal, context] = invocation;
284
449
  const resolved = await this.resolveEmbeddingModel(provider, model, signal);
285
450
  const profile = this.embeddingProfile(resolved, options);
286
451
  const connection = await this.#connect(provider, signal, context);
@@ -289,7 +454,10 @@ var GeminiEmbeddingAdapter = class extends EmbeddingAdapter {
289
454
  profile,
290
455
  spaceId: deriveSpaceId(profile),
291
456
  limits: resolveBatchLimits(resolved, options.limits),
292
- embedBatch: (batch, invocation = context) => this.#dispatch(connection, resolved, profile, batch, invocation)
457
+ embedBatch: (batch, invocation = context) => this.#dispatch(connection, {
458
+ model: resolved,
459
+ profile
460
+ }, batch, invocation)
293
461
  });
294
462
  }
295
463
  /**
@@ -303,7 +471,10 @@ var GeminiEmbeddingAdapter = class extends EmbeddingAdapter {
303
471
  const resolved = await this.resolveEmbeddingModel(batch.provider, batch.model, batch.signal);
304
472
  const profile = this.embeddingProfile(resolved, { ...batch.dimensions === void 0 ? {} : { dimensions: batch.dimensions } });
305
473
  const connection = await this.#connect(batch.provider, batch.signal, context);
306
- return await this.#dispatch(connection, resolved, profile, batch, context);
474
+ return await this.#dispatch(connection, {
475
+ model: resolved,
476
+ profile
477
+ }, batch, context);
307
478
  }
308
479
  /** Resolve the credential and bounds into one frozen snapshot. */
309
480
  async #connect(provider, signal, context) {
@@ -322,18 +493,12 @@ var GeminiEmbeddingAdapter = class extends EmbeddingAdapter {
322
493
  }),
323
494
  models: this.#models,
324
495
  retryPolicy: this.#retryPolicy,
325
- ...options.allowInsecureHttp === void 0 ? {} : { allowInsecureHttp: options.allowInsecureHttp },
326
- ...options.requestTimeoutMs === void 0 ? {} : { requestTimeoutMs: options.requestTimeoutMs },
327
- ...options.maxRequestBytes === void 0 ? {} : { maxRequestBytes: options.maxRequestBytes },
328
- ...options.maxResponseBytes === void 0 ? {} : { maxResponseBytes: options.maxResponseBytes },
329
- ...options.maxResponseChunks === void 0 ? {} : { maxResponseChunks: options.maxResponseChunks },
330
- ...options.maxErrorBodyBytes === void 0 ? {} : { maxErrorBodyBytes: options.maxErrorBodyBytes },
331
- ...options.requestLoggerTimeoutMs === void 0 ? {} : { requestLoggerTimeoutMs: options.requestLoggerTimeoutMs },
332
- ...options.fetch === void 0 ? {} : { fetch: options.fetch }
496
+ ...embeddingTransportOptions(options)
333
497
  }, TRANSPORT_HEADERS);
334
498
  }
335
499
  /** One `Provider_Attempt`: build the body, send it, decode the response. */
336
- async #dispatch(connection, model, profile, batch, context) {
500
+ async #dispatch(connection, facts, batch, context) {
501
+ const { model, profile } = facts;
337
502
  if (batch.truncation === "allow") throw new EmbeddingError("Gemini batchEmbedContents exposes no truncation parameter", EMBEDDING_ERROR_CODES.TRUNCATION_UNSUPPORTED, {
338
503
  provider: batch.provider,
339
504
  model: batch.model
@@ -341,7 +506,7 @@ var GeminiEmbeddingAdapter = class extends EmbeddingAdapter {
341
506
  const modelId = bareModelId(batch.model);
342
507
  const body = { requests: batch.items.map((item) => embedRequest(item, model, batch, modelId)) };
343
508
  const encoded = JSON.stringify(body);
344
- return decodeBatch(batch, profile, await transportJson({
509
+ const received = await transportJson({
345
510
  connection,
346
511
  displayName: DISPLAY_NAME,
347
512
  provider: batch.provider,
@@ -358,7 +523,8 @@ var GeminiEmbeddingAdapter = class extends EmbeddingAdapter {
358
523
  }, (session, payload) => Object.freeze({
359
524
  payload,
360
525
  ...session.providerRequestId === void 0 ? {} : { providerRequestId: session.providerRequestId }
361
- })));
526
+ }));
527
+ return decodeBatch(batch, profile, received);
362
528
  }
363
529
  };
364
530
  /**
@@ -399,148 +565,6 @@ function geminiEmbeddingPlugin(options) {
399
565
  }
400
566
  });
401
567
  }
402
- /** Resolve a literal key or a credential source, without caching the secret. */
403
- async function resolveCredential(apiKey, signal, context) {
404
- if (typeof apiKey === "string") return apiKey;
405
- return await apiKey.resolve({
406
- signal: signal ?? NEVER_ABORTED_SIGNAL,
407
- logger: context?.logger ?? NULL_LOGGER
408
- });
409
- }
410
- /** Accept both `gemini-embedding-001` and the `models/`-prefixed resource name. */
411
- function bareModelId(model) {
412
- return model.startsWith("models/") ? model.slice(7) : model;
413
- }
414
- /**
415
- * Build one request element.
416
- *
417
- * `taskType` appears only when the route DECLARES a wire parameter for purpose,
418
- * and it is spelled with the declared parameter name. A route that declares
419
- * nothing gets the text verbatim — an undeclared parameter would be this adapter
420
- * inventing a mechanism (Requirement 7.3).
421
- */
422
- function embedRequest(item, model, batch, modelId) {
423
- const purposeHandling = model.purposeHandling;
424
- const wireParameter = purposeHandling.state === "supported" && purposeHandling.value.kind === "wire-parameter" ? purposeHandling.value.parameter : void 0;
425
- const width = outputDimensionality(model, batch);
426
- return {
427
- model: `models/${modelId}`,
428
- content: { parts: item.contentParts.map((part) => ({ text: part.text })) },
429
- ...wireParameter === void 0 ? {} : { [wireParameter]: TASK_TYPES[batch.purpose] },
430
- ...width === void 0 ? {} : { outputDimensionality: width }
431
- };
432
- }
433
- /**
434
- * `outputDimensionality` travels only when the route declares selectable widths.
435
- *
436
- * With an `unknown` declaration there is nothing saying the parameter exists, and
437
- * sending it anyway would make a capability claim on the route's behalf
438
- * (Requirement 14.4).
439
- */
440
- function outputDimensionality(model, batch) {
441
- if (batch.dimensions === void 0) return void 0;
442
- return model.dimensions.state === "supported" ? batch.dimensions : void 0;
443
- }
444
- /**
445
- * The recorded step a narrower-than-native vector needs.
446
- *
447
- * Gemini documents that only the native width comes back unit-length, so a
448
- * narrower request declares `l2-renormalize` in the profile and this adapter
449
- * performs exactly that. It is NOT a slice or a pad: the model produced the
450
- * narrower vector itself (Requirement 9.8).
451
- */
452
- function postProcessingFor(model, dimensions) {
453
- if (model.defaultDimensions.state !== "supported") return void 0;
454
- const native = model.defaultDimensions.value;
455
- if (dimensions <= 0 || dimensions >= native) return void 0;
456
- return Object.freeze({
457
- kind: "l2-renormalize",
458
- revision: POST_PROCESSING_REVISION
459
- });
460
- }
461
- /**
462
- * Turn one response into vectors, positionally, with the count checked.
463
- *
464
- * Order: structural shape, then count, then the SHARED
465
- * {@link validateBatchResult} — so the same malformed response yields the same
466
- * code here as it does for any other provider — and only then the recorded
467
- * post-processing step.
468
- */
469
- function decodeBatch(batch, profile, received) {
470
- const embeddings = readEmbeddings(batch, received.payload);
471
- 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, {
472
- provider: batch.provider,
473
- model: batch.model
474
- });
475
- const vectors = embeddings.map((embedding, position) => Object.freeze({
476
- index: batch.items[position].index,
477
- values: readValues(batch, embedding, batch.items[position].index)
478
- }));
479
- const raw = Object.freeze({
480
- vectors: Object.freeze(vectors),
481
- ...received.providerRequestId === void 0 ? {} : { providerRequestId: received.providerRequestId }
482
- });
483
- validateBatchResult(batch, raw);
484
- return applyPostProcessing(raw, profile);
485
- }
486
- /** Read `embeddings[]`, refusing any other shape rather than guessing at it. */
487
- function readEmbeddings(batch, payload) {
488
- if (typeof payload !== "object" || payload === null) throw malformed(batch, "Gemini response is not a JSON object");
489
- const embeddings = Reflect.get(payload, "embeddings");
490
- if (!Array.isArray(embeddings)) throw malformed(batch, "Gemini response carries no embeddings array");
491
- return embeddings;
492
- }
493
- /** Read one `values[]`, leaving every number exactly as the provider sent it. */
494
- function readValues(batch, embedding, index) {
495
- if (typeof embedding !== "object" || embedding === null) throw malformed(batch, "Gemini embedding entry is not an object", index);
496
- const values = Reflect.get(embedding, "values");
497
- if (!Array.isArray(values)) throw malformed(batch, "Gemini embedding entry carries no values array", index);
498
- return Object.freeze([...values]);
499
- }
500
- /** One place the structural-failure code is spelled. */
501
- function malformed(batch, message, index) {
502
- return new EmbeddingError(message, EMBEDDING_ERROR_CODES.RESPONSE_MALFORMED, {
503
- provider: batch.provider,
504
- model: batch.model,
505
- ...index === void 0 ? {} : { itemIndexes: [index] }
506
- });
507
- }
508
- /**
509
- * Perform the step the profile declares, and nothing else.
510
- *
511
- * A profile with no `postProcessing` returns the provider's values untouched, so
512
- * the vectors a caller receives are faithful to what came back (Property 22). A
513
- * zero vector has no direction to preserve, so it is passed through rather than
514
- * turned into `NaN`.
515
- */
516
- function applyPostProcessing(result, profile) {
517
- if (profile.postProcessing?.kind !== "l2-renormalize") return result;
518
- return Object.freeze({
519
- ...result,
520
- vectors: Object.freeze(result.vectors.map((vector) => Object.freeze({
521
- ...vector,
522
- values: l2Renormalize(vector.values)
523
- })))
524
- });
525
- }
526
- /** Scale a vector to unit L2 length. */
527
- function l2Renormalize(values) {
528
- let sum = 0;
529
- for (const value of values) sum += value * value;
530
- const norm = Math.sqrt(sum);
531
- if (!Number.isFinite(norm) || norm === 0) return values;
532
- return Object.freeze(values.map((value) => value / norm));
533
- }
534
- /** A string default model needs exactly one route to belong to. */
535
- function defaultModelTarget(value, routes) {
536
- if (value === void 0) return {};
537
- if (typeof value !== "string") return { defaultModel: value };
538
- if (routes.length !== 1) throw new TypeError("A string defaultModel requires exactly one Gemini embedding route");
539
- return { defaultModel: Object.freeze({
540
- provider: routes[0],
541
- id: value
542
- }) };
543
- }
544
568
 
545
569
  //#endregion
546
570
  export { GEMINI_BASE_URL, GEMINI_EMBEDDING_BASE_URL, GEMINI_EMBEDDING_MODELS, geminiAdapter, geminiEmbeddingAdapter, geminiEmbeddingPlugin, geminiInteractionsProtocol, geminiPlugin };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
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 /**\n * How this route's failures are classified as retryable. Classification\n * only: nothing retries until the adapter is wrapped with `withRetry`.\n */\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;AAiE/B,SAAgB,cAAc,SAAiD;CAC7E,OAAO,mBAAmB;EACxB,aAAa,QAAQ,eAAe;EACpC,UAAUA;EACV,SAAS,QAAQ;EACjB,MAAM,OAAO,OAAO;EACpB,SAAS,UAAU,OAAO;EAC1B,GAAI,QAAQ,WAAW,SAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;EACjE,GAAI,QAAQ,qBAAqB,SAAY,CAAC,IAAI,EAAE,kBAAkB,QAAQ,iBAAiB;EAC/F,GAAI,QAAQ,yBAAyB,SAAY,CAAC,IAAI,EAAE,sBAAsB,QAAQ,qBAAqB;EAC3G,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,QAAQ,cAAc;EACtF,GAAI,QAAQ,mBAAmB,SAAY,CAAC,IAAI,EAAE,gBAAgB,QAAQ,eAAe;CAC3F,CAAC;AACH;AAkBA,SAAgB,aACd,SACuF;CACvF,IAAI,CAAC,uBAAuB,OAAO,GAAG,OAAO,mBAAmB,OAAO;CACvE,MAAM,KAAK,QAAQ,MAAM;CACzB,MAAM,SAAS,OAAO,OAAO,CAAC,GAAI,QAAQ,UAAU,CAAC,EAAE,CAAE,CAAC;CAC1D,OAAO,0BAA0B;EAC/B;EACA,QAAQ;EACR,aAAa,QAAQ,eAAe;EACpC;EACA,GAAG,oBAAoB,QAAQ,cAAc,MAAM;EACnD,MAAM,WAAW;GACf,MAAM,SAAS,UAAU,gBAAgB,2B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AO,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-support.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 /**\n * How this route's failures are classified as retryable. Classification\n * only: nothing retries until the adapter is wrapped with `withRetry`.\n */\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 ...requestOverrides(options),\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\n }\n}\n\nfunction requestOverrides(options: GeminiAdapterOptions | GeminiProviderOptions) {\n return {\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\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\n }\n}\n","import {\n type ModelInvocationContext,\n type SdkLogger,\n} from '@alvin0/ai-agent-sdk-core'\nimport {\n EMBEDDING_ERROR_CODES,\n EmbeddingError,\n validateBatchResult,\n type EmbeddingBatchRequest,\n type EmbeddingBatchResult,\n type EmbeddingPostProcessing,\n type EmbeddingProfile,\n type EmbeddingPurpose,\n type EmbeddingVector,\n type ResolvedEmbeddingModelInfo,\n} from '@alvin0/ai-agent-sdk-core/embedding'\nimport {\n type CredentialInput,\n type ModelTarget,\n} from '@alvin0/ai-agent-sdk-core/provider'\n\nimport type { GeminiEmbeddingProviderOptions } from './embedding-types.ts'\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. */\nexport const 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/** 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/** Resolve a literal key or a credential source, without caching the secret. */\nexport async 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. */\nexport function 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 */\nexport function 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 */\nexport function 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 */\nexport function 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. */\nexport function 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\nexport function profileNormalization(model: ResolvedEmbeddingModelInfo,\n postProcessing: EmbeddingPostProcessing | undefined) {\n if (postProcessing !== undefined) return 'unit-l2'\n return model.normalization.state === 'supported' ? model.normalization.value : 'unknown'\n}\n\nexport function embeddingTransportOptions(options: GeminiEmbeddingProviderOptions) {\n return {\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 }\n}\n","import { DEFAULT_RECIPE_REVISION } from './embedding-support.ts'\nimport { resolveCredential, bareModelId, embedRequest, postProcessingFor, decodeBatch, defaultModelTarget,\n profileNormalization, embeddingTransportOptions ,\n} from './embedding-support.ts'\nimport type { GeminiEmbeddingProviderOptions } from './embedding-types.ts'\nexport type { GeminiEmbeddingProviderOptions } from './embedding-types.ts'\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} from '@alvin0/ai-agent-sdk-core'\nimport {\n EMBEDDING_ERROR_CODES,\n EmbeddingAdapter,\n EmbeddingError,\n defaultEmbeddingProfile,\n deriveSpaceId,\n resolveBatchLimits,\n type EmbeddingBatchRequest,\n type EmbeddingBatchResult,\n type EmbeddingModelInfo,\n type EmbeddingProfile,\n type EmbeddingProfileInput,\n type PrepareEmbeddingOptions,\n type PreparedEmbeddingCall,\n type ResolvedEmbeddingModelInfo,\n} from '@alvin0/ai-agent-sdk-core/embedding'\nimport {\n defineEmbeddingProviderPlugin,\n type ComposableEmbeddingProviderPlugin,\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/**\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/**\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: profileNormalization(model, postProcessing),\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 ...invocation: [signal?: AbortSignal, context?: ModelInvocationContext]\n ): Promise<PreparedEmbeddingCall> {\n const [signal, context] = invocation\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, { model: 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, { model: 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 ...embeddingTransportOptions(options),\n }, TRANSPORT_HEADERS)\n }\n\n /** One `Provider_Attempt`: build the body, send it, decode the response. */\n async #dispatch(\n connection: EmbeddingHttpConnection,\n facts: { model: ResolvedEmbeddingModelInfo; profile: EmbeddingProfile },\n batch: EmbeddingBatchRequest,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingBatchResult> {\n const { model, profile } = facts\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"],"mappings":";;;;;;;;AA2BA,MAAa,kBAAkB;AAiE/B,SAAgB,cAAc,SAAiD;CAC7E,OAAO,mBAAmB;EACxB,aAAa,QAAQ,eAAe;EACpC,UAAUA;EACV,SAAS,QAAQ;EACjB,MAAM,OAAO,OAAO;EACpB,SAAS,UAAU,OAAO;EAC1B,GAAI,QAAQ,WAAW,SAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;EACjE,GAAI,QAAQ,qBAAqB,SAAY,CAAC,IAAI,EAAE,kBAAkB,QAAQ,iBAAiB;EAC/F,GAAI,QAAQ,yBAAyB,SAAY,CAAC,IAAI,EAAE,sBAAsB,QAAQ,qBAAqB;EAC3G,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,QAAQ,cAAc;EACtF,GAAI,QAAQ,mBAAmB,SAAY,CAAC,IAAI,EAAE,gBAAgB,QAAQ,eAAe;CAC3F,CAAC;AACH;AAkBA,SAAgB,aACd,SACuF;CACvF,IAAI,CAAC,uBAAuB,OAAO,GAAG,OAAO,mBAAmB,OAAO;CACvE,MAAM,KAAK,QAA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3C;GACA,GAAI,MAAM,WAAW,SAAY,CAAC,IAAI,EAAE,QAAQ,MAAM,OAAO;GAC7D,GAAI,YAAY,SAAY,CAAC,IAAI,EAAE,QAAQ;EAC7C,IAAI,SAAS,YAAY,OAAO,OAAO;GACrC;GACA,GAAI,QAAQ,sBAAsB,SAC9B,CAAC,IACD,EAAE,mBAAmB,QAAQ,kBAAkB;EACrD,CAAC,CAAC;EACF,OAAO,YAAY,OAAO,SAAS,QAAQ;CAC7C;AACF;;;;;;;;;AAUA,SAAgB,uBACd,SACkB;CAClB,OAAO,IAAI,uBAAuB,OAAO;AAC3C;;;;;;;;;;AAWA,SAAgB,sBACd,SACmE;CACnE,MAAM,KAAK,QAAQ,MAAM;CACzB,MAAM,SAAS,OAAO,OAAO,CAAC,GAAI,QAAQ,UAAU,CAAC,EAAE,CAAE,CAAC;CAC1D,MAAM,UAAU,uBAAuB,OAAO;CAC9C,OAAO,8BAA8B;EACnC;EACA,QAAQ;EACR,aAAa;EACb;EACA,GAAG,mBAAmB,QAAQ,cAAc,MAAM;EAClD,MAAM,WAAW;GACf,MAAM,SAAS,UAAU,yBAAyB,OAAO;GACzD,aAAa;IACX,OAAO;GAET;EACF;CACF,CAAC;AACH"}
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.10",
7
+ "version": "0.1.12",
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.10",
42
- "@alvin0/ai-agent-sdk-protocol-gemini-interactions": "^0.1.10"
41
+ "@alvin0/ai-agent-sdk-provider-http": "^0.1.12",
42
+ "@alvin0/ai-agent-sdk-protocol-gemini-interactions": "^0.1.12"
43
43
  },
44
44
  "peerDependencies": {
45
- "@alvin0/ai-agent-sdk-core": "^0.1.10"
45
+ "@alvin0/ai-agent-sdk-core": "^0.1.12"
46
46
  },
47
47
  "devDependencies": {
48
- "@alvin0/ai-agent-sdk-core": "^0.1.10",
49
- "@alvin0/ai-agent-sdk-testkit": "^0.1.10",
48
+ "@alvin0/ai-agent-sdk-core": "^0.1.12",
49
+ "@alvin0/ai-agent-sdk-testkit": "^0.1.12",
50
50
  "@arethetypeswrong/cli": "0.18.5",
51
51
  "playwright": "1.62.1",
52
52
  "publint": "0.3.24",