@jeffusion/bungee-llms 6.7.2 → 6.8.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.
package/README.md CHANGED
@@ -12,4 +12,4 @@ const request = session.convertRequest({input: 'Hello'});
12
12
  session.dispose();
13
13
  ```
14
14
 
15
- The matrix has four passthrough pairs, ten direct conversions and two rejected Responses/Gemini pairs. Explicit reasoning controls require a verified wire policy. Tools, history and output constraints fail with a safe reason and param when their semantics cannot be preserved. See [LLM Protocol Adapter](../../docs/reference/llm-protocol-adapter.md).
15
+ The matrix has four passthrough pairs, eleven direct conversions and one rejected Gemini-to-Responses pair. Explicit reasoning controls require a verified wire policy. Tools, history and output constraints fail with a safe reason and param when their semantics cannot be preserved. See [LLM Protocol Adapter](../../docs/reference/llm-protocol-adapter.md).
package/dist/index.js CHANGED
@@ -3732,7 +3732,7 @@ function definitionKey(value) {
3732
3732
  return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${definitionKey(value[key])}`).join(",")}}`;
3733
3733
  return JSON.stringify(value);
3734
3734
  }
3735
- function decodeResponsesRequest(raw, protocol, capabilities = {}) {
3735
+ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {}) {
3736
3736
  const body = record(raw, "Responses request");
3737
3737
  if (capabilities.agentMessageDelivery !== undefined && capabilities.agentMessageDelivery !== "plaintext")
3738
3738
  fail("invalid_payload", "Unknown agent message delivery policy", "agentMessageDelivery");
@@ -3999,12 +3999,16 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}) {
3999
3999
  if (item.content != null)
4000
4000
  fail("unsupported_reasoning", "Reasoning content requires an explicit history mapping", `${messageParam}.content`);
4001
4001
  const summary = list(item.summary, "reasoning summary");
4002
- pendingReasoning += summary.map((part) => {
4002
+ const text = summary.map((part) => {
4003
4003
  const p = record(part, "reasoning summary");
4004
4004
  if (p.type !== "summary_text")
4005
4005
  fail("unsupported_reasoning", "Unknown reasoning summary");
4006
4006
  return string(p.text, "summary text");
4007
4007
  }).join("");
4008
+ if (options.preserveContentOrder)
4009
+ addMessage({ role: "assistant", content: null, reasoning_content: text, ...item.id === undefined ? {} : { id: string(item.id, "item.id", true) } });
4010
+ else
4011
+ pendingReasoning += text;
4008
4012
  return;
4009
4013
  }
4010
4014
  if (item.type === "function_call" || item.type === "custom_tool_call") {
@@ -4019,7 +4023,7 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}) {
4019
4023
  argumentObject(args);
4020
4024
  const call = { id, type: "function", function: { name: resolve(item, custom), arguments: args } };
4021
4025
  const previous = chat.at(-1);
4022
- if (previous?.role === "assistant") {
4026
+ if (previous?.role === "assistant" && !options.preserveContentOrder) {
4023
4027
  previous.tool_calls = [...previous.tool_calls ?? [], call];
4024
4028
  if (pendingReasoning)
4025
4029
  previous.reasoning_content = pendingReasoning;
@@ -4043,6 +4047,8 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}) {
4043
4047
  if (!["user", "assistant", "system", "developer"].includes(role))
4044
4048
  fail("unsupported_content", "Unknown message role");
4045
4049
  const message = { role, content: normalizeContent(item.content, role) };
4050
+ if (options.preserveContentOrder && item.id !== undefined)
4051
+ message.id = string(item.id, "item.id", true);
4046
4052
  if (pendingReasoning) {
4047
4053
  if (role !== "assistant")
4048
4054
  fail("unsupported_reasoning", "Reasoning must precede an assistant item");
@@ -4583,6 +4589,9 @@ function encodeResponsesResult(raw, protocol, model, toolNames = new Map, config
4583
4589
  fail("missing_terminal", "JSON response has no terminal result");
4584
4590
  return record(end.response, "Responses result");
4585
4591
  }
4592
+ // src/protocol-session/gemini.ts
4593
+ import { createHash } from "crypto";
4594
+
4586
4595
  // src/protocol-session/validation.ts
4587
4596
  function fields2(value, allowed, path, code = "unsupported_request") {
4588
4597
  for (const key of Object.keys(value))
@@ -4627,6 +4636,145 @@ function textParts(raw, path, style, role) {
4627
4636
  });
4628
4637
  }
4629
4638
 
4639
+ // src/protocol-session/gemini.ts
4640
+ var signatureSeparator = "__thought__";
4641
+ function checkedSignature(value, maxBytes) {
4642
+ const signature = bounded(string(value, "thoughtSignature", true), maxBytes, "thoughtSignature");
4643
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(signature) || signature.length % 4 === 1 || signature.includes("=") && signature.length % 4 !== 0 || Buffer.from(signature, "base64").toString("base64").replace(/=+$/, "") !== signature.replace(/=+$/, ""))
4644
+ fail("invalid_tool_arguments", "Invalid Gemini thought signature encoding", "thoughtSignature");
4645
+ return signature;
4646
+ }
4647
+ var envelopePrefix = "bungee_gemini:";
4648
+ var geminiEnvelopeBytes = (payloadBytes) => envelopePrefix.length + Math.ceil(payloadBytes * 4 / 3);
4649
+ var geminiTextHash = (text) => createHash("sha256").update(text).digest("base64url");
4650
+ function geminiSignatureItem(items, budget) {
4651
+ const payload = serialized({ version: 1, items }, budget.maxArgumentBytes, "Gemini signatures");
4652
+ return {
4653
+ type: "reasoning",
4654
+ id: `rs_gemini_${crypto.randomUUID().replaceAll("-", "")}`,
4655
+ summary: [],
4656
+ encrypted_content: bounded(envelopePrefix + Buffer.from(payload).toString("base64url"), budget.maxArgumentBytes, "Gemini signatures")
4657
+ };
4658
+ }
4659
+ function readGeminiSignatures(item, budget) {
4660
+ fields2(item, ["type", "id", "summary", "encrypted_content", "status"], "Gemini signatures", "unsupported_reasoning");
4661
+ if (item.type !== "reasoning" || list(item.summary, "summary").length)
4662
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier");
4663
+ string(item.id, "signature item id", true);
4664
+ const opaque = bounded(string(item.encrypted_content, "encrypted_content", true), budget.maxArgumentBytes, "Gemini signatures");
4665
+ if (!opaque.startsWith(envelopePrefix))
4666
+ fail("unsupported_reasoning", "Native encrypted reasoning cannot be restored to Gemini");
4667
+ const encoded = opaque.slice(envelopePrefix.length), bytes = Buffer.from(encoded, "base64url");
4668
+ if (!encoded || bytes.toString("base64url") !== encoded)
4669
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier encoding");
4670
+ let raw;
4671
+ try {
4672
+ raw = JSON.parse(bytes.toString("utf8"));
4673
+ } catch {
4674
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier JSON");
4675
+ }
4676
+ const body = record(raw, "Gemini signatures");
4677
+ fields2(body, ["version", "items"], "Gemini signatures", "unsupported_reasoning");
4678
+ if (body.version !== 1)
4679
+ fail("unsupported_reasoning", "Unknown Gemini signature format");
4680
+ const ids = new Set;
4681
+ let partCount = 0;
4682
+ const result = list(body.items, "signature items").map((raw) => {
4683
+ const item = record(raw, "signature item");
4684
+ fields2(item, ["id", "thought", "parts"], "signature item", "unsupported_reasoning");
4685
+ const id = string(item.id, "signed item id", true);
4686
+ if (ids.has(id) || typeof item.thought !== "boolean")
4687
+ fail("unsupported_reasoning", "Invalid signed item identity");
4688
+ ids.add(id);
4689
+ const parts = list(item.parts, "signed parts").map((raw) => {
4690
+ if (++partCount > budget.maxItems)
4691
+ fail("resource_limit", "Too many signed Gemini parts");
4692
+ const part = record(raw, "signed part");
4693
+ fields2(part, ["length", "hash", "signature", "textAbsent"], "signed part", "unsupported_reasoning");
4694
+ const length = integer(part.length, "signed part length"), hash = string(part.hash, "signed part hash", true);
4695
+ if (!/^[A-Za-z0-9_-]{43}$/.test(hash))
4696
+ fail("unsupported_reasoning", "Invalid signed part hash");
4697
+ const signature = part.signature === undefined ? undefined : checkedSignature(part.signature, budget.maxArgumentBytes);
4698
+ if (part.textAbsent !== undefined && (part.textAbsent !== true || length !== 0 || signature === undefined))
4699
+ fail("unsupported_reasoning", "Invalid empty signed part");
4700
+ return { length, hash, ...signature === undefined ? {} : { signature }, ...part.textAbsent ? { textAbsent: true } : {} };
4701
+ });
4702
+ if (!parts.some((p) => p.signature !== undefined))
4703
+ fail("unsupported_reasoning", "Signature carrier has no signature");
4704
+ return { id, thought: item.thought, parts };
4705
+ });
4706
+ if (!result.length || result.length > budget.maxItems)
4707
+ fail("unsupported_reasoning", "Invalid signature item count");
4708
+ return result;
4709
+ }
4710
+ function restoreGeminiHistory(input, budget) {
4711
+ const original = typeof input === "string" ? [] : list(input, "input").map((raw) => record(raw, "input item"));
4712
+ const carriers = new Set, parts = new Map, ids = new Map;
4713
+ original.forEach((item, i) => {
4714
+ if (typeof item.id === "string") {
4715
+ if (ids.has(item.id))
4716
+ fail("invalid_tool_history", "Duplicate history item id", "input.id");
4717
+ ids.set(item.id, i);
4718
+ }
4719
+ });
4720
+ original.forEach((carrier, index) => {
4721
+ if (carrier.encrypted_content == null)
4722
+ return;
4723
+ const signed = readGeminiSignatures(carrier, budget);
4724
+ carriers.add(carrier);
4725
+ let previous = -1;
4726
+ for (const item of signed) {
4727
+ const at = ids.get(item.id);
4728
+ if (at === undefined || at >= index || at <= previous || parts.has(item.id))
4729
+ fail("unsupported_reasoning", "Signed history reference is missing or ambiguous");
4730
+ previous = at;
4731
+ const source = original[at];
4732
+ if (item.thought ? source.type !== "reasoning" || source.encrypted_content != null : source.role !== "assistant" || source.type !== undefined && source.type !== "message")
4733
+ fail("unsupported_reasoning", "Signed history item kind changed");
4734
+ const content = item.thought ? list(source.summary, "summary") : typeof source.content === "string" ? [{ type: "output_text", text: source.content }] : list(source.content, "content");
4735
+ const text = content.map((raw) => {
4736
+ const p = record(raw, "signed text");
4737
+ if (p.type !== (item.thought ? "summary_text" : "output_text") && !(p.type === "input_text" && !item.thought))
4738
+ fail("unsupported_reasoning", "Signed history content kind changed");
4739
+ return string(p.text, "signed text");
4740
+ }).join("");
4741
+ let offset = 0;
4742
+ const restored = item.parts.map((part) => {
4743
+ const value = text.slice(offset, offset + part.length);
4744
+ offset += part.length;
4745
+ if (value.length !== part.length || geminiTextHash(value) !== part.hash)
4746
+ fail("unsupported_reasoning", "Signed history text changed");
4747
+ return { ...part.textAbsent ? {} : { text: value }, ...item.thought ? { thought: true } : {}, ...part.signature === undefined ? {} : { thoughtSignature: part.signature } };
4748
+ });
4749
+ if (offset !== text.length)
4750
+ fail("unsupported_reasoning", "Signed history text was not fully consumed");
4751
+ parts.set(item.id, restored);
4752
+ }
4753
+ });
4754
+ return {
4755
+ input: typeof input === "string" ? input : original.filter((item) => !carriers.has(item)),
4756
+ parts,
4757
+ canonicalHistory(decoded) {
4758
+ if (!carriers.size)
4759
+ return decoded;
4760
+ let next = 0;
4761
+ return original.flatMap((item) => carriers.has(item) ? [item] : item.type === "additional_tools" ? [] : [decoded[next++]]);
4762
+ }
4763
+ };
4764
+ }
4765
+ function encodeGeminiCallId(id, signature, maxBytes) {
4766
+ if (id.includes(signatureSeparator))
4767
+ fail("invalid_tool_arguments", "Gemini call id contains the signature separator", "functionCall.id");
4768
+ return signature === undefined ? id : `${id}${signatureSeparator}${checkedSignature(signature, maxBytes)}`;
4769
+ }
4770
+ function decodeGeminiCallId(value, maxBytes) {
4771
+ const separator = value.indexOf(signatureSeparator);
4772
+ if (separator < 0)
4773
+ return { id: value };
4774
+ const id = string(value.slice(0, separator), "functionCall.id", true);
4775
+ return { id, thoughtSignature: checkedSignature(value.slice(separator + signatureSeparator.length), maxBytes) };
4776
+ }
4777
+
4630
4778
  // src/protocol-session/schema.ts
4631
4779
  function geminiSchemaToJson(raw, path, code = "unsupported_request", depth = 0) {
4632
4780
  if (depth > 64)
@@ -5060,6 +5208,9 @@ function convertProtocolRequest(raw, context) {
5060
5208
  b.stream = context.streaming;
5061
5209
  }
5062
5210
  validateCanonical(b, context);
5211
+ const geminiHistory = context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content" ? restoreGeminiHistory(b.input, limits(context.capabilities?.limits)) : undefined;
5212
+ if (geminiHistory)
5213
+ b.input = geminiHistory.input;
5063
5214
  const cap = { ...context.capabilities, agentMessageDelivery: context.agentMessageDelivery ?? context.capabilities?.agentMessageDelivery, omitOptionalWebSearch: true, preserveToolIdentityDescription: true, preserveRefusalContent: true }, policy = context.reasoningPolicy;
5064
5215
  const reasoning = b.reasoning === undefined ? undefined : record(b.reasoning, "reasoning");
5065
5216
  const sourceThinking = b.sourceThinking;
@@ -5085,10 +5236,10 @@ function convertProtocolRequest(raw, context) {
5085
5236
  if (sourceThinking !== undefined && reasoning?.effort === undefined && policy?.targetEffort !== undefined)
5086
5237
  mappedEffort = string(policy.targetEffort, "reasoningPolicy.targetEffort", true);
5087
5238
  const target = context.targetProtocol;
5088
- if (target === "gemini_generate_content" && reasoning?.effort !== undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
5239
+ if (target === "gemini_generate_content" && reasoning?.effort !== undefined && mappedEffort === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
5089
5240
  fail("unsupported_reasoning", "Gemini requires an explicit thinking budget or level", "reasoning.effort");
5090
5241
  if (sourceThinking !== undefined) {
5091
- const represented = target === "responses" || target === "chat_completions" ? mappedEffort !== undefined : target === "anthropic_messages" ? mappedEffort !== undefined || policy?.anthropicThinkingMode !== undefined || policy?.anthropicThinkingBudget !== undefined : policy?.geminiThinkingBudget !== undefined || policy?.geminiThinkingLevel !== undefined;
5242
+ const represented = target === "responses" || target === "chat_completions" ? mappedEffort !== undefined : target === "anthropic_messages" ? mappedEffort !== undefined || policy?.anthropicThinkingMode !== undefined || policy?.anthropicThinkingBudget !== undefined : mappedEffort !== undefined || policy?.geminiThinkingBudget !== undefined || policy?.geminiThinkingLevel !== undefined;
5092
5243
  if (!represented)
5093
5244
  fail("unsupported_reasoning", "Source thinking mode needs an explicit target wire policy", "thinking");
5094
5245
  }
@@ -5147,9 +5298,13 @@ function convertProtocolRequest(raw, context) {
5147
5298
  const decodingTarget = target === "gemini_generate_content" ? "chat_completions" : target;
5148
5299
  if (target === "gemini_generate_content" && reasoning)
5149
5300
  b.reasoning = { ...reasoning, effort: undefined };
5150
- const decoded = decodeResponsesRequest(b, decodingTarget, { ...cap, reasoningHistory: target !== "anthropic_messages" && cap.reasoningHistory === true, reasoningEffort: target === "chat_completions" && cap.reasoningEffort === true, anthropicThinkingBudget: undefined });
5301
+ const decoded = decodeResponsesRequest(b, decodingTarget, { ...cap, reasoningHistory: target !== "anthropic_messages" && cap.reasoningHistory === true, reasoningEffort: target === "chat_completions" && cap.reasoningEffort === true, anthropicThinkingBudget: undefined }, { preserveContentOrder: target === "gemini_generate_content" });
5151
5302
  const diagnostics = decoded.diagnostics;
5152
- const body = target === "gemini_generate_content" ? renderGemini(decoded.body, cap.geminiJsonSchema === true) : decoded.body;
5303
+ if (target === "gemini_generate_content" && decoded.body.parallel_tool_calls === true) {
5304
+ delete decoded.body.parallel_tool_calls;
5305
+ diagnostics.push({ param: "parallel_tool_calls", action: "omitted", reason: "gemini_parallel_tool_calls_allowed" });
5306
+ }
5307
+ const body = target === "gemini_generate_content" ? renderGemini(decoded.body, context, geminiHistory?.parts, diagnostics) : decoded.body;
5153
5308
  if (stop !== undefined)
5154
5309
  body[target === "chat_completions" ? "stop" : target === "anthropic_messages" ? "stop_sequences" : "generationConfig"] = target === "gemini_generate_content" ? { ...record(body.generationConfig ?? {}, "generationConfig"), stopSequences: typeof stop === "string" ? [stop] : stop } : typeof stop === "string" ? [stop] : stop;
5155
5310
  if (target === "anthropic_messages") {
@@ -5171,18 +5326,24 @@ function convertProtocolRequest(raw, context) {
5171
5326
  body.thinking = { type: "enabled", budget_tokens: budget };
5172
5327
  }
5173
5328
  }
5174
- if (target === "gemini_generate_content" && (policy?.geminiThinkingBudget !== undefined || policy?.geminiThinkingLevel !== undefined)) {
5175
- if (policy.geminiThinkingBudget !== undefined && policy.geminiThinkingLevel !== undefined)
5329
+ if (target === "gemini_generate_content" && (mappedEffort !== undefined || policy?.geminiThinkingBudget !== undefined || policy?.geminiThinkingLevel !== undefined)) {
5330
+ const level = policy?.geminiThinkingLevel ?? mappedEffort;
5331
+ if (policy?.geminiThinkingBudget !== undefined && level !== undefined)
5176
5332
  fail("unsupported_reasoning", "Choose one Gemini thinking policy", "reasoningPolicy");
5177
- const thinkingConfig = policy.geminiThinkingBudget !== undefined ? { thinkingBudget: integer(policy.geminiThinkingBudget, "reasoningPolicy.geminiThinkingBudget", -1) } : { thinkingLevel: string(policy.geminiThinkingLevel, "reasoningPolicy.geminiThinkingLevel", true) };
5333
+ if (level !== undefined && !["minimal", "low", "medium", "high"].includes(level))
5334
+ fail("unsupported_reasoning", "Unknown Gemini thinking level", "reasoning.effort");
5335
+ if (mappedEffort !== undefined && policy?.geminiThinkingLevel !== undefined && mappedEffort !== policy.geminiThinkingLevel)
5336
+ fail("unsupported_reasoning", "Conflicting Gemini thinking levels", "reasoning.effort");
5337
+ const thinkingConfig = policy?.geminiThinkingBudget !== undefined ? { thinkingBudget: integer(policy.geminiThinkingBudget, "reasoningPolicy.geminiThinkingBudget", -1) } : { thinkingLevel: string(level, "reasoningPolicy.geminiThinkingLevel", true) };
5178
5338
  body.generationConfig = { ...record(body.generationConfig ?? {}, "generationConfig"), thinkingConfig };
5179
5339
  }
5180
5340
  if (mappedEffort !== undefined || sourceThinking !== undefined || policy?.anthropicThinkingBudget !== undefined)
5181
5341
  diagnostics.push({ param: "reasoning", action: "mapped", reason: "explicit_verified_wire_policy" });
5182
- return { body, canonicalHistory: decoded.canonicalInput, diagnostics, toolNames: decoded.toolNames, streaming: b.stream === true };
5342
+ return { body, canonicalHistory: geminiHistory?.canonicalHistory(decoded.canonicalInput) ?? decoded.canonicalInput, diagnostics, toolNames: decoded.toolNames, streaming: b.stream === true };
5183
5343
  }
5184
- function renderGemini(chat, jsonSchema) {
5344
+ function renderGemini(chat, context, signedParts, diagnostics) {
5185
5345
  const result = { contents: [] }, contents = result.contents, system = [], calls = new Map;
5346
+ const nativeIds = new Set;
5186
5347
  const append = (role, parts) => {
5187
5348
  const prev = contents.at(-1);
5188
5349
  if (prev?.role === role)
@@ -5191,14 +5352,22 @@ function renderGemini(chat, jsonSchema) {
5191
5352
  contents.push({ role, parts });
5192
5353
  };
5193
5354
  for (const m of chat.messages) {
5355
+ const signed = signedParts?.get(m.id);
5356
+ if (signed) {
5357
+ append("model", signed);
5358
+ continue;
5359
+ }
5194
5360
  const parts = m.content == null ? [] : typeof m.content === "string" ? [{ text: m.content }] : m.content.map((p) => {
5195
5361
  if (p.type !== "text")
5196
5362
  fail("unsupported_content", "This content cannot cross to Gemini", "input");
5197
5363
  return { text: p.text };
5198
5364
  });
5199
5365
  if (m.role === "system" || m.role === "developer") {
5200
- if (contents.length)
5201
- fail("unsupported_content", "Mid-conversation instructions cannot be relocated", "input");
5366
+ if (contents.length) {
5367
+ if (context.sourceProtocol !== "responses")
5368
+ fail("unsupported_content", "Mid-conversation instructions cannot be relocated", "input");
5369
+ diagnostics.push({ param: "input", action: "mapped", reason: "gemini_mid_conversation_instructions_consolidated" });
5370
+ }
5202
5371
  system.push(...parts);
5203
5372
  continue;
5204
5373
  }
@@ -5208,7 +5377,8 @@ function renderGemini(chat, jsonSchema) {
5208
5377
  fail("invalid_tool_history", "Unknown tool result", "input");
5209
5378
  if (m.is_error === true)
5210
5379
  fail("unsupported_content", "Tool error authority cannot be represented by Gemini", "input");
5211
- append("user", [{ functionResponse: { id: m.tool_call_id, name, response: { output: m.content } } }]);
5380
+ const { id } = context.sourceProtocol === "responses" ? decodeGeminiCallId(m.tool_call_id, limits(context.capabilities?.limits).maxArgumentBytes) : { id: m.tool_call_id };
5381
+ append("user", [{ functionResponse: { id, name, response: { output: m.content } } }]);
5212
5382
  continue;
5213
5383
  }
5214
5384
  if (m.reasoning_content !== undefined)
@@ -5216,10 +5386,20 @@ function renderGemini(chat, jsonSchema) {
5216
5386
  for (const c of m.tool_calls ?? []) {
5217
5387
  const fn = record(c.function, "function");
5218
5388
  calls.set(c.id, fn.name);
5219
- parts.push({ functionCall: { id: c.id, name: fn.name, args: argumentObject(fn.arguments) } });
5389
+ const { id, thoughtSignature } = context.sourceProtocol === "responses" ? decodeGeminiCallId(c.id, limits(context.capabilities?.limits).maxArgumentBytes) : { id: c.id, thoughtSignature: undefined };
5390
+ if (nativeIds.has(id))
5391
+ fail("invalid_tool_history", "Duplicate decoded Gemini call id", "call_id");
5392
+ nativeIds.add(id);
5393
+ parts.push({ functionCall: { id, name: fn.name, args: argumentObject(fn.arguments) }, ...thoughtSignature === undefined ? {} : { thoughtSignature } });
5220
5394
  }
5221
5395
  append(m.role === "assistant" ? "model" : "user", parts);
5222
5396
  }
5397
+ if (chat.parallel_tool_calls !== undefined) {
5398
+ if (context.sourceProtocol !== "responses" || chat.parallel_tool_calls !== false)
5399
+ fail("unsupported_request", "Gemini cannot enforce parallel tool preference", "parallel_tool_calls");
5400
+ system.push({ text: "Call at most one tool per response." });
5401
+ diagnostics.push({ param: "parallel_tool_calls", action: "mapped", reason: "gemini_serial_tool_calls_prompt_only" });
5402
+ }
5223
5403
  if (system.length)
5224
5404
  result.systemInstruction = { parts: system };
5225
5405
  const generation = {};
@@ -5228,12 +5408,10 @@ function renderGemini(chat, jsonSchema) {
5228
5408
  generation[to] = chat[from];
5229
5409
  if (chat.metadata !== undefined)
5230
5410
  fail("unsupported_request", "Gemini has no compatible request metadata", "metadata");
5231
- if (chat.parallel_tool_calls !== undefined)
5232
- fail("unsupported_request", "Gemini cannot enforce parallel tool preference", "parallel_tool_calls");
5233
5411
  if (chat.response_format !== undefined) {
5234
5412
  const f = record(chat.response_format, "format");
5235
5413
  if (f.type === "json_schema") {
5236
- if (!jsonSchema)
5414
+ if (!context.capabilities?.geminiJsonSchema)
5237
5415
  fail("unsupported_request", "Target JSON schema capability is required", "text.format");
5238
5416
  const s = record(f.json_schema, "schema");
5239
5417
  if (s.strict === false)
@@ -5378,7 +5556,11 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
5378
5556
  fail("unsupported_content", "Output annotations cannot cross protocols", path);
5379
5557
  }
5380
5558
  } else if (t.type === "reasoning") {
5381
- if (t.encrypted_content != null || t.content != null)
5559
+ if (t.encrypted_content != null && context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content")
5560
+ readGeminiSignatures(t, limits(context.capabilities?.limits));
5561
+ else if (t.encrypted_content != null)
5562
+ fail("unsupported_reasoning", "Opaque reasoning cannot cross protocols", path);
5563
+ if (t.content != null)
5382
5564
  fail("unsupported_reasoning", "Opaque or raw reasoning output cannot cross protocols", path);
5383
5565
  for (const rawPart of list(t.summary, "summary")) {
5384
5566
  const p = record(rawPart, "summary");
@@ -5501,20 +5683,28 @@ function responseFromCanonical(raw, protocol, context) {
5501
5683
 
5502
5684
  class GeminiCanonicalDecoder {
5503
5685
  context;
5686
+ streaming;
5504
5687
  encoder;
5505
5688
  serial = 0;
5506
5689
  ended = false;
5507
5690
  tools = false;
5508
5691
  ids = new Set;
5509
- constructor(context, names) {
5692
+ sequence = 0;
5693
+ contentId;
5694
+ partCount = 0;
5695
+ replayBytes = Buffer.byteLength(JSON.stringify({ version: 1, items: [] }));
5696
+ signedItems = 0;
5697
+ signed = new Map;
5698
+ constructor(context, names, streaming = true) {
5510
5699
  this.context = context;
5511
- this.encoder = new ResponsesEventEncoder("chat_completions", context.responseModel ?? context.model, names, context.capabilities?.limits, { preserveContentOrder: true });
5700
+ this.streaming = streaming;
5701
+ this.encoder = new ResponsesEventEncoder("chat_completions", context.responseModel ?? context.model, names, context.capabilities?.limits, { preserveContentOrder: true, agentMessageDelivery: context.capabilities?.agentMessageDelivery });
5512
5702
  }
5513
5703
  push(raw) {
5514
5704
  const b = record(raw, "Gemini response");
5515
5705
  fields2(b, ["candidates", "usageMetadata", "modelVersion", "responseId", "promptFeedback", "error"], "", "unsupported_response");
5516
5706
  if (b.error !== undefined)
5517
- return this.encoder.push({ error: safeProtocolError() });
5707
+ return this.decorate(this.encoder.push({ error: safeProtocolError() }));
5518
5708
  const events = [];
5519
5709
  if (b.promptFeedback !== undefined) {
5520
5710
  const p = record(b.promptFeedback, "promptFeedback");
@@ -5532,34 +5722,69 @@ class GeminiCanonicalDecoder {
5532
5722
  fields2(c, ["index", "content", "finishReason", "safetyRatings", "finishMessage"], "candidates", "unsupported_response");
5533
5723
  if (c.index !== undefined && c.index !== 0)
5534
5724
  fail("unsupported_response", "Only candidate index zero is supported", "candidates.index");
5535
- if (c.content !== undefined) {
5725
+ if (c.content !== undefined && c.content !== null) {
5536
5726
  const content = record(c.content, "content");
5537
5727
  fields2(content, ["role", "parts"], "candidates.content", "unsupported_content");
5538
5728
  if (content.role !== undefined && content.role !== "model")
5539
5729
  fail("unsupported_response", "Response role must be model", "candidates.content.role");
5540
- const parts = list(content.parts, "parts");
5730
+ const parts = list(content.parts ?? [], "parts");
5541
5731
  if (this.ended && parts.length)
5542
5732
  fail("invalid_stream", "Content arrived after Gemini terminal");
5543
5733
  for (const [i, rawPart] of parts.entries()) {
5544
5734
  const p = record(rawPart, "part");
5545
5735
  fields2(p, ["text", "thought", "functionCall", "thoughtSignature"], "candidates.content.parts", "unsupported_content");
5546
- if (p.thoughtSignature !== undefined)
5736
+ if (p.thoughtSignature !== undefined && this.context.sourceProtocol !== "responses")
5547
5737
  fail("unsupported_reasoning", "Thought signatures cannot cross protocols", "candidates.content.parts.thoughtSignature");
5548
5738
  if (p.functionCall !== undefined) {
5549
5739
  if (p.text !== undefined || p.thought !== undefined)
5550
5740
  fail("unsupported_content", "Mixed Gemini part kinds", "candidates.content.parts");
5551
5741
  const f = record(p.functionCall, "functionCall");
5552
5742
  fields2(f, ["id", "name", "args"], "functionCall", "unsupported_tool");
5553
- const index = this.serial++, id = f.id === undefined ? `call_gemini_${index}` : string(f.id, "functionCall.id", true);
5554
- if (this.ids.has(id))
5743
+ const index = this.serial++, originalId = f.id === undefined ? `call_gemini_${crypto.randomUUID().replaceAll("-", "")}` : string(f.id, "functionCall.id", true);
5744
+ if (this.ids.has(originalId))
5555
5745
  fail("invalid_tool_arguments", "Duplicate Gemini call id", "functionCall.id");
5556
- this.ids.add(id);
5746
+ this.ids.add(originalId);
5747
+ const id = this.context.sourceProtocol === "responses" ? encodeGeminiCallId(originalId, p.thoughtSignature, limits(this.context.capabilities?.limits).maxArgumentBytes) : originalId;
5557
5748
  this.tools = true;
5558
5749
  events.push(...this.encoder.push({ choices: [{ delta: { tool_calls: [{ index, id, type: "function", function: { name: string(f.name, "functionCall.name", true), arguments: JSON.stringify(record(f.args ?? {}, "functionCall.args")) } }] } }] }));
5559
5750
  } else {
5560
5751
  if (p.thought !== undefined && typeof p.thought !== "boolean")
5561
5752
  fail("invalid_payload", "Thought flag must be boolean", "thought");
5562
- events.push(...this.encoder.push({ choices: [{ delta: { [p.thought === true ? "reasoning_content" : "content"]: string(p.text, `parts[${i}].text`) } }] }));
5753
+ const text = string(p.text ?? (p.thoughtSignature === undefined ? undefined : ""), `parts[${i}].text`);
5754
+ const output = this.encoder.push({ choices: [{ delta: { [p.thought === true ? "reasoning_content" : "content"]: text } }] });
5755
+ const added = output.find((e) => e.type === "response.output_item.added");
5756
+ if (added)
5757
+ this.contentId = record(added.item, "item").id;
5758
+ const id = this.contentId;
5759
+ let item = this.signed.get(id);
5760
+ if (!item) {
5761
+ item = { id, thought: p.thought === true, parts: [], hasSignature: false, metadataBytes: Buffer.byteLength(JSON.stringify({ id, thought: p.thought === true, parts: [] })) };
5762
+ this.signed.set(id, item);
5763
+ }
5764
+ const signature = p.thoughtSignature === undefined ? undefined : checkedSignature(p.thoughtSignature, limits(this.context.capabilities?.limits).maxArgumentBytes);
5765
+ const previous = item.parts.at(-1);
5766
+ const merge = this.streaming && signature === undefined && previous && previous.signature === undefined && !previous.textAbsent;
5767
+ const partBytes = Buffer.byteLength(JSON.stringify({ length: text.length + (merge ? previous.text.length : 0), hash: "x".repeat(43), ...signature === undefined ? {} : { signature }, ...p.text === undefined ? { textAbsent: true } : {} }));
5768
+ const metadataBytes = item.metadataBytes + partBytes - (merge ? previous.metadataBytes : 0) + (!merge && item.parts.length ? 1 : 0);
5769
+ const hasSignature = item.hasSignature || signature !== undefined;
5770
+ const replayBytes = this.replayBytes + (item.hasSignature ? metadataBytes - item.metadataBytes : hasSignature ? metadataBytes + (this.signedItems ? 1 : 0) : 0);
5771
+ const budget = limits(this.context.capabilities?.limits);
5772
+ if (hasSignature && geminiEnvelopeBytes(replayBytes) > Math.min(budget.maxArgumentBytes, budget.maxOutputBytes))
5773
+ fail("resource_limit", "Accumulated Gemini signatures exceed replay budget");
5774
+ if (hasSignature && !item.hasSignature)
5775
+ this.signedItems++;
5776
+ this.replayBytes = replayBytes;
5777
+ item.metadataBytes = metadataBytes;
5778
+ item.hasSignature = hasSignature;
5779
+ if (merge) {
5780
+ previous.text += text;
5781
+ previous.metadataBytes = partBytes;
5782
+ } else {
5783
+ if (++this.partCount > limits(this.context.capabilities?.limits).maxItems)
5784
+ fail("resource_limit", "Too many Gemini parts");
5785
+ item.parts.push({ text, metadataBytes: partBytes, ...signature === undefined ? {} : { signature }, ...p.text === undefined ? { textAbsent: true } : {} });
5786
+ }
5787
+ events.push(...output);
5563
5788
  }
5564
5789
  }
5565
5790
  }
@@ -5576,25 +5801,47 @@ class GeminiCanonicalDecoder {
5576
5801
  }
5577
5802
  if (b.usageMetadata !== undefined) {
5578
5803
  const u = record(b.usageMetadata, "usageMetadata");
5579
- fields2(u, ["promptTokenCount", "candidatesTokenCount", "totalTokenCount", "cachedContentTokenCount", "thoughtsTokenCount"], "usageMetadata", "unsupported_response");
5580
- for (const [k, v] of Object.entries(u))
5581
- integer(v, `usageMetadata.${k}`);
5582
- const input = u.promptTokenCount ?? 0, thoughts = u.thoughtsTokenCount ?? 0, output = (u.candidatesTokenCount ?? 0) + thoughts;
5804
+ for (const k of ["promptTokenCount", "candidatesTokenCount", "totalTokenCount", "cachedContentTokenCount", "thoughtsTokenCount", "toolUsePromptTokenCount"])
5805
+ if (u[k] !== undefined && u[k] !== null)
5806
+ integer(u[k], `usageMetadata.${k}`);
5807
+ const input = (u.promptTokenCount ?? 0) + (u.toolUsePromptTokenCount ?? 0), thoughts = u.thoughtsTokenCount ?? 0, output = (u.candidatesTokenCount ?? 0) + thoughts;
5583
5808
  if (u.totalTokenCount !== undefined && u.totalTokenCount !== input + output)
5584
5809
  fail("invalid_usage", "Gemini total does not match reported components", "usageMetadata.totalTokenCount");
5585
5810
  events.push(...this.encoder.push({ choices: [], usage: { prompt_tokens: input, completion_tokens: output, prompt_tokens_details: { cached_tokens: u.cachedContentTokenCount ?? 0 }, completion_tokens_details: { reasoning_tokens: thoughts } } }));
5586
5811
  }
5587
- return events;
5812
+ return this.decorate(events);
5813
+ }
5814
+ decorate(events) {
5815
+ const output = [];
5816
+ for (const event of events) {
5817
+ if (["response.completed", "response.incomplete", "response.failed"].includes(event.type)) {
5818
+ const signed = [...this.signed.values()].filter((item) => item.parts.some((p) => p.signature !== undefined));
5819
+ if (signed.length) {
5820
+ const budget = limits(this.context.capabilities?.limits), response = record(event.response, "response");
5821
+ const items = list(response.output, "output");
5822
+ if (items.length >= budget.maxItems)
5823
+ fail("resource_limit", "Too many Gemini output items");
5824
+ const item = geminiSignatureItem(signed.map((item) => ({ id: item.id, thought: item.thought, parts: item.parts.map((p) => ({ length: p.text.length, hash: geminiTextHash(p.text), ...p.signature === undefined ? {} : { signature: p.signature }, ...p.textAbsent ? { textAbsent: true } : {} })) })), budget);
5825
+ const body = { ...response, output: [...items, item] };
5826
+ serialized(body, budget.maxOutputBytes, "Gemini response");
5827
+ output.push({ type: "response.output_item.added", response_id: response.id, output_index: items.length, item }, { type: "response.output_item.done", response_id: response.id, output_index: items.length, item });
5828
+ output.push({ ...event, response: body });
5829
+ continue;
5830
+ }
5831
+ }
5832
+ output.push(event);
5833
+ }
5834
+ return output.map((event) => ({ ...event, sequence_number: this.sequence++ }));
5588
5835
  }
5589
5836
  finish() {
5590
- return this.encoder.finish();
5837
+ return this.decorate(this.encoder.finish());
5591
5838
  }
5592
5839
  }
5593
5840
  function canonicalResponse(raw, context, names) {
5594
5841
  if (context.targetProtocol === "responses")
5595
5842
  return validateCanonicalResponse(raw, context);
5596
5843
  if (context.targetProtocol === "gemini_generate_content") {
5597
- const decoder = new GeminiCanonicalDecoder(context, names);
5844
+ const decoder = new GeminiCanonicalDecoder(context, names, false);
5598
5845
  const events = [...decoder.push(raw), ...decoder.finish()];
5599
5846
  return record(events.at(-1)?.response, "response");
5600
5847
  }
@@ -5976,7 +6223,7 @@ class CanonicalStreamRenderer {
5976
6223
  var LLM_PROTOCOLS = ["responses", "chat_completions", "anthropic_messages", "gemini_generate_content"];
5977
6224
 
5978
6225
  // src/protocol-session/index.ts
5979
- var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.1";
6226
+ var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.4";
5980
6227
  function describeProtocolConversion() {
5981
6228
  return {
5982
6229
  rulesVersion: PROTOCOL_CONVERSION_RULES_VERSION,
@@ -5984,7 +6231,7 @@ function describeProtocolConversion() {
5984
6231
  matrix: LLM_PROTOCOLS.flatMap((sourceProtocol) => LLM_PROTOCOLS.map((targetProtocol) => ({
5985
6232
  sourceProtocol,
5986
6233
  targetProtocol,
5987
- mode: sourceProtocol === targetProtocol ? "passthrough" : sourceProtocol === "responses" && targetProtocol === "gemini_generate_content" || sourceProtocol === "gemini_generate_content" && targetProtocol === "responses" ? "unsupported" : "convert"
6234
+ mode: sourceProtocol === targetProtocol ? "passthrough" : sourceProtocol === "gemini_generate_content" && targetProtocol === "responses" ? "unsupported" : "convert"
5988
6235
  })))
5989
6236
  };
5990
6237
  }
@@ -6002,9 +6249,9 @@ function createProtocolSession(context) {
6002
6249
  fail("unsupported_protocol", "Unknown protocol");
6003
6250
  if (typeof context.model !== "string" || !context.model)
6004
6251
  fail("invalid_payload", "Target model is required", "model");
6005
- const unsupported = context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content" || context.sourceProtocol === "gemini_generate_content" && context.targetProtocol === "responses";
6252
+ const unsupported = context.sourceProtocol === "gemini_generate_content" && context.targetProtocol === "responses";
6006
6253
  if (unsupported)
6007
- fail("unsupported_protocol_pair", "Responses and Gemini direct conversion is not supported");
6254
+ fail("unsupported_protocol_pair", "Gemini to Responses conversion is not supported");
6008
6255
  const same = context.sourceProtocol === context.targetProtocol;
6009
6256
  let disposed = false, poisoned = false, requested = false, mode, finished = false, passTerminal = false, passAnthropicStopped = false;
6010
6257
  let names = new Map;
@@ -2772,7 +2772,7 @@ function definitionKey(value) {
2772
2772
  return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${definitionKey(value[key])}`).join(",")}}`;
2773
2773
  return JSON.stringify(value);
2774
2774
  }
2775
- function decodeResponsesRequest(raw, protocol, capabilities = {}) {
2775
+ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {}) {
2776
2776
  const body = record(raw, "Responses request");
2777
2777
  if (capabilities.agentMessageDelivery !== undefined && capabilities.agentMessageDelivery !== "plaintext")
2778
2778
  fail("invalid_payload", "Unknown agent message delivery policy", "agentMessageDelivery");
@@ -3039,12 +3039,16 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}) {
3039
3039
  if (item.content != null)
3040
3040
  fail("unsupported_reasoning", "Reasoning content requires an explicit history mapping", `${messageParam}.content`);
3041
3041
  const summary = list(item.summary, "reasoning summary");
3042
- pendingReasoning += summary.map((part) => {
3042
+ const text = summary.map((part) => {
3043
3043
  const p = record(part, "reasoning summary");
3044
3044
  if (p.type !== "summary_text")
3045
3045
  fail("unsupported_reasoning", "Unknown reasoning summary");
3046
3046
  return string(p.text, "summary text");
3047
3047
  }).join("");
3048
+ if (options.preserveContentOrder)
3049
+ addMessage({ role: "assistant", content: null, reasoning_content: text, ...item.id === undefined ? {} : { id: string(item.id, "item.id", true) } });
3050
+ else
3051
+ pendingReasoning += text;
3048
3052
  return;
3049
3053
  }
3050
3054
  if (item.type === "function_call" || item.type === "custom_tool_call") {
@@ -3059,7 +3063,7 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}) {
3059
3063
  argumentObject(args);
3060
3064
  const call = { id, type: "function", function: { name: resolve(item, custom), arguments: args } };
3061
3065
  const previous = chat.at(-1);
3062
- if (previous?.role === "assistant") {
3066
+ if (previous?.role === "assistant" && !options.preserveContentOrder) {
3063
3067
  previous.tool_calls = [...previous.tool_calls ?? [], call];
3064
3068
  if (pendingReasoning)
3065
3069
  previous.reasoning_content = pendingReasoning;
@@ -3083,6 +3087,8 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}) {
3083
3087
  if (!["user", "assistant", "system", "developer"].includes(role))
3084
3088
  fail("unsupported_content", "Unknown message role");
3085
3089
  const message = { role, content: normalizeContent(item.content, role) };
3090
+ if (options.preserveContentOrder && item.id !== undefined)
3091
+ message.id = string(item.id, "item.id", true);
3086
3092
  if (pendingReasoning) {
3087
3093
  if (role !== "assistant")
3088
3094
  fail("unsupported_reasoning", "Reasoning must precede an assistant item");
@@ -3623,6 +3629,9 @@ function encodeResponsesResult(raw, protocol, model, toolNames = new Map, config
3623
3629
  fail("missing_terminal", "JSON response has no terminal result");
3624
3630
  return record(end.response, "Responses result");
3625
3631
  }
3632
+ // src/protocol-session/gemini.ts
3633
+ import { createHash } from "crypto";
3634
+
3626
3635
  // src/protocol-session/validation.ts
3627
3636
  function fields2(value, allowed, path, code = "unsupported_request") {
3628
3637
  for (const key of Object.keys(value))
@@ -3667,6 +3676,145 @@ function textParts(raw, path, style, role) {
3667
3676
  });
3668
3677
  }
3669
3678
 
3679
+ // src/protocol-session/gemini.ts
3680
+ var signatureSeparator = "__thought__";
3681
+ function checkedSignature(value, maxBytes) {
3682
+ const signature = bounded(string(value, "thoughtSignature", true), maxBytes, "thoughtSignature");
3683
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(signature) || signature.length % 4 === 1 || signature.includes("=") && signature.length % 4 !== 0 || Buffer.from(signature, "base64").toString("base64").replace(/=+$/, "") !== signature.replace(/=+$/, ""))
3684
+ fail("invalid_tool_arguments", "Invalid Gemini thought signature encoding", "thoughtSignature");
3685
+ return signature;
3686
+ }
3687
+ var envelopePrefix = "bungee_gemini:";
3688
+ var geminiEnvelopeBytes = (payloadBytes) => envelopePrefix.length + Math.ceil(payloadBytes * 4 / 3);
3689
+ var geminiTextHash = (text) => createHash("sha256").update(text).digest("base64url");
3690
+ function geminiSignatureItem(items, budget) {
3691
+ const payload = serialized({ version: 1, items }, budget.maxArgumentBytes, "Gemini signatures");
3692
+ return {
3693
+ type: "reasoning",
3694
+ id: `rs_gemini_${crypto.randomUUID().replaceAll("-", "")}`,
3695
+ summary: [],
3696
+ encrypted_content: bounded(envelopePrefix + Buffer.from(payload).toString("base64url"), budget.maxArgumentBytes, "Gemini signatures")
3697
+ };
3698
+ }
3699
+ function readGeminiSignatures(item, budget) {
3700
+ fields2(item, ["type", "id", "summary", "encrypted_content", "status"], "Gemini signatures", "unsupported_reasoning");
3701
+ if (item.type !== "reasoning" || list(item.summary, "summary").length)
3702
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier");
3703
+ string(item.id, "signature item id", true);
3704
+ const opaque = bounded(string(item.encrypted_content, "encrypted_content", true), budget.maxArgumentBytes, "Gemini signatures");
3705
+ if (!opaque.startsWith(envelopePrefix))
3706
+ fail("unsupported_reasoning", "Native encrypted reasoning cannot be restored to Gemini");
3707
+ const encoded = opaque.slice(envelopePrefix.length), bytes = Buffer.from(encoded, "base64url");
3708
+ if (!encoded || bytes.toString("base64url") !== encoded)
3709
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier encoding");
3710
+ let raw;
3711
+ try {
3712
+ raw = JSON.parse(bytes.toString("utf8"));
3713
+ } catch {
3714
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier JSON");
3715
+ }
3716
+ const body = record(raw, "Gemini signatures");
3717
+ fields2(body, ["version", "items"], "Gemini signatures", "unsupported_reasoning");
3718
+ if (body.version !== 1)
3719
+ fail("unsupported_reasoning", "Unknown Gemini signature format");
3720
+ const ids = new Set;
3721
+ let partCount = 0;
3722
+ const result = list(body.items, "signature items").map((raw) => {
3723
+ const item = record(raw, "signature item");
3724
+ fields2(item, ["id", "thought", "parts"], "signature item", "unsupported_reasoning");
3725
+ const id = string(item.id, "signed item id", true);
3726
+ if (ids.has(id) || typeof item.thought !== "boolean")
3727
+ fail("unsupported_reasoning", "Invalid signed item identity");
3728
+ ids.add(id);
3729
+ const parts = list(item.parts, "signed parts").map((raw) => {
3730
+ if (++partCount > budget.maxItems)
3731
+ fail("resource_limit", "Too many signed Gemini parts");
3732
+ const part = record(raw, "signed part");
3733
+ fields2(part, ["length", "hash", "signature", "textAbsent"], "signed part", "unsupported_reasoning");
3734
+ const length = integer(part.length, "signed part length"), hash = string(part.hash, "signed part hash", true);
3735
+ if (!/^[A-Za-z0-9_-]{43}$/.test(hash))
3736
+ fail("unsupported_reasoning", "Invalid signed part hash");
3737
+ const signature = part.signature === undefined ? undefined : checkedSignature(part.signature, budget.maxArgumentBytes);
3738
+ if (part.textAbsent !== undefined && (part.textAbsent !== true || length !== 0 || signature === undefined))
3739
+ fail("unsupported_reasoning", "Invalid empty signed part");
3740
+ return { length, hash, ...signature === undefined ? {} : { signature }, ...part.textAbsent ? { textAbsent: true } : {} };
3741
+ });
3742
+ if (!parts.some((p) => p.signature !== undefined))
3743
+ fail("unsupported_reasoning", "Signature carrier has no signature");
3744
+ return { id, thought: item.thought, parts };
3745
+ });
3746
+ if (!result.length || result.length > budget.maxItems)
3747
+ fail("unsupported_reasoning", "Invalid signature item count");
3748
+ return result;
3749
+ }
3750
+ function restoreGeminiHistory(input, budget) {
3751
+ const original = typeof input === "string" ? [] : list(input, "input").map((raw) => record(raw, "input item"));
3752
+ const carriers = new Set, parts = new Map, ids = new Map;
3753
+ original.forEach((item, i) => {
3754
+ if (typeof item.id === "string") {
3755
+ if (ids.has(item.id))
3756
+ fail("invalid_tool_history", "Duplicate history item id", "input.id");
3757
+ ids.set(item.id, i);
3758
+ }
3759
+ });
3760
+ original.forEach((carrier, index) => {
3761
+ if (carrier.encrypted_content == null)
3762
+ return;
3763
+ const signed = readGeminiSignatures(carrier, budget);
3764
+ carriers.add(carrier);
3765
+ let previous = -1;
3766
+ for (const item of signed) {
3767
+ const at = ids.get(item.id);
3768
+ if (at === undefined || at >= index || at <= previous || parts.has(item.id))
3769
+ fail("unsupported_reasoning", "Signed history reference is missing or ambiguous");
3770
+ previous = at;
3771
+ const source = original[at];
3772
+ if (item.thought ? source.type !== "reasoning" || source.encrypted_content != null : source.role !== "assistant" || source.type !== undefined && source.type !== "message")
3773
+ fail("unsupported_reasoning", "Signed history item kind changed");
3774
+ const content = item.thought ? list(source.summary, "summary") : typeof source.content === "string" ? [{ type: "output_text", text: source.content }] : list(source.content, "content");
3775
+ const text = content.map((raw) => {
3776
+ const p = record(raw, "signed text");
3777
+ if (p.type !== (item.thought ? "summary_text" : "output_text") && !(p.type === "input_text" && !item.thought))
3778
+ fail("unsupported_reasoning", "Signed history content kind changed");
3779
+ return string(p.text, "signed text");
3780
+ }).join("");
3781
+ let offset = 0;
3782
+ const restored = item.parts.map((part) => {
3783
+ const value = text.slice(offset, offset + part.length);
3784
+ offset += part.length;
3785
+ if (value.length !== part.length || geminiTextHash(value) !== part.hash)
3786
+ fail("unsupported_reasoning", "Signed history text changed");
3787
+ return { ...part.textAbsent ? {} : { text: value }, ...item.thought ? { thought: true } : {}, ...part.signature === undefined ? {} : { thoughtSignature: part.signature } };
3788
+ });
3789
+ if (offset !== text.length)
3790
+ fail("unsupported_reasoning", "Signed history text was not fully consumed");
3791
+ parts.set(item.id, restored);
3792
+ }
3793
+ });
3794
+ return {
3795
+ input: typeof input === "string" ? input : original.filter((item) => !carriers.has(item)),
3796
+ parts,
3797
+ canonicalHistory(decoded) {
3798
+ if (!carriers.size)
3799
+ return decoded;
3800
+ let next = 0;
3801
+ return original.flatMap((item) => carriers.has(item) ? [item] : item.type === "additional_tools" ? [] : [decoded[next++]]);
3802
+ }
3803
+ };
3804
+ }
3805
+ function encodeGeminiCallId(id, signature, maxBytes) {
3806
+ if (id.includes(signatureSeparator))
3807
+ fail("invalid_tool_arguments", "Gemini call id contains the signature separator", "functionCall.id");
3808
+ return signature === undefined ? id : `${id}${signatureSeparator}${checkedSignature(signature, maxBytes)}`;
3809
+ }
3810
+ function decodeGeminiCallId(value, maxBytes) {
3811
+ const separator = value.indexOf(signatureSeparator);
3812
+ if (separator < 0)
3813
+ return { id: value };
3814
+ const id = string(value.slice(0, separator), "functionCall.id", true);
3815
+ return { id, thoughtSignature: checkedSignature(value.slice(separator + signatureSeparator.length), maxBytes) };
3816
+ }
3817
+
3670
3818
  // src/protocol-session/schema.ts
3671
3819
  function geminiSchemaToJson(raw, path, code = "unsupported_request", depth = 0) {
3672
3820
  if (depth > 64)
@@ -4100,6 +4248,9 @@ function convertProtocolRequest(raw, context) {
4100
4248
  b.stream = context.streaming;
4101
4249
  }
4102
4250
  validateCanonical(b, context);
4251
+ const geminiHistory = context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content" ? restoreGeminiHistory(b.input, limits(context.capabilities?.limits)) : undefined;
4252
+ if (geminiHistory)
4253
+ b.input = geminiHistory.input;
4103
4254
  const cap = { ...context.capabilities, agentMessageDelivery: context.agentMessageDelivery ?? context.capabilities?.agentMessageDelivery, omitOptionalWebSearch: true, preserveToolIdentityDescription: true, preserveRefusalContent: true }, policy = context.reasoningPolicy;
4104
4255
  const reasoning = b.reasoning === undefined ? undefined : record(b.reasoning, "reasoning");
4105
4256
  const sourceThinking = b.sourceThinking;
@@ -4125,10 +4276,10 @@ function convertProtocolRequest(raw, context) {
4125
4276
  if (sourceThinking !== undefined && reasoning?.effort === undefined && policy?.targetEffort !== undefined)
4126
4277
  mappedEffort = string(policy.targetEffort, "reasoningPolicy.targetEffort", true);
4127
4278
  const target = context.targetProtocol;
4128
- if (target === "gemini_generate_content" && reasoning?.effort !== undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
4279
+ if (target === "gemini_generate_content" && reasoning?.effort !== undefined && mappedEffort === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
4129
4280
  fail("unsupported_reasoning", "Gemini requires an explicit thinking budget or level", "reasoning.effort");
4130
4281
  if (sourceThinking !== undefined) {
4131
- const represented = target === "responses" || target === "chat_completions" ? mappedEffort !== undefined : target === "anthropic_messages" ? mappedEffort !== undefined || policy?.anthropicThinkingMode !== undefined || policy?.anthropicThinkingBudget !== undefined : policy?.geminiThinkingBudget !== undefined || policy?.geminiThinkingLevel !== undefined;
4282
+ const represented = target === "responses" || target === "chat_completions" ? mappedEffort !== undefined : target === "anthropic_messages" ? mappedEffort !== undefined || policy?.anthropicThinkingMode !== undefined || policy?.anthropicThinkingBudget !== undefined : mappedEffort !== undefined || policy?.geminiThinkingBudget !== undefined || policy?.geminiThinkingLevel !== undefined;
4132
4283
  if (!represented)
4133
4284
  fail("unsupported_reasoning", "Source thinking mode needs an explicit target wire policy", "thinking");
4134
4285
  }
@@ -4187,9 +4338,13 @@ function convertProtocolRequest(raw, context) {
4187
4338
  const decodingTarget = target === "gemini_generate_content" ? "chat_completions" : target;
4188
4339
  if (target === "gemini_generate_content" && reasoning)
4189
4340
  b.reasoning = { ...reasoning, effort: undefined };
4190
- const decoded = decodeResponsesRequest(b, decodingTarget, { ...cap, reasoningHistory: target !== "anthropic_messages" && cap.reasoningHistory === true, reasoningEffort: target === "chat_completions" && cap.reasoningEffort === true, anthropicThinkingBudget: undefined });
4341
+ const decoded = decodeResponsesRequest(b, decodingTarget, { ...cap, reasoningHistory: target !== "anthropic_messages" && cap.reasoningHistory === true, reasoningEffort: target === "chat_completions" && cap.reasoningEffort === true, anthropicThinkingBudget: undefined }, { preserveContentOrder: target === "gemini_generate_content" });
4191
4342
  const diagnostics = decoded.diagnostics;
4192
- const body = target === "gemini_generate_content" ? renderGemini(decoded.body, cap.geminiJsonSchema === true) : decoded.body;
4343
+ if (target === "gemini_generate_content" && decoded.body.parallel_tool_calls === true) {
4344
+ delete decoded.body.parallel_tool_calls;
4345
+ diagnostics.push({ param: "parallel_tool_calls", action: "omitted", reason: "gemini_parallel_tool_calls_allowed" });
4346
+ }
4347
+ const body = target === "gemini_generate_content" ? renderGemini(decoded.body, context, geminiHistory?.parts, diagnostics) : decoded.body;
4193
4348
  if (stop !== undefined)
4194
4349
  body[target === "chat_completions" ? "stop" : target === "anthropic_messages" ? "stop_sequences" : "generationConfig"] = target === "gemini_generate_content" ? { ...record(body.generationConfig ?? {}, "generationConfig"), stopSequences: typeof stop === "string" ? [stop] : stop } : typeof stop === "string" ? [stop] : stop;
4195
4350
  if (target === "anthropic_messages") {
@@ -4211,18 +4366,24 @@ function convertProtocolRequest(raw, context) {
4211
4366
  body.thinking = { type: "enabled", budget_tokens: budget };
4212
4367
  }
4213
4368
  }
4214
- if (target === "gemini_generate_content" && (policy?.geminiThinkingBudget !== undefined || policy?.geminiThinkingLevel !== undefined)) {
4215
- if (policy.geminiThinkingBudget !== undefined && policy.geminiThinkingLevel !== undefined)
4369
+ if (target === "gemini_generate_content" && (mappedEffort !== undefined || policy?.geminiThinkingBudget !== undefined || policy?.geminiThinkingLevel !== undefined)) {
4370
+ const level = policy?.geminiThinkingLevel ?? mappedEffort;
4371
+ if (policy?.geminiThinkingBudget !== undefined && level !== undefined)
4216
4372
  fail("unsupported_reasoning", "Choose one Gemini thinking policy", "reasoningPolicy");
4217
- const thinkingConfig = policy.geminiThinkingBudget !== undefined ? { thinkingBudget: integer(policy.geminiThinkingBudget, "reasoningPolicy.geminiThinkingBudget", -1) } : { thinkingLevel: string(policy.geminiThinkingLevel, "reasoningPolicy.geminiThinkingLevel", true) };
4373
+ if (level !== undefined && !["minimal", "low", "medium", "high"].includes(level))
4374
+ fail("unsupported_reasoning", "Unknown Gemini thinking level", "reasoning.effort");
4375
+ if (mappedEffort !== undefined && policy?.geminiThinkingLevel !== undefined && mappedEffort !== policy.geminiThinkingLevel)
4376
+ fail("unsupported_reasoning", "Conflicting Gemini thinking levels", "reasoning.effort");
4377
+ const thinkingConfig = policy?.geminiThinkingBudget !== undefined ? { thinkingBudget: integer(policy.geminiThinkingBudget, "reasoningPolicy.geminiThinkingBudget", -1) } : { thinkingLevel: string(level, "reasoningPolicy.geminiThinkingLevel", true) };
4218
4378
  body.generationConfig = { ...record(body.generationConfig ?? {}, "generationConfig"), thinkingConfig };
4219
4379
  }
4220
4380
  if (mappedEffort !== undefined || sourceThinking !== undefined || policy?.anthropicThinkingBudget !== undefined)
4221
4381
  diagnostics.push({ param: "reasoning", action: "mapped", reason: "explicit_verified_wire_policy" });
4222
- return { body, canonicalHistory: decoded.canonicalInput, diagnostics, toolNames: decoded.toolNames, streaming: b.stream === true };
4382
+ return { body, canonicalHistory: geminiHistory?.canonicalHistory(decoded.canonicalInput) ?? decoded.canonicalInput, diagnostics, toolNames: decoded.toolNames, streaming: b.stream === true };
4223
4383
  }
4224
- function renderGemini(chat, jsonSchema) {
4384
+ function renderGemini(chat, context, signedParts, diagnostics) {
4225
4385
  const result = { contents: [] }, contents = result.contents, system = [], calls = new Map;
4386
+ const nativeIds = new Set;
4226
4387
  const append = (role, parts) => {
4227
4388
  const prev = contents.at(-1);
4228
4389
  if (prev?.role === role)
@@ -4231,14 +4392,22 @@ function renderGemini(chat, jsonSchema) {
4231
4392
  contents.push({ role, parts });
4232
4393
  };
4233
4394
  for (const m of chat.messages) {
4395
+ const signed = signedParts?.get(m.id);
4396
+ if (signed) {
4397
+ append("model", signed);
4398
+ continue;
4399
+ }
4234
4400
  const parts = m.content == null ? [] : typeof m.content === "string" ? [{ text: m.content }] : m.content.map((p) => {
4235
4401
  if (p.type !== "text")
4236
4402
  fail("unsupported_content", "This content cannot cross to Gemini", "input");
4237
4403
  return { text: p.text };
4238
4404
  });
4239
4405
  if (m.role === "system" || m.role === "developer") {
4240
- if (contents.length)
4241
- fail("unsupported_content", "Mid-conversation instructions cannot be relocated", "input");
4406
+ if (contents.length) {
4407
+ if (context.sourceProtocol !== "responses")
4408
+ fail("unsupported_content", "Mid-conversation instructions cannot be relocated", "input");
4409
+ diagnostics.push({ param: "input", action: "mapped", reason: "gemini_mid_conversation_instructions_consolidated" });
4410
+ }
4242
4411
  system.push(...parts);
4243
4412
  continue;
4244
4413
  }
@@ -4248,7 +4417,8 @@ function renderGemini(chat, jsonSchema) {
4248
4417
  fail("invalid_tool_history", "Unknown tool result", "input");
4249
4418
  if (m.is_error === true)
4250
4419
  fail("unsupported_content", "Tool error authority cannot be represented by Gemini", "input");
4251
- append("user", [{ functionResponse: { id: m.tool_call_id, name, response: { output: m.content } } }]);
4420
+ const { id } = context.sourceProtocol === "responses" ? decodeGeminiCallId(m.tool_call_id, limits(context.capabilities?.limits).maxArgumentBytes) : { id: m.tool_call_id };
4421
+ append("user", [{ functionResponse: { id, name, response: { output: m.content } } }]);
4252
4422
  continue;
4253
4423
  }
4254
4424
  if (m.reasoning_content !== undefined)
@@ -4256,10 +4426,20 @@ function renderGemini(chat, jsonSchema) {
4256
4426
  for (const c of m.tool_calls ?? []) {
4257
4427
  const fn = record(c.function, "function");
4258
4428
  calls.set(c.id, fn.name);
4259
- parts.push({ functionCall: { id: c.id, name: fn.name, args: argumentObject(fn.arguments) } });
4429
+ const { id, thoughtSignature } = context.sourceProtocol === "responses" ? decodeGeminiCallId(c.id, limits(context.capabilities?.limits).maxArgumentBytes) : { id: c.id, thoughtSignature: undefined };
4430
+ if (nativeIds.has(id))
4431
+ fail("invalid_tool_history", "Duplicate decoded Gemini call id", "call_id");
4432
+ nativeIds.add(id);
4433
+ parts.push({ functionCall: { id, name: fn.name, args: argumentObject(fn.arguments) }, ...thoughtSignature === undefined ? {} : { thoughtSignature } });
4260
4434
  }
4261
4435
  append(m.role === "assistant" ? "model" : "user", parts);
4262
4436
  }
4437
+ if (chat.parallel_tool_calls !== undefined) {
4438
+ if (context.sourceProtocol !== "responses" || chat.parallel_tool_calls !== false)
4439
+ fail("unsupported_request", "Gemini cannot enforce parallel tool preference", "parallel_tool_calls");
4440
+ system.push({ text: "Call at most one tool per response." });
4441
+ diagnostics.push({ param: "parallel_tool_calls", action: "mapped", reason: "gemini_serial_tool_calls_prompt_only" });
4442
+ }
4263
4443
  if (system.length)
4264
4444
  result.systemInstruction = { parts: system };
4265
4445
  const generation = {};
@@ -4268,12 +4448,10 @@ function renderGemini(chat, jsonSchema) {
4268
4448
  generation[to] = chat[from];
4269
4449
  if (chat.metadata !== undefined)
4270
4450
  fail("unsupported_request", "Gemini has no compatible request metadata", "metadata");
4271
- if (chat.parallel_tool_calls !== undefined)
4272
- fail("unsupported_request", "Gemini cannot enforce parallel tool preference", "parallel_tool_calls");
4273
4451
  if (chat.response_format !== undefined) {
4274
4452
  const f = record(chat.response_format, "format");
4275
4453
  if (f.type === "json_schema") {
4276
- if (!jsonSchema)
4454
+ if (!context.capabilities?.geminiJsonSchema)
4277
4455
  fail("unsupported_request", "Target JSON schema capability is required", "text.format");
4278
4456
  const s = record(f.json_schema, "schema");
4279
4457
  if (s.strict === false)
@@ -4418,7 +4596,11 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
4418
4596
  fail("unsupported_content", "Output annotations cannot cross protocols", path);
4419
4597
  }
4420
4598
  } else if (t.type === "reasoning") {
4421
- if (t.encrypted_content != null || t.content != null)
4599
+ if (t.encrypted_content != null && context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content")
4600
+ readGeminiSignatures(t, limits(context.capabilities?.limits));
4601
+ else if (t.encrypted_content != null)
4602
+ fail("unsupported_reasoning", "Opaque reasoning cannot cross protocols", path);
4603
+ if (t.content != null)
4422
4604
  fail("unsupported_reasoning", "Opaque or raw reasoning output cannot cross protocols", path);
4423
4605
  for (const rawPart of list(t.summary, "summary")) {
4424
4606
  const p = record(rawPart, "summary");
@@ -4541,20 +4723,28 @@ function responseFromCanonical(raw, protocol, context) {
4541
4723
 
4542
4724
  class GeminiCanonicalDecoder {
4543
4725
  context;
4726
+ streaming;
4544
4727
  encoder;
4545
4728
  serial = 0;
4546
4729
  ended = false;
4547
4730
  tools = false;
4548
4731
  ids = new Set;
4549
- constructor(context, names) {
4732
+ sequence = 0;
4733
+ contentId;
4734
+ partCount = 0;
4735
+ replayBytes = Buffer.byteLength(JSON.stringify({ version: 1, items: [] }));
4736
+ signedItems = 0;
4737
+ signed = new Map;
4738
+ constructor(context, names, streaming = true) {
4550
4739
  this.context = context;
4551
- this.encoder = new ResponsesEventEncoder("chat_completions", context.responseModel ?? context.model, names, context.capabilities?.limits, { preserveContentOrder: true });
4740
+ this.streaming = streaming;
4741
+ this.encoder = new ResponsesEventEncoder("chat_completions", context.responseModel ?? context.model, names, context.capabilities?.limits, { preserveContentOrder: true, agentMessageDelivery: context.capabilities?.agentMessageDelivery });
4552
4742
  }
4553
4743
  push(raw) {
4554
4744
  const b = record(raw, "Gemini response");
4555
4745
  fields2(b, ["candidates", "usageMetadata", "modelVersion", "responseId", "promptFeedback", "error"], "", "unsupported_response");
4556
4746
  if (b.error !== undefined)
4557
- return this.encoder.push({ error: safeProtocolError() });
4747
+ return this.decorate(this.encoder.push({ error: safeProtocolError() }));
4558
4748
  const events = [];
4559
4749
  if (b.promptFeedback !== undefined) {
4560
4750
  const p = record(b.promptFeedback, "promptFeedback");
@@ -4572,34 +4762,69 @@ class GeminiCanonicalDecoder {
4572
4762
  fields2(c, ["index", "content", "finishReason", "safetyRatings", "finishMessage"], "candidates", "unsupported_response");
4573
4763
  if (c.index !== undefined && c.index !== 0)
4574
4764
  fail("unsupported_response", "Only candidate index zero is supported", "candidates.index");
4575
- if (c.content !== undefined) {
4765
+ if (c.content !== undefined && c.content !== null) {
4576
4766
  const content = record(c.content, "content");
4577
4767
  fields2(content, ["role", "parts"], "candidates.content", "unsupported_content");
4578
4768
  if (content.role !== undefined && content.role !== "model")
4579
4769
  fail("unsupported_response", "Response role must be model", "candidates.content.role");
4580
- const parts = list(content.parts, "parts");
4770
+ const parts = list(content.parts ?? [], "parts");
4581
4771
  if (this.ended && parts.length)
4582
4772
  fail("invalid_stream", "Content arrived after Gemini terminal");
4583
4773
  for (const [i, rawPart] of parts.entries()) {
4584
4774
  const p = record(rawPart, "part");
4585
4775
  fields2(p, ["text", "thought", "functionCall", "thoughtSignature"], "candidates.content.parts", "unsupported_content");
4586
- if (p.thoughtSignature !== undefined)
4776
+ if (p.thoughtSignature !== undefined && this.context.sourceProtocol !== "responses")
4587
4777
  fail("unsupported_reasoning", "Thought signatures cannot cross protocols", "candidates.content.parts.thoughtSignature");
4588
4778
  if (p.functionCall !== undefined) {
4589
4779
  if (p.text !== undefined || p.thought !== undefined)
4590
4780
  fail("unsupported_content", "Mixed Gemini part kinds", "candidates.content.parts");
4591
4781
  const f = record(p.functionCall, "functionCall");
4592
4782
  fields2(f, ["id", "name", "args"], "functionCall", "unsupported_tool");
4593
- const index = this.serial++, id = f.id === undefined ? `call_gemini_${index}` : string(f.id, "functionCall.id", true);
4594
- if (this.ids.has(id))
4783
+ const index = this.serial++, originalId = f.id === undefined ? `call_gemini_${crypto.randomUUID().replaceAll("-", "")}` : string(f.id, "functionCall.id", true);
4784
+ if (this.ids.has(originalId))
4595
4785
  fail("invalid_tool_arguments", "Duplicate Gemini call id", "functionCall.id");
4596
- this.ids.add(id);
4786
+ this.ids.add(originalId);
4787
+ const id = this.context.sourceProtocol === "responses" ? encodeGeminiCallId(originalId, p.thoughtSignature, limits(this.context.capabilities?.limits).maxArgumentBytes) : originalId;
4597
4788
  this.tools = true;
4598
4789
  events.push(...this.encoder.push({ choices: [{ delta: { tool_calls: [{ index, id, type: "function", function: { name: string(f.name, "functionCall.name", true), arguments: JSON.stringify(record(f.args ?? {}, "functionCall.args")) } }] } }] }));
4599
4790
  } else {
4600
4791
  if (p.thought !== undefined && typeof p.thought !== "boolean")
4601
4792
  fail("invalid_payload", "Thought flag must be boolean", "thought");
4602
- events.push(...this.encoder.push({ choices: [{ delta: { [p.thought === true ? "reasoning_content" : "content"]: string(p.text, `parts[${i}].text`) } }] }));
4793
+ const text = string(p.text ?? (p.thoughtSignature === undefined ? undefined : ""), `parts[${i}].text`);
4794
+ const output = this.encoder.push({ choices: [{ delta: { [p.thought === true ? "reasoning_content" : "content"]: text } }] });
4795
+ const added = output.find((e) => e.type === "response.output_item.added");
4796
+ if (added)
4797
+ this.contentId = record(added.item, "item").id;
4798
+ const id = this.contentId;
4799
+ let item = this.signed.get(id);
4800
+ if (!item) {
4801
+ item = { id, thought: p.thought === true, parts: [], hasSignature: false, metadataBytes: Buffer.byteLength(JSON.stringify({ id, thought: p.thought === true, parts: [] })) };
4802
+ this.signed.set(id, item);
4803
+ }
4804
+ const signature = p.thoughtSignature === undefined ? undefined : checkedSignature(p.thoughtSignature, limits(this.context.capabilities?.limits).maxArgumentBytes);
4805
+ const previous = item.parts.at(-1);
4806
+ const merge = this.streaming && signature === undefined && previous && previous.signature === undefined && !previous.textAbsent;
4807
+ const partBytes = Buffer.byteLength(JSON.stringify({ length: text.length + (merge ? previous.text.length : 0), hash: "x".repeat(43), ...signature === undefined ? {} : { signature }, ...p.text === undefined ? { textAbsent: true } : {} }));
4808
+ const metadataBytes = item.metadataBytes + partBytes - (merge ? previous.metadataBytes : 0) + (!merge && item.parts.length ? 1 : 0);
4809
+ const hasSignature = item.hasSignature || signature !== undefined;
4810
+ const replayBytes = this.replayBytes + (item.hasSignature ? metadataBytes - item.metadataBytes : hasSignature ? metadataBytes + (this.signedItems ? 1 : 0) : 0);
4811
+ const budget = limits(this.context.capabilities?.limits);
4812
+ if (hasSignature && geminiEnvelopeBytes(replayBytes) > Math.min(budget.maxArgumentBytes, budget.maxOutputBytes))
4813
+ fail("resource_limit", "Accumulated Gemini signatures exceed replay budget");
4814
+ if (hasSignature && !item.hasSignature)
4815
+ this.signedItems++;
4816
+ this.replayBytes = replayBytes;
4817
+ item.metadataBytes = metadataBytes;
4818
+ item.hasSignature = hasSignature;
4819
+ if (merge) {
4820
+ previous.text += text;
4821
+ previous.metadataBytes = partBytes;
4822
+ } else {
4823
+ if (++this.partCount > limits(this.context.capabilities?.limits).maxItems)
4824
+ fail("resource_limit", "Too many Gemini parts");
4825
+ item.parts.push({ text, metadataBytes: partBytes, ...signature === undefined ? {} : { signature }, ...p.text === undefined ? { textAbsent: true } : {} });
4826
+ }
4827
+ events.push(...output);
4603
4828
  }
4604
4829
  }
4605
4830
  }
@@ -4616,25 +4841,47 @@ class GeminiCanonicalDecoder {
4616
4841
  }
4617
4842
  if (b.usageMetadata !== undefined) {
4618
4843
  const u = record(b.usageMetadata, "usageMetadata");
4619
- fields2(u, ["promptTokenCount", "candidatesTokenCount", "totalTokenCount", "cachedContentTokenCount", "thoughtsTokenCount"], "usageMetadata", "unsupported_response");
4620
- for (const [k, v] of Object.entries(u))
4621
- integer(v, `usageMetadata.${k}`);
4622
- const input = u.promptTokenCount ?? 0, thoughts = u.thoughtsTokenCount ?? 0, output = (u.candidatesTokenCount ?? 0) + thoughts;
4844
+ for (const k of ["promptTokenCount", "candidatesTokenCount", "totalTokenCount", "cachedContentTokenCount", "thoughtsTokenCount", "toolUsePromptTokenCount"])
4845
+ if (u[k] !== undefined && u[k] !== null)
4846
+ integer(u[k], `usageMetadata.${k}`);
4847
+ const input = (u.promptTokenCount ?? 0) + (u.toolUsePromptTokenCount ?? 0), thoughts = u.thoughtsTokenCount ?? 0, output = (u.candidatesTokenCount ?? 0) + thoughts;
4623
4848
  if (u.totalTokenCount !== undefined && u.totalTokenCount !== input + output)
4624
4849
  fail("invalid_usage", "Gemini total does not match reported components", "usageMetadata.totalTokenCount");
4625
4850
  events.push(...this.encoder.push({ choices: [], usage: { prompt_tokens: input, completion_tokens: output, prompt_tokens_details: { cached_tokens: u.cachedContentTokenCount ?? 0 }, completion_tokens_details: { reasoning_tokens: thoughts } } }));
4626
4851
  }
4627
- return events;
4852
+ return this.decorate(events);
4853
+ }
4854
+ decorate(events) {
4855
+ const output = [];
4856
+ for (const event of events) {
4857
+ if (["response.completed", "response.incomplete", "response.failed"].includes(event.type)) {
4858
+ const signed = [...this.signed.values()].filter((item) => item.parts.some((p) => p.signature !== undefined));
4859
+ if (signed.length) {
4860
+ const budget = limits(this.context.capabilities?.limits), response = record(event.response, "response");
4861
+ const items = list(response.output, "output");
4862
+ if (items.length >= budget.maxItems)
4863
+ fail("resource_limit", "Too many Gemini output items");
4864
+ const item = geminiSignatureItem(signed.map((item) => ({ id: item.id, thought: item.thought, parts: item.parts.map((p) => ({ length: p.text.length, hash: geminiTextHash(p.text), ...p.signature === undefined ? {} : { signature: p.signature }, ...p.textAbsent ? { textAbsent: true } : {} })) })), budget);
4865
+ const body = { ...response, output: [...items, item] };
4866
+ serialized(body, budget.maxOutputBytes, "Gemini response");
4867
+ output.push({ type: "response.output_item.added", response_id: response.id, output_index: items.length, item }, { type: "response.output_item.done", response_id: response.id, output_index: items.length, item });
4868
+ output.push({ ...event, response: body });
4869
+ continue;
4870
+ }
4871
+ }
4872
+ output.push(event);
4873
+ }
4874
+ return output.map((event) => ({ ...event, sequence_number: this.sequence++ }));
4628
4875
  }
4629
4876
  finish() {
4630
- return this.encoder.finish();
4877
+ return this.decorate(this.encoder.finish());
4631
4878
  }
4632
4879
  }
4633
4880
  function canonicalResponse(raw, context, names) {
4634
4881
  if (context.targetProtocol === "responses")
4635
4882
  return validateCanonicalResponse(raw, context);
4636
4883
  if (context.targetProtocol === "gemini_generate_content") {
4637
- const decoder = new GeminiCanonicalDecoder(context, names);
4884
+ const decoder = new GeminiCanonicalDecoder(context, names, false);
4638
4885
  const events = [...decoder.push(raw), ...decoder.finish()];
4639
4886
  return record(events.at(-1)?.response, "response");
4640
4887
  }
@@ -5016,7 +5263,7 @@ class CanonicalStreamRenderer {
5016
5263
  var LLM_PROTOCOLS = ["responses", "chat_completions", "anthropic_messages", "gemini_generate_content"];
5017
5264
 
5018
5265
  // src/protocol-session/index.ts
5019
- var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.1";
5266
+ var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.4";
5020
5267
  function describeProtocolConversion() {
5021
5268
  return {
5022
5269
  rulesVersion: PROTOCOL_CONVERSION_RULES_VERSION,
@@ -5024,7 +5271,7 @@ function describeProtocolConversion() {
5024
5271
  matrix: LLM_PROTOCOLS.flatMap((sourceProtocol) => LLM_PROTOCOLS.map((targetProtocol) => ({
5025
5272
  sourceProtocol,
5026
5273
  targetProtocol,
5027
- mode: sourceProtocol === targetProtocol ? "passthrough" : sourceProtocol === "responses" && targetProtocol === "gemini_generate_content" || sourceProtocol === "gemini_generate_content" && targetProtocol === "responses" ? "unsupported" : "convert"
5274
+ mode: sourceProtocol === targetProtocol ? "passthrough" : sourceProtocol === "gemini_generate_content" && targetProtocol === "responses" ? "unsupported" : "convert"
5028
5275
  })))
5029
5276
  };
5030
5277
  }
@@ -5042,9 +5289,9 @@ function createProtocolSession(context) {
5042
5289
  fail("unsupported_protocol", "Unknown protocol");
5043
5290
  if (typeof context.model !== "string" || !context.model)
5044
5291
  fail("invalid_payload", "Target model is required", "model");
5045
- const unsupported = context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content" || context.sourceProtocol === "gemini_generate_content" && context.targetProtocol === "responses";
5292
+ const unsupported = context.sourceProtocol === "gemini_generate_content" && context.targetProtocol === "responses";
5046
5293
  if (unsupported)
5047
- fail("unsupported_protocol_pair", "Responses and Gemini direct conversion is not supported");
5294
+ fail("unsupported_protocol_pair", "Gemini to Responses conversion is not supported");
5048
5295
  const same = context.sourceProtocol === context.targetProtocol;
5049
5296
  let disposed = false, poisoned = false, requested = false, mode, finished = false, passTerminal = false, passAnthropicStopped = false;
5050
5297
  let names = new Map;
@@ -0,0 +1,29 @@
1
+ import { type JsonRecord, type ResponsesCodecLimits } from '../responses-codec/common';
2
+ export declare function checkedSignature(value: unknown, maxBytes: number): string;
3
+ export declare const geminiEnvelopeBytes: (payloadBytes: number) => number;
4
+ type SignedPart = {
5
+ length: number;
6
+ hash: string;
7
+ signature?: string;
8
+ textAbsent?: boolean;
9
+ };
10
+ type SignedItem = {
11
+ id: string;
12
+ thought: boolean;
13
+ parts: SignedPart[];
14
+ };
15
+ export declare const geminiTextHash: (text: string) => string;
16
+ /** Provider-bound replay data travels in a Responses opaque reasoning item, never in a server cache. */
17
+ export declare function geminiSignatureItem(items: SignedItem[], budget: ResponsesCodecLimits): JsonRecord;
18
+ export declare function readGeminiSignatures(item: JsonRecord, budget: ResponsesCodecLimits): SignedItem[];
19
+ export declare function restoreGeminiHistory(input: unknown, budget: ResponsesCodecLimits): {
20
+ input: string | JsonRecord[];
21
+ parts: Map<string, JsonRecord[]>;
22
+ canonicalHistory(decoded: JsonRecord[]): JsonRecord[];
23
+ };
24
+ export declare function encodeGeminiCallId(id: string, signature: unknown, maxBytes: number): string;
25
+ export declare function decodeGeminiCallId(value: string, maxBytes: number): {
26
+ id: string;
27
+ thoughtSignature?: string;
28
+ };
29
+ export {};
@@ -1,6 +1,6 @@
1
1
  import { type ProtocolSession, type ProtocolSessionContext } from './types';
2
2
  export * from './types';
3
- export declare const PROTOCOL_CONVERSION_RULES_VERSION = "1.0.1";
3
+ export declare const PROTOCOL_CONVERSION_RULES_VERSION = "1.0.4";
4
4
  export declare function describeProtocolConversion(): {
5
5
  rulesVersion: string;
6
6
  protocols: ("chat_completions" | "anthropic_messages" | "responses" | "gemini_generate_content")[];
@@ -11,13 +11,21 @@ export declare function responseFromCanonical(raw: unknown, protocol: LLMProtoco
11
11
  /** Gemini chunks carry complete function-call objects, never JSON argument deltas. */
12
12
  export declare class GeminiCanonicalDecoder {
13
13
  private context;
14
+ private streaming;
14
15
  private encoder;
15
16
  private serial;
16
17
  private ended;
17
18
  private tools;
18
19
  private ids;
19
- constructor(context: ProtocolSessionContext, names: ResponsesToolNames);
20
+ private sequence;
21
+ private contentId?;
22
+ private partCount;
23
+ private replayBytes;
24
+ private signedItems;
25
+ private signed;
26
+ constructor(context: ProtocolSessionContext, names: ResponsesToolNames, streaming?: boolean);
20
27
  push(raw: unknown): JsonRecord[];
28
+ private decorate;
21
29
  finish(): JsonRecord[];
22
30
  }
23
31
  export declare function canonicalResponse(raw: unknown, context: ProtocolSessionContext, names: ResponsesToolNames): JsonRecord;
@@ -6,4 +6,6 @@ export interface DecodedResponsesRequest {
6
6
  diagnostics: ResponsesConversionDiagnostic[];
7
7
  }
8
8
  /** Converts only self-contained history. Reference resolution belongs to the caller. */
9
- export declare function decodeResponsesRequest(raw: unknown, protocol: ResponsesProtocol, capabilities?: ResponsesCodecCapabilities): DecodedResponsesRequest;
9
+ export declare function decodeResponsesRequest(raw: unknown, protocol: ResponsesProtocol, capabilities?: ResponsesCodecCapabilities, options?: {
10
+ preserveContentOrder?: boolean;
11
+ }): DecodedResponsesRequest;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jeffusion/bungee-llms",
3
- "version": "6.7.2",
3
+ "version": "6.8.0",
4
4
  "description": "Extensible LLM adapters and protocol conversion package for Bungee",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -11,7 +11,7 @@
11
11
  "prepublishOnly": "bun run build"
12
12
  },
13
13
  "dependencies": {
14
- "@jeffusion/bungee-types": "^6.7.2"
14
+ "@jeffusion/bungee-types": "^6.8.0"
15
15
  },
16
16
  "devDependencies": {
17
17
  "bun-types": "^1.3.2",