@memberjunction/ai-gemini 6.2.0-edge.5 → 6.2.0-edge.7

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
@@ -12,6 +12,17 @@ import { BaseLLM, ChatMessage, ChatParams, ChatResult, SummarizeParams, Summariz
12
12
  * so the model reads it as the opening request rather than as noise.
13
13
  */
14
14
  export declare const GEMINI_LEADING_USER_TURN_TEXT = "Proceed with the task described in the system instructions.";
15
+ /**
16
+ * The user turn Gemini is given when a conversation would otherwise end with a model turn.
17
+ *
18
+ * Gemini answers a request whose last turn is the user's; one ending with a model turn is a 400
19
+ * ("Requests ending with a model turn are not supported"). The driver sends the last turn as the
20
+ * new message, and the SDK always sends that message as a user turn, so a trailing model turn would
21
+ * otherwise go out with its own parts relabelled as the user's. It stays a model turn in the
22
+ * history instead, and this turn asks the model to go on. Gemini models here take no assistant
23
+ * prefill, so no caller means a trailing model turn as one.
24
+ */
25
+ export declare const GEMINI_TRAILING_USER_TURN_TEXT = "Continue with the task.";
15
26
  export declare class GeminiLLM extends BaseLLM {
16
27
  protected _gemini: GoogleGenAI | null;
17
28
  private _geminiPromise;
@@ -48,7 +59,35 @@ export declare class GeminiLLM extends BaseLLM {
48
59
  * `functionResponse` parts).
49
60
  */
50
61
  get SupportsTools(): boolean;
62
+ /**
63
+ * Shapes converted messages into the alternating `contents` Gemini accepts: consecutive turns of
64
+ * one role are combined, and the conversation opens with a user turn (see
65
+ * {@link GEMINI_LEADING_USER_TURN_TEXT}).
66
+ *
67
+ * Two exceptions to combining:
68
+ * - A model turn with nothing in it (an assistant message with no text, no calls and no
69
+ * reasoning) is dropped. It carries nothing, and Gemini rejects an empty turn.
70
+ * - A user turn that follows a function-response turn is kept as a turn of its own. Vertex AI
71
+ * rejects a turn whose function responses are followed by text with "Requests ending with a
72
+ * model turn are not supported", although the turn is the user's. Google AI Studio accepts both
73
+ * shapes. The agent loop sends exactly this: a tool turn, then its per-turn runtime-state message.
74
+ */
51
75
  protected geminiMessageSpacing(messages: Content[]): Content[];
76
+ /** Whether a turn is a model turn with nothing in it: no parts, or only empty text with no signature. */
77
+ private static isEmptyModelTurn;
78
+ /** Whether `next` is a user turn of other parts after a function-response turn, and so must stay separate. */
79
+ private static endsFunctionResponseTurn;
80
+ /**
81
+ * Splits shaped `contents` into the chat history and the message to send. The SDK sends the
82
+ * message as a user turn, so only a user turn is taken off the end. A conversation that ends
83
+ * with a model turn keeps it in the history and sends {@link GEMINI_TRAILING_USER_TURN_TEXT};
84
+ * one with no turns at all sends {@link GEMINI_LEADING_USER_TURN_TEXT}, since Vertex AI rejects
85
+ * an empty message ("Model input cannot be empty").
86
+ */
87
+ protected SplitForSend(contents: Content[]): {
88
+ history: Content[];
89
+ message: Part[];
90
+ };
52
91
  /**
53
92
  * Implementation of non-streaming chat completion for Gemini
54
93
  */
@@ -78,6 +117,12 @@ export declare class GeminiLLM extends BaseLLM {
78
117
  protected get ThoughtSignatureEndpoint(): string;
79
118
  /** Endpoint plus model — the scope a thought signature validates in. */
80
119
  protected thoughtSignatureOrigin(modelName: string): string;
120
+ /**
121
+ * The normalized finish reason for a tool call Gemini rejected — `MALFORMED_FUNCTION_CALL` (the
122
+ * call could not be read) or `UNEXPECTED_TOOL_CALL` (a call to a tool the request did not offer)
123
+ * — or undefined for any other finish reason.
124
+ */
125
+ private static rejectedToolCallReason;
81
126
  /**
82
127
  * Pulls `functionCall` parts out of a Gemini candidate and normalizes them.
83
128
  *
@@ -125,8 +170,10 @@ export declare class GeminiLLM extends BaseLLM {
125
170
  private thinkingReplacementKey;
126
171
  /**
127
172
  * Puts the `thinkingConfig` for `effortLevel` on the request (see {@link ResolveGeminiThinkingConfig}),
128
- * or what replaced it after the model rejected it earlier in this process. Nothing is added when
129
- * no effort is set; an effort that cannot be used is reported once.
173
+ * or what replaced it after the model rejected it earlier in this process. With no usable effort, a
174
+ * `thinkingConfig` already on the request (from `modelSpecificResponseFormat`) gets the same
175
+ * replacement, so a rejected setting is not re-sent on every call. An effort that cannot be used is
176
+ * reported once.
130
177
  */
131
178
  private applyThinkingConfig;
132
179
  /**
@@ -223,6 +270,28 @@ export declare class GeminiLLM extends BaseLLM {
223
270
  * otherwise the documented placeholder. A signature with no recorded origin is replayed as-is.
224
271
  */
225
272
  private static signatureForReplay;
273
+ /**
274
+ * A turn's thought parts and signed text parts, as replayable reasoning.
275
+ *
276
+ * Thought parts are kept with their signature when they have one. Text parts are kept only when
277
+ * at least one of them is signed, and then all of them, in order — the replay rebuilds the
278
+ * turn's text from these blocks, so each signature lands back on the text it was minted for.
279
+ * Function-call signatures travel on the calls themselves (see {@link extractToolCalls}).
280
+ *
281
+ * @param parts The candidate's content parts
282
+ * @param signatureOrigin Where this response's signatures validate (see {@link thoughtSignatureOrigin})
283
+ * @returns The blocks, or undefined when the turn had nothing to replay
284
+ */
285
+ private static extractReasoning;
286
+ /**
287
+ * The parts that replay a model turn's own reasoning: its thought parts, and — when its text
288
+ * parts were signed and the message text is still exactly theirs — those text parts with their
289
+ * signatures. `text` is undefined when the message's content should be mapped as usual: no
290
+ * signed text, or text that was changed after the turn (compaction), which a signature would
291
+ * no longer match. Blocks from another provider, or signed where this request is not going,
292
+ * are dropped — a foreign signature is a hard 400.
293
+ */
294
+ private static reasoningPartsForReplay;
226
295
  /**
227
296
  * Maps one MJ message to a Gemini history entry.
228
297
  *
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAY,OAAO,EAAE,IAAI,EAAmJ,MAAM,eAAe,CAAC;AAGtN,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,eAAe,EAAE,eAAe,EAA0B,kBAAkB,EAAsD,gBAAgB,EAAuF,MAAM,oBAAoB,CAAC;AAyC3T;;;;;;;;;;GAUG;AACH,eAAO,MAAM,6BAA6B,gEAAgE,CAAC;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IACH,OAAO,CAAC,MAAM,CAAC,6BAA6B;IAS5C;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAC,MAAM,CAAC,0BAA0B;WAqD3B,yBAAyB,CAAC,OAAO,EAAE,kBAAkB,GAAG,KAAK,CAAC,IAAI,CAAC;IAQjF;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,kBAAkB;IAWjC;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,MAAM,CAAC,gBAAgB;IAgB/B;;;;;;;OAOG;IACH,OAAO,CAAC,MAAM,CAAC,uBAAuB;IActC;;;;;;OAMG;WACW,gCAAgC,CAAC,OAAO,EAAE,WAAW,EAAE,eAAe,CAAC,EAAE,MAAM,GAAG,OAAO;IA4BvG;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,gCAAgC;CASlD;AAID,cAAc,eAAe,CAAC;AAG9B,cAAc,kBAAkB,CAAC;AACjC,OAAO,EAAE,6BAA6B,EAAE,KAAK,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAG9F,OAAO,EAAE,+BAA+B,EAAE,uCAAuC,EAAE,kCAAkC,EAAE,MAAM,4BAA4B,CAAC;AAG1J,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,KAAK,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC/G,OAAO,EAAE,qBAAqB,EAAE,KAAK,4BAA4B,EAAE,MAAM,yBAAyB,CAAC;AAGnG,cAAc,mBAAmB,CAAC"}
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ var GeminiLLM_1;
11
11
  // Google Gemini Import
12
12
  import { GoogleGenAI, ApiError, FunctionCallingConfigMode } from "@google/genai";
13
13
  // MJ stuff
14
- import { BaseLLM, ChatResult, ModelUsage, ErrorAnalyzer, CHAT_FINISH_REASON_TOOL_CALLS, CHAT_FINISH_REASON_MALFORMED_TOOL_CALL } from "@memberjunction/ai";
14
+ import { BaseLLM, ChatResult, ModelUsage, ErrorAnalyzer, CHAT_FINISH_REASON_TOOL_CALLS, CHAT_FINISH_REASON_MALFORMED_TOOL_CALL, CHAT_FINISH_REASON_UNEXPECTED_TOOL_CALL } from "@memberjunction/ai";
15
15
  import { RegisterClass, ToJSONSafe } from "@memberjunction/global";
16
16
  import { AcceptsCustomSampling } from "./geminiSampling.js";
17
17
  import { GeminiThinkingFallback, ResolveGeminiThinkingConfig } from "./geminiThinking.js";
@@ -29,6 +29,8 @@ const GEMINI_INJECTED_CALL_THOUGHT_SIGNATURE = 'skip_thought_signature_validator
29
29
  * on capture, compared on replay, and a foreign signature is replaced with the placeholder.
30
30
  */
31
31
  const THOUGHT_SIGNATURE_ORIGIN_KEY = 'thoughtSignatureOrigin';
32
+ /** The `provider` this driver (and Vertex, which extends it) stamps on its {@link ChatReasoningBlock}s. */
33
+ const GEMINI_REASONING_PROVIDER = 'gemini';
32
34
  /**
33
35
  * The user turn Gemini is given when a conversation would otherwise open with a model turn.
34
36
  *
@@ -41,6 +43,17 @@ const THOUGHT_SIGNATURE_ORIGIN_KEY = 'thoughtSignatureOrigin';
41
43
  * so the model reads it as the opening request rather than as noise.
42
44
  */
43
45
  export const GEMINI_LEADING_USER_TURN_TEXT = 'Proceed with the task described in the system instructions.';
46
+ /**
47
+ * The user turn Gemini is given when a conversation would otherwise end with a model turn.
48
+ *
49
+ * Gemini answers a request whose last turn is the user's; one ending with a model turn is a 400
50
+ * ("Requests ending with a model turn are not supported"). The driver sends the last turn as the
51
+ * new message, and the SDK always sends that message as a user turn, so a trailing model turn would
52
+ * otherwise go out with its own parts relabelled as the user's. It stays a model turn in the
53
+ * history instead, and this turn asks the model to go on. Gemini models here take no assistant
54
+ * prefill, so no caller means a trailing model turn as one.
55
+ */
56
+ export const GEMINI_TRAILING_USER_TURN_TEXT = 'Continue with the task.';
44
57
  let GeminiLLM = class GeminiLLM extends BaseLLM {
45
58
  static { GeminiLLM_1 = this; }
46
59
  constructor(apiKey) {
@@ -123,40 +136,65 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
123
136
  get SupportsTools() {
124
137
  return true;
125
138
  }
139
+ /**
140
+ * Shapes converted messages into the alternating `contents` Gemini accepts: consecutive turns of
141
+ * one role are combined, and the conversation opens with a user turn (see
142
+ * {@link GEMINI_LEADING_USER_TURN_TEXT}).
143
+ *
144
+ * Two exceptions to combining:
145
+ * - A model turn with nothing in it (an assistant message with no text, no calls and no
146
+ * reasoning) is dropped. It carries nothing, and Gemini rejects an empty turn.
147
+ * - A user turn that follows a function-response turn is kept as a turn of its own. Vertex AI
148
+ * rejects a turn whose function responses are followed by text with "Requests ending with a
149
+ * model turn are not supported", although the turn is the user's. Google AI Studio accepts both
150
+ * shapes. The agent loop sends exactly this: a tool turn, then its per-turn runtime-state message.
151
+ */
126
152
  geminiMessageSpacing(messages) {
127
- // This method ensures messages alternate between user and model roles
128
- // by combining consecutive messages with the same role
129
- if (messages.length === 0) {
130
- return [];
131
- }
132
153
  const result = [];
133
- let currentMessage = null;
134
154
  for (const message of messages) {
135
- if (currentMessage === null) {
136
- // First message - start accumulating
137
- currentMessage = { role: message.role, parts: [...message.parts] };
155
+ if (GeminiLLM_1.isEmptyModelTurn(message)) {
156
+ continue;
138
157
  }
139
- else if (currentMessage.role === message.role) {
140
- // Same role as current - combine the parts
141
- currentMessage.parts.push(...message.parts);
158
+ const current = result[result.length - 1];
159
+ if (current && current.role === message.role && !GeminiLLM_1.endsFunctionResponseTurn(current, message)) {
160
+ current.parts = [...(current.parts ?? []), ...(message.parts ?? [])];
142
161
  }
143
162
  else {
144
- // Different role - push current and start new
145
- result.push(currentMessage);
146
- currentMessage = { role: message.role, parts: [...message.parts] };
163
+ result.push({ role: message.role, parts: [...(message.parts ?? [])] });
147
164
  }
148
165
  }
149
- // Push the last accumulated message
150
- if (currentMessage !== null) {
151
- result.push(currentMessage);
152
- }
153
- // The conversation must open with a user turn — see GEMINI_LEADING_USER_TURN_TEXT for why a
154
- // model turn here (an agent with no user message replaying its own tool calls) is rejected.
155
166
  if (result.length > 0 && result[0].role === 'model') {
156
167
  result.unshift({ role: 'user', parts: [{ text: GEMINI_LEADING_USER_TURN_TEXT }] });
157
168
  }
158
169
  return result;
159
170
  }
171
+ /** Whether a turn is a model turn with nothing in it: no parts, or only empty text with no signature. */
172
+ static isEmptyModelTurn(content) {
173
+ return content.role === 'model'
174
+ && (content.parts ?? []).every((p) => p.text === '' && !p.thoughtSignature && !p.thought && Object.keys(p).length === 1);
175
+ }
176
+ /** Whether `next` is a user turn of other parts after a function-response turn, and so must stay separate. */
177
+ static endsFunctionResponseTurn(current, next) {
178
+ const hasResponses = (c) => (c.parts ?? []).some((p) => !!p.functionResponse);
179
+ return current.role === 'user' && hasResponses(current) && !(next.parts ?? []).every((p) => !!p.functionResponse);
180
+ }
181
+ /**
182
+ * Splits shaped `contents` into the chat history and the message to send. The SDK sends the
183
+ * message as a user turn, so only a user turn is taken off the end. A conversation that ends
184
+ * with a model turn keeps it in the history and sends {@link GEMINI_TRAILING_USER_TURN_TEXT};
185
+ * one with no turns at all sends {@link GEMINI_LEADING_USER_TURN_TEXT}, since Vertex AI rejects
186
+ * an empty message ("Model input cannot be empty").
187
+ */
188
+ SplitForSend(contents) {
189
+ const last = contents[contents.length - 1];
190
+ if (!last) {
191
+ return { history: [], message: [{ text: GEMINI_LEADING_USER_TURN_TEXT }] };
192
+ }
193
+ if (last.role === 'model') {
194
+ return { history: contents, message: [{ text: GEMINI_TRAILING_USER_TURN_TEXT }] };
195
+ }
196
+ return { history: contents.slice(0, -1), message: last.parts?.length ? last.parts : [{ text: GEMINI_LEADING_USER_TURN_TEXT }] };
197
+ }
160
198
  /**
161
199
  * Implementation of non-streaming chat completion for Gemini
162
200
  */
@@ -175,20 +213,11 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
175
213
  const signatureOrigin = this.thoughtSignatureOrigin(modelName);
176
214
  const convertedMessages = noSystemMessages.map(m => GeminiLLM_1.MapMJMessageToGeminiHistoryEntry(m, signatureOrigin));
177
215
  const tempMessages = this.geminiMessageSpacing(convertedMessages);
178
- // Split: all but last message go in history, last message gets system instructions prepended
179
- const history = tempMessages.slice(0, -1);
180
- const lastMessage = tempMessages.length > 0 ? tempMessages[tempMessages.length - 1] : null;
181
- // The system prompt is passed via systemInstruction (below), NOT bundled into the user
182
- // message — bundling put the stable prompt AFTER the variable history, defeating Gemini's
183
- // implicit prompt caching. The final message is just the latest user turn's parts.
184
- let finalMessageParts = [];
185
- if (lastMessage) {
186
- finalMessageParts.push(...lastMessage.parts);
187
- }
188
- // If no messages at all, send empty
189
- if (finalMessageParts.length === 0) {
190
- finalMessageParts = [{ text: '' }];
191
- }
216
+ // All but the last user turn go in the history; that turn is the message sent. The system
217
+ // prompt is passed via systemInstruction (below), NOT bundled into the user message —
218
+ // bundling put the stable prompt AFTER the variable history, defeating Gemini's implicit
219
+ // prompt caching.
220
+ const { history, message: finalMessageParts } = this.SplitForSend(tempMessages);
192
221
  // Sampling + response-format options, shaped for the model's version (see buildGenerationOptions)
193
222
  const modelOptions = this.buildGenerationOptions(params, modelName);
194
223
  // Ensure Gemini client is initialized
@@ -242,13 +271,19 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
242
271
  .join(', ');
243
272
  throw new Error(`Content blocked by model: ${finishReason}${blockedCategories ? ` - ${blockedCategories}` : ''}`);
244
273
  }
245
- const rawContent = candidate.content?.parts?.find(part => part.text && !part.thought)?.text || '';
274
+ // Every visible text part, not only the first: a turn can split its answer across parts.
275
+ const rawContent = (candidate.content?.parts ?? []).filter(part => part.text && !part.thought).map(part => part.text).join('');
246
276
  const thinking = (candidate.content?.parts ?? []).filter(part => part.thought && part.text).map(part => part.text).join('');
247
277
  const toolCalls = this.extractToolCalls(candidate.content?.parts, this.thoughtSignatureOrigin(modelName));
278
+ const reasoning = GeminiLLM_1.extractReasoning(candidate.content?.parts, this.thoughtSignatureOrigin(modelName));
248
279
  // Check if we got empty content despite no blocking. A native tool call IS output, and a
249
280
  // forced/clean tool-call turn legitimately carries no text at all — so tool calls
250
281
  // satisfy this check just as text does.
251
- if (!rawContent && !thinking && !toolCalls) {
282
+ // A rejected tool call is an answer the tool loop must correct, not missing output — but
283
+ // only for a request that declared tools. Without any, no tool loop can correct it, and
284
+ // the empty turn stays the error it always was, so failover can try another model.
285
+ const rejectedCall = params.tools?.length ? GeminiLLM_1.rejectedToolCallReason(finishReason) : undefined;
286
+ if (!rawContent && !thinking && !toolCalls && !rejectedCall) {
252
287
  const usage = result.usageMetadata;
253
288
  throw new Error(`No output received from model (finishReason: ${finishReason || 'none'}, ` +
254
289
  `promptTokens: ${usage?.promptTokenCount || 0}, ` +
@@ -288,14 +323,14 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
288
323
  role: 'assistant',
289
324
  content: content,
290
325
  thinking: thinkingContent || undefined,
291
- toolCalls: toolCalls
326
+ toolCalls: toolCalls,
327
+ ...(reasoning ? { reasoning } : {})
292
328
  },
293
329
  // Normalize the tool-call case and Gemini's "tried to call a tool but the call was
294
330
  // unreadable" case; every other reason keeps Gemini's own value.
295
- finish_reason: toolCalls ? CHAT_FINISH_REASON_TOOL_CALLS
296
- : finishReason === 'MALFORMED_FUNCTION_CALL' ? CHAT_FINISH_REASON_MALFORMED_TOOL_CALL
297
- : (finishReason || "completed"),
298
- index: 0
331
+ finish_reason: toolCalls ? CHAT_FINISH_REASON_TOOL_CALLS : (rejectedCall ?? (finishReason || "completed")),
332
+ index: 0,
333
+ ...(rejectedCall && candidate.finishMessage ? { finishMessage: candidate.finishMessage } : {})
299
334
  }],
300
335
  usage: geminiUsage
301
336
  },
@@ -357,8 +392,9 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
357
392
  const toolConfig = { functionCallingConfig: this.mapToolChoice(params.toolChoice) };
358
393
  requestConfig.toolConfig = toolConfig;
359
394
  }
360
- if (params.parallelToolCalls !== undefined) {
361
- console.warn('Gemini provider does not support the parallelToolCalls parameter, ignoring');
395
+ // Gemini always allows parallel calls, so only a request to turn them off goes unmet.
396
+ if (params.parallelToolCalls === false) {
397
+ console.warn('Gemini provider does not support turning parallel tool calls off, ignoring parallelToolCalls=false');
362
398
  }
363
399
  }
364
400
  /**
@@ -390,6 +426,18 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
390
426
  thoughtSignatureOrigin(modelName) {
391
427
  return `${this.ThoughtSignatureEndpoint}:${modelName}`;
392
428
  }
429
+ /**
430
+ * The normalized finish reason for a tool call Gemini rejected — `MALFORMED_FUNCTION_CALL` (the
431
+ * call could not be read) or `UNEXPECTED_TOOL_CALL` (a call to a tool the request did not offer)
432
+ * — or undefined for any other finish reason.
433
+ */
434
+ static rejectedToolCallReason(finishReason) {
435
+ switch (finishReason) {
436
+ case 'MALFORMED_FUNCTION_CALL': return CHAT_FINISH_REASON_MALFORMED_TOOL_CALL;
437
+ case 'UNEXPECTED_TOOL_CALL': return CHAT_FINISH_REASON_UNEXPECTED_TOOL_CALL;
438
+ default: return undefined;
439
+ }
440
+ }
393
441
  /**
394
442
  * Pulls `functionCall` parts out of a Gemini candidate and normalizes them.
395
443
  *
@@ -463,15 +511,12 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
463
511
  this.warnUnsupportedSampling(modelName, 'topP', params.topP);
464
512
  this.warnUnsupportedSampling(modelName, 'topK', params.topK);
465
513
  }
466
- switch (params.responseFormat) {
467
- case 'JSON':
468
- modelOptions.responseMimeType = 'application/json';
469
- break;
470
- case 'ModelSpecific':
471
- if (params.modelSpecificResponseFormat) {
472
- Object.assign(modelOptions, params.modelSpecificResponseFormat);
473
- }
474
- break;
514
+ // Provider options (e.g. a thinkingConfig) ride along with JSON too, not only ModelSpecific.
515
+ if (params.modelSpecificResponseFormat && (params.responseFormat === 'ModelSpecific' || params.responseFormat === 'JSON')) {
516
+ Object.assign(modelOptions, params.modelSpecificResponseFormat);
517
+ }
518
+ if (params.responseFormat === 'JSON') {
519
+ modelOptions.responseMimeType = 'application/json';
475
520
  }
476
521
  if (params.stopSequences != null && params.stopSequences.length > 0) {
477
522
  modelOptions.stopSequences = params.stopSequences;
@@ -511,26 +556,36 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
511
556
  /** Thinking warnings already logged, so each is logged once per process. */
512
557
  static { this._warnedThinking = new Set(); }
513
558
  thinkingReplacementKey(modelName, config) {
514
- return `${this.constructor.name}|${modelName}|${JSON.stringify(config)}`;
559
+ // Sorted keys, so the same setting with its keys in another order hits the same memo.
560
+ return `${this.constructor.name}|${modelName}|${JSON.stringify(config, Object.keys(config).sort())}`;
515
561
  }
516
562
  /**
517
563
  * Puts the `thinkingConfig` for `effortLevel` on the request (see {@link ResolveGeminiThinkingConfig}),
518
- * or what replaced it after the model rejected it earlier in this process. Nothing is added when
519
- * no effort is set; an effort that cannot be used is reported once.
564
+ * or what replaced it after the model rejected it earlier in this process. With no usable effort, a
565
+ * `thinkingConfig` already on the request (from `modelSpecificResponseFormat`) gets the same
566
+ * replacement, so a rejected setting is not re-sent on every call. An effort that cannot be used is
567
+ * reported once.
520
568
  */
521
569
  applyThinkingConfig(requestConfig, modelName, effortLevel) {
522
570
  const resolution = ResolveGeminiThinkingConfig(modelName, effortLevel);
523
571
  if (resolution.Ignored) {
524
572
  this.warnThinkingOnce(`${modelName}:${resolution.Ignored}`, `Gemini: ${resolution.Ignored}; sending no thinking setting, so the model thinks at its default.`);
525
573
  }
526
- if (!resolution.Config) {
574
+ const supplied = requestConfig.thinkingConfig;
575
+ const wanted = resolution.Config ?? supplied;
576
+ if (!wanted) {
527
577
  return;
528
578
  }
529
- const key = this.thinkingReplacementKey(modelName, resolution.Config);
530
- const config = GeminiLLM_1._thinkingReplacements.has(key) ? GeminiLLM_1._thinkingReplacements.get(key) : resolution.Config;
579
+ const key = this.thinkingReplacementKey(modelName, wanted);
580
+ const config = GeminiLLM_1._thinkingReplacements.has(key) ? GeminiLLM_1._thinkingReplacements.get(key) : wanted;
531
581
  if (config) {
532
582
  requestConfig.thinkingConfig = config;
533
583
  }
584
+ else if (!supplied || wanted === supplied) {
585
+ delete requestConfig.thinkingConfig;
586
+ }
587
+ // Otherwise the effort's own setting was rejected with nothing to fall back to, and the caller's
588
+ // `thinkingConfig` stays, as it would have with no effort level.
534
589
  }
535
590
  /**
536
591
  * Sends a request, and when it carried a thinking setting and Google answered 400, sends it once
@@ -613,9 +668,8 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
613
668
  const signatureOrigin = this.thoughtSignatureOrigin(modelName);
614
669
  const convertedMessages = noSystemMessages.map(m => GeminiLLM_1.MapMJMessageToGeminiHistoryEntry(m, signatureOrigin));
615
670
  const tempMessages = this.geminiMessageSpacing(convertedMessages);
616
- // Split: all but last message go in history, last message gets system instructions prepended
617
- const history = tempMessages.slice(0, -1);
618
- const lastMessage = tempMessages.length > 0 ? tempMessages[tempMessages.length - 1] : null;
671
+ // All but the last user turn go in the history; that turn is the message sent (see SplitForSend).
672
+ const { history, message: finalMessageParts } = this.SplitForSend(tempMessages);
619
673
  // Capture the request's cacheable-prefix info so the final streamed chunk's usage can be
620
674
  // logged next to it (GEMINI_CACHE_DEBUG only; processStreamingChunk reads this).
621
675
  this._cacheDiagContext = process.env.GEMINI_CACHE_DEBUG
@@ -623,15 +677,7 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
623
677
  : null;
624
678
  // System prompt is passed via systemInstruction (below), NOT bundled into the user message
625
679
  // — bundling defeats Gemini's implicit prompt caching (stable prompt ends up after the
626
- // variable history). The final message is just the latest user turn's parts.
627
- let finalMessageParts = [];
628
- if (lastMessage) {
629
- finalMessageParts.push(...lastMessage.parts);
630
- }
631
- // If no messages at all, send empty
632
- if (finalMessageParts.length === 0) {
633
- finalMessageParts = [{ text: '' }];
634
- }
680
+ // variable history).
635
681
  // Sampling + response-format options, shaped for the model's version (see buildGenerationOptions)
636
682
  const modelOptions = this.buildGenerationOptions(params, modelName);
637
683
  // Ensure Gemini client is initialized
@@ -1008,6 +1054,51 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
1008
1054
  const foreign = signatureOrigin !== undefined && typeof origin === 'string' && origin !== signatureOrigin;
1009
1055
  return foreign ? GEMINI_INJECTED_CALL_THOUGHT_SIGNATURE : signature;
1010
1056
  }
1057
+ /**
1058
+ * A turn's thought parts and signed text parts, as replayable reasoning.
1059
+ *
1060
+ * Thought parts are kept with their signature when they have one. Text parts are kept only when
1061
+ * at least one of them is signed, and then all of them, in order — the replay rebuilds the
1062
+ * turn's text from these blocks, so each signature lands back on the text it was minted for.
1063
+ * Function-call signatures travel on the calls themselves (see {@link extractToolCalls}).
1064
+ *
1065
+ * @param parts The candidate's content parts
1066
+ * @param signatureOrigin Where this response's signatures validate (see {@link thoughtSignatureOrigin})
1067
+ * @returns The blocks, or undefined when the turn had nothing to replay
1068
+ */
1069
+ static extractReasoning(parts, signatureOrigin) {
1070
+ const all = parts ?? [];
1071
+ const signature = (part) => (part.thoughtSignature ? { signature: part.thoughtSignature } : {});
1072
+ const blocks = all
1073
+ .filter((part) => part.thought && part.text)
1074
+ .map((part) => ({ provider: GEMINI_REASONING_PROVIDER, kind: 'thought', text: part.text, ...signature(part), origin: signatureOrigin }));
1075
+ // Gemini can put a turn's signature on a trailing part with empty text; it has to come back too.
1076
+ const textParts = all.filter((part) => typeof part.text === 'string' && !part.thought && !part.functionCall
1077
+ && (part.text.length > 0 || !!part.thoughtSignature));
1078
+ if (textParts.some((part) => part.thoughtSignature)) {
1079
+ blocks.push(...textParts.map((part) => ({ provider: GEMINI_REASONING_PROVIDER, kind: 'signed_text', text: part.text, ...signature(part), origin: signatureOrigin })));
1080
+ }
1081
+ return blocks.length > 0 ? blocks : undefined;
1082
+ }
1083
+ /**
1084
+ * The parts that replay a model turn's own reasoning: its thought parts, and — when its text
1085
+ * parts were signed and the message text is still exactly theirs — those text parts with their
1086
+ * signatures. `text` is undefined when the message's content should be mapped as usual: no
1087
+ * signed text, or text that was changed after the turn (compaction), which a signature would
1088
+ * no longer match. Blocks from another provider, or signed where this request is not going,
1089
+ * are dropped — a foreign signature is a hard 400.
1090
+ */
1091
+ static reasoningPartsForReplay(message, signatureOrigin) {
1092
+ const usable = (message.reasoning ?? []).filter((block) => block.provider === GEMINI_REASONING_PROVIDER
1093
+ && !(signatureOrigin !== undefined && block.origin !== undefined && block.origin !== signatureOrigin));
1094
+ const toPart = (block, thought) => ({ text: block.text ?? '', ...(thought ? { thought: true } : {}), ...(block.signature ? { thoughtSignature: block.signature } : {}) });
1095
+ const thoughts = usable.filter((block) => block.kind === 'thought').map((block) => toPart(block, true));
1096
+ const signedText = usable.filter((block) => block.kind === 'signed_text');
1097
+ const textMatches = typeof message.content === 'string'
1098
+ && signedText.length > 0
1099
+ && signedText.map((block) => block.text ?? '').join('').trim() === message.content.trim();
1100
+ return { thoughts, text: textMatches ? signedText.map((block) => toPart(block, false)) : undefined };
1101
+ }
1011
1102
  /**
1012
1103
  * Maps one MJ message to a Gemini history entry.
1013
1104
  *
@@ -1016,7 +1107,10 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
1016
1107
  * call's thought signature from anywhere else is swapped for the placeholder.
1017
1108
  */
1018
1109
  static MapMJMessageToGeminiHistoryEntry(message, signatureOrigin) {
1019
- const parts = GeminiLLM_1.MapMJContentToGeminiParts(message.content);
1110
+ // A model turn replays its own thoughts first, then its text, then its calls — the order
1111
+ // Gemini produced them in.
1112
+ const replay = message.role === 'assistant' ? GeminiLLM_1.reasoningPartsForReplay(message, signatureOrigin) : { thoughts: [] };
1113
+ const parts = [...replay.thoughts, ...(replay.text ?? GeminiLLM_1.MapMJContentToGeminiParts(message.content))];
1020
1114
  // An assistant turn that called tools must replay those calls as `functionCall` parts so the
1021
1115
  // `functionResponse` parts that follow have something to pair with.
1022
1116
  if (message.toolCalls?.length) {
@@ -1028,8 +1122,9 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
1028
1122
  }
1029
1123
  }
1030
1124
  // Gemini rejects an empty part list, and a pure tool-call turn has no prose — drop the empty
1031
- // text part that content mapping produces once real parts are carrying the turn.
1032
- const meaningfulParts = parts.length > 1 ? parts.filter(p => p.text !== '') : parts;
1125
+ // text part that content mapping produces once real parts are carrying the turn. An empty
1126
+ // part that carries a signature is the model's own, and stays.
1127
+ const meaningfulParts = parts.length > 1 ? parts.filter(p => p.text !== '' || !!p.thoughtSignature) : parts;
1033
1128
  return {
1034
1129
  role: message.role === 'assistant' ? 'model' : 'user', // google calls all messages other than the replies from the model 'user' which would include the system prompt
1035
1130
  parts: meaningfulParts.length > 0 ? meaningfulParts : [{ text: '' }]