@jeffusion/bungee-llms 6.15.0 → 6.16.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/dist/index.js CHANGED
@@ -3601,8 +3601,242 @@ function validateEncryptedFunctionArgs(item, delivery, path) {
3601
3601
  fail("unsupported_content", "Encrypted function arguments cannot cross protocols", param);
3602
3602
  }
3603
3603
 
3604
+ // src/protocol-session/gemini.ts
3605
+ import { createHash } from "crypto";
3606
+
3607
+ // src/protocol-session/validation.ts
3608
+ function fields(value, allowed, path, code = "unsupported_request") {
3609
+ for (const key of Object.keys(value))
3610
+ if (!allowed.includes(key))
3611
+ fail(code, "Field cannot be represented by the target protocol", path ? `${path}.${key}` : key);
3612
+ }
3613
+ function bool(value, path) {
3614
+ if (typeof value !== "boolean")
3615
+ fail("invalid_payload", "Expected a boolean", path);
3616
+ return value;
3617
+ }
3618
+ function integer(value, path, min = 0) {
3619
+ if (!Number.isSafeInteger(value) || value < min)
3620
+ fail("invalid_payload", "Expected an integer in the supported range", path);
3621
+ return value;
3622
+ }
3623
+ function textParts(raw, path, style, role) {
3624
+ if (typeof raw === "string")
3625
+ return [{ type: "input_text", text: raw }];
3626
+ return list(raw, path).map((rawPart, index) => {
3627
+ const p = record(rawPart, path), at = `${path}[${index}]`;
3628
+ if (style === "gemini") {
3629
+ fields(p, ["text", "thought"], at, "unsupported_content");
3630
+ if (p.thought === true)
3631
+ fail("unsupported_reasoning", "Reasoning must be represented as a separate history item", at);
3632
+ return { type: "input_text", text: string(p.text, at) };
3633
+ }
3634
+ if (style === "chat" && p.type === "image_url" && role === "user") {
3635
+ fields(p, ["type", "image_url"], at, "unsupported_content");
3636
+ const image = record(p.image_url, at);
3637
+ fields(image, ["url", "detail"], `${at}.image_url`, "unsupported_content");
3638
+ return { type: "input_image", image_url: string(image.url, at, true), ...image.detail !== undefined ? { detail: image.detail } : {} };
3639
+ }
3640
+ if (style === "chat" && p.type === "refusal" && role === "assistant") {
3641
+ fields(p, ["type", "refusal"], at, "unsupported_content");
3642
+ return { type: "refusal", refusal: string(p.refusal, at) };
3643
+ }
3644
+ if (p.type !== "text")
3645
+ fail("unsupported_content", "Content block cannot be represented by the target protocol", at);
3646
+ fields(p, ["type", "text"], at, "unsupported_content");
3647
+ return { type: "input_text", text: string(p.text, at) };
3648
+ });
3649
+ }
3650
+
3651
+ // src/protocol-session/gemini.ts
3652
+ var signatureSeparator = "__thought__";
3653
+ function geminiInlineImage(image, path, budget) {
3654
+ const param = `${path}.image_url`;
3655
+ const url = bounded(string(image.url, "image URL", true), budget.maxRequestBytes, param);
3656
+ const match = /^data:([^;,]+);base64,([\s\S]*)$/.exec(url);
3657
+ if (!match || !["image/png", "image/jpeg", "image/webp"].includes(match[1]))
3658
+ fail("unsupported_content", "Gemini images require inline PNG, JPEG or WebP data", param);
3659
+ const data = match[2];
3660
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(data) || data.length % 4 === 1 || data.includes("=") && data.length % 4 !== 0 || Buffer.from(data, "base64").toString("base64").replace(/=+$/, "") !== data.replace(/=+$/, ""))
3661
+ fail("invalid_payload", "Invalid image Base64 encoding", param);
3662
+ return { mimeType: match[1], data };
3663
+ }
3664
+ function geminiToolResponse(content, path, budget, diagnostics) {
3665
+ if (!Array.isArray(content) || !content.some((part) => part.type === "image_url"))
3666
+ return { response: { output: content } };
3667
+ if (content.length > budget.maxItems)
3668
+ fail("resource_limit", "Too many tool output parts", path);
3669
+ const parts = [];
3670
+ const output = content.map((part, index) => atParam(`${path}[${index}]`, () => {
3671
+ if (part.type === "text")
3672
+ return part;
3673
+ if (part.type !== "image_url")
3674
+ fail("unsupported_content", "Unsupported Gemini tool result content");
3675
+ const image = record(part.image_url, "tool image");
3676
+ const inlineData = geminiInlineImage(image, `${path}[${index}]`, budget);
3677
+ const displayName = `tool-image-${index}.${inlineData.mimeType.slice("image/".length)}`;
3678
+ parts.push({ inlineData: { ...inlineData, displayName } });
3679
+ if (image.detail !== undefined)
3680
+ diagnostics.push({ param: `${path}[${index}].detail`, action: "omitted", reason: "gemini_tool_image_detail_unavailable" });
3681
+ return { $ref: displayName };
3682
+ }));
3683
+ return { response: { output }, parts };
3684
+ }
3685
+ function checkedSignature(value, maxBytes) {
3686
+ const signature = bounded(string(value, "thoughtSignature", true), maxBytes, "thoughtSignature");
3687
+ 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(/=+$/, ""))
3688
+ fail("invalid_tool_arguments", "Invalid Gemini thought signature encoding", "thoughtSignature");
3689
+ return signature;
3690
+ }
3691
+ var envelopePrefix = "bungee_gemini:";
3692
+ var isGeminiSignatureCarrier = (value) => typeof value === "string" && value.startsWith(envelopePrefix);
3693
+ var geminiEnvelopeBytes = (payloadBytes) => envelopePrefix.length + Math.ceil(payloadBytes * 4 / 3);
3694
+ var geminiTextHash = (text) => createHash("sha256").update(text).digest("base64url");
3695
+ function geminiSignatureItem(items, budget) {
3696
+ const payload = serialized({ version: 1, items }, budget.maxArgumentBytes, "Gemini signatures");
3697
+ return {
3698
+ type: "reasoning",
3699
+ id: `rs_gemini_${crypto.randomUUID().replaceAll("-", "")}`,
3700
+ summary: [],
3701
+ encrypted_content: bounded(envelopePrefix + Buffer.from(payload).toString("base64url"), budget.maxArgumentBytes, "Gemini signatures")
3702
+ };
3703
+ }
3704
+ function readGeminiSignatures(item, budget) {
3705
+ fields(item, ["type", "id", "summary", "encrypted_content", "status"], "Gemini signatures", "unsupported_reasoning");
3706
+ if (item.type !== "reasoning" || list(item.summary, "summary").length)
3707
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier");
3708
+ string(item.id, "signature item id", true);
3709
+ const opaque = bounded(string(item.encrypted_content, "encrypted_content", true), budget.maxArgumentBytes, "Gemini signatures");
3710
+ if (!isGeminiSignatureCarrier(opaque))
3711
+ fail("unsupported_reasoning", "Native encrypted reasoning cannot be restored to Gemini");
3712
+ const encoded = opaque.slice(envelopePrefix.length), bytes = Buffer.from(encoded, "base64url");
3713
+ if (!encoded || bytes.toString("base64url") !== encoded)
3714
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier encoding");
3715
+ let raw;
3716
+ try {
3717
+ raw = JSON.parse(bytes.toString("utf8"));
3718
+ } catch {
3719
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier JSON");
3720
+ }
3721
+ const body = record(raw, "Gemini signatures");
3722
+ fields(body, ["version", "items"], "Gemini signatures", "unsupported_reasoning");
3723
+ if (body.version !== 1)
3724
+ fail("unsupported_reasoning", "Unknown Gemini signature format");
3725
+ const ids = new Set;
3726
+ let partCount = 0;
3727
+ const result = list(body.items, "signature items").map((raw) => {
3728
+ const item = record(raw, "signature item");
3729
+ fields(item, ["id", "thought", "parts"], "signature item", "unsupported_reasoning");
3730
+ const id = string(item.id, "signed item id", true);
3731
+ if (ids.has(id) || typeof item.thought !== "boolean")
3732
+ fail("unsupported_reasoning", "Invalid signed item identity");
3733
+ ids.add(id);
3734
+ const parts = list(item.parts, "signed parts").map((raw) => {
3735
+ if (++partCount > budget.maxItems)
3736
+ fail("resource_limit", "Too many signed Gemini parts");
3737
+ const part = record(raw, "signed part");
3738
+ fields(part, ["length", "hash", "signature", "textAbsent"], "signed part", "unsupported_reasoning");
3739
+ const length = integer(part.length, "signed part length"), hash = string(part.hash, "signed part hash", true);
3740
+ if (!/^[A-Za-z0-9_-]{43}$/.test(hash))
3741
+ fail("unsupported_reasoning", "Invalid signed part hash");
3742
+ const signature = part.signature === undefined ? undefined : checkedSignature(part.signature, budget.maxArgumentBytes);
3743
+ if (part.textAbsent !== undefined && (part.textAbsent !== true || length !== 0 || signature === undefined))
3744
+ fail("unsupported_reasoning", "Invalid empty signed part");
3745
+ return { length, hash, ...signature === undefined ? {} : { signature }, ...part.textAbsent ? { textAbsent: true } : {} };
3746
+ });
3747
+ if (!parts.some((p) => p.signature !== undefined))
3748
+ fail("unsupported_reasoning", "Signature carrier has no signature");
3749
+ return { id, thought: item.thought, parts };
3750
+ });
3751
+ if (!result.length || result.length > budget.maxItems)
3752
+ fail("unsupported_reasoning", "Invalid signature item count");
3753
+ return result;
3754
+ }
3755
+ function restoreGeminiHistory(input, budget) {
3756
+ const original = typeof input === "string" ? [] : list(input, "input").map((raw) => record(raw, "input item"));
3757
+ if (original.length > budget.maxItems)
3758
+ fail("resource_limit", "Too many input items", "input");
3759
+ const retained = new Map, parts = new Map, ids = new Map;
3760
+ original.forEach((item, i) => {
3761
+ if (typeof item.id === "string") {
3762
+ if (ids.has(item.id))
3763
+ fail("invalid_tool_history", "Duplicate history item id", "input.id");
3764
+ ids.set(item.id, i);
3765
+ }
3766
+ });
3767
+ original.forEach((carrier, index) => {
3768
+ if (carrier.type === "configuration_update") {
3769
+ retained.set(carrier, carrier);
3770
+ return;
3771
+ }
3772
+ if (carrier.encrypted_content == null)
3773
+ return;
3774
+ const { content, internal_chat_message_metadata_passthrough: metadata, ...normalized } = carrier;
3775
+ if (content !== undefined && content !== null)
3776
+ fail("unsupported_reasoning", "Gemini signature carriers cannot contain reasoning content", `input[${index}].content`);
3777
+ if (metadata !== undefined)
3778
+ atParam(`input[${index}].internal_chat_message_metadata_passthrough`, () => record(metadata, "message metadata"));
3779
+ const signed = readGeminiSignatures(normalized, budget);
3780
+ retained.set(carrier, normalized);
3781
+ let previous = -1;
3782
+ for (const item of signed) {
3783
+ const at = ids.get(item.id);
3784
+ if (at === undefined || at >= index || at <= previous || parts.has(item.id))
3785
+ fail("unsupported_reasoning", "Signed history reference is missing or ambiguous");
3786
+ previous = at;
3787
+ const source = original[at];
3788
+ if (item.thought ? source.type !== "reasoning" || source.encrypted_content != null : source.role !== "assistant" || source.type !== undefined && source.type !== "message")
3789
+ fail("unsupported_reasoning", "Signed history item kind changed");
3790
+ const content = item.thought ? list(source.summary, "summary") : typeof source.content === "string" ? [{ type: "output_text", text: source.content }] : list(source.content, "content");
3791
+ const text = content.map((raw) => {
3792
+ const p = record(raw, "signed text");
3793
+ if (p.type !== (item.thought ? "summary_text" : "output_text") && !(p.type === "input_text" && !item.thought))
3794
+ fail("unsupported_reasoning", "Signed history content kind changed");
3795
+ return string(p.text, "signed text");
3796
+ }).join("");
3797
+ let offset = 0;
3798
+ const restored = item.parts.map((part) => {
3799
+ const value = text.slice(offset, offset + part.length);
3800
+ offset += part.length;
3801
+ if (value.length !== part.length || geminiTextHash(value) !== part.hash)
3802
+ fail("unsupported_reasoning", "Signed history text changed");
3803
+ return { ...part.textAbsent ? {} : { text: value }, ...item.thought ? { thought: true } : {}, ...part.signature === undefined ? {} : { thoughtSignature: part.signature } };
3804
+ });
3805
+ if (offset !== text.length)
3806
+ fail("unsupported_reasoning", "Signed history text was not fully consumed");
3807
+ parts.set(item.id, restored);
3808
+ }
3809
+ });
3810
+ const positions = original.flatMap((item, index) => retained.has(item) ? [] : [index]);
3811
+ return {
3812
+ input: typeof input === "string" ? input : positions.map((index) => original[index]),
3813
+ parts,
3814
+ sourceParam(param) {
3815
+ return param.replace(/^input\[(\d+)\]/, (match, index) => positions[Number(index)] === undefined ? match : `input[${positions[Number(index)]}]`);
3816
+ },
3817
+ canonicalHistory(decoded) {
3818
+ if (!retained.size)
3819
+ return decoded;
3820
+ let next = 0;
3821
+ return original.filter((item) => item.type !== "additional_tools").map((item) => retained.get(item) ?? decoded[next++]);
3822
+ }
3823
+ };
3824
+ }
3825
+ function encodeGeminiCallId(id, signature, maxBytes) {
3826
+ if (id.includes(signatureSeparator))
3827
+ fail("invalid_tool_arguments", "Gemini call id contains the signature separator", "functionCall.id");
3828
+ return signature === undefined ? id : `${id}${signatureSeparator}${checkedSignature(signature, maxBytes)}`;
3829
+ }
3830
+ function decodeGeminiCallId(value, maxBytes) {
3831
+ const separator = value.indexOf(signatureSeparator);
3832
+ if (separator < 0)
3833
+ return { id: value };
3834
+ const id = string(value.slice(0, separator), "functionCall.id", true);
3835
+ return { id, thoughtSignature: checkedSignature(value.slice(separator + signatureSeparator.length), maxBytes) };
3836
+ }
3837
+
3604
3838
  // src/responses-codec/request-preferences.ts
3605
- function fields(value, allowed, path) {
3839
+ function fields2(value, allowed, path) {
3606
3840
  for (const key of Object.keys(value))
3607
3841
  if (!allowed.includes(key)) {
3608
3842
  fail("unsupported_request", "Unrecognized request option", `${path}.${key}`);
@@ -3613,7 +3847,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
3613
3847
  if (body.stream_options !== undefined)
3614
3848
  atParam("stream_options", () => {
3615
3849
  const options = record(body.stream_options, "stream_options");
3616
- fields(options, ["include_usage", "reasoning_summary_delivery"], "stream_options");
3850
+ fields2(options, ["include_usage", "reasoning_summary_delivery"], "stream_options");
3617
3851
  if (options.include_usage !== undefined) {
3618
3852
  if (typeof options.include_usage !== "boolean")
3619
3853
  fail("invalid_payload", "Usage preference must be boolean", "stream_options.include_usage");
@@ -3628,7 +3862,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
3628
3862
  if (body.access_programs !== undefined)
3629
3863
  atParam("access_programs", () => {
3630
3864
  const programs = record(body.access_programs, "access_programs");
3631
- fields(programs, ["cyber"], "access_programs");
3865
+ fields2(programs, ["cyber"], "access_programs");
3632
3866
  if (programs.cyber !== undefined && programs.cyber !== "standard") {
3633
3867
  if (programs.cyber === "daybreak_blue" || programs.cyber === "daybreak_red") {
3634
3868
  fail("unsupported_access_program", "Selected access program cannot be represented by the target protocol", "access_programs.cyber");
@@ -3640,7 +3874,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
3640
3874
  if (body.reasoning !== undefined)
3641
3875
  atParam("reasoning", () => {
3642
3876
  const reasoning = record(body.reasoning, "reasoning");
3643
- fields(reasoning, ["effort", "summary", "context"], "reasoning");
3877
+ fields2(reasoning, ["effort", "summary", "context"], "reasoning");
3644
3878
  if (reasoning.summary !== undefined) {
3645
3879
  if (typeof reasoning.summary !== "string" || !["none", "auto", "concise", "detailed"].includes(reasoning.summary))
3646
3880
  fail("invalid_payload", "Invalid reasoning summary preference", "reasoning.summary");
@@ -3671,7 +3905,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
3671
3905
  if (body.text !== undefined)
3672
3906
  atParam("text", () => {
3673
3907
  const text = record(body.text, "text");
3674
- fields(text, ["verbosity", "format"], "text");
3908
+ fields2(text, ["verbosity", "format"], "text");
3675
3909
  if (text.verbosity !== undefined) {
3676
3910
  if (typeof text.verbosity !== "string" || !["low", "medium", "high"].includes(text.verbosity))
3677
3911
  fail("invalid_payload", "Invalid text verbosity preference", "text.verbosity");
@@ -3734,6 +3968,7 @@ function definitionKey(value) {
3734
3968
  }
3735
3969
  function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {}) {
3736
3970
  const body = record(raw, "Responses request");
3971
+ const allowLossyContinuation = protocol === "chat_completions" && options.allowLossyContinuation === true;
3737
3972
  if (capabilities.agentMessageDelivery !== undefined && capabilities.agentMessageDelivery !== "plaintext")
3738
3973
  fail("invalid_payload", "Unknown agent message delivery policy", "agentMessageDelivery");
3739
3974
  const budget = limits(capabilities.limits);
@@ -3802,6 +4037,7 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3802
4037
  const byOriginal = new Map;
3803
4038
  const definitions = new Map;
3804
4039
  let examinedTools = 0;
4040
+ let hasCompaction = false;
3805
4041
  const tools = [];
3806
4042
  const identity = (name, namespace) => JSON.stringify([namespace ?? null, name]);
3807
4043
  const register = (name, namespace, custom) => {
@@ -3899,6 +4135,31 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3899
4135
  for (const [index, rawItem] of input.entries())
3900
4136
  atParam(`input[${index}]`, () => {
3901
4137
  const item = record(rawItem, "input item");
4138
+ if (Object.hasOwn(item, "phase")) {
4139
+ const param = `input[${index}].phase`;
4140
+ if (!allowLossyContinuation || item.type !== undefined && item.type !== "message" || item.role !== "assistant")
4141
+ fail("unsupported_content", "Message phase requires opted-in Chat assistant history", param);
4142
+ if (item.phase !== null && item.phase !== "commentary" && item.phase !== "final_answer")
4143
+ fail("invalid_payload", "Invalid assistant message phase", param);
4144
+ diagnostics.push({ param, action: "omitted", reason: "chat_assistant_phase_unavailable" });
4145
+ }
4146
+ if (allowLossyContinuation && item.type === "compaction") {
4147
+ const path = `input[${index}]`;
4148
+ for (const key of Object.keys(item))
4149
+ if (!["type", "id", "created_by", "encrypted_content", "internal_chat_message_metadata_passthrough"].includes(key))
4150
+ fail("unsupported_content", "Unknown compaction field", `${path}.${key}`);
4151
+ const param = `${path}.encrypted_content`;
4152
+ const encryptedContent = atParam(param, () => string(item.encrypted_content, "compaction encrypted content", true));
4153
+ if (!encryptedContent.trim())
4154
+ fail("invalid_payload", "Compaction encrypted content must be non-empty", param);
4155
+ if (isGeminiSignatureCarrier(encryptedContent))
4156
+ fail("unsupported_content", "Gemini signature carriers cannot cross into Chat", param);
4157
+ if (item.id != null)
4158
+ atParam(`${path}.id`, () => string(item.id, "compaction id", true));
4159
+ if (item.created_by !== undefined)
4160
+ atParam(`${path}.created_by`, () => string(item.created_by, "compaction created_by", true));
4161
+ hasCompaction = true;
4162
+ }
3902
4163
  if (item.type !== "additional_tools") {
3903
4164
  if (item.internal_chat_message_metadata_passthrough !== undefined) {
3904
4165
  record(item.internal_chat_message_metadata_passthrough, "message metadata");
@@ -3934,6 +4195,12 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3934
4195
  const partPath = `${path}[${index}]`;
3935
4196
  atParam(partPath, () => {
3936
4197
  const part = record(rawPart, "content part");
4198
+ if (Object.hasOwn(part, "logprobs")) {
4199
+ const param = `${partPath}.logprobs`;
4200
+ if (!allowLossyContinuation || role !== "assistant" || part.type !== "output_text" || !Array.isArray(part.logprobs) || part.logprobs.length !== 0)
4201
+ fail("unsupported_content", "Only empty assistant output log probabilities can be omitted", param);
4202
+ diagnostics.push({ param, action: "omitted", reason: "chat_empty_output_logprobs" });
4203
+ }
3937
4204
  if (part.type === "input_text" || part.type === "output_text" || part.type === "text")
3938
4205
  string(part.text, "content text");
3939
4206
  else if (part.type === "refusal" && role === "assistant") {
@@ -3983,6 +4250,8 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3983
4250
  let messageParam = "instructions";
3984
4251
  const callIds = new Set;
3985
4252
  const callToolNames = new Map;
4253
+ const callsAwaitingResult = new Map;
4254
+ let encryptedToolBatch;
3986
4255
  const answered = new Set;
3987
4256
  const deferredInstructions = [];
3988
4257
  const normalizeChatHistory = protocol === "chat_completions" && !options.preserveContentOrder;
@@ -4001,18 +4270,43 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
4001
4270
  addMessage({ role: "user", content: [{ type: "text", text: `Images returned by tool ${JSON.stringify(name)} (call ${JSON.stringify(callId)}):` }, ...images] });
4002
4271
  projectedToolImages.length = 0;
4003
4272
  };
4273
+ const checkPendingToolHistory = (item, toolOutput) => {
4274
+ const message = item.type === undefined || item.type === "message";
4275
+ const instruction = message && (item.role === "system" || item.role === "developer");
4276
+ const toolCall = item.type === "function_call" || item.type === "custom_tool_call";
4277
+ if (hasCompaction && toolOutput && callsAwaitingResult.size && pendingReasoning)
4278
+ fail("invalid_tool_history", "Attach the reasoning summary before the Chat tool results", messageParam);
4279
+ if (toolOutput || instruction)
4280
+ return;
4281
+ if (deferredInstructions.length)
4282
+ fail("invalid_tool_history", "Only instructions and tool results may follow a deferred instruction until all tool results arrive", messageParam);
4283
+ if (encryptedToolBatch && !(toolCall && chat.at(-1)?.role === "assistant"))
4284
+ fail("invalid_tool_history", "Complete the encrypted tool batch before another turn or reasoning item", messageParam);
4285
+ if (hasCompaction && callsAwaitingResult.size && !(normalizeChatHistory && chat.at(-1)?.role === "assistant" && (toolCall || item.type === "reasoning" || message && item.role === "assistant")))
4286
+ fail("invalid_tool_history", "Complete the Chat tool batch before another message", messageParam);
4287
+ };
4004
4288
  if (body.instructions !== undefined)
4005
4289
  addMessage({ role: "system", content: string(body.instructions, "instructions") });
4006
4290
  for (const [inputIndex, rawItem] of input.entries())
4007
4291
  atParam(`input[${inputIndex}]`, () => {
4008
4292
  messageParam = `input[${inputIndex}]`;
4009
4293
  const item = record(rawItem, "input item");
4010
- if (item.type !== "function_call_output" && item.type !== "custom_tool_call_output")
4294
+ const toolOutput = item.type === "function_call_output" || item.type === "custom_tool_call_output";
4295
+ if (!toolOutput)
4011
4296
  flushToolImages();
4012
- if (item.type === "additional_tools")
4297
+ if (item.type === "additional_tools" || allowLossyContinuation && item.type === "configuration_update" && options.chatConfigurationUpdates?.has(item))
4013
4298
  return;
4014
- if (deferredInstructions.length && item.type !== "function_call_output" && item.type !== "custom_tool_call_output" && !((item.type === undefined || item.type === "message") && (item.role === "system" || item.role === "developer")))
4015
- fail("invalid_tool_history", "Only instructions and tool results may follow a deferred instruction until all tool results arrive", messageParam);
4299
+ if (item.type !== "reasoning")
4300
+ checkPendingToolHistory(item, toolOutput);
4301
+ if (allowLossyContinuation && item.type === "compaction") {
4302
+ if (callIds.size !== answered.size)
4303
+ fail("invalid_tool_history", "Compaction cannot split a Chat tool batch", messageParam);
4304
+ if (pendingReasoning)
4305
+ fail("unsupported_reasoning", "Reasoning must precede an assistant item", messageParam);
4306
+ addMessage({ role: "user", content: "[Earlier conversation context was compacted and is unavailable. Continue from the visible messages and ask for any details you need.]" });
4307
+ diagnostics.push({ param: messageParam, action: "mapped", reason: "chat_compaction_placeholder" });
4308
+ return;
4309
+ }
4016
4310
  if (item.type === "agent_message") {
4017
4311
  validateAgentMessage(item, messageParam, capabilities.limits);
4018
4312
  if (capabilities.agentMessageDelivery !== "plaintext")
@@ -4024,24 +4318,34 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
4024
4318
  diagnostics.push({ param: messageParam, action: "mapped", reason: "agent_message_plaintext_delivery" });
4025
4319
  return;
4026
4320
  }
4027
- if (item.encrypted_content != null)
4028
- fail("unsupported_content", "Encrypted content cannot cross protocols", `${messageParam}.encrypted_content`);
4321
+ const encrypted = item.encrypted_content != null;
4322
+ if (encrypted) {
4323
+ const param = `${messageParam}.encrypted_content`;
4324
+ if (!allowLossyContinuation || item.type !== "reasoning" && item.type !== "function_call")
4325
+ fail("unsupported_content", "Encrypted content cannot cross protocols", param);
4326
+ atParam(param, () => string(item.encrypted_content, "encrypted content", true));
4327
+ diagnostics.push({ param, action: "omitted", reason: "chat_opaque_history_content_unavailable" });
4328
+ }
4029
4329
  if (item.type === "compaction")
4030
4330
  fail("unsupported_content", "Encrypted reasoning and compaction cannot be restored");
4031
4331
  if (item.type === "item_reference")
4032
4332
  fail("unresolved_reference", "Input item references must be resolved before conversion");
4033
4333
  if (item.type === "reasoning") {
4034
- if (protocol !== "chat_completions" || !(capabilities.reasoningHistory || capabilities.reasoningEffort))
4035
- fail("unsupported_reasoning", "Reasoning history requires an explicit compatible reasoning capability");
4036
- if (item.content != null)
4334
+ if (item.content != null && !(encrypted && Array.isArray(item.content) && !item.content.length))
4037
4335
  fail("unsupported_reasoning", "Reasoning content requires an explicit history mapping", `${messageParam}.content`);
4038
- const summary = list(item.summary, "reasoning summary");
4039
- const text = summary.map((part) => {
4336
+ const summaryParam = `${messageParam}.summary`;
4337
+ const summary = encrypted && item.summary === undefined ? [] : atParam(summaryParam, () => list(item.summary, "reasoning summary"));
4338
+ const text = summary.map((part, index) => atParam(`${summaryParam}[${index}]`, () => {
4040
4339
  const p = record(part, "reasoning summary");
4041
4340
  if (p.type !== "summary_text")
4042
4341
  fail("unsupported_reasoning", "Unknown reasoning summary");
4043
4342
  return string(p.text, "summary text");
4044
- }).join("");
4343
+ })).join("");
4344
+ if (encrypted && !text)
4345
+ return;
4346
+ checkPendingToolHistory(item, false);
4347
+ if (protocol !== "chat_completions" || !(capabilities.reasoningHistory || capabilities.reasoningEffort))
4348
+ fail("unsupported_reasoning", "Reasoning history requires an explicit compatible reasoning capability");
4045
4349
  if (options.preserveContentOrder)
4046
4350
  addMessage({ role: "assistant", content: null, reasoning_content: text, ...item.id === undefined ? {} : { id: string(item.id, "item.id", true) } });
4047
4351
  else
@@ -4051,16 +4355,30 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
4051
4355
  if (item.type === "function_call" || item.type === "custom_tool_call") {
4052
4356
  const custom = item.type === "custom_tool_call";
4053
4357
  validateEncryptedFunctionArgs(item, capabilities.agentMessageDelivery, messageParam);
4358
+ if (encrypted && item.status !== undefined && item.status !== "completed")
4359
+ fail("invalid_tool_history", "Encrypted tool history requires a completed function call", `${messageParam}.status`);
4054
4360
  const id = string(item.call_id, "call_id", true);
4055
4361
  if (callIds.has(id))
4056
4362
  fail("invalid_tool_history", "Duplicate tool call identifier");
4363
+ const previous = chat.at(-1);
4364
+ if (encrypted && callIds.size !== answered.size) {
4365
+ const adjacent = previous?.role === "assistant" ? previous.tool_calls?.length ?? 0 : 0;
4366
+ if (adjacent !== callIds.size - answered.size)
4367
+ fail("invalid_tool_history", "Encrypted function call cannot join a split tool batch", `${messageParam}.call_id`);
4368
+ }
4057
4369
  callIds.add(id);
4058
- const args = custom ? JSON.stringify({ input: string(item.input, "custom input") }) : string(item.arguments, "arguments");
4059
- bounded(args, budget.maxArgumentBytes, "arguments");
4060
- argumentObject(args);
4370
+ if (hasCompaction || encrypted)
4371
+ callsAwaitingResult.set(id, { param: `${messageParam}.call_id`, outputType: custom ? "custom_tool_call_output" : "function_call_output" });
4372
+ if (encrypted)
4373
+ encryptedToolBatch ??= `${messageParam}.call_id`;
4374
+ const args = atParam(encrypted ? `${messageParam}.arguments` : messageParam, () => {
4375
+ const text = custom ? JSON.stringify({ input: string(item.input, "custom input") }) : string(item.arguments, "arguments");
4376
+ bounded(text, budget.maxArgumentBytes, "arguments");
4377
+ argumentObject(text);
4378
+ return text;
4379
+ });
4061
4380
  const call = { id, type: "function", function: { name: resolve(item, custom), arguments: args } };
4062
4381
  callToolNames.set(id, String(item.name));
4063
- const previous = chat.at(-1);
4064
4382
  if (previous?.role === "assistant" && !options.preserveContentOrder) {
4065
4383
  previous.tool_calls = [...previous.tool_calls ?? [], call];
4066
4384
  if (pendingReasoning)
@@ -4074,6 +4392,10 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
4074
4392
  const id = string(item.call_id, "call_id", true);
4075
4393
  if (!callIds.has(id) || answered.has(id))
4076
4394
  fail("invalid_tool_history", "Unmatched or duplicate tool result");
4395
+ const pending = callsAwaitingResult.get(id);
4396
+ if (pending && item.type !== pending.outputType)
4397
+ fail("invalid_tool_history", "Tool result type must match the corresponding call", `${messageParam}.type`);
4398
+ callsAwaitingResult.delete(id);
4077
4399
  answered.add(id);
4078
4400
  if (Array.isArray(item.output) && item.output.length > budget.maxItems && item.output.some((part) => part && typeof part === "object" && part.type === "input_image"))
4079
4401
  fail("resource_limit", "Too many tool output content parts", `${messageParam}.output`);
@@ -4092,6 +4414,7 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
4092
4414
  }
4093
4415
  addMessage({ role: "tool", tool_call_id: id, content: output, ...item.is_error === true ? { is_error: true } : {} });
4094
4416
  if (callIds.size === answered.size) {
4417
+ encryptedToolBatch = undefined;
4095
4418
  for (const instruction of deferredInstructions) {
4096
4419
  messageParam = instruction.param;
4097
4420
  addMessage(instruction.message);
@@ -4130,6 +4453,11 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
4130
4453
  }
4131
4454
  addMessage(message);
4132
4455
  });
4456
+ const missingResult = callsAwaitingResult.values().next().value;
4457
+ if (missingResult)
4458
+ fail("invalid_tool_history", "Tool call requires a matching result", missingResult.param);
4459
+ if (encryptedToolBatch)
4460
+ fail("invalid_tool_history", "All calls in the encrypted tool batch require matching results", encryptedToolBatch);
4133
4461
  if (pendingReasoning)
4134
4462
  fail("unsupported_reasoning", "Orphan reasoning history cannot be represented");
4135
4463
  if (deferredInstructions.length)
@@ -4684,251 +5012,12 @@ function encodeResponsesResult(raw, protocol, model, toolNames = new Map, config
4684
5012
  fail("missing_terminal", "JSON response has no terminal result");
4685
5013
  return record(end.response, "Responses result");
4686
5014
  }
4687
- // src/protocol-session/gemini.ts
4688
- import { createHash } from "crypto";
4689
-
4690
- // src/protocol-session/validation.ts
4691
- function fields2(value, allowed, path, code = "unsupported_request") {
4692
- for (const key of Object.keys(value))
4693
- if (!allowed.includes(key))
4694
- fail(code, "Field cannot be represented by the target protocol", path ? `${path}.${key}` : key);
4695
- }
4696
- function bool(value, path) {
4697
- if (typeof value !== "boolean")
4698
- fail("invalid_payload", "Expected a boolean", path);
4699
- return value;
4700
- }
4701
- function integer(value, path, min = 0) {
4702
- if (!Number.isSafeInteger(value) || value < min)
4703
- fail("invalid_payload", "Expected an integer in the supported range", path);
4704
- return value;
4705
- }
4706
- function textParts(raw, path, style, role) {
4707
- if (typeof raw === "string")
4708
- return [{ type: "input_text", text: raw }];
4709
- return list(raw, path).map((rawPart, index) => {
4710
- const p = record(rawPart, path), at = `${path}[${index}]`;
4711
- if (style === "gemini") {
4712
- fields2(p, ["text", "thought"], at, "unsupported_content");
4713
- if (p.thought === true)
4714
- fail("unsupported_reasoning", "Reasoning must be represented as a separate history item", at);
4715
- return { type: "input_text", text: string(p.text, at) };
4716
- }
4717
- if (style === "chat" && p.type === "image_url" && role === "user") {
4718
- fields2(p, ["type", "image_url"], at, "unsupported_content");
4719
- const image = record(p.image_url, at);
4720
- fields2(image, ["url", "detail"], `${at}.image_url`, "unsupported_content");
4721
- return { type: "input_image", image_url: string(image.url, at, true), ...image.detail !== undefined ? { detail: image.detail } : {} };
4722
- }
4723
- if (style === "chat" && p.type === "refusal" && role === "assistant") {
4724
- fields2(p, ["type", "refusal"], at, "unsupported_content");
4725
- return { type: "refusal", refusal: string(p.refusal, at) };
4726
- }
4727
- if (p.type !== "text")
4728
- fail("unsupported_content", "Content block cannot be represented by the target protocol", at);
4729
- fields2(p, ["type", "text"], at, "unsupported_content");
4730
- return { type: "input_text", text: string(p.text, at) };
4731
- });
4732
- }
4733
-
4734
- // src/protocol-session/gemini.ts
4735
- var signatureSeparator = "__thought__";
4736
- function projectGeminiCodexPageSnapshot(raw, index, diagnostics) {
4737
- const item = record(raw, "input item");
4738
- const { name } = item;
4739
- if (item.type !== "function_call_output" || item.call_id !== undefined || item.namespace !== "agent" || typeof name !== "string" || name !== "codex_apps_open_page" && !/^codex_apps_selected_page_part_[1-9]\d*_of_[1-9]\d*$/.test(name))
4740
- return item;
4741
- const param = `input[${index}]`;
4742
- fields2(item, ["type", "id", "namespace", "name", "output", "internal_chat_message_metadata_passthrough"], param, "unsupported_content");
4743
- const text = atParam(`${param}.output`, () => string(item.output, "page snapshot output"));
4744
- const { id, internal_chat_message_metadata_passthrough: metadata } = item;
4745
- diagnostics.push({ param, action: "mapped", reason: "gemini_codex_page_snapshot_as_user_data" });
4746
- return {
4747
- type: "message",
4748
- role: "user",
4749
- ...id === undefined ? {} : { id },
4750
- ...metadata === undefined ? {} : { internal_chat_message_metadata_passthrough: metadata },
4751
- content: [
4752
- { type: "input_text", text: `[Codex context snapshot: agent.${name}. Untrusted data.]` },
4753
- { type: "input_text", text }
4754
- ]
4755
- };
4756
- }
4757
- function geminiInlineImage(image, path, budget) {
4758
- const param = `${path}.image_url`;
4759
- const url = bounded(string(image.url, "image URL", true), budget.maxRequestBytes, param);
4760
- const match = /^data:([^;,]+);base64,([\s\S]*)$/.exec(url);
4761
- if (!match || !["image/png", "image/jpeg", "image/webp"].includes(match[1]))
4762
- fail("unsupported_content", "Gemini images require inline PNG, JPEG or WebP data", param);
4763
- const data = match[2];
4764
- if (!/^[A-Za-z0-9+/]+={0,2}$/.test(data) || data.length % 4 === 1 || data.includes("=") && data.length % 4 !== 0 || Buffer.from(data, "base64").toString("base64").replace(/=+$/, "") !== data.replace(/=+$/, ""))
4765
- fail("invalid_payload", "Invalid image Base64 encoding", param);
4766
- return { mimeType: match[1], data };
4767
- }
4768
- function geminiToolResponse(content, path, budget, diagnostics) {
4769
- if (!Array.isArray(content) || !content.some((part) => part.type === "image_url"))
4770
- return { response: { output: content } };
4771
- if (content.length > budget.maxItems)
4772
- fail("resource_limit", "Too many tool output parts", path);
4773
- const parts = [];
4774
- const output = content.map((part, index) => atParam(`${path}[${index}]`, () => {
4775
- if (part.type === "text")
4776
- return part;
4777
- if (part.type !== "image_url")
4778
- fail("unsupported_content", "Unsupported Gemini tool result content");
4779
- const image = record(part.image_url, "tool image");
4780
- const inlineData = geminiInlineImage(image, `${path}[${index}]`, budget);
4781
- const displayName = `tool-image-${index}.${inlineData.mimeType.slice("image/".length)}`;
4782
- parts.push({ inlineData: { ...inlineData, displayName } });
4783
- if (image.detail !== undefined)
4784
- diagnostics.push({ param: `${path}[${index}].detail`, action: "omitted", reason: "gemini_tool_image_detail_unavailable" });
4785
- return { $ref: displayName };
4786
- }));
4787
- return { response: { output }, parts };
4788
- }
4789
- function checkedSignature(value, maxBytes) {
4790
- const signature = bounded(string(value, "thoughtSignature", true), maxBytes, "thoughtSignature");
4791
- 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(/=+$/, ""))
4792
- fail("invalid_tool_arguments", "Invalid Gemini thought signature encoding", "thoughtSignature");
4793
- return signature;
4794
- }
4795
- var envelopePrefix = "bungee_gemini:";
4796
- var geminiEnvelopeBytes = (payloadBytes) => envelopePrefix.length + Math.ceil(payloadBytes * 4 / 3);
4797
- var geminiTextHash = (text) => createHash("sha256").update(text).digest("base64url");
4798
- function geminiSignatureItem(items, budget) {
4799
- const payload = serialized({ version: 1, items }, budget.maxArgumentBytes, "Gemini signatures");
4800
- return {
4801
- type: "reasoning",
4802
- id: `rs_gemini_${crypto.randomUUID().replaceAll("-", "")}`,
4803
- summary: [],
4804
- encrypted_content: bounded(envelopePrefix + Buffer.from(payload).toString("base64url"), budget.maxArgumentBytes, "Gemini signatures")
4805
- };
4806
- }
4807
- function readGeminiSignatures(item, budget) {
4808
- fields2(item, ["type", "id", "summary", "encrypted_content", "status"], "Gemini signatures", "unsupported_reasoning");
4809
- if (item.type !== "reasoning" || list(item.summary, "summary").length)
4810
- fail("unsupported_reasoning", "Invalid Gemini signature carrier");
4811
- string(item.id, "signature item id", true);
4812
- const opaque = bounded(string(item.encrypted_content, "encrypted_content", true), budget.maxArgumentBytes, "Gemini signatures");
4813
- if (!opaque.startsWith(envelopePrefix))
4814
- fail("unsupported_reasoning", "Native encrypted reasoning cannot be restored to Gemini");
4815
- const encoded = opaque.slice(envelopePrefix.length), bytes = Buffer.from(encoded, "base64url");
4816
- if (!encoded || bytes.toString("base64url") !== encoded)
4817
- fail("unsupported_reasoning", "Invalid Gemini signature carrier encoding");
4818
- let raw;
4819
- try {
4820
- raw = JSON.parse(bytes.toString("utf8"));
4821
- } catch {
4822
- fail("unsupported_reasoning", "Invalid Gemini signature carrier JSON");
4823
- }
4824
- const body = record(raw, "Gemini signatures");
4825
- fields2(body, ["version", "items"], "Gemini signatures", "unsupported_reasoning");
4826
- if (body.version !== 1)
4827
- fail("unsupported_reasoning", "Unknown Gemini signature format");
4828
- const ids = new Set;
4829
- let partCount = 0;
4830
- const result = list(body.items, "signature items").map((raw) => {
4831
- const item = record(raw, "signature item");
4832
- fields2(item, ["id", "thought", "parts"], "signature item", "unsupported_reasoning");
4833
- const id = string(item.id, "signed item id", true);
4834
- if (ids.has(id) || typeof item.thought !== "boolean")
4835
- fail("unsupported_reasoning", "Invalid signed item identity");
4836
- ids.add(id);
4837
- const parts = list(item.parts, "signed parts").map((raw) => {
4838
- if (++partCount > budget.maxItems)
4839
- fail("resource_limit", "Too many signed Gemini parts");
4840
- const part = record(raw, "signed part");
4841
- fields2(part, ["length", "hash", "signature", "textAbsent"], "signed part", "unsupported_reasoning");
4842
- const length = integer(part.length, "signed part length"), hash = string(part.hash, "signed part hash", true);
4843
- if (!/^[A-Za-z0-9_-]{43}$/.test(hash))
4844
- fail("unsupported_reasoning", "Invalid signed part hash");
4845
- const signature = part.signature === undefined ? undefined : checkedSignature(part.signature, budget.maxArgumentBytes);
4846
- if (part.textAbsent !== undefined && (part.textAbsent !== true || length !== 0 || signature === undefined))
4847
- fail("unsupported_reasoning", "Invalid empty signed part");
4848
- return { length, hash, ...signature === undefined ? {} : { signature }, ...part.textAbsent ? { textAbsent: true } : {} };
4849
- });
4850
- if (!parts.some((p) => p.signature !== undefined))
4851
- fail("unsupported_reasoning", "Signature carrier has no signature");
4852
- return { id, thought: item.thought, parts };
4853
- });
4854
- if (!result.length || result.length > budget.maxItems)
4855
- fail("unsupported_reasoning", "Invalid signature item count");
4856
- return result;
4857
- }
4858
- function restoreGeminiHistory(input, budget) {
4859
- const original = typeof input === "string" ? [] : list(input, "input").map((raw) => record(raw, "input item"));
4860
- const carriers = new Set, parts = new Map, ids = new Map;
4861
- original.forEach((item, i) => {
4862
- if (typeof item.id === "string") {
4863
- if (ids.has(item.id))
4864
- fail("invalid_tool_history", "Duplicate history item id", "input.id");
4865
- ids.set(item.id, i);
4866
- }
4867
- });
4868
- original.forEach((carrier, index) => {
4869
- if (carrier.encrypted_content == null)
4870
- return;
4871
- const signed = readGeminiSignatures(carrier, budget);
4872
- carriers.add(carrier);
4873
- let previous = -1;
4874
- for (const item of signed) {
4875
- const at = ids.get(item.id);
4876
- if (at === undefined || at >= index || at <= previous || parts.has(item.id))
4877
- fail("unsupported_reasoning", "Signed history reference is missing or ambiguous");
4878
- previous = at;
4879
- const source = original[at];
4880
- if (item.thought ? source.type !== "reasoning" || source.encrypted_content != null : source.role !== "assistant" || source.type !== undefined && source.type !== "message")
4881
- fail("unsupported_reasoning", "Signed history item kind changed");
4882
- const content = item.thought ? list(source.summary, "summary") : typeof source.content === "string" ? [{ type: "output_text", text: source.content }] : list(source.content, "content");
4883
- const text = content.map((raw) => {
4884
- const p = record(raw, "signed text");
4885
- if (p.type !== (item.thought ? "summary_text" : "output_text") && !(p.type === "input_text" && !item.thought))
4886
- fail("unsupported_reasoning", "Signed history content kind changed");
4887
- return string(p.text, "signed text");
4888
- }).join("");
4889
- let offset = 0;
4890
- const restored = item.parts.map((part) => {
4891
- const value = text.slice(offset, offset + part.length);
4892
- offset += part.length;
4893
- if (value.length !== part.length || geminiTextHash(value) !== part.hash)
4894
- fail("unsupported_reasoning", "Signed history text changed");
4895
- return { ...part.textAbsent ? {} : { text: value }, ...item.thought ? { thought: true } : {}, ...part.signature === undefined ? {} : { thoughtSignature: part.signature } };
4896
- });
4897
- if (offset !== text.length)
4898
- fail("unsupported_reasoning", "Signed history text was not fully consumed");
4899
- parts.set(item.id, restored);
4900
- }
4901
- });
4902
- return {
4903
- input: typeof input === "string" ? input : original.filter((item) => !carriers.has(item)),
4904
- parts,
4905
- canonicalHistory(decoded) {
4906
- if (!carriers.size)
4907
- return decoded;
4908
- let next = 0;
4909
- return original.flatMap((item) => carriers.has(item) ? [item] : item.type === "additional_tools" ? [] : [decoded[next++]]);
4910
- }
4911
- };
4912
- }
4913
- function encodeGeminiCallId(id, signature, maxBytes) {
4914
- if (id.includes(signatureSeparator))
4915
- fail("invalid_tool_arguments", "Gemini call id contains the signature separator", "functionCall.id");
4916
- return signature === undefined ? id : `${id}${signatureSeparator}${checkedSignature(signature, maxBytes)}`;
4917
- }
4918
- function decodeGeminiCallId(value, maxBytes) {
4919
- const separator = value.indexOf(signatureSeparator);
4920
- if (separator < 0)
4921
- return { id: value };
4922
- const id = string(value.slice(0, separator), "functionCall.id", true);
4923
- return { id, thoughtSignature: checkedSignature(value.slice(separator + signatureSeparator.length), maxBytes) };
4924
- }
4925
-
4926
5015
  // src/protocol-session/schema.ts
4927
5016
  function geminiSchemaToJson(raw, path, code = "unsupported_request", depth = 0) {
4928
5017
  if (depth > 64)
4929
5018
  fail("resource_limit", "Schema nesting exceeds the conversion limit", path);
4930
5019
  const s = record(raw, path);
4931
- fields2(s, ["type", "format", "title", "description", "nullable", "enum", "items", "properties", "required", "minimum", "maximum", "minLength", "maxLength", "pattern", "minItems", "maxItems", "minProperties", "maxProperties", "anyOf", "default", "example"], path, code);
5020
+ fields(s, ["type", "format", "title", "description", "nullable", "enum", "items", "properties", "required", "minimum", "maximum", "minLength", "maxLength", "pattern", "minItems", "maxItems", "minProperties", "maxProperties", "anyOf", "default", "example"], path, code);
4932
5021
  const out = {};
4933
5022
  if (s.type !== undefined) {
4934
5023
  const types = { STRING: "string", NUMBER: "number", INTEGER: "integer", BOOLEAN: "boolean", ARRAY: "array", OBJECT: "object", NULL: "null" };
@@ -4968,19 +5057,19 @@ function message(input, role, content, style, path) {
4968
5057
  function toolDefinition(raw, style, path) {
4969
5058
  const t = record(raw, path);
4970
5059
  if (style === "chat") {
4971
- fields2(t, t.type === "custom" ? ["type", "custom"] : ["type", "function"], path, "unsupported_tool");
5060
+ fields(t, t.type === "custom" ? ["type", "custom"] : ["type", "function"], path, "unsupported_tool");
4972
5061
  if (t.type === "custom") {
4973
5062
  const custom = record(t.custom, `${path}.custom`);
4974
- fields2(custom, ["name", "description", "format"], `${path}.custom`, "unsupported_tool");
5063
+ fields(custom, ["name", "description", "format"], `${path}.custom`, "unsupported_tool");
4975
5064
  return { type: "custom", ...custom };
4976
5065
  }
4977
5066
  if (t.type !== "function")
4978
5067
  fail("unsupported_tool", "Unsupported tool kind", `${path}.type`);
4979
5068
  const fn = record(t.function, path);
4980
- fields2(fn, ["name", "description", "parameters", "strict"], `${path}.function`, "unsupported_tool");
5069
+ fields(fn, ["name", "description", "parameters", "strict"], `${path}.function`, "unsupported_tool");
4981
5070
  return { type: "function", ...fn };
4982
5071
  }
4983
- fields2(t, style === "anthropic" ? ["name", "description", "input_schema", "strict"] : ["name", "description", "parametersJsonSchema", "parameters"], path, "unsupported_tool");
5072
+ fields(t, style === "anthropic" ? ["name", "description", "input_schema", "strict"] : ["name", "description", "parametersJsonSchema", "parameters"], path, "unsupported_tool");
4984
5073
  if (t.parameters !== undefined && t.parametersJsonSchema !== undefined)
4985
5074
  fail("unsupported_tool", "Ambiguous schema dialect", path);
4986
5075
  return {
@@ -5003,13 +5092,13 @@ function canonicalRequest(raw, protocol, model) {
5003
5092
  };
5004
5093
  if (protocol === "chat_completions") {
5005
5094
  const callKinds = new Map;
5006
- fields2(b, ["model", "messages", "tools", "tool_choice", "parallel_tool_calls", "stream", "stream_options", "temperature", "top_p", "max_tokens", "max_completion_tokens", "metadata", "response_format", "reasoning_effort", "stop", "n"], "");
5095
+ fields(b, ["model", "messages", "tools", "tool_choice", "parallel_tool_calls", "stream", "stream_options", "temperature", "top_p", "max_tokens", "max_completion_tokens", "metadata", "response_format", "reasoning_effort", "stop", "n"], "");
5007
5096
  if (b.max_tokens !== undefined && b.max_completion_tokens !== undefined)
5008
5097
  fail("unsupported_request", "Ambiguous token limits", "max_tokens");
5009
5098
  copy({ stream: "stream", stream_options: "stream_options", temperature: "temperature", top_p: "top_p", max_tokens: "max_output_tokens", max_completion_tokens: "max_output_tokens", metadata: "metadata", parallel_tool_calls: "parallel_tool_calls", n: "n", stop: "stop" });
5010
5099
  for (const [index, rawMessage] of list(b.messages, "messages").entries()) {
5011
5100
  const m = record(rawMessage, "message"), path = `messages[${index}]`;
5012
- fields2(m, ["role", "content", "tool_calls", "tool_call_id", "reasoning_content", "reasoning", "refusal", "name"], path, "unsupported_content");
5101
+ fields(m, ["role", "content", "tool_calls", "tool_call_id", "reasoning_content", "reasoning", "refusal", "name"], path, "unsupported_content");
5013
5102
  if (m.name !== undefined)
5014
5103
  fail("unsupported_content", "Named messages cannot be represented faithfully", `${path}.name`);
5015
5104
  const role = string(m.role, "role", true);
@@ -5044,12 +5133,12 @@ function canonicalRequest(raw, protocol, model) {
5044
5133
  fail("invalid_tool_history", "Tool calls require assistant role", path);
5045
5134
  for (const [j, rawCall] of list(m.tool_calls, "tool_calls").entries()) {
5046
5135
  const c = record(rawCall, "tool call"), at = `${path}.tool_calls[${j}]`;
5047
- fields2(c, ["id", "type", "function", "custom"], at, "unsupported_tool");
5136
+ fields(c, ["id", "type", "function", "custom"], at, "unsupported_tool");
5048
5137
  const custom = c.type === "custom";
5049
5138
  if (!custom && c.type !== "function")
5050
5139
  fail("unsupported_tool", "Unknown call type", at);
5051
5140
  const fn = record(custom ? c.custom : c.function, "tool call");
5052
- fields2(fn, custom ? ["name", "input"] : ["name", "arguments"], at, "unsupported_tool");
5141
+ fields(fn, custom ? ["name", "input"] : ["name", "arguments"], at, "unsupported_tool");
5053
5142
  callKinds.set(string(c.id, "id", true), custom);
5054
5143
  input.push({
5055
5144
  type: custom ? "custom_tool_call" : "function_call",
@@ -5068,9 +5157,9 @@ function canonicalRequest(raw, protocol, model) {
5068
5157
  out.tool_choice = c;
5069
5158
  else {
5070
5159
  const choice = record(c, "tool_choice");
5071
- fields2(choice, ["type", "function", "custom"], "tool_choice");
5160
+ fields(choice, ["type", "function", "custom"], "tool_choice");
5072
5161
  const fn = record(choice.function ?? choice.custom, "tool_choice");
5073
- fields2(fn, ["name"], "tool_choice.function");
5162
+ fields(fn, ["name"], "tool_choice.function");
5074
5163
  out.tool_choice = { type: choice.type, name: fn.name };
5075
5164
  }
5076
5165
  }
@@ -5078,19 +5167,19 @@ function canonicalRequest(raw, protocol, model) {
5078
5167
  out.reasoning = { effort: b.reasoning_effort };
5079
5168
  if (b.response_format !== undefined) {
5080
5169
  const format = record(b.response_format, "response_format");
5081
- fields2(format, ["type", "json_schema"], "response_format");
5170
+ fields(format, ["type", "json_schema"], "response_format");
5082
5171
  out.text = { format: format.type === "json_schema" ? { type: "json_schema", ...record(format.json_schema, "json_schema") } : format };
5083
5172
  }
5084
5173
  return out;
5085
5174
  }
5086
5175
  if (protocol === "anthropic_messages") {
5087
- fields2(b, ["model", "messages", "system", "tools", "tool_choice", "stream", "temperature", "top_p", "max_tokens", "metadata", "stop_sequences", "thinking", "output_config"], "");
5176
+ fields(b, ["model", "messages", "system", "tools", "tool_choice", "stream", "temperature", "top_p", "max_tokens", "metadata", "stop_sequences", "thinking", "output_config"], "");
5088
5177
  copy({ stream: "stream", temperature: "temperature", top_p: "top_p", max_tokens: "max_output_tokens", metadata: "metadata", stop_sequences: "stop" });
5089
5178
  if (b.system !== undefined)
5090
5179
  message(input, "system", b.system, "anthropic", "system");
5091
5180
  for (const [index, rawMessage] of list(b.messages, "messages").entries()) {
5092
5181
  const m = record(rawMessage, "message"), path = `messages[${index}]`;
5093
- fields2(m, ["role", "content"], path, "unsupported_content");
5182
+ fields(m, ["role", "content"], path, "unsupported_content");
5094
5183
  if (m.role !== "user" && m.role !== "assistant")
5095
5184
  fail("unsupported_content", "Anthropic messages require user or assistant role", `${path}.role`);
5096
5185
  if (typeof m.content === "string") {
@@ -5102,15 +5191,15 @@ function canonicalRequest(raw, protocol, model) {
5102
5191
  if (p.type === "tool_use") {
5103
5192
  if (m.role !== "assistant")
5104
5193
  fail("invalid_tool_history", "Tool calls require assistant role", at);
5105
- fields2(p, ["type", "id", "name", "input"], at, "unsupported_content");
5194
+ fields(p, ["type", "id", "name", "input"], at, "unsupported_content");
5106
5195
  input.push({ type: "function_call", call_id: string(p.id, at, true), name: string(p.name, at, true), arguments: JSON.stringify(record(p.input, at)) });
5107
5196
  } else if (p.type === "tool_result") {
5108
5197
  if (m.role !== "user")
5109
5198
  fail("invalid_tool_history", "Tool results require user role", at);
5110
- fields2(p, ["type", "tool_use_id", "content", "is_error"], at, "unsupported_content");
5199
+ fields(p, ["type", "tool_use_id", "content", "is_error"], at, "unsupported_content");
5111
5200
  input.push({ type: "function_call_output", call_id: string(p.tool_use_id, at, true), output: typeof p.content === "string" ? p.content : textParts(p.content, at, "anthropic", "tool"), ...p.is_error !== undefined ? { is_error: bool(p.is_error, at) } : {} });
5112
5201
  } else if (p.type === "thinking") {
5113
- fields2(p, ["type", "thinking", "signature"], at, "unsupported_reasoning");
5202
+ fields(p, ["type", "thinking", "signature"], at, "unsupported_reasoning");
5114
5203
  if (p.signature != null)
5115
5204
  fail("unsupported_reasoning", "Provider-bound reasoning signatures cannot cross protocols", `${at}.signature`);
5116
5205
  if (m.role !== "assistant")
@@ -5124,7 +5213,7 @@ function canonicalRequest(raw, protocol, model) {
5124
5213
  out.tools = list(b.tools, "tools").map((t, i) => toolDefinition(t, "anthropic", `tools[${i}]`));
5125
5214
  if (b.tool_choice !== undefined) {
5126
5215
  const c = record(b.tool_choice, "tool_choice");
5127
- fields2(c, ["type", "name", "disable_parallel_tool_use"], "tool_choice");
5216
+ fields(c, ["type", "name", "disable_parallel_tool_use"], "tool_choice");
5128
5217
  if (c.type === "tool")
5129
5218
  out.tool_choice = { type: "function", name: c.name };
5130
5219
  else if (["auto", "none", "any"].includes(String(c.type)))
@@ -5136,7 +5225,7 @@ function canonicalRequest(raw, protocol, model) {
5136
5225
  }
5137
5226
  if (b.thinking !== undefined) {
5138
5227
  const t = record(b.thinking, "thinking");
5139
- fields2(t, ["type", "budget_tokens"], "thinking", "unsupported_reasoning");
5228
+ fields(t, ["type", "budget_tokens"], "thinking", "unsupported_reasoning");
5140
5229
  if (!["enabled", "adaptive", "disabled"].includes(String(t.type)))
5141
5230
  fail("unsupported_reasoning", "Unknown thinking mode", "thinking.type");
5142
5231
  if (t.type === "enabled")
@@ -5147,12 +5236,12 @@ function canonicalRequest(raw, protocol, model) {
5147
5236
  }
5148
5237
  if (b.output_config !== undefined) {
5149
5238
  const c = record(b.output_config, "output_config");
5150
- fields2(c, ["effort", "format"], "output_config");
5239
+ fields(c, ["effort", "format"], "output_config");
5151
5240
  if (c.effort !== undefined)
5152
5241
  out.reasoning = { effort: c.effort };
5153
5242
  if (c.format !== undefined) {
5154
5243
  const f = record(c.format, "format");
5155
- fields2(f, ["type", "schema"], "output_config.format");
5244
+ fields(f, ["type", "schema"], "output_config.format");
5156
5245
  if (f.type !== "json_schema")
5157
5246
  fail("unsupported_request", "Unknown structured output type", "output_config.format.type");
5158
5247
  out.text = { format: { type: "json_schema", name: "response", schema: f.schema } };
@@ -5160,12 +5249,12 @@ function canonicalRequest(raw, protocol, model) {
5160
5249
  }
5161
5250
  return out;
5162
5251
  }
5163
- fields2(b, ["contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "model", "stream"], "");
5252
+ fields(b, ["contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "model", "stream"], "");
5164
5253
  if (b.stream !== undefined)
5165
5254
  out.stream = b.stream;
5166
5255
  if (b.systemInstruction !== undefined) {
5167
5256
  const s = record(b.systemInstruction, "systemInstruction");
5168
- fields2(s, ["role", "parts"], "systemInstruction");
5257
+ fields(s, ["role", "parts"], "systemInstruction");
5169
5258
  if (s.role !== undefined && s.role !== "system")
5170
5259
  fail("unsupported_content", "Invalid system role", "systemInstruction.role");
5171
5260
  message(input, "system", s.parts, "gemini", "systemInstruction");
@@ -5175,12 +5264,12 @@ function canonicalRequest(raw, protocol, model) {
5175
5264
  for (const [index, rawContent] of list(b.contents, "contents").entries()) {
5176
5265
  const original = record(rawContent, "content"), path = `contents[${index}]`;
5177
5266
  const c = { ...original, role: original.role ?? "user" };
5178
- fields2(c, ["role", "parts"], path, "unsupported_content");
5267
+ fields(c, ["role", "parts"], path, "unsupported_content");
5179
5268
  if (c.role !== "user" && c.role !== "model")
5180
5269
  fail("unsupported_content", "Gemini contents require user or model role", `${path}.role`);
5181
5270
  for (const [j, rawPart] of list(c.parts, "parts").entries()) {
5182
5271
  const p = record(rawPart, "part"), at = `${path}.parts[${j}]`;
5183
- fields2(p, ["text", "thought", "functionCall", "functionResponse", "thoughtSignature"], at, "unsupported_content");
5272
+ fields(p, ["text", "thought", "functionCall", "functionResponse", "thoughtSignature"], at, "unsupported_content");
5184
5273
  if (p.thoughtSignature !== undefined)
5185
5274
  fail("unsupported_reasoning", "Provider-bound thought signatures cannot cross protocols", `${at}.thoughtSignature`);
5186
5275
  if ([p.text, p.functionCall, p.functionResponse].filter((v) => v !== undefined).length !== 1)
@@ -5189,7 +5278,7 @@ function canonicalRequest(raw, protocol, model) {
5189
5278
  if (c.role !== "model")
5190
5279
  fail("invalid_tool_history", "Function calls require model role", at);
5191
5280
  const f = record(p.functionCall, at);
5192
- fields2(f, ["name", "args", "id"], `${at}.functionCall`, "unsupported_tool");
5281
+ fields(f, ["name", "args", "id"], `${at}.functionCall`, "unsupported_tool");
5193
5282
  const name = string(f.name, at, true), id = f.id === undefined ? `call_gemini_${serial++}` : string(f.id, at, true);
5194
5283
  if (calls.has(id))
5195
5284
  fail("invalid_tool_history", "Duplicate tool call id", at);
@@ -5199,7 +5288,7 @@ function canonicalRequest(raw, protocol, model) {
5199
5288
  if (c.role !== "user")
5200
5289
  fail("invalid_tool_history", "Function results require user role", at);
5201
5290
  const f = record(p.functionResponse, at);
5202
- fields2(f, ["name", "response", "id"], `${at}.functionResponse`, "unsupported_tool");
5291
+ fields(f, ["name", "response", "id"], `${at}.functionResponse`, "unsupported_tool");
5203
5292
  const matches = [...calls.values()].filter((v) => v.name === f.name);
5204
5293
  const id = f.id === undefined ? matches.length === 1 ? matches[0].id : fail("invalid_tool_history", "Function result requires an unambiguous call id", at) : string(f.id, at, true);
5205
5294
  if (calls.get(id)?.name !== f.name)
@@ -5218,7 +5307,7 @@ function canonicalRequest(raw, protocol, model) {
5218
5307
  const tools = [];
5219
5308
  for (const [i, rawTool] of list(b.tools, "tools").entries()) {
5220
5309
  const t = record(rawTool, "tool");
5221
- fields2(t, ["functionDeclarations"], `tools[${i}]`, "unsupported_tool");
5310
+ fields(t, ["functionDeclarations"], `tools[${i}]`, "unsupported_tool");
5222
5311
  for (const [j, f] of list(t.functionDeclarations, "functionDeclarations").entries())
5223
5312
  tools.push(toolDefinition(f, "gemini", `tools[${i}].functionDeclarations[${j}]`));
5224
5313
  }
@@ -5226,9 +5315,9 @@ function canonicalRequest(raw, protocol, model) {
5226
5315
  }
5227
5316
  if (b.toolConfig !== undefined) {
5228
5317
  const config = record(b.toolConfig, "toolConfig");
5229
- fields2(config, ["functionCallingConfig"], "toolConfig");
5318
+ fields(config, ["functionCallingConfig"], "toolConfig");
5230
5319
  const c = record(config.functionCallingConfig, "functionCallingConfig");
5231
- fields2(c, ["mode", "allowedFunctionNames"], "toolConfig.functionCallingConfig");
5320
+ fields(c, ["mode", "allowedFunctionNames"], "toolConfig.functionCallingConfig");
5232
5321
  if (!["AUTO", "NONE", "ANY"].includes(String(c.mode)))
5233
5322
  fail("unsupported_tool_choice", "Unknown function calling mode", "toolConfig.functionCallingConfig.mode");
5234
5323
  if (c.allowedFunctionNames !== undefined) {
@@ -5241,7 +5330,7 @@ function canonicalRequest(raw, protocol, model) {
5241
5330
  }
5242
5331
  if (b.generationConfig !== undefined) {
5243
5332
  const c = record(b.generationConfig, "generationConfig");
5244
- fields2(c, ["temperature", "topP", "maxOutputTokens", "stopSequences", "candidateCount", "responseMimeType", "responseJsonSchema", "responseSchema", "thinkingConfig"], "generationConfig");
5333
+ fields(c, ["temperature", "topP", "maxOutputTokens", "stopSequences", "candidateCount", "responseMimeType", "responseJsonSchema", "responseSchema", "thinkingConfig"], "generationConfig");
5245
5334
  for (const [from, to] of Object.entries({ temperature: "temperature", topP: "top_p", maxOutputTokens: "max_output_tokens", stopSequences: "stop", candidateCount: "n" }))
5246
5335
  if (c[from] !== undefined)
5247
5336
  out[to] = c[from];
@@ -5259,7 +5348,7 @@ function canonicalRequest(raw, protocol, model) {
5259
5348
  }
5260
5349
  if (c.thinkingConfig !== undefined) {
5261
5350
  const t = record(c.thinkingConfig, "thinkingConfig");
5262
- fields2(t, ["thinkingBudget", "thinkingLevel", "includeThoughts"], "generationConfig.thinkingConfig", "unsupported_reasoning");
5351
+ fields(t, ["thinkingBudget", "thinkingLevel", "includeThoughts"], "generationConfig.thinkingConfig", "unsupported_reasoning");
5263
5352
  if (t.thinkingBudget !== undefined)
5264
5353
  integer(t.thinkingBudget, "generationConfig.thinkingConfig.thinkingBudget", -1);
5265
5354
  if (t.thinkingLevel !== undefined)
@@ -5271,7 +5360,10 @@ function canonicalRequest(raw, protocol, model) {
5271
5360
  }
5272
5361
  return out;
5273
5362
  }
5274
- function validateCanonical(b, context) {
5363
+ function validateCanonical(b, context, chatConfigurationUpdates) {
5364
+ const responsesToGemini = context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content";
5365
+ const allowLossyContinuation = chatConfigurationUpdates !== undefined;
5366
+ let configuration;
5275
5367
  for (const key of ["stream", "parallel_tool_calls", "store", "background"])
5276
5368
  if (b[key] !== undefined)
5277
5369
  bool(b[key], key);
@@ -5279,13 +5371,13 @@ function validateCanonical(b, context) {
5279
5371
  if (b[key] !== undefined && (typeof b[key] !== "number" || !Number.isFinite(b[key])))
5280
5372
  fail("invalid_payload", "Sampling value must be finite", key);
5281
5373
  if (b.tool_choice !== undefined && typeof b.tool_choice !== "string")
5282
- fields2(record(b.tool_choice, "tool_choice"), ["type", "name", "namespace"], "tool_choice", "unsupported_tool_choice");
5374
+ fields(record(b.tool_choice, "tool_choice"), ["type", "name", "namespace"], "tool_choice", "unsupported_tool_choice");
5283
5375
  if (b.text !== undefined) {
5284
5376
  const text = record(b.text, "text");
5285
- fields2(text, ["format", "verbosity"], "text");
5377
+ fields(text, ["format", "verbosity"], "text");
5286
5378
  if (text.format !== undefined) {
5287
5379
  const f = record(text.format, "text.format");
5288
- fields2(f, f.type === "json_schema" ? ["type", "name", "schema", "strict", "description"] : ["type"], "text.format");
5380
+ fields(f, f.type === "json_schema" ? ["type", "name", "schema", "strict", "description"] : ["type"], "text.format");
5289
5381
  if (!["text", "json_object", "json_schema"].includes(String(f.type)))
5290
5382
  fail("unsupported_request", "Unknown structured output format", "text.format.type");
5291
5383
  if (f.type === "json_schema") {
@@ -5301,21 +5393,40 @@ function validateCanonical(b, context) {
5301
5393
  const input = typeof b.input === "string" ? [] : list(b.input, "input");
5302
5394
  for (const [i, raw] of input.entries()) {
5303
5395
  const t = record(raw, "input item"), p = `input[${i}]`;
5396
+ if ((responsesToGemini || allowLossyContinuation) && t.type === "configuration_update") {
5397
+ fields(t, ["type", "reasoning"], p, "unsupported_content");
5398
+ const reasoning = atParam(`${p}.reasoning`, () => record(t.reasoning, "configuration reasoning"));
5399
+ fields(reasoning, ["effort"], `${p}.reasoning`, "unsupported_reasoning");
5400
+ const param = `${p}.reasoning.effort`;
5401
+ const effort = atParam(param, () => string(reasoning.effort, "configuration effort", true));
5402
+ const map = context.reasoningPolicy?.effortMap;
5403
+ const level = map && Object.hasOwn(map, effort) ? map[effort] : undefined;
5404
+ if (typeof level !== "string" || !level || responsesToGemini && !["minimal", "low", "medium", "high"].includes(level))
5405
+ fail("unsupported_reasoning", responsesToGemini ? "Configuration update requires an explicit Gemini level mapping" : "Configuration update requires an explicit Chat effort mapping", param);
5406
+ configuration = { effort, level, param };
5407
+ chatConfigurationUpdates?.add(t);
5408
+ continue;
5409
+ }
5304
5410
  if (t.type === "agent_message") {
5305
5411
  validateAgentMessage(t, p, context.capabilities?.limits);
5306
5412
  continue;
5307
5413
  }
5308
- const allowed = t.type === "function_call" ? ["type", "id", "status", "call_id", "name", "namespace", "arguments", "encrypted_function_args"] : t.type === "custom_tool_call" ? ["type", "id", "status", "call_id", "name", "namespace", "input"] : t.type === "function_call_output" || t.type === "custom_tool_call_output" ? ["type", "id", "call_id", "output", "is_error"] : t.type === "reasoning" ? ["type", "id", "status", "summary", "content", "encrypted_content", "internal_chat_message_metadata_passthrough"] : t.type === "additional_tools" ? ["type", "id", "role", "tools"] : ["type", "id", "status", "role", "content", "internal_chat_message_metadata_passthrough"];
5309
- fields2(t, [...allowed, "internal_chat_message_metadata_passthrough"], p, "unsupported_content");
5414
+ if (allowLossyContinuation && isGeminiSignatureCarrier(t.encrypted_content))
5415
+ fail("unsupported_content", "Gemini signature carriers cannot cross into Chat", `${p}.encrypted_content`);
5416
+ if (allowLossyContinuation && t.type === "compaction")
5417
+ continue;
5418
+ const allowed = t.type === "function_call" ? ["type", "id", "status", "call_id", "name", "namespace", "arguments", "encrypted_function_args", ...allowLossyContinuation && t.encrypted_content != null ? ["encrypted_content"] : []] : t.type === "custom_tool_call" ? ["type", "id", "status", "call_id", "name", "namespace", "input"] : t.type === "function_call_output" || t.type === "custom_tool_call_output" ? ["type", "id", "call_id", "output", "is_error"] : t.type === "reasoning" ? ["type", "id", "status", "summary", "content", "encrypted_content", "internal_chat_message_metadata_passthrough"] : t.type === "additional_tools" ? ["type", "id", "role", "tools"] : ["type", "id", "status", "role", "content", "internal_chat_message_metadata_passthrough"];
5419
+ const assistantPhase = allowLossyContinuation && (t.type === undefined || t.type === "message") && t.role === "assistant";
5420
+ fields(t, [...allowed, "internal_chat_message_metadata_passthrough", ...assistantPhase ? ["phase"] : []], p, "unsupported_content");
5310
5421
  if (t.is_error !== undefined)
5311
5422
  bool(t.is_error, `${p}.is_error`);
5312
- if (t.type === "reasoning")
5313
- for (const [j, part] of list(t.summary, "summary").entries())
5314
- fields2(record(part, "summary"), ["type", "text"], `${p}.summary[${j}]`, "unsupported_reasoning");
5423
+ if (t.type === "reasoning" && !(allowLossyContinuation && t.encrypted_content != null && t.summary === undefined))
5424
+ for (const [j, part] of atParam(`${p}.summary`, () => list(t.summary, "summary")).entries())
5425
+ atParam(`${p}.summary[${j}]`, () => fields(record(part, "summary"), ["type", "text"], `${p}.summary[${j}]`, "unsupported_reasoning"));
5315
5426
  if (Array.isArray(t.content))
5316
5427
  for (const [j, part] of t.content.entries()) {
5317
5428
  const c = record(part, "part");
5318
- fields2(c, c.type === "input_image" ? ["type", "image_url", "detail"] : c.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], `${p}.content[${j}]`, "unsupported_content");
5429
+ fields(c, c.type === "input_image" ? ["type", "image_url", "detail"] : c.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations", ...assistantPhase && c.type === "output_text" ? ["logprobs"] : []], `${p}.content[${j}]`, "unsupported_content");
5319
5430
  if (context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content" && t.role === "user" && c.type === "input_image") {
5320
5431
  atParam(`${p}.content[${j}].image_url`, () => string(c.image_url, "image URL", true));
5321
5432
  if (c.detail !== undefined && (typeof c.detail !== "string" || !["auto", "low", "high"].includes(c.detail)))
@@ -5326,7 +5437,7 @@ function validateCanonical(b, context) {
5326
5437
  for (const [j, part] of t.output.entries())
5327
5438
  atParam(`${p}.output[${j}]`, () => {
5328
5439
  const c = record(part, "tool output part");
5329
- fields2(c, c.type === "input_image" ? ["type", "image_url", "detail"] : ["type", "text", "annotations"], `${p}.output[${j}]`, "unsupported_content");
5440
+ fields(c, c.type === "input_image" ? ["type", "image_url", "detail"] : ["type", "text", "annotations"], `${p}.output[${j}]`, "unsupported_content");
5330
5441
  if (c.type === "input_image") {
5331
5442
  atParam(`${p}.output[${j}].image_url`, () => string(c.image_url, "image URL", true));
5332
5443
  if (c.detail !== undefined && (typeof c.detail !== "string" || !["auto", "low", "high"].includes(c.detail)))
@@ -5352,7 +5463,7 @@ function validateCanonical(b, context) {
5352
5463
  }
5353
5464
  if (t.type === "custom" && t.format !== undefined) {
5354
5465
  const f = record(t.format, "custom format");
5355
- fields2(f, f.type === "grammar" ? ["type", "syntax", "definition"] : ["type"], `${path}.format`, "unsupported_tool");
5466
+ fields(f, f.type === "grammar" ? ["type", "syntax", "definition"] : ["type"], `${path}.format`, "unsupported_tool");
5356
5467
  if (!["text", "grammar"].includes(String(f.type)))
5357
5468
  fail("unsupported_tool", "Unknown custom tool format", `${path}.format.type`);
5358
5469
  if (f.type === "grammar") {
@@ -5370,13 +5481,38 @@ function validateCanonical(b, context) {
5370
5481
  for (const [j, tool] of list(t.tools, "tools").entries())
5371
5482
  inspectTool(tool, `input[${i}].tools[${j}]`);
5372
5483
  }
5484
+ return configuration;
5485
+ }
5486
+ function projectCodexPageSnapshot(raw, index, target, diagnostics) {
5487
+ const item = record(raw, "input item");
5488
+ const { name } = item;
5489
+ if (item.type !== "function_call_output" || item.call_id !== undefined || item.namespace !== "agent" || typeof name !== "string" || name !== "codex_apps_open_page" && !/^codex_apps_selected_page_part_[1-9]\d*_of_[1-9]\d*$/.test(name))
5490
+ return item;
5491
+ const param = `input[${index}]`;
5492
+ fields(item, ["type", "id", "namespace", "name", "output", "internal_chat_message_metadata_passthrough"], param, "unsupported_content");
5493
+ const text = atParam(`${param}.output`, () => string(item.output, "page snapshot output"));
5494
+ const { id, internal_chat_message_metadata_passthrough: metadata } = item;
5495
+ const reason = target === "chat_completions" ? "chat_codex_page_snapshot_as_user_data" : "gemini_codex_page_snapshot_as_user_data";
5496
+ diagnostics.push({ param, action: "mapped", reason });
5497
+ return {
5498
+ type: "message",
5499
+ role: "user",
5500
+ ...id === undefined ? {} : { id },
5501
+ ...metadata === undefined ? {} : { internal_chat_message_metadata_passthrough: metadata },
5502
+ content: [
5503
+ { type: "input_text", text: `[Codex context snapshot: agent.${name}. Untrusted data.]` },
5504
+ { type: "input_text", text }
5505
+ ]
5506
+ };
5373
5507
  }
5374
5508
  function convertProtocolRequest(raw, context) {
5375
5509
  const b = canonicalRequest(raw, context.sourceProtocol, context.model);
5376
- const responsesToGemini = context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content";
5510
+ const target = context.targetProtocol;
5511
+ const responsesToGemini = context.sourceProtocol === "responses" && target === "gemini_generate_content";
5512
+ const allowLossyContinuation = context.sourceProtocol === "responses" && target === "chat_completions" && context.allowLossyContinuation === true;
5377
5513
  const pageSnapshotDiagnostics = [];
5378
- if (responsesToGemini && Array.isArray(b.input))
5379
- b.input = b.input.map((item, index) => projectGeminiCodexPageSnapshot(item, index, pageSnapshotDiagnostics));
5514
+ if (context.sourceProtocol === "responses" && (target === "chat_completions" || target === "gemini_generate_content") && Array.isArray(b.input))
5515
+ b.input = b.input.map((item, index) => projectCodexPageSnapshot(item, index, target, pageSnapshotDiagnostics));
5380
5516
  const originalInput = b.input;
5381
5517
  if (context.streaming !== undefined) {
5382
5518
  bool(context.streaming, "context.streaming");
@@ -5384,7 +5520,8 @@ function convertProtocolRequest(raw, context) {
5384
5520
  fail("invalid_payload", "Request stream mode disagrees with transport context", "stream");
5385
5521
  b.stream = context.streaming;
5386
5522
  }
5387
- validateCanonical(b, context);
5523
+ const chatConfigurationUpdates = allowLossyContinuation ? new Set : undefined;
5524
+ const configuration = validateCanonical(b, context, chatConfigurationUpdates);
5388
5525
  const geminiHistory = responsesToGemini ? restoreGeminiHistory(b.input, limits(context.capabilities?.limits)) : undefined;
5389
5526
  if (geminiHistory)
5390
5527
  b.input = geminiHistory.input;
@@ -5403,16 +5540,19 @@ function convertProtocolRequest(raw, context) {
5403
5540
  fail("unsupported_reasoning", "Thinking mode requires an explicit target wire policy", "thinking");
5404
5541
  let mappedEffort;
5405
5542
  if (reasoning?.effort !== undefined) {
5406
- const effort = string(reasoning.effort, "reasoning.effort", true);
5407
- mappedEffort = policy?.effortMap?.[effort];
5408
- if (mappedEffort === undefined && policy?.anthropicThinkingBudget === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
5409
- fail("unsupported_reasoning", "Reasoning effort requires an explicit verified wire mapping", "reasoning.effort");
5410
- if (mappedEffort !== undefined)
5411
- string(mappedEffort, "reasoningPolicy.effortMap", true);
5543
+ const effort = atParam("reasoning.effort", () => string(reasoning.effort, "reasoning.effort", true));
5544
+ if (!allowLossyContinuation || !configuration) {
5545
+ mappedEffort = policy?.effortMap?.[effort];
5546
+ if (mappedEffort === undefined && policy?.anthropicThinkingBudget === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
5547
+ fail("unsupported_reasoning", "Reasoning effort requires an explicit verified wire mapping", "reasoning.effort");
5548
+ if (mappedEffort !== undefined)
5549
+ string(mappedEffort, "reasoningPolicy.effortMap", true);
5550
+ }
5412
5551
  }
5552
+ if (configuration)
5553
+ mappedEffort = configuration.level;
5413
5554
  if (sourceThinking !== undefined && reasoning?.effort === undefined && policy?.targetEffort !== undefined)
5414
5555
  mappedEffort = string(policy.targetEffort, "reasoningPolicy.targetEffort", true);
5415
- const target = context.targetProtocol;
5416
5556
  if (target === "gemini_generate_content" && reasoning?.effort !== undefined && mappedEffort === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
5417
5557
  fail("unsupported_reasoning", "Gemini requires an explicit thinking budget or level", "reasoning.effort");
5418
5558
  if (sourceThinking !== undefined) {
@@ -5451,7 +5591,7 @@ function convertProtocolRequest(raw, context) {
5451
5591
  }
5452
5592
  if (b.metadata !== undefined) {
5453
5593
  const metadata = record(b.metadata, "metadata");
5454
- fields2(metadata, ["user_id"], "metadata");
5594
+ fields(metadata, ["user_id"], "metadata");
5455
5595
  if (metadata.user_id !== undefined)
5456
5596
  string(metadata.user_id, "metadata.user_id");
5457
5597
  }
@@ -5463,7 +5603,7 @@ function convertProtocolRequest(raw, context) {
5463
5603
  } else if (target === "chat_completions") {
5464
5604
  if (reasoning?.effort !== undefined || mappedEffort !== undefined) {
5465
5605
  if (!cap.reasoningEffort)
5466
- fail("unsupported_reasoning", "Target effort capability is required", "reasoning.effort");
5606
+ fail("unsupported_reasoning", "Target effort capability is required", configuration?.param ?? "reasoning.effort");
5467
5607
  b.reasoning = { ...reasoning, effort: mappedEffort };
5468
5608
  if (mappedEffort === undefined)
5469
5609
  fail("unsupported_reasoning", "Chat requires a target effort mapping", "reasoning.effort");
@@ -5475,9 +5615,21 @@ function convertProtocolRequest(raw, context) {
5475
5615
  const decodingTarget = target === "gemini_generate_content" ? "chat_completions" : target;
5476
5616
  if (target === "gemini_generate_content" && reasoning)
5477
5617
  b.reasoning = { ...reasoning, effort: undefined };
5478
- 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", toolOutputImages: responsesToGemini });
5618
+ let decoded;
5619
+ try {
5620
+ 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", toolOutputImages: responsesToGemini, allowLossyContinuation, chatConfigurationUpdates });
5621
+ } catch (error) {
5622
+ if (geminiHistory && error instanceof ResponsesCodecError && error.param !== undefined)
5623
+ throw new ResponsesCodecError(error.code, error.message, geminiHistory.sourceParam(error.param));
5624
+ throw error;
5625
+ }
5479
5626
  const diagnostics = decoded.diagnostics;
5627
+ if (geminiHistory)
5628
+ for (const diagnostic of diagnostics)
5629
+ diagnostic.param = geminiHistory.sourceParam(diagnostic.param);
5480
5630
  diagnostics.push(...pageSnapshotDiagnostics);
5631
+ if (configuration)
5632
+ diagnostics.push({ param: configuration.param, action: "mapped", reason: responsesToGemini ? "gemini_configuration_effort_update" : "chat_configuration_effort_update" });
5481
5633
  if (target === "gemini_generate_content" && decoded.body.parallel_tool_calls === true) {
5482
5634
  delete decoded.body.parallel_tool_calls;
5483
5635
  diagnostics.push({ param: "parallel_tool_calls", action: "omitted", reason: "gemini_parallel_tool_calls_allowed" });
@@ -5507,17 +5659,24 @@ function convertProtocolRequest(raw, context) {
5507
5659
  if (target === "gemini_generate_content" && (mappedEffort !== undefined || policy?.geminiThinkingBudget !== undefined || policy?.geminiThinkingLevel !== undefined)) {
5508
5660
  const level = policy?.geminiThinkingLevel ?? mappedEffort;
5509
5661
  if (policy?.geminiThinkingBudget !== undefined && level !== undefined)
5510
- fail("unsupported_reasoning", "Choose one Gemini thinking policy", "reasoningPolicy");
5662
+ fail("unsupported_reasoning", "Choose one Gemini thinking policy", configuration?.param ?? "reasoningPolicy");
5511
5663
  if (level !== undefined && !["minimal", "low", "medium", "high"].includes(level))
5512
5664
  fail("unsupported_reasoning", "Unknown Gemini thinking level", "reasoning.effort");
5513
5665
  if (mappedEffort !== undefined && policy?.geminiThinkingLevel !== undefined && mappedEffort !== policy.geminiThinkingLevel)
5514
- fail("unsupported_reasoning", "Conflicting Gemini thinking levels", "reasoning.effort");
5666
+ fail("unsupported_reasoning", "Conflicting Gemini thinking levels", configuration?.param ?? "reasoning.effort");
5515
5667
  const thinkingConfig = policy?.geminiThinkingBudget !== undefined ? { thinkingBudget: integer(policy.geminiThinkingBudget, "reasoningPolicy.geminiThinkingBudget", -1) } : { thinkingLevel: string(level, "reasoningPolicy.geminiThinkingLevel", true) };
5516
5668
  body.generationConfig = { ...record(body.generationConfig ?? {}, "generationConfig"), thinkingConfig };
5517
5669
  }
5518
5670
  if (mappedEffort !== undefined || sourceThinking !== undefined || policy?.anthropicThinkingBudget !== undefined)
5519
5671
  diagnostics.push({ param: "reasoning", action: "mapped", reason: "explicit_verified_wire_policy" });
5520
- return { body, canonicalHistory: geminiHistory?.canonicalHistory(decoded.canonicalInput) ?? decoded.canonicalInput, diagnostics, toolNames: decoded.toolNames, streaming: b.stream === true };
5672
+ return {
5673
+ body,
5674
+ canonicalHistory: geminiHistory?.canonicalHistory(decoded.canonicalInput) ?? decoded.canonicalInput,
5675
+ diagnostics,
5676
+ toolNames: decoded.toolNames,
5677
+ streaming: b.stream === true,
5678
+ ...configuration ? { effectiveReasoningEffort: configuration.effort } : {}
5679
+ };
5521
5680
  }
5522
5681
  function renderGemini(chat, context, input, signedParts, diagnostics) {
5523
5682
  const result = { contents: [] }, contents = result.contents, system = [], calls = new Map;
@@ -5665,11 +5824,11 @@ function validateUsage(raw, protocol) {
5665
5824
  return;
5666
5825
  }
5667
5826
  const keys = protocol === "anthropic_messages" ? ["input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"] : ["input_tokens", "output_tokens", "total_tokens", "input_tokens_details", "output_tokens_details"];
5668
- fields2(u, keys, "usage", "unsupported_response");
5827
+ fields(u, keys, "usage", "unsupported_response");
5669
5828
  for (const [key, value] of Object.entries(u)) {
5670
5829
  if (key.endsWith("_details")) {
5671
5830
  const d = record(value, "usage details");
5672
- fields2(d, key.includes("output") || key.includes("completion") ? ["reasoning_tokens"] : ["cached_tokens", "cache_creation_tokens"], `usage.${key}`, "unsupported_response");
5831
+ fields(d, key.includes("output") || key.includes("completion") ? ["reasoning_tokens"] : ["cached_tokens", "cache_creation_tokens"], `usage.${key}`, "unsupported_response");
5673
5832
  for (const [k, v] of Object.entries(d))
5674
5833
  integer(v, `usage.${key}.${k}`);
5675
5834
  } else
@@ -5690,10 +5849,10 @@ function validateProviderResponse(raw, protocol) {
5690
5849
  const m = record(c.message, "message");
5691
5850
  for (const [callIndex, rawCall] of (m.tool_calls == null ? [] : list(m.tool_calls, "tool_calls")).entries()) {
5692
5851
  const call = record(rawCall, "call");
5693
- fields2(call, ["id", "type", "function", "index"], "tool_calls", "unsupported_tool");
5852
+ fields(call, ["id", "type", "function", "index"], "tool_calls", "unsupported_tool");
5694
5853
  if (call.index !== undefined && integer(call.index, `tool_calls[${callIndex}].index`) !== callIndex)
5695
5854
  fail("invalid_payload", "Tool call index must match its array position", `tool_calls[${callIndex}].index`);
5696
- fields2(record(call.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
5855
+ fields(record(call.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
5697
5856
  }
5698
5857
  }
5699
5858
  validateUsage(b.usage, protocol);
@@ -5707,14 +5866,14 @@ function validateProviderResponse(raw, protocol) {
5707
5866
  return b;
5708
5867
  }
5709
5868
  function validateAnthropicBlock(b, path) {
5710
- fields2(b, b.type === "text" ? ["type", "text"] : b.type === "thinking" ? ["type", "thinking", "signature"] : ["type", "id", "name", "input"], path, "unsupported_content");
5869
+ fields(b, b.type === "text" ? ["type", "text"] : b.type === "thinking" ? ["type", "thinking", "signature"] : ["type", "id", "name", "input"], path, "unsupported_content");
5711
5870
  if (b.signature !== undefined)
5712
5871
  fail("unsupported_reasoning", "Signed provider reasoning cannot cross protocols", `${path}.signature`);
5713
5872
  }
5714
5873
  function validateCanonicalResponse(raw, context, itemOnly = false) {
5715
5874
  const b = record(raw, "response");
5716
5875
  serialized(b, limits(context.capabilities?.limits).maxOutputBytes, "response");
5717
- fields2(b, ["id", "object", "created_at", "model", "status", "output", "usage", "error", "incomplete_details", "metadata", "parallel_tool_calls", "tools", "tool_choice", "temperature", "top_p", "max_output_tokens", "reasoning", "text", "store", "background", "truncation", "previous_response_id", "instructions", "service_tier"], "", "unsupported_response");
5876
+ fields(b, ["id", "object", "created_at", "model", "status", "output", "usage", "error", "incomplete_details", "metadata", "parallel_tool_calls", "tools", "tool_choice", "temperature", "top_p", "max_output_tokens", "reasoning", "text", "store", "background", "truncation", "previous_response_id", "instructions", "service_tier"], "", "unsupported_response");
5718
5877
  if (!itemOnly) {
5719
5878
  string(b.id, "response.id", true);
5720
5879
  integer(b.created_at, "response.created_at");
@@ -5725,7 +5884,7 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
5725
5884
  fail("missing_terminal", "Response has no explicit supported terminal", "status");
5726
5885
  if (b.status === "incomplete") {
5727
5886
  const d = record(b.incomplete_details, "incomplete_details");
5728
- fields2(d, ["reason"], "incomplete_details", "unsupported_response");
5887
+ fields(d, ["reason"], "incomplete_details", "unsupported_response");
5729
5888
  if (!["max_output_tokens", "content_filter"].includes(String(d.reason)))
5730
5889
  fail("unknown_terminal", "Unknown incomplete reason", "incomplete_details.reason");
5731
5890
  }
@@ -5740,13 +5899,13 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
5740
5899
  fail("unsupported_response", "Unknown item status", `${path}.status`);
5741
5900
  if (b.status === "completed" && t.status !== undefined && t.status !== "completed")
5742
5901
  fail("invalid_stream", "Completed response contains an unfinished item", `${path}.status`);
5743
- fields2(t, t.type === "message" ? ["type", "id", "role", "status", "content"] : t.type === "reasoning" ? ["type", "id", "summary", "status", "encrypted_content", "content"] : t.type === "function_call" ? ["type", "id", "status", "name", "namespace", "call_id", "arguments", "encrypted_function_args"] : ["type", "id", "status", "name", "namespace", "call_id", "input"], path, "unsupported_content");
5902
+ fields(t, t.type === "message" ? ["type", "id", "role", "status", "content"] : t.type === "reasoning" ? ["type", "id", "summary", "status", "encrypted_content", "content"] : t.type === "function_call" ? ["type", "id", "status", "name", "namespace", "call_id", "arguments", "encrypted_function_args"] : ["type", "id", "status", "name", "namespace", "call_id", "input"], path, "unsupported_content");
5744
5903
  if (t.type === "message") {
5745
5904
  if (t.role !== "assistant")
5746
5905
  fail("unsupported_content", "Output message must be assistant", `${path}.role`);
5747
5906
  for (const [j, rawPart] of list(t.content, "content").entries()) {
5748
5907
  const p = record(rawPart, "part");
5749
- fields2(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], `${path}.content[${j}]`, "unsupported_content");
5908
+ fields(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], `${path}.content[${j}]`, "unsupported_content");
5750
5909
  if (p.type === "output_text")
5751
5910
  string(p.text, "text");
5752
5911
  else if (p.type === "refusal")
@@ -5765,7 +5924,7 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
5765
5924
  fail("unsupported_reasoning", "Opaque or raw reasoning output cannot cross protocols", path);
5766
5925
  for (const rawPart of list(t.summary, "summary")) {
5767
5926
  const p = record(rawPart, "summary");
5768
- fields2(p, ["type", "text"], path, "unsupported_reasoning");
5927
+ fields(p, ["type", "text"], path, "unsupported_reasoning");
5769
5928
  if (p.type !== "summary_text")
5770
5929
  fail("unsupported_reasoning", "Unknown reasoning summary type", path);
5771
5930
  string(p.text, "summary");
@@ -5908,7 +6067,7 @@ class GeminiCanonicalDecoder {
5908
6067
  const events = [];
5909
6068
  if (b.promptFeedback !== undefined) {
5910
6069
  const p = record(b.promptFeedback, "promptFeedback");
5911
- fields2(p, ["blockReason", "blockReasonMessage", "safetyRatings"], "promptFeedback", "unsupported_response");
6070
+ fields(p, ["blockReason", "blockReasonMessage", "safetyRatings"], "promptFeedback", "unsupported_response");
5912
6071
  if (p.blockReason !== undefined && p.blockReason !== "BLOCK_REASON_UNSPECIFIED") {
5913
6072
  this.ended = true;
5914
6073
  events.push(...this.encoder.push({ choices: [{ delta: {}, finish_reason: "content_filter" }] }));
@@ -5923,7 +6082,7 @@ class GeminiCanonicalDecoder {
5923
6082
  fail("unsupported_response", "Only candidate index zero is supported", "candidates.index");
5924
6083
  if (c.content !== undefined && c.content !== null) {
5925
6084
  const content = record(c.content, "content");
5926
- fields2(content, ["role", "parts"], "candidates.content", "unsupported_content");
6085
+ fields(content, ["role", "parts"], "candidates.content", "unsupported_content");
5927
6086
  if (content.role !== undefined && content.role !== "model")
5928
6087
  fail("unsupported_response", "Response role must be model", "candidates.content.role");
5929
6088
  const parts = list(content.parts ?? [], "parts");
@@ -5931,14 +6090,14 @@ class GeminiCanonicalDecoder {
5931
6090
  fail("invalid_stream", "Content arrived after Gemini terminal");
5932
6091
  for (const [i, rawPart] of parts.entries()) {
5933
6092
  const p = record(rawPart, "part");
5934
- fields2(p, ["text", "thought", "functionCall", "thoughtSignature"], "candidates.content.parts", "unsupported_content");
6093
+ fields(p, ["text", "thought", "functionCall", "thoughtSignature"], "candidates.content.parts", "unsupported_content");
5935
6094
  if (p.thoughtSignature !== undefined && this.context.sourceProtocol !== "responses")
5936
6095
  fail("unsupported_reasoning", "Thought signatures cannot cross protocols", "candidates.content.parts.thoughtSignature");
5937
6096
  if (p.functionCall !== undefined) {
5938
6097
  if (p.text !== undefined || p.thought !== undefined)
5939
6098
  fail("unsupported_content", "Mixed Gemini part kinds", "candidates.content.parts");
5940
6099
  const f = record(p.functionCall, "functionCall");
5941
- fields2(f, ["id", "name", "args"], "functionCall", "unsupported_tool");
6100
+ fields(f, ["id", "name", "args"], "functionCall", "unsupported_tool");
5942
6101
  const index = this.serial++, originalId = f.id === undefined ? `call_gemini_${crypto.randomUUID().replaceAll("-", "")}` : string(f.id, "functionCall.id", true);
5943
6102
  if (this.ids.has(originalId))
5944
6103
  fail("invalid_tool_arguments", "Duplicate Gemini call id", "functionCall.id");
@@ -6092,7 +6251,7 @@ class CanonicalStreamValidator {
6092
6251
  this.sequence = n;
6093
6252
  }
6094
6253
  if (["response.created", "response.in_progress", "response.completed", "response.incomplete", "response.failed"].includes(type)) {
6095
- fields2(e, [...common, "response"], "", "unsupported_response");
6254
+ fields(e, [...common, "response"], "", "unsupported_response");
6096
6255
  const r = record(e.response, "response");
6097
6256
  const id = string(r.id, "response.id", true);
6098
6257
  if (this.responseId !== undefined && this.responseId !== id)
@@ -6149,7 +6308,7 @@ class CanonicalStreamValidator {
6149
6308
  ];
6150
6309
  if (!known.includes(type))
6151
6310
  fail("unsupported_response", "Unknown Responses stream event", "type");
6152
- fields2(e, [...common, "response_id", "output_index", ...itemEvent ? ["item"] : ["item_id", ...type.includes("reasoning_summary") ? ["summary_index"] : type.includes("function_call") || type.includes("custom_tool") ? [] : ["content_index"], part ? "part" : delta ? "delta" : type.includes("function_call") ? "arguments" : type.includes("custom_tool") ? "input" : type.includes("refusal") ? "refusal" : "text"]], "", "unsupported_response");
6311
+ fields(e, [...common, "response_id", "output_index", ...itemEvent ? ["item"] : ["item_id", ...type.includes("reasoning_summary") ? ["summary_index"] : type.includes("function_call") || type.includes("custom_tool") ? [] : ["content_index"], part ? "part" : delta ? "delta" : type.includes("function_call") ? "arguments" : type.includes("custom_tool") ? "input" : type.includes("refusal") ? "refusal" : "text"]], "", "unsupported_response");
6153
6312
  if (e.response_id !== undefined && e.response_id !== this.responseId)
6154
6313
  fail("invalid_stream", "Event response id changed", "response_id");
6155
6314
  const index = integer(e.output_index, "output_index");
@@ -6243,7 +6402,7 @@ class CanonicalStreamValidator {
6243
6402
  fail("unsupported_content", "Unknown content part type", "part.type");
6244
6403
  if (summary ? p.type !== "summary_text" : p.type === "summary_text")
6245
6404
  fail("invalid_stream", "Part kind differs from its output item", "part.type");
6246
- fields2(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
6405
+ fields(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
6247
6406
  if (p.annotations !== undefined && Array.isArray(p.annotations) && p.annotations.length)
6248
6407
  fail("unsupported_content", "Annotations cannot cross protocols", "part.annotations");
6249
6408
  const initial = string(p[p.type === "refusal" ? "refusal" : "text"], "part text");
@@ -6268,7 +6427,7 @@ class CanonicalStreamValidator {
6268
6427
  if (!p.textDone)
6269
6428
  fail("invalid_stream", "Part done before text done");
6270
6429
  const v = record(e.part, "part");
6271
- fields2(v, p.kind === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
6430
+ fields(v, p.kind === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
6272
6431
  if (v.annotations !== undefined && (!Array.isArray(v.annotations) || v.annotations.length))
6273
6432
  fail("unsupported_content", "Annotations cannot cross protocols", "part.annotations");
6274
6433
  if (v.type !== p.kind || v[p.kind === "refusal" ? "refusal" : "text"] !== p.text)
@@ -6422,7 +6581,7 @@ class CanonicalStreamRenderer {
6422
6581
  var LLM_PROTOCOLS = ["responses", "chat_completions", "anthropic_messages", "gemini_generate_content"];
6423
6582
 
6424
6583
  // src/protocol-session/index.ts
6425
- var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.4";
6584
+ var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.6";
6426
6585
  function describeProtocolConversion() {
6427
6586
  return {
6428
6587
  rulesVersion: PROTOCOL_CONVERSION_RULES_VERSION,
@@ -6631,9 +6790,9 @@ function validateStreamEnvelope(raw, protocol) {
6631
6790
  if (Array.isArray(d.tool_calls))
6632
6791
  for (const rawCall of d.tool_calls) {
6633
6792
  const t = record(rawCall, "tool call");
6634
- fields2(t, ["index", "id", "type", "function"], "tool_calls", "unsupported_tool");
6793
+ fields(t, ["index", "id", "type", "function"], "tool_calls", "unsupported_tool");
6635
6794
  if (t.function !== undefined)
6636
- fields2(record(t.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
6795
+ fields(record(t.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
6637
6796
  }
6638
6797
  }
6639
6798
  validateUsage(e.usage, protocol);
@@ -6642,12 +6801,12 @@ function validateStreamEnvelope(raw, protocol) {
6642
6801
  validateAnthropicBlock(record(e.content_block, "block"), "content_block");
6643
6802
  if (e.type === "content_block_delta") {
6644
6803
  const d = record(e.delta, "delta");
6645
- fields2(d, d.type === "text_delta" ? ["type", "text"] : d.type === "thinking_delta" ? ["type", "thinking"] : d.type === "signature_delta" ? ["type", "signature"] : ["type", "partial_json"], "delta", "unsupported_content");
6804
+ fields(d, d.type === "text_delta" ? ["type", "text"] : d.type === "thinking_delta" ? ["type", "thinking"] : d.type === "signature_delta" ? ["type", "signature"] : ["type", "partial_json"], "delta", "unsupported_content");
6646
6805
  if (d.type === "signature_delta" || d.signature !== undefined)
6647
6806
  fail("unsupported_reasoning", "Signed provider reasoning cannot cross protocols", "delta.signature");
6648
6807
  }
6649
6808
  if (e.type === "message_delta")
6650
- fields2(record(e.delta, "delta"), ["stop_reason", "stop_sequence"], "delta", "unsupported_response");
6809
+ fields(record(e.delta, "delta"), ["stop_reason", "stop_sequence"], "delta", "unsupported_response");
6651
6810
  if (e.type === "message_start") {
6652
6811
  const m = record(e.message, "message");
6653
6812
  validateUsage(m.usage, protocol);