agentfootprint 9.12.0 → 9.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/adapters/llm/GeminiProvider.js +519 -0
  2. package/dist/adapters/llm/GeminiProvider.js.map +1 -0
  3. package/dist/adapters/llm/contextWindow.js +20 -0
  4. package/dist/adapters/llm/contextWindow.js.map +1 -1
  5. package/dist/adapters/llm/createProvider.js +3 -0
  6. package/dist/adapters/llm/createProvider.js.map +1 -1
  7. package/dist/adapters/llm/googleGenAI.js +109 -0
  8. package/dist/adapters/llm/googleGenAI.js.map +1 -0
  9. package/dist/embedders/index.js +233 -1
  10. package/dist/embedders/index.js.map +1 -1
  11. package/dist/esm/adapters/llm/GeminiProvider.d.ts +204 -0
  12. package/dist/esm/adapters/llm/GeminiProvider.js +514 -0
  13. package/dist/esm/adapters/llm/GeminiProvider.js.map +1 -0
  14. package/dist/esm/adapters/llm/contextWindow.js +20 -0
  15. package/dist/esm/adapters/llm/contextWindow.js.map +1 -1
  16. package/dist/esm/adapters/llm/createProvider.d.ts +4 -1
  17. package/dist/esm/adapters/llm/createProvider.js +3 -0
  18. package/dist/esm/adapters/llm/createProvider.js.map +1 -1
  19. package/dist/esm/adapters/llm/googleGenAI.d.ts +67 -0
  20. package/dist/esm/adapters/llm/googleGenAI.js +105 -0
  21. package/dist/esm/adapters/llm/googleGenAI.js.map +1 -0
  22. package/dist/esm/embedders/index.d.ts +188 -1
  23. package/dist/esm/embedders/index.js +231 -0
  24. package/dist/esm/embedders/index.js.map +1 -1
  25. package/dist/esm/providers.d.ts +3 -0
  26. package/dist/esm/providers.js +2 -0
  27. package/dist/esm/providers.js.map +1 -1
  28. package/dist/providers.js +5 -1
  29. package/dist/providers.js.map +1 -1
  30. package/dist/types/adapters/llm/GeminiProvider.d.ts +205 -0
  31. package/dist/types/adapters/llm/GeminiProvider.d.ts.map +1 -0
  32. package/dist/types/adapters/llm/contextWindow.d.ts.map +1 -1
  33. package/dist/types/adapters/llm/createProvider.d.ts +4 -1
  34. package/dist/types/adapters/llm/createProvider.d.ts.map +1 -1
  35. package/dist/types/adapters/llm/googleGenAI.d.ts +68 -0
  36. package/dist/types/adapters/llm/googleGenAI.d.ts.map +1 -0
  37. package/dist/types/embedders/index.d.ts +188 -1
  38. package/dist/types/embedders/index.d.ts.map +1 -1
  39. package/dist/types/providers.d.ts +3 -0
  40. package/dist/types/providers.d.ts.map +1 -1
  41. package/package.json +7 -1
@@ -0,0 +1,514 @@
1
+ /**
2
+ * GeminiProvider — wraps `@google/genai` as an `LLMProvider` (9.13.0).
3
+ *
4
+ * Pattern: Adapter (GoF) + Ports-and-Adapters (Cockburn 2005).
5
+ * Role: Outer ring — translates `LLMRequest`/`LLMResponse` to/from Google's
6
+ * `generateContent` API. Knows nothing about agents, recorders, or
7
+ * compositions.
8
+ * Emits: N/A — providers don't emit; recorders observe via Agent.
9
+ *
10
+ * ─── Two doors, one adapter ─────────────────────────────────────────
11
+ *
12
+ * The same SDK reaches two different services, and which one you get is a
13
+ * property of the OPTIONS, not of a separate factory:
14
+ *
15
+ * • **Vertex** — `gemini({ project, location })` builds
16
+ * `new GoogleGenAI({ vertexai: true, project, location, googleAuthOptions })`.
17
+ * Auth is Application Default Credentials (env key file, gcloud user
18
+ * credentials, or the metadata server on GCE / Cloud Run / Agent Runtime).
19
+ * No API key exists on this path.
20
+ * • **Gemini API (AI Studio)** — `gemini({ apiKey })` builds
21
+ * `new GoogleGenAI({ apiKey })`. One key, no cloud project.
22
+ *
23
+ * Neither is guessed. The factory refuses at construction when it can resolve
24
+ * neither a project nor a key, naming both doors — because the SDK's own
25
+ * behaviour in that case is to WARN on stderr, construct anyway, and fail on
26
+ * the first call, which reads like a network problem rather than a missing
27
+ * setting.
28
+ *
29
+ * ─── Why native, and not `openai({ baseURL })` ──────────────────────
30
+ *
31
+ * Google publishes an OpenAI-compatible endpoint, and it does work — for about
32
+ * an hour. It authenticates with an OAuth access token that expires and has no
33
+ * refresh home in `OpenAIProviderOptions`; its `tools.function.parameters` is
34
+ * **OpenAPI**, not JSON Schema, so `$ref` / `oneOf` / `additionalProperties`
35
+ * diverge silently; unsupported parameters are ignored rather than refused; and
36
+ * its documented response carries no cached- or reasoning-token counts. This
37
+ * adapter exists because every one of those is answerable on the native SDK:
38
+ * ADC refreshes itself, tools go over as JSON Schema untranslated
39
+ * (`parametersJsonSchema`), a forced single tool is expressible, and
40
+ * `usageMetadata` reports cached and thinking tokens as separate numbers.
41
+ *
42
+ * ─── Limitations (stated, not discovered) ───────────────────────────
43
+ *
44
+ * • Multi-modal input/output NOT supported — `LLMMessage.content` is `string`,
45
+ * so this adapter sends and reads text parts only. Inline data, files and
46
+ * generated images are out of scope for the port as it stands.
47
+ * • **Thought summaries are not requested.** `usage.thinking` is reported
48
+ * honestly from `thoughtsTokenCount`, and `req.thinking.budget` is threaded
49
+ * to `thinkingConfig.thinkingBudget` — but `includeThoughts` is deliberately
50
+ * left unset, so no `rawThinking` is produced. Gemini's thought parts carry a
51
+ * `thoughtSignature` that has to be echoed byte-exact on the next turn, and
52
+ * there is no Gemini `ThinkingHandler` in this release to normalize and
53
+ * round-trip them. Asking for content nothing can carry would be a leak, not
54
+ * a feature. `thinkingConfig.thinkingLevel` has no field on `LLMRequest` and
55
+ * is likewise not sent.
56
+ * • `responseJsonSchema` (native structured output) is NOT exposed; use
57
+ * `.outputSchema(...)`, which goes over as a forced tool — a shape this
58
+ * adapter DOES carry.
59
+ * • Grounding tools (Google Search, code execution, URL context, MCP servers)
60
+ * are not exposed. `tools` carries function declarations only.
61
+ */
62
+ import { asContextWindowExceeded } from './contextWindow.js';
63
+ import { resolveGoogleGenAIClient } from './googleGenAI.js';
64
+ /**
65
+ * Which roles this wire carries inside `contents`.
66
+ *
67
+ * `'system'` is ABSENT, and it is the wire's own rule: Gemini takes the system
68
+ * prompt as `config.systemInstruction`, a field OUTSIDE the turn list, exactly
69
+ * like Anthropic's top-level `system`. So this is an Anthropic-family wire, not
70
+ * an OpenAI-family one, and a `slot: 'messages'` injection with
71
+ * `role: 'system'` is refused at run start rather than silently dropped between
72
+ * the recording and the request.
73
+ */
74
+ const CARRIES_IN_MESSAGES = Object.freeze(['user', 'assistant']);
75
+ /** The model asked for when the request says only `'gemini'`. */
76
+ const DEFAULT_MODEL = 'gemini-2.5-flash';
77
+ /**
78
+ * Prefix on a tool-call id THIS ADAPTER invented.
79
+ *
80
+ * `FunctionCall.id` is optional on Gemini's wire and is routinely absent —
81
+ * Vertex omits it. Our `LLMResponse.toolCalls[].id` is not optional, because
82
+ * the agent matches a tool RESULT back to its call by id, so one has to exist.
83
+ * Inventing it is safe; sending it BACK is not — Gemini never issued it, and a
84
+ * `functionResponse.id` the service does not recognise is a request field that
85
+ * means nothing to the model. The prefix is how the return trip tells the two
86
+ * apart without holding state across provider instances (a resumed run rebuilds
87
+ * its history from a checkpoint, so state would not survive anyway).
88
+ */
89
+ const SYNTHETIC_ID_PREFIX = 'gemini-call-';
90
+ /**
91
+ * Build an `LLMProvider` backed by Gemini — on Vertex or on the Gemini API.
92
+ *
93
+ * @example Vertex (Application Default Credentials)
94
+ * ```ts
95
+ * import { Agent } from 'agentfootprint';
96
+ * import { gemini } from 'agentfootprint/providers';
97
+ *
98
+ * const agent = Agent.create({
99
+ * provider: gemini({ project: 'my-project', location: 'us-central1' }),
100
+ * model: 'gemini',
101
+ * })
102
+ * .tool(weatherTool)
103
+ * .build();
104
+ * ```
105
+ *
106
+ * @example Gemini API (one key, no cloud project)
107
+ * ```ts
108
+ * const provider = gemini({ apiKey: process.env.GEMINI_API_KEY });
109
+ * ```
110
+ *
111
+ * @throws at construction when neither a project nor an API key is resolvable,
112
+ * and when `@google/genai` is not installed.
113
+ */
114
+ export function gemini(options = {}) {
115
+ const client = resolveGoogleGenAIClient(options, 'gemini', options._client);
116
+ const defaultModel = options.defaultModel ?? DEFAULT_MODEL;
117
+ const defaultMaxTokens = options.defaultMaxTokens;
118
+ // Ids are invented per PROVIDER INSTANCE, in call order — the same shape
119
+ // `ollama()` uses, and for the same reason: the wire omits them.
120
+ let toolCallSeq = 0;
121
+ const nextToolCallId = () => `${SYNTHETIC_ID_PREFIX}${++toolCallSeq}`;
122
+ // The ONE secret this adapter holds, so the ONE string its errors promise
123
+ // never to print — see `wrapError`.
124
+ const wrap = (err) => wrapError(err, options.apiKey);
125
+ const provider = {
126
+ name: 'gemini',
127
+ carriesInMessages: CARRIES_IN_MESSAGES,
128
+ // Earned, not assumed: `toolConfig.functionCallingConfig` with
129
+ // `mode: 'ANY'` and a single `allowedFunctionNames` entry constrains the
130
+ // model to answer through exactly that function. Both doors of this
131
+ // adapter speak the same field, so unlike the OpenAI-compatible path there
132
+ // is no endpoint whose behaviour we would be promising on its behalf.
133
+ carriesForcedToolChoice: true,
134
+ async complete(req) {
135
+ const params = buildParams(req, defaultModel, defaultMaxTokens);
136
+ try {
137
+ const response = await client.models.generateContent(params);
138
+ return fromGeminiResponse(response, nextToolCallId);
139
+ }
140
+ catch (err) {
141
+ throw wrap(err);
142
+ }
143
+ },
144
+ async *stream(req) {
145
+ const params = buildParams(req, defaultModel, defaultMaxTokens);
146
+ let stream;
147
+ try {
148
+ // Two awaits, one call: `generateContentStream` answers with a PROMISE
149
+ // of an async generator, so `for await` over the return value directly
150
+ // iterates a promise and yields nothing.
151
+ stream = await client.models.generateContentStream(params);
152
+ }
153
+ catch (err) {
154
+ throw wrap(err);
155
+ }
156
+ const textParts = [];
157
+ const functionCalls = [];
158
+ let usage;
159
+ let finishReason;
160
+ let responseId;
161
+ let tokenIndex = 0;
162
+ try {
163
+ for await (const chunk of stream) {
164
+ // Usage FIRST, and outside any content guard. Gemini puts
165
+ // `usageMetadata` on the chunk that closes the stream, whose
166
+ // candidate carries no new text — a `continue` on an empty part list
167
+ // throws away the only token counts the stream ever reports, which is
168
+ // the failure that made streamed turns bill as zero on two other
169
+ // adapters before this one.
170
+ if (chunk.usageMetadata)
171
+ usage = chunk.usageMetadata;
172
+ if (chunk.responseId)
173
+ responseId = chunk.responseId;
174
+ const candidate = chunk.candidates?.[0];
175
+ if (candidate?.finishReason)
176
+ finishReason = candidate.finishReason;
177
+ for (const part of candidate?.content?.parts ?? []) {
178
+ if (part.functionCall)
179
+ functionCalls.push(part.functionCall);
180
+ // A thought-summary part is not visible content and is never
181
+ // streamed as one. Nothing asks for them today (see the file
182
+ // header); the guard is here so that a model that volunteers one
183
+ // cannot leak reasoning into the answer.
184
+ if (part.thought)
185
+ continue;
186
+ if (part.text) {
187
+ textParts.push(part.text);
188
+ yield { tokenIndex, content: part.text, done: false };
189
+ tokenIndex++;
190
+ }
191
+ }
192
+ }
193
+ const toolCalls = functionCalls.map((fc) => toLLMToolCall(fc, nextToolCallId));
194
+ const response = {
195
+ content: textParts.join(''),
196
+ toolCalls,
197
+ // What the wire said, and nothing else. When a stream reports no
198
+ // usage at all these are zero rather than an estimate: `countTokens`
199
+ // would answer a DIFFERENT question (what a request tokenises to)
200
+ // from the one a cost meter is asking (what this call was billed
201
+ // for), and a plausible number in the right range is worse than a
202
+ // zero somebody can see. Same law as `openai()` and `ollama()`.
203
+ usage: toUsage(usage),
204
+ stopReason: normalizeStopReason(finishReason, toolCalls.length > 0),
205
+ ...(responseId !== undefined && { providerRef: responseId }),
206
+ };
207
+ yield { tokenIndex, content: '', done: true, response };
208
+ }
209
+ catch (err) {
210
+ throw wrap(err);
211
+ }
212
+ },
213
+ };
214
+ return provider;
215
+ }
216
+ /**
217
+ * Class form for consumers who prefer `new GeminiProvider(...)` over the
218
+ * `gemini(...)` factory. Identical behavior; trivial wrapper.
219
+ */
220
+ export class GeminiProvider {
221
+ name = 'gemini';
222
+ carriesInMessages = CARRIES_IN_MESSAGES;
223
+ carriesForcedToolChoice = true;
224
+ inner;
225
+ constructor(options = {}) {
226
+ this.inner = gemini(options);
227
+ }
228
+ // `hooks` is FORWARDED, not dropped — see LLMCallHooks in adapters/types.ts.
229
+ complete(req, hooks) {
230
+ return this.inner.complete(req, hooks);
231
+ }
232
+ stream(req, hooks) {
233
+ if (!this.inner.stream) {
234
+ throw new Error('stream() unavailable on inner provider');
235
+ }
236
+ return this.inner.stream(req, hooks);
237
+ }
238
+ }
239
+ // ─── Internals ──────────────────────────────────────────────────────
240
+ function buildParams(req, defaultModel, defaultMaxTokens) {
241
+ const config = {};
242
+ // The system prompt is a top-level field, not a turn — see
243
+ // CARRIES_IN_MESSAGES.
244
+ if (req.systemPrompt)
245
+ config.systemInstruction = req.systemPrompt;
246
+ if (req.temperature !== undefined)
247
+ config.temperature = req.temperature;
248
+ const maxTokens = req.maxTokens ?? defaultMaxTokens;
249
+ if (maxTokens !== undefined)
250
+ config.maxOutputTokens = maxTokens;
251
+ if (req.stop && req.stop.length > 0)
252
+ config.stopSequences = [...req.stop];
253
+ // Threaded so an aborted run stops paying for tokens nobody is waiting for.
254
+ if (req.signal)
255
+ config.abortSignal = req.signal;
256
+ if (req.tools && req.tools.length > 0) {
257
+ config.tools = [{ functionDeclarations: req.tools.map(toGeminiFunctionDeclaration) }];
258
+ }
259
+ // A budget, and only a budget — `includeThoughts` and `thinkingLevel` are
260
+ // deliberately not sent (see the file header). A budget of 0 is a real value
261
+ // on this wire (it turns thinking off), so the guard is on presence.
262
+ if (req.thinking)
263
+ config.thinkingConfig = { thinkingBudget: req.thinking.budget };
264
+ // Forced choice of ONE named function. Guarded on tools being present for
265
+ // the same reason the Anthropic and OpenAI adapters guard: a tool choice
266
+ // naming a function the request does not carry is a request that cannot be
267
+ // served, and Gemini would refuse it.
268
+ if (req.toolChoice && config.tools !== undefined) {
269
+ config.toolConfig = {
270
+ functionCallingConfig: { mode: 'ANY', allowedFunctionNames: [req.toolChoice.name] },
271
+ };
272
+ }
273
+ return {
274
+ model: req.model === 'gemini' ? defaultModel : req.model,
275
+ contents: toGeminiContents(req.messages),
276
+ ...(Object.keys(config).length > 0 && { config }),
277
+ };
278
+ }
279
+ /**
280
+ * messages → Gemini `contents`.
281
+ *
282
+ * Key transforms:
283
+ * • `role: 'system'` is DROPPED — it rides `config.systemInstruction`.
284
+ * • `role: 'assistant'` becomes `role: 'model'`, with `toolCalls` restored as
285
+ * `functionCall` parts so a multi-turn tool conversation round-trips.
286
+ * • `role: 'tool'` becomes a `functionResponse` part inside a **user** turn,
287
+ * which is where Gemini expects results. Consecutive tool messages merge
288
+ * into ONE user turn, so a reply that called three tools is answered by one
289
+ * turn carrying three responses — the same coalescing the Anthropic adapter
290
+ * does with `tool_result` blocks.
291
+ */
292
+ function toGeminiContents(messages) {
293
+ const result = [];
294
+ for (const m of messages) {
295
+ if (m.role === 'system')
296
+ continue;
297
+ if (m.role === 'user') {
298
+ result.push({ role: 'user', parts: [{ text: m.content }] });
299
+ continue;
300
+ }
301
+ if (m.role === 'assistant') {
302
+ const parts = [];
303
+ if (m.content)
304
+ parts.push({ text: m.content });
305
+ for (const tc of m.toolCalls ?? []) {
306
+ parts.push({
307
+ functionCall: {
308
+ // Only an id GEMINI issued goes back to Gemini — see
309
+ // SYNTHETIC_ID_PREFIX.
310
+ ...(isRealId(tc.id) && { id: tc.id }),
311
+ name: tc.name,
312
+ args: { ...tc.args },
313
+ },
314
+ });
315
+ }
316
+ // An assistant turn with neither text nor calls still has to occupy its
317
+ // position, or the user/model alternation the wire expects breaks.
318
+ result.push({ role: 'model', parts: parts.length > 0 ? parts : [{ text: '' }] });
319
+ continue;
320
+ }
321
+ if (m.role === 'tool') {
322
+ const part = {
323
+ functionResponse: {
324
+ ...(isRealId(m.toolCallId) && { id: m.toolCallId }),
325
+ // Gemini matches a response to its call BY NAME, so the name is the
326
+ // load-bearing field here — not the id.
327
+ name: m.toolName ?? '',
328
+ // The wire takes an object, and a tool result in this library is a
329
+ // string. `{ output }` is that string in the one field the model can
330
+ // read, unwrapped; inventing a schema for it would make every tool
331
+ // result a different shape.
332
+ response: { output: m.content },
333
+ },
334
+ };
335
+ const last = result[result.length - 1];
336
+ if (last && last.role === 'user' && last.parts[0]?.functionResponse) {
337
+ last.parts.push(part);
338
+ }
339
+ else {
340
+ result.push({ role: 'user', parts: [part] });
341
+ }
342
+ continue;
343
+ }
344
+ }
345
+ return result;
346
+ }
347
+ /** Did the SERVICE issue this id, or did we? */
348
+ function isRealId(id) {
349
+ return id !== undefined && id.length > 0 && !id.startsWith(SYNTHETIC_ID_PREFIX);
350
+ }
351
+ /**
352
+ * `LLMToolSchema` → `FunctionDeclaration`, with the schema untranslated.
353
+ *
354
+ * `parametersJsonSchema` is the whole reason this adapter exists rather than a
355
+ * `baseURL` on the OpenAI one: it takes JSON Schema as JSON Schema. The
356
+ * `parameters` field beside it takes an OpenAPI subset, where `$ref`,
357
+ * `oneOf` and `additionalProperties` mean something else or nothing at all —
358
+ * which is a divergence you only find out about from a model that ignored half
359
+ * your constraints.
360
+ */
361
+ function toGeminiFunctionDeclaration(schema) {
362
+ return {
363
+ name: schema.name,
364
+ description: schema.description,
365
+ parametersJsonSchema: { ...schema.inputSchema },
366
+ };
367
+ }
368
+ function fromGeminiResponse(response, nextToolCallId) {
369
+ const candidate = response.candidates?.[0];
370
+ const textParts = [];
371
+ const toolCalls = [];
372
+ for (const part of candidate?.content?.parts ?? []) {
373
+ if (part.functionCall)
374
+ toolCalls.push(toLLMToolCall(part.functionCall, nextToolCallId));
375
+ // Thought summaries are not the answer. See the header.
376
+ if (part.thought)
377
+ continue;
378
+ if (part.text)
379
+ textParts.push(part.text);
380
+ }
381
+ return {
382
+ content: textParts.join(''),
383
+ toolCalls,
384
+ usage: toUsage(response.usageMetadata),
385
+ stopReason: normalizeStopReason(candidate?.finishReason, toolCalls.length > 0),
386
+ ...(response.responseId !== undefined && { providerRef: response.responseId }),
387
+ };
388
+ }
389
+ function toLLMToolCall(fc, nextToolCallId) {
390
+ return {
391
+ id: fc.id && fc.id.length > 0 ? fc.id : nextToolCallId(),
392
+ name: fc.name ?? '',
393
+ args: { ...(fc.args ?? {}) },
394
+ };
395
+ }
396
+ /**
397
+ * `usageMetadata` → the port's four numbers.
398
+ *
399
+ * This is the payoff of going native. `cachedContentTokenCount` and
400
+ * `thoughtsTokenCount` are separate line items on Google's own wire, so
401
+ * `usage.cacheRead` and `usage.thinking` are REPORTED rather than left
402
+ * undefined — the OpenAI-compatible endpoint's documented response has neither
403
+ * field, so a cost dashboard behind it can only ever show the total.
404
+ *
405
+ * `cacheWrite` stays undefined on purpose: Gemini's context caching is created
406
+ * by a separate `caches.create` call that this adapter does not make, so there
407
+ * is no write for a `generateContent` turn to report.
408
+ */
409
+ function toUsage(usage) {
410
+ return {
411
+ input: usage?.promptTokenCount ?? 0,
412
+ output: usage?.candidatesTokenCount ?? 0,
413
+ ...(usage?.cachedContentTokenCount !== undefined && {
414
+ cacheRead: usage.cachedContentTokenCount,
415
+ }),
416
+ ...(usage?.thoughtsTokenCount !== undefined && { thinking: usage.thoughtsTokenCount }),
417
+ };
418
+ }
419
+ /**
420
+ * `FinishReason` → agentfootprint's stop vocabulary.
421
+ *
422
+ * Two facts shape this. First, **Gemini has no `tool_use` finish reason**: a
423
+ * turn that asks for a function still finishes `STOP`, so the presence of
424
+ * function calls is what distinguishes it — the same correction `ollama()`
425
+ * makes on its wire. Second, everything not listed passes through UNCHANGED,
426
+ * in Google's own spelling. `RECITATION`, `MALFORMED_FUNCTION_CALL`,
427
+ * `TOO_MANY_TOOL_CALLS` and the image-specific reasons are real answers with no
428
+ * equivalent in this vocabulary, and mapping them onto the nearest word would
429
+ * be this adapter guessing on the model's behalf.
430
+ */
431
+ function normalizeStopReason(raw, hasToolCalls) {
432
+ if (hasToolCalls && (raw === undefined || raw === 'STOP' || raw === ''))
433
+ return 'tool_use';
434
+ switch (raw) {
435
+ case undefined:
436
+ case '':
437
+ return 'stop';
438
+ case 'STOP':
439
+ return 'stop';
440
+ case 'MAX_TOKENS':
441
+ return 'max_tokens';
442
+ // The four that are unmistakably a safety refusal rather than an ending.
443
+ case 'SAFETY':
444
+ case 'PROHIBITED_CONTENT':
445
+ case 'BLOCKLIST':
446
+ case 'SPII':
447
+ return 'content_filter';
448
+ default:
449
+ return raw;
450
+ }
451
+ }
452
+ /**
453
+ * Vendor error → ours, with the key taken out.
454
+ *
455
+ * The prefix-and-rename half is the same as every other adapter's. The
456
+ * REDACTION half is this adapter's alone, and it is narrow on purpose: the only
457
+ * string removed is the literal API key this provider was constructed with, and
458
+ * it is removed because a thrown provider error is handed to the model as a
459
+ * tool result, written to the commit log, rendered in the narrative and
460
+ * serialized by every attached recorder — one interpolation reaches all of them.
461
+ *
462
+ * This is not a heuristic scrubber and must never become one. It cannot know
463
+ * about a secret it was not given, and a pattern that guessed at "things that
464
+ * look like keys" would eventually delete the sentence that explains the
465
+ * failure. What it guarantees is exactly what it can: the key YOU passed in
466
+ * does not come back out, whoever put it in the message.
467
+ */
468
+ function wrapError(err, apiKey) {
469
+ // See OpenAIProvider.wrapError — one shared detector, one typed error, so
470
+ // "the request did not fit" reads the same whichever vendor said it. Google's
471
+ // sentence is "The input token count (N) exceeds the maximum number of tokens
472
+ // allowed (M)."; the phrase list in contextWindow.ts carries it.
473
+ const tooBig = asContextWindowExceeded(err, { provider: 'gemini' });
474
+ if (tooBig)
475
+ return redactKey(tooBig, apiKey);
476
+ if (err instanceof Error) {
477
+ return redactKey(Object.assign(new Error(`[gemini] ${redact(err.message, apiKey)}`), {
478
+ name: 'GeminiProviderError',
479
+ cause: err,
480
+ // `ApiError` from @google/genai carries `status`; withRetry reads it.
481
+ status: err.status,
482
+ }), apiKey);
483
+ }
484
+ return new Error(`[gemini] ${redact(String(err), apiKey)}`);
485
+ }
486
+ /** A key short enough to be an accident is not redacted — replacing a two-
487
+ * character string everywhere would shred the message it appears in. */
488
+ function redact(text, apiKey) {
489
+ if (apiKey === undefined || apiKey.length < 8)
490
+ return text;
491
+ return text.split(apiKey).join('[redacted apiKey]');
492
+ }
493
+ /**
494
+ * A `stack` is built from the message at construction, and a `cause` carries
495
+ * the vendor's untouched original — both are printed by ordinary logging, so
496
+ * neither may keep a copy of the key the message just gave up.
497
+ */
498
+ function redactKey(error, apiKey) {
499
+ if (apiKey === undefined || apiKey.length < 8)
500
+ return error;
501
+ if (typeof error.stack === 'string' && error.stack.includes(apiKey)) {
502
+ error.stack = redact(error.stack, apiKey);
503
+ }
504
+ const cause = error.cause;
505
+ if (cause instanceof Error) {
506
+ if (cause.message.includes(apiKey))
507
+ cause.message = redact(cause.message, apiKey);
508
+ if (typeof cause.stack === 'string' && cause.stack.includes(apiKey)) {
509
+ cause.stack = redact(cause.stack, apiKey);
510
+ }
511
+ }
512
+ return error;
513
+ }
514
+ //# sourceMappingURL=GeminiProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GeminiProvider.js","sourceRoot":"","sources":["../../../../src/adapters/llm/GeminiProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4DG;AAYH,OAAO,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,wBAAwB,EAAqC,MAAM,kBAAkB,CAAC;AAyH/F;;;;;;;;;GASG;AACH,MAAM,mBAAmB,GAAwB,MAAM,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC;AAEtF,iEAAiE;AACjE,MAAM,aAAa,GAAG,kBAAkB,CAAC;AAEzC;;;;;;;;;;;GAWG;AACH,MAAM,mBAAmB,GAAG,cAAc,CAAC;AAE3C;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,MAAM,CAAC,UAAiC,EAAE;IACxD,MAAM,MAAM,GAAG,wBAAwB,CAAmB,OAAO,EAAE,QAAQ,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IAC9F,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,aAAa,CAAC;IAC3D,MAAM,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAElD,yEAAyE;IACzE,iEAAiE;IACjE,IAAI,WAAW,GAAG,CAAC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200000
104
104
  * bedrock Input is too long for requested model.
105
105
  * bedrock (ValidationException carrying either anthropic phrase)
106
+ * gemini The input token count (1200293) exceeds the maximum number
107
+ * of tokens allowed (1048576).
106
108
  */
107
109
  const CONTEXT_PHRASES = [
108
110
  /context_length_exceeded/i,
@@ -116,6 +118,11 @@ const CONTEXT_PHRASES = [
116
118
  // OUTPUT `max_tokens` cap, which has a different fix — and a pattern that
117
119
  // cannot tell those apart sends callers to the wrong one.
118
120
  /exceeds? the maximum (?:allowed )?(?:number of )?input tokens/i,
121
+ // gemini (9.13.0) — the same claim with the words in the other order, which
122
+ // is why the pattern above does not catch it. "INPUT token count" is what
123
+ // keeps it off a `max_tokens` validation error, and Google spells a rate
124
+ // limit "quota exceeded", so there is no overlap with throttling either.
125
+ /input token count[^.]{0,80}exceeds the maximum number of tokens allowed/i,
119
126
  ];
120
127
  /** `"272,000"` → `272000`; anything unparseable → undefined. */
121
128
  function num(raw) {
@@ -142,6 +149,19 @@ function readNumbers(text) {
142
149
  ...(num(sum[3]) !== undefined && { limitTokens: num(sum[3]) }),
143
150
  };
144
151
  }
152
+ // gemini: "The input token count (1200293) exceeds the maximum number of
153
+ // tokens allowed (1048576)." Both parentheses are matched loosely because
154
+ // Google sometimes ships the first one EMPTY — `num('')` is undefined, so a
155
+ // half-stated sentence yields the half it stated rather than nothing.
156
+ const geminiPair = /input token count\s*\(([\d,_]*)\)\s*exceeds the maximum number of tokens allowed\s*\(([\d,_]*)\)/i.exec(text);
157
+ if (geminiPair) {
158
+ const actual = num(geminiPair[1]);
159
+ const limit = num(geminiPair[2]);
160
+ return {
161
+ ...(actual !== undefined && { actualTokens: actual }),
162
+ ...(limit !== undefined && { limitTokens: limit }),
163
+ };
164
+ }
145
165
  const limit = num(/maximum context length is\s*([\d,_]+)/i.exec(text)?.[1]) ??
146
166
  num(/configured limit of\s*([\d,_]+)/i.exec(text)?.[1]) ??
147
167
  num(/limit of\s*([\d,_]+)\s*tokens/i.exec(text)?.[1]);
@@ -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AC,QAAQ,+CAA+C,IAAI,IAAI;QACxE,4EAA4E;QAC5E,4DAA4D;QAC5D,wEAAwE;QACxE,2EAA2E;QAC3E,8DAA8D;QAC9D,uEAAuE;QACvE,4EAA4E;QAC5E,kBAAkB;QAClB,yEAAyE;QACzE,0EAA0E;QAC1E,2EAA2E;QAC3E,8BAA8B;QAC9B,oBAAoB,IAAI,CAAC,eAAe,EAAE,CAC3C,CAAC;AACJ,CAAC"}
@@ -25,10 +25,11 @@ import { type AnthropicProviderOptions } from './AnthropicProvider.js';
25
25
  import { type OpenAIProviderOptions } from './OpenAIProvider.js';
26
26
  import { type OllamaProviderOptions } from './OllamaProvider.js';
27
27
  import { type BedrockProviderOptions } from './BedrockProvider.js';
28
+ import { type GeminiProviderOptions } from './GeminiProvider.js';
28
29
  import { type BrowserAnthropicProviderOptions } from './BrowserAnthropicProvider.js';
29
30
  import { type BrowserOpenAIProviderOptions } from './BrowserOpenAIProvider.js';
30
31
  /** Built-in provider kinds. Custom providers don't go through this factory. */
31
- export type ProviderKind = 'mock' | 'anthropic' | 'openai' | 'ollama' | 'bedrock' | 'browser-anthropic' | 'browser-openai';
32
+ export type ProviderKind = 'mock' | 'anthropic' | 'openai' | 'ollama' | 'bedrock' | 'gemini' | 'browser-anthropic' | 'browser-openai';
32
33
  /**
33
34
  * Common subset of options accepted across all built-in providers.
34
35
  * Provider-specific keys (region for Bedrock, host for Ollama,
@@ -46,6 +47,8 @@ export type CreateProviderOptions = ({
46
47
  } & OllamaProviderOptions) | ({
47
48
  readonly kind: 'bedrock';
48
49
  } & BedrockProviderOptions) | ({
50
+ readonly kind: 'gemini';
51
+ } & GeminiProviderOptions) | ({
49
52
  readonly kind: 'browser-anthropic';
50
53
  } & BrowserAnthropicProviderOptions) | ({
51
54
  readonly kind: 'browser-openai';
@@ -24,6 +24,7 @@ import { anthropic } from './AnthropicProvider.js';
24
24
  import { openai, azureOpenai } from './OpenAIProvider.js';
25
25
  import { ollama } from './OllamaProvider.js';
26
26
  import { bedrock } from './BedrockProvider.js';
27
+ import { gemini } from './GeminiProvider.js';
27
28
  import { browserAnthropic, } from './BrowserAnthropicProvider.js';
28
29
  import { browserOpenai } from './BrowserOpenAIProvider.js';
29
30
  /**
@@ -41,6 +42,8 @@ export function createProvider(options) {
41
42
  return ollama(options);
42
43
  case 'bedrock':
43
44
  return bedrock(options);
45
+ case 'gemini':
46
+ return gemini(options);
44
47
  case 'browser-anthropic':
45
48
  return browserAnthropic(options);
46
49
  case 'browser-openai':