@jeffusion/bungee-llms 6.15.1 → 6.16.1

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,245 +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 geminiInlineImage(image, path, budget) {
4737
- const param = `${path}.image_url`;
4738
- const url = bounded(string(image.url, "image URL", true), budget.maxRequestBytes, param);
4739
- const match = /^data:([^;,]+);base64,([\s\S]*)$/.exec(url);
4740
- if (!match || !["image/png", "image/jpeg", "image/webp"].includes(match[1]))
4741
- fail("unsupported_content", "Gemini images require inline PNG, JPEG or WebP data", param);
4742
- const data = match[2];
4743
- 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(/=+$/, ""))
4744
- fail("invalid_payload", "Invalid image Base64 encoding", param);
4745
- return { mimeType: match[1], data };
4746
- }
4747
- function geminiToolResponse(content, path, budget, diagnostics) {
4748
- if (!Array.isArray(content) || !content.some((part) => part.type === "image_url"))
4749
- return { response: { output: content } };
4750
- if (content.length > budget.maxItems)
4751
- fail("resource_limit", "Too many tool output parts", path);
4752
- const parts = [];
4753
- const output = content.map((part, index) => atParam(`${path}[${index}]`, () => {
4754
- if (part.type === "text")
4755
- return part;
4756
- if (part.type !== "image_url")
4757
- fail("unsupported_content", "Unsupported Gemini tool result content");
4758
- const image = record(part.image_url, "tool image");
4759
- const inlineData = geminiInlineImage(image, `${path}[${index}]`, budget);
4760
- const displayName = `tool-image-${index}.${inlineData.mimeType.slice("image/".length)}`;
4761
- parts.push({ inlineData: { ...inlineData, displayName } });
4762
- if (image.detail !== undefined)
4763
- diagnostics.push({ param: `${path}[${index}].detail`, action: "omitted", reason: "gemini_tool_image_detail_unavailable" });
4764
- return { $ref: displayName };
4765
- }));
4766
- return { response: { output }, parts };
4767
- }
4768
- function checkedSignature(value, maxBytes) {
4769
- const signature = bounded(string(value, "thoughtSignature", true), maxBytes, "thoughtSignature");
4770
- 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(/=+$/, ""))
4771
- fail("invalid_tool_arguments", "Invalid Gemini thought signature encoding", "thoughtSignature");
4772
- return signature;
4773
- }
4774
- var envelopePrefix = "bungee_gemini:";
4775
- var geminiEnvelopeBytes = (payloadBytes) => envelopePrefix.length + Math.ceil(payloadBytes * 4 / 3);
4776
- var geminiTextHash = (text) => createHash("sha256").update(text).digest("base64url");
4777
- function geminiSignatureItem(items, budget) {
4778
- const payload = serialized({ version: 1, items }, budget.maxArgumentBytes, "Gemini signatures");
4779
- return {
4780
- type: "reasoning",
4781
- id: `rs_gemini_${crypto.randomUUID().replaceAll("-", "")}`,
4782
- summary: [],
4783
- encrypted_content: bounded(envelopePrefix + Buffer.from(payload).toString("base64url"), budget.maxArgumentBytes, "Gemini signatures")
4784
- };
4785
- }
4786
- function readGeminiSignatures(item, budget) {
4787
- fields2(item, ["type", "id", "summary", "encrypted_content", "status"], "Gemini signatures", "unsupported_reasoning");
4788
- if (item.type !== "reasoning" || list(item.summary, "summary").length)
4789
- fail("unsupported_reasoning", "Invalid Gemini signature carrier");
4790
- string(item.id, "signature item id", true);
4791
- const opaque = bounded(string(item.encrypted_content, "encrypted_content", true), budget.maxArgumentBytes, "Gemini signatures");
4792
- if (!opaque.startsWith(envelopePrefix))
4793
- fail("unsupported_reasoning", "Native encrypted reasoning cannot be restored to Gemini");
4794
- const encoded = opaque.slice(envelopePrefix.length), bytes = Buffer.from(encoded, "base64url");
4795
- if (!encoded || bytes.toString("base64url") !== encoded)
4796
- fail("unsupported_reasoning", "Invalid Gemini signature carrier encoding");
4797
- let raw;
4798
- try {
4799
- raw = JSON.parse(bytes.toString("utf8"));
4800
- } catch {
4801
- fail("unsupported_reasoning", "Invalid Gemini signature carrier JSON");
4802
- }
4803
- const body = record(raw, "Gemini signatures");
4804
- fields2(body, ["version", "items"], "Gemini signatures", "unsupported_reasoning");
4805
- if (body.version !== 1)
4806
- fail("unsupported_reasoning", "Unknown Gemini signature format");
4807
- const ids = new Set;
4808
- let partCount = 0;
4809
- const result = list(body.items, "signature items").map((raw) => {
4810
- const item = record(raw, "signature item");
4811
- fields2(item, ["id", "thought", "parts"], "signature item", "unsupported_reasoning");
4812
- const id = string(item.id, "signed item id", true);
4813
- if (ids.has(id) || typeof item.thought !== "boolean")
4814
- fail("unsupported_reasoning", "Invalid signed item identity");
4815
- ids.add(id);
4816
- const parts = list(item.parts, "signed parts").map((raw) => {
4817
- if (++partCount > budget.maxItems)
4818
- fail("resource_limit", "Too many signed Gemini parts");
4819
- const part = record(raw, "signed part");
4820
- fields2(part, ["length", "hash", "signature", "textAbsent"], "signed part", "unsupported_reasoning");
4821
- const length = integer(part.length, "signed part length"), hash = string(part.hash, "signed part hash", true);
4822
- if (!/^[A-Za-z0-9_-]{43}$/.test(hash))
4823
- fail("unsupported_reasoning", "Invalid signed part hash");
4824
- const signature = part.signature === undefined ? undefined : checkedSignature(part.signature, budget.maxArgumentBytes);
4825
- if (part.textAbsent !== undefined && (part.textAbsent !== true || length !== 0 || signature === undefined))
4826
- fail("unsupported_reasoning", "Invalid empty signed part");
4827
- return { length, hash, ...signature === undefined ? {} : { signature }, ...part.textAbsent ? { textAbsent: true } : {} };
4828
- });
4829
- if (!parts.some((p) => p.signature !== undefined))
4830
- fail("unsupported_reasoning", "Signature carrier has no signature");
4831
- return { id, thought: item.thought, parts };
4832
- });
4833
- if (!result.length || result.length > budget.maxItems)
4834
- fail("unsupported_reasoning", "Invalid signature item count");
4835
- return result;
4836
- }
4837
- function restoreGeminiHistory(input, budget) {
4838
- const original = typeof input === "string" ? [] : list(input, "input").map((raw) => record(raw, "input item"));
4839
- if (original.length > budget.maxItems)
4840
- fail("resource_limit", "Too many input items", "input");
4841
- const retained = new Map, parts = new Map, ids = new Map;
4842
- original.forEach((item, i) => {
4843
- if (typeof item.id === "string") {
4844
- if (ids.has(item.id))
4845
- fail("invalid_tool_history", "Duplicate history item id", "input.id");
4846
- ids.set(item.id, i);
4847
- }
4848
- });
4849
- original.forEach((carrier, index) => {
4850
- if (carrier.type === "configuration_update") {
4851
- retained.set(carrier, carrier);
4852
- return;
4853
- }
4854
- if (carrier.encrypted_content == null)
4855
- return;
4856
- const { content, internal_chat_message_metadata_passthrough: metadata, ...normalized } = carrier;
4857
- if (content !== undefined && content !== null)
4858
- fail("unsupported_reasoning", "Gemini signature carriers cannot contain reasoning content", `input[${index}].content`);
4859
- if (metadata !== undefined)
4860
- atParam(`input[${index}].internal_chat_message_metadata_passthrough`, () => record(metadata, "message metadata"));
4861
- const signed = readGeminiSignatures(normalized, budget);
4862
- retained.set(carrier, normalized);
4863
- let previous = -1;
4864
- for (const item of signed) {
4865
- const at = ids.get(item.id);
4866
- if (at === undefined || at >= index || at <= previous || parts.has(item.id))
4867
- fail("unsupported_reasoning", "Signed history reference is missing or ambiguous");
4868
- previous = at;
4869
- const source = original[at];
4870
- if (item.thought ? source.type !== "reasoning" || source.encrypted_content != null : source.role !== "assistant" || source.type !== undefined && source.type !== "message")
4871
- fail("unsupported_reasoning", "Signed history item kind changed");
4872
- const content = item.thought ? list(source.summary, "summary") : typeof source.content === "string" ? [{ type: "output_text", text: source.content }] : list(source.content, "content");
4873
- const text = content.map((raw) => {
4874
- const p = record(raw, "signed text");
4875
- if (p.type !== (item.thought ? "summary_text" : "output_text") && !(p.type === "input_text" && !item.thought))
4876
- fail("unsupported_reasoning", "Signed history content kind changed");
4877
- return string(p.text, "signed text");
4878
- }).join("");
4879
- let offset = 0;
4880
- const restored = item.parts.map((part) => {
4881
- const value = text.slice(offset, offset + part.length);
4882
- offset += part.length;
4883
- if (value.length !== part.length || geminiTextHash(value) !== part.hash)
4884
- fail("unsupported_reasoning", "Signed history text changed");
4885
- return { ...part.textAbsent ? {} : { text: value }, ...item.thought ? { thought: true } : {}, ...part.signature === undefined ? {} : { thoughtSignature: part.signature } };
4886
- });
4887
- if (offset !== text.length)
4888
- fail("unsupported_reasoning", "Signed history text was not fully consumed");
4889
- parts.set(item.id, restored);
4890
- }
4891
- });
4892
- const positions = original.flatMap((item, index) => retained.has(item) ? [] : [index]);
4893
- return {
4894
- input: typeof input === "string" ? input : positions.map((index) => original[index]),
4895
- parts,
4896
- sourceParam(param) {
4897
- return param.replace(/^input\[(\d+)\]/, (match, index) => positions[Number(index)] === undefined ? match : `input[${positions[Number(index)]}]`);
4898
- },
4899
- canonicalHistory(decoded) {
4900
- if (!retained.size)
4901
- return decoded;
4902
- let next = 0;
4903
- return original.filter((item) => item.type !== "additional_tools").map((item) => retained.get(item) ?? decoded[next++]);
4904
- }
4905
- };
4906
- }
4907
- function encodeGeminiCallId(id, signature, maxBytes) {
4908
- if (id.includes(signatureSeparator))
4909
- fail("invalid_tool_arguments", "Gemini call id contains the signature separator", "functionCall.id");
4910
- return signature === undefined ? id : `${id}${signatureSeparator}${checkedSignature(signature, maxBytes)}`;
4911
- }
4912
- function decodeGeminiCallId(value, maxBytes) {
4913
- const separator = value.indexOf(signatureSeparator);
4914
- if (separator < 0)
4915
- return { id: value };
4916
- const id = string(value.slice(0, separator), "functionCall.id", true);
4917
- return { id, thoughtSignature: checkedSignature(value.slice(separator + signatureSeparator.length), maxBytes) };
4918
- }
4919
-
4920
5015
  // src/protocol-session/schema.ts
4921
5016
  function geminiSchemaToJson(raw, path, code = "unsupported_request", depth = 0) {
4922
5017
  if (depth > 64)
4923
5018
  fail("resource_limit", "Schema nesting exceeds the conversion limit", path);
4924
5019
  const s = record(raw, path);
4925
- 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);
4926
5021
  const out = {};
4927
5022
  if (s.type !== undefined) {
4928
5023
  const types = { STRING: "string", NUMBER: "number", INTEGER: "integer", BOOLEAN: "boolean", ARRAY: "array", OBJECT: "object", NULL: "null" };
@@ -4962,19 +5057,19 @@ function message(input, role, content, style, path) {
4962
5057
  function toolDefinition(raw, style, path) {
4963
5058
  const t = record(raw, path);
4964
5059
  if (style === "chat") {
4965
- 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");
4966
5061
  if (t.type === "custom") {
4967
5062
  const custom = record(t.custom, `${path}.custom`);
4968
- fields2(custom, ["name", "description", "format"], `${path}.custom`, "unsupported_tool");
5063
+ fields(custom, ["name", "description", "format"], `${path}.custom`, "unsupported_tool");
4969
5064
  return { type: "custom", ...custom };
4970
5065
  }
4971
5066
  if (t.type !== "function")
4972
5067
  fail("unsupported_tool", "Unsupported tool kind", `${path}.type`);
4973
5068
  const fn = record(t.function, path);
4974
- fields2(fn, ["name", "description", "parameters", "strict"], `${path}.function`, "unsupported_tool");
5069
+ fields(fn, ["name", "description", "parameters", "strict"], `${path}.function`, "unsupported_tool");
4975
5070
  return { type: "function", ...fn };
4976
5071
  }
4977
- 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");
4978
5073
  if (t.parameters !== undefined && t.parametersJsonSchema !== undefined)
4979
5074
  fail("unsupported_tool", "Ambiguous schema dialect", path);
4980
5075
  return {
@@ -4997,13 +5092,13 @@ function canonicalRequest(raw, protocol, model) {
4997
5092
  };
4998
5093
  if (protocol === "chat_completions") {
4999
5094
  const callKinds = new Map;
5000
- 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"], "");
5001
5096
  if (b.max_tokens !== undefined && b.max_completion_tokens !== undefined)
5002
5097
  fail("unsupported_request", "Ambiguous token limits", "max_tokens");
5003
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" });
5004
5099
  for (const [index, rawMessage] of list(b.messages, "messages").entries()) {
5005
5100
  const m = record(rawMessage, "message"), path = `messages[${index}]`;
5006
- 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");
5007
5102
  if (m.name !== undefined)
5008
5103
  fail("unsupported_content", "Named messages cannot be represented faithfully", `${path}.name`);
5009
5104
  const role = string(m.role, "role", true);
@@ -5038,12 +5133,12 @@ function canonicalRequest(raw, protocol, model) {
5038
5133
  fail("invalid_tool_history", "Tool calls require assistant role", path);
5039
5134
  for (const [j, rawCall] of list(m.tool_calls, "tool_calls").entries()) {
5040
5135
  const c = record(rawCall, "tool call"), at = `${path}.tool_calls[${j}]`;
5041
- fields2(c, ["id", "type", "function", "custom"], at, "unsupported_tool");
5136
+ fields(c, ["id", "type", "function", "custom"], at, "unsupported_tool");
5042
5137
  const custom = c.type === "custom";
5043
5138
  if (!custom && c.type !== "function")
5044
5139
  fail("unsupported_tool", "Unknown call type", at);
5045
5140
  const fn = record(custom ? c.custom : c.function, "tool call");
5046
- fields2(fn, custom ? ["name", "input"] : ["name", "arguments"], at, "unsupported_tool");
5141
+ fields(fn, custom ? ["name", "input"] : ["name", "arguments"], at, "unsupported_tool");
5047
5142
  callKinds.set(string(c.id, "id", true), custom);
5048
5143
  input.push({
5049
5144
  type: custom ? "custom_tool_call" : "function_call",
@@ -5062,9 +5157,9 @@ function canonicalRequest(raw, protocol, model) {
5062
5157
  out.tool_choice = c;
5063
5158
  else {
5064
5159
  const choice = record(c, "tool_choice");
5065
- fields2(choice, ["type", "function", "custom"], "tool_choice");
5160
+ fields(choice, ["type", "function", "custom"], "tool_choice");
5066
5161
  const fn = record(choice.function ?? choice.custom, "tool_choice");
5067
- fields2(fn, ["name"], "tool_choice.function");
5162
+ fields(fn, ["name"], "tool_choice.function");
5068
5163
  out.tool_choice = { type: choice.type, name: fn.name };
5069
5164
  }
5070
5165
  }
@@ -5072,19 +5167,19 @@ function canonicalRequest(raw, protocol, model) {
5072
5167
  out.reasoning = { effort: b.reasoning_effort };
5073
5168
  if (b.response_format !== undefined) {
5074
5169
  const format = record(b.response_format, "response_format");
5075
- fields2(format, ["type", "json_schema"], "response_format");
5170
+ fields(format, ["type", "json_schema"], "response_format");
5076
5171
  out.text = { format: format.type === "json_schema" ? { type: "json_schema", ...record(format.json_schema, "json_schema") } : format };
5077
5172
  }
5078
5173
  return out;
5079
5174
  }
5080
5175
  if (protocol === "anthropic_messages") {
5081
- 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"], "");
5082
5177
  copy({ stream: "stream", temperature: "temperature", top_p: "top_p", max_tokens: "max_output_tokens", metadata: "metadata", stop_sequences: "stop" });
5083
5178
  if (b.system !== undefined)
5084
5179
  message(input, "system", b.system, "anthropic", "system");
5085
5180
  for (const [index, rawMessage] of list(b.messages, "messages").entries()) {
5086
5181
  const m = record(rawMessage, "message"), path = `messages[${index}]`;
5087
- fields2(m, ["role", "content"], path, "unsupported_content");
5182
+ fields(m, ["role", "content"], path, "unsupported_content");
5088
5183
  if (m.role !== "user" && m.role !== "assistant")
5089
5184
  fail("unsupported_content", "Anthropic messages require user or assistant role", `${path}.role`);
5090
5185
  if (typeof m.content === "string") {
@@ -5096,15 +5191,15 @@ function canonicalRequest(raw, protocol, model) {
5096
5191
  if (p.type === "tool_use") {
5097
5192
  if (m.role !== "assistant")
5098
5193
  fail("invalid_tool_history", "Tool calls require assistant role", at);
5099
- fields2(p, ["type", "id", "name", "input"], at, "unsupported_content");
5194
+ fields(p, ["type", "id", "name", "input"], at, "unsupported_content");
5100
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)) });
5101
5196
  } else if (p.type === "tool_result") {
5102
5197
  if (m.role !== "user")
5103
5198
  fail("invalid_tool_history", "Tool results require user role", at);
5104
- 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");
5105
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) } : {} });
5106
5201
  } else if (p.type === "thinking") {
5107
- fields2(p, ["type", "thinking", "signature"], at, "unsupported_reasoning");
5202
+ fields(p, ["type", "thinking", "signature"], at, "unsupported_reasoning");
5108
5203
  if (p.signature != null)
5109
5204
  fail("unsupported_reasoning", "Provider-bound reasoning signatures cannot cross protocols", `${at}.signature`);
5110
5205
  if (m.role !== "assistant")
@@ -5118,7 +5213,7 @@ function canonicalRequest(raw, protocol, model) {
5118
5213
  out.tools = list(b.tools, "tools").map((t, i) => toolDefinition(t, "anthropic", `tools[${i}]`));
5119
5214
  if (b.tool_choice !== undefined) {
5120
5215
  const c = record(b.tool_choice, "tool_choice");
5121
- fields2(c, ["type", "name", "disable_parallel_tool_use"], "tool_choice");
5216
+ fields(c, ["type", "name", "disable_parallel_tool_use"], "tool_choice");
5122
5217
  if (c.type === "tool")
5123
5218
  out.tool_choice = { type: "function", name: c.name };
5124
5219
  else if (["auto", "none", "any"].includes(String(c.type)))
@@ -5130,7 +5225,7 @@ function canonicalRequest(raw, protocol, model) {
5130
5225
  }
5131
5226
  if (b.thinking !== undefined) {
5132
5227
  const t = record(b.thinking, "thinking");
5133
- fields2(t, ["type", "budget_tokens"], "thinking", "unsupported_reasoning");
5228
+ fields(t, ["type", "budget_tokens"], "thinking", "unsupported_reasoning");
5134
5229
  if (!["enabled", "adaptive", "disabled"].includes(String(t.type)))
5135
5230
  fail("unsupported_reasoning", "Unknown thinking mode", "thinking.type");
5136
5231
  if (t.type === "enabled")
@@ -5141,12 +5236,12 @@ function canonicalRequest(raw, protocol, model) {
5141
5236
  }
5142
5237
  if (b.output_config !== undefined) {
5143
5238
  const c = record(b.output_config, "output_config");
5144
- fields2(c, ["effort", "format"], "output_config");
5239
+ fields(c, ["effort", "format"], "output_config");
5145
5240
  if (c.effort !== undefined)
5146
5241
  out.reasoning = { effort: c.effort };
5147
5242
  if (c.format !== undefined) {
5148
5243
  const f = record(c.format, "format");
5149
- fields2(f, ["type", "schema"], "output_config.format");
5244
+ fields(f, ["type", "schema"], "output_config.format");
5150
5245
  if (f.type !== "json_schema")
5151
5246
  fail("unsupported_request", "Unknown structured output type", "output_config.format.type");
5152
5247
  out.text = { format: { type: "json_schema", name: "response", schema: f.schema } };
@@ -5154,12 +5249,12 @@ function canonicalRequest(raw, protocol, model) {
5154
5249
  }
5155
5250
  return out;
5156
5251
  }
5157
- fields2(b, ["contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "model", "stream"], "");
5252
+ fields(b, ["contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "model", "stream"], "");
5158
5253
  if (b.stream !== undefined)
5159
5254
  out.stream = b.stream;
5160
5255
  if (b.systemInstruction !== undefined) {
5161
5256
  const s = record(b.systemInstruction, "systemInstruction");
5162
- fields2(s, ["role", "parts"], "systemInstruction");
5257
+ fields(s, ["role", "parts"], "systemInstruction");
5163
5258
  if (s.role !== undefined && s.role !== "system")
5164
5259
  fail("unsupported_content", "Invalid system role", "systemInstruction.role");
5165
5260
  message(input, "system", s.parts, "gemini", "systemInstruction");
@@ -5169,12 +5264,12 @@ function canonicalRequest(raw, protocol, model) {
5169
5264
  for (const [index, rawContent] of list(b.contents, "contents").entries()) {
5170
5265
  const original = record(rawContent, "content"), path = `contents[${index}]`;
5171
5266
  const c = { ...original, role: original.role ?? "user" };
5172
- fields2(c, ["role", "parts"], path, "unsupported_content");
5267
+ fields(c, ["role", "parts"], path, "unsupported_content");
5173
5268
  if (c.role !== "user" && c.role !== "model")
5174
5269
  fail("unsupported_content", "Gemini contents require user or model role", `${path}.role`);
5175
5270
  for (const [j, rawPart] of list(c.parts, "parts").entries()) {
5176
5271
  const p = record(rawPart, "part"), at = `${path}.parts[${j}]`;
5177
- fields2(p, ["text", "thought", "functionCall", "functionResponse", "thoughtSignature"], at, "unsupported_content");
5272
+ fields(p, ["text", "thought", "functionCall", "functionResponse", "thoughtSignature"], at, "unsupported_content");
5178
5273
  if (p.thoughtSignature !== undefined)
5179
5274
  fail("unsupported_reasoning", "Provider-bound thought signatures cannot cross protocols", `${at}.thoughtSignature`);
5180
5275
  if ([p.text, p.functionCall, p.functionResponse].filter((v) => v !== undefined).length !== 1)
@@ -5183,7 +5278,7 @@ function canonicalRequest(raw, protocol, model) {
5183
5278
  if (c.role !== "model")
5184
5279
  fail("invalid_tool_history", "Function calls require model role", at);
5185
5280
  const f = record(p.functionCall, at);
5186
- fields2(f, ["name", "args", "id"], `${at}.functionCall`, "unsupported_tool");
5281
+ fields(f, ["name", "args", "id"], `${at}.functionCall`, "unsupported_tool");
5187
5282
  const name = string(f.name, at, true), id = f.id === undefined ? `call_gemini_${serial++}` : string(f.id, at, true);
5188
5283
  if (calls.has(id))
5189
5284
  fail("invalid_tool_history", "Duplicate tool call id", at);
@@ -5193,7 +5288,7 @@ function canonicalRequest(raw, protocol, model) {
5193
5288
  if (c.role !== "user")
5194
5289
  fail("invalid_tool_history", "Function results require user role", at);
5195
5290
  const f = record(p.functionResponse, at);
5196
- fields2(f, ["name", "response", "id"], `${at}.functionResponse`, "unsupported_tool");
5291
+ fields(f, ["name", "response", "id"], `${at}.functionResponse`, "unsupported_tool");
5197
5292
  const matches = [...calls.values()].filter((v) => v.name === f.name);
5198
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);
5199
5294
  if (calls.get(id)?.name !== f.name)
@@ -5212,7 +5307,7 @@ function canonicalRequest(raw, protocol, model) {
5212
5307
  const tools = [];
5213
5308
  for (const [i, rawTool] of list(b.tools, "tools").entries()) {
5214
5309
  const t = record(rawTool, "tool");
5215
- fields2(t, ["functionDeclarations"], `tools[${i}]`, "unsupported_tool");
5310
+ fields(t, ["functionDeclarations"], `tools[${i}]`, "unsupported_tool");
5216
5311
  for (const [j, f] of list(t.functionDeclarations, "functionDeclarations").entries())
5217
5312
  tools.push(toolDefinition(f, "gemini", `tools[${i}].functionDeclarations[${j}]`));
5218
5313
  }
@@ -5220,9 +5315,9 @@ function canonicalRequest(raw, protocol, model) {
5220
5315
  }
5221
5316
  if (b.toolConfig !== undefined) {
5222
5317
  const config = record(b.toolConfig, "toolConfig");
5223
- fields2(config, ["functionCallingConfig"], "toolConfig");
5318
+ fields(config, ["functionCallingConfig"], "toolConfig");
5224
5319
  const c = record(config.functionCallingConfig, "functionCallingConfig");
5225
- fields2(c, ["mode", "allowedFunctionNames"], "toolConfig.functionCallingConfig");
5320
+ fields(c, ["mode", "allowedFunctionNames"], "toolConfig.functionCallingConfig");
5226
5321
  if (!["AUTO", "NONE", "ANY"].includes(String(c.mode)))
5227
5322
  fail("unsupported_tool_choice", "Unknown function calling mode", "toolConfig.functionCallingConfig.mode");
5228
5323
  if (c.allowedFunctionNames !== undefined) {
@@ -5235,7 +5330,7 @@ function canonicalRequest(raw, protocol, model) {
5235
5330
  }
5236
5331
  if (b.generationConfig !== undefined) {
5237
5332
  const c = record(b.generationConfig, "generationConfig");
5238
- 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");
5239
5334
  for (const [from, to] of Object.entries({ temperature: "temperature", topP: "top_p", maxOutputTokens: "max_output_tokens", stopSequences: "stop", candidateCount: "n" }))
5240
5335
  if (c[from] !== undefined)
5241
5336
  out[to] = c[from];
@@ -5253,7 +5348,7 @@ function canonicalRequest(raw, protocol, model) {
5253
5348
  }
5254
5349
  if (c.thinkingConfig !== undefined) {
5255
5350
  const t = record(c.thinkingConfig, "thinkingConfig");
5256
- fields2(t, ["thinkingBudget", "thinkingLevel", "includeThoughts"], "generationConfig.thinkingConfig", "unsupported_reasoning");
5351
+ fields(t, ["thinkingBudget", "thinkingLevel", "includeThoughts"], "generationConfig.thinkingConfig", "unsupported_reasoning");
5257
5352
  if (t.thinkingBudget !== undefined)
5258
5353
  integer(t.thinkingBudget, "generationConfig.thinkingConfig.thinkingBudget", -1);
5259
5354
  if (t.thinkingLevel !== undefined)
@@ -5265,8 +5360,9 @@ function canonicalRequest(raw, protocol, model) {
5265
5360
  }
5266
5361
  return out;
5267
5362
  }
5268
- function validateCanonical(b, context) {
5363
+ function validateCanonical(b, context, chatConfigurationUpdates) {
5269
5364
  const responsesToGemini = context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content";
5365
+ const allowLossyContinuation = chatConfigurationUpdates !== undefined;
5270
5366
  let configuration;
5271
5367
  for (const key of ["stream", "parallel_tool_calls", "store", "background"])
5272
5368
  if (b[key] !== undefined)
@@ -5275,13 +5371,13 @@ function validateCanonical(b, context) {
5275
5371
  if (b[key] !== undefined && (typeof b[key] !== "number" || !Number.isFinite(b[key])))
5276
5372
  fail("invalid_payload", "Sampling value must be finite", key);
5277
5373
  if (b.tool_choice !== undefined && typeof b.tool_choice !== "string")
5278
- 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");
5279
5375
  if (b.text !== undefined) {
5280
5376
  const text = record(b.text, "text");
5281
- fields2(text, ["format", "verbosity"], "text");
5377
+ fields(text, ["format", "verbosity"], "text");
5282
5378
  if (text.format !== undefined) {
5283
5379
  const f = record(text.format, "text.format");
5284
- 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");
5285
5381
  if (!["text", "json_object", "json_schema"].includes(String(f.type)))
5286
5382
  fail("unsupported_request", "Unknown structured output format", "text.format.type");
5287
5383
  if (f.type === "json_schema") {
@@ -5297,34 +5393,40 @@ function validateCanonical(b, context) {
5297
5393
  const input = typeof b.input === "string" ? [] : list(b.input, "input");
5298
5394
  for (const [i, raw] of input.entries()) {
5299
5395
  const t = record(raw, "input item"), p = `input[${i}]`;
5300
- if (responsesToGemini && t.type === "configuration_update") {
5301
- fields2(t, ["type", "reasoning"], p, "unsupported_content");
5396
+ if ((responsesToGemini || allowLossyContinuation) && t.type === "configuration_update") {
5397
+ fields(t, ["type", "reasoning"], p, "unsupported_content");
5302
5398
  const reasoning = atParam(`${p}.reasoning`, () => record(t.reasoning, "configuration reasoning"));
5303
- fields2(reasoning, ["effort"], `${p}.reasoning`, "unsupported_reasoning");
5399
+ fields(reasoning, ["effort"], `${p}.reasoning`, "unsupported_reasoning");
5304
5400
  const param = `${p}.reasoning.effort`;
5305
5401
  const effort = atParam(param, () => string(reasoning.effort, "configuration effort", true));
5306
5402
  const map = context.reasoningPolicy?.effortMap;
5307
5403
  const level = map && Object.hasOwn(map, effort) ? map[effort] : undefined;
5308
- if (level === undefined || !["minimal", "low", "medium", "high"].includes(level))
5309
- fail("unsupported_reasoning", "Configuration update requires an explicit Gemini level mapping", param);
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);
5310
5406
  configuration = { effort, level, param };
5407
+ chatConfigurationUpdates?.add(t);
5311
5408
  continue;
5312
5409
  }
5313
5410
  if (t.type === "agent_message") {
5314
5411
  validateAgentMessage(t, p, context.capabilities?.limits);
5315
5412
  continue;
5316
5413
  }
5317
- 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"];
5318
- 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");
5319
5421
  if (t.is_error !== undefined)
5320
5422
  bool(t.is_error, `${p}.is_error`);
5321
- if (t.type === "reasoning")
5322
- for (const [j, part] of list(t.summary, "summary").entries())
5323
- 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"));
5324
5426
  if (Array.isArray(t.content))
5325
5427
  for (const [j, part] of t.content.entries()) {
5326
5428
  const c = record(part, "part");
5327
- 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");
5328
5430
  if (context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content" && t.role === "user" && c.type === "input_image") {
5329
5431
  atParam(`${p}.content[${j}].image_url`, () => string(c.image_url, "image URL", true));
5330
5432
  if (c.detail !== undefined && (typeof c.detail !== "string" || !["auto", "low", "high"].includes(c.detail)))
@@ -5335,7 +5437,7 @@ function validateCanonical(b, context) {
5335
5437
  for (const [j, part] of t.output.entries())
5336
5438
  atParam(`${p}.output[${j}]`, () => {
5337
5439
  const c = record(part, "tool output part");
5338
- 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");
5339
5441
  if (c.type === "input_image") {
5340
5442
  atParam(`${p}.output[${j}].image_url`, () => string(c.image_url, "image URL", true));
5341
5443
  if (c.detail !== undefined && (typeof c.detail !== "string" || !["auto", "low", "high"].includes(c.detail)))
@@ -5361,7 +5463,7 @@ function validateCanonical(b, context) {
5361
5463
  }
5362
5464
  if (t.type === "custom" && t.format !== undefined) {
5363
5465
  const f = record(t.format, "custom format");
5364
- 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");
5365
5467
  if (!["text", "grammar"].includes(String(f.type)))
5366
5468
  fail("unsupported_tool", "Unknown custom tool format", `${path}.format.type`);
5367
5469
  if (f.type === "grammar") {
@@ -5387,7 +5489,7 @@ function projectCodexPageSnapshot(raw, index, target, diagnostics) {
5387
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))
5388
5490
  return item;
5389
5491
  const param = `input[${index}]`;
5390
- fields2(item, ["type", "id", "namespace", "name", "output", "internal_chat_message_metadata_passthrough"], param, "unsupported_content");
5492
+ fields(item, ["type", "id", "namespace", "name", "output", "internal_chat_message_metadata_passthrough"], param, "unsupported_content");
5391
5493
  const text = atParam(`${param}.output`, () => string(item.output, "page snapshot output"));
5392
5494
  const { id, internal_chat_message_metadata_passthrough: metadata } = item;
5393
5495
  const reason = target === "chat_completions" ? "chat_codex_page_snapshot_as_user_data" : "gemini_codex_page_snapshot_as_user_data";
@@ -5407,6 +5509,7 @@ function convertProtocolRequest(raw, context) {
5407
5509
  const b = canonicalRequest(raw, context.sourceProtocol, context.model);
5408
5510
  const target = context.targetProtocol;
5409
5511
  const responsesToGemini = context.sourceProtocol === "responses" && target === "gemini_generate_content";
5512
+ const allowLossyContinuation = context.sourceProtocol === "responses" && target === "chat_completions" && context.allowLossyContinuation === true;
5410
5513
  const pageSnapshotDiagnostics = [];
5411
5514
  if (context.sourceProtocol === "responses" && (target === "chat_completions" || target === "gemini_generate_content") && Array.isArray(b.input))
5412
5515
  b.input = b.input.map((item, index) => projectCodexPageSnapshot(item, index, target, pageSnapshotDiagnostics));
@@ -5417,7 +5520,8 @@ function convertProtocolRequest(raw, context) {
5417
5520
  fail("invalid_payload", "Request stream mode disagrees with transport context", "stream");
5418
5521
  b.stream = context.streaming;
5419
5522
  }
5420
- const configuration = validateCanonical(b, context);
5523
+ const chatConfigurationUpdates = allowLossyContinuation ? new Set : undefined;
5524
+ const configuration = validateCanonical(b, context, chatConfigurationUpdates);
5421
5525
  const geminiHistory = responsesToGemini ? restoreGeminiHistory(b.input, limits(context.capabilities?.limits)) : undefined;
5422
5526
  if (geminiHistory)
5423
5527
  b.input = geminiHistory.input;
@@ -5436,12 +5540,14 @@ function convertProtocolRequest(raw, context) {
5436
5540
  fail("unsupported_reasoning", "Thinking mode requires an explicit target wire policy", "thinking");
5437
5541
  let mappedEffort;
5438
5542
  if (reasoning?.effort !== undefined) {
5439
- const effort = string(reasoning.effort, "reasoning.effort", true);
5440
- mappedEffort = policy?.effortMap?.[effort];
5441
- if (mappedEffort === undefined && policy?.anthropicThinkingBudget === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
5442
- fail("unsupported_reasoning", "Reasoning effort requires an explicit verified wire mapping", "reasoning.effort");
5443
- if (mappedEffort !== undefined)
5444
- 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
+ }
5445
5551
  }
5446
5552
  if (configuration)
5447
5553
  mappedEffort = configuration.level;
@@ -5485,7 +5591,7 @@ function convertProtocolRequest(raw, context) {
5485
5591
  }
5486
5592
  if (b.metadata !== undefined) {
5487
5593
  const metadata = record(b.metadata, "metadata");
5488
- fields2(metadata, ["user_id"], "metadata");
5594
+ fields(metadata, ["user_id"], "metadata");
5489
5595
  if (metadata.user_id !== undefined)
5490
5596
  string(metadata.user_id, "metadata.user_id");
5491
5597
  }
@@ -5497,7 +5603,7 @@ function convertProtocolRequest(raw, context) {
5497
5603
  } else if (target === "chat_completions") {
5498
5604
  if (reasoning?.effort !== undefined || mappedEffort !== undefined) {
5499
5605
  if (!cap.reasoningEffort)
5500
- fail("unsupported_reasoning", "Target effort capability is required", "reasoning.effort");
5606
+ fail("unsupported_reasoning", "Target effort capability is required", configuration?.param ?? "reasoning.effort");
5501
5607
  b.reasoning = { ...reasoning, effort: mappedEffort };
5502
5608
  if (mappedEffort === undefined)
5503
5609
  fail("unsupported_reasoning", "Chat requires a target effort mapping", "reasoning.effort");
@@ -5511,7 +5617,7 @@ function convertProtocolRequest(raw, context) {
5511
5617
  b.reasoning = { ...reasoning, effort: undefined };
5512
5618
  let decoded;
5513
5619
  try {
5514
- 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 });
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 });
5515
5621
  } catch (error) {
5516
5622
  if (geminiHistory && error instanceof ResponsesCodecError && error.param !== undefined)
5517
5623
  throw new ResponsesCodecError(error.code, error.message, geminiHistory.sourceParam(error.param));
@@ -5523,7 +5629,7 @@ function convertProtocolRequest(raw, context) {
5523
5629
  diagnostic.param = geminiHistory.sourceParam(diagnostic.param);
5524
5630
  diagnostics.push(...pageSnapshotDiagnostics);
5525
5631
  if (configuration)
5526
- diagnostics.push({ param: configuration.param, action: "mapped", reason: "gemini_configuration_effort_update" });
5632
+ diagnostics.push({ param: configuration.param, action: "mapped", reason: responsesToGemini ? "gemini_configuration_effort_update" : "chat_configuration_effort_update" });
5527
5633
  if (target === "gemini_generate_content" && decoded.body.parallel_tool_calls === true) {
5528
5634
  delete decoded.body.parallel_tool_calls;
5529
5635
  diagnostics.push({ param: "parallel_tool_calls", action: "omitted", reason: "gemini_parallel_tool_calls_allowed" });
@@ -5718,11 +5824,11 @@ function validateUsage(raw, protocol) {
5718
5824
  return;
5719
5825
  }
5720
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"];
5721
- fields2(u, keys, "usage", "unsupported_response");
5827
+ fields(u, keys, "usage", "unsupported_response");
5722
5828
  for (const [key, value] of Object.entries(u)) {
5723
5829
  if (key.endsWith("_details")) {
5724
5830
  const d = record(value, "usage details");
5725
- 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");
5726
5832
  for (const [k, v] of Object.entries(d))
5727
5833
  integer(v, `usage.${key}.${k}`);
5728
5834
  } else
@@ -5743,10 +5849,10 @@ function validateProviderResponse(raw, protocol) {
5743
5849
  const m = record(c.message, "message");
5744
5850
  for (const [callIndex, rawCall] of (m.tool_calls == null ? [] : list(m.tool_calls, "tool_calls")).entries()) {
5745
5851
  const call = record(rawCall, "call");
5746
- fields2(call, ["id", "type", "function", "index"], "tool_calls", "unsupported_tool");
5852
+ fields(call, ["id", "type", "function", "index"], "tool_calls", "unsupported_tool");
5747
5853
  if (call.index !== undefined && integer(call.index, `tool_calls[${callIndex}].index`) !== callIndex)
5748
5854
  fail("invalid_payload", "Tool call index must match its array position", `tool_calls[${callIndex}].index`);
5749
- 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");
5750
5856
  }
5751
5857
  }
5752
5858
  validateUsage(b.usage, protocol);
@@ -5760,14 +5866,14 @@ function validateProviderResponse(raw, protocol) {
5760
5866
  return b;
5761
5867
  }
5762
5868
  function validateAnthropicBlock(b, path) {
5763
- 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");
5764
5870
  if (b.signature !== undefined)
5765
5871
  fail("unsupported_reasoning", "Signed provider reasoning cannot cross protocols", `${path}.signature`);
5766
5872
  }
5767
5873
  function validateCanonicalResponse(raw, context, itemOnly = false) {
5768
5874
  const b = record(raw, "response");
5769
5875
  serialized(b, limits(context.capabilities?.limits).maxOutputBytes, "response");
5770
- 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");
5771
5877
  if (!itemOnly) {
5772
5878
  string(b.id, "response.id", true);
5773
5879
  integer(b.created_at, "response.created_at");
@@ -5778,7 +5884,7 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
5778
5884
  fail("missing_terminal", "Response has no explicit supported terminal", "status");
5779
5885
  if (b.status === "incomplete") {
5780
5886
  const d = record(b.incomplete_details, "incomplete_details");
5781
- fields2(d, ["reason"], "incomplete_details", "unsupported_response");
5887
+ fields(d, ["reason"], "incomplete_details", "unsupported_response");
5782
5888
  if (!["max_output_tokens", "content_filter"].includes(String(d.reason)))
5783
5889
  fail("unknown_terminal", "Unknown incomplete reason", "incomplete_details.reason");
5784
5890
  }
@@ -5793,13 +5899,13 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
5793
5899
  fail("unsupported_response", "Unknown item status", `${path}.status`);
5794
5900
  if (b.status === "completed" && t.status !== undefined && t.status !== "completed")
5795
5901
  fail("invalid_stream", "Completed response contains an unfinished item", `${path}.status`);
5796
- 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");
5797
5903
  if (t.type === "message") {
5798
5904
  if (t.role !== "assistant")
5799
5905
  fail("unsupported_content", "Output message must be assistant", `${path}.role`);
5800
5906
  for (const [j, rawPart] of list(t.content, "content").entries()) {
5801
5907
  const p = record(rawPart, "part");
5802
- 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");
5803
5909
  if (p.type === "output_text")
5804
5910
  string(p.text, "text");
5805
5911
  else if (p.type === "refusal")
@@ -5818,7 +5924,7 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
5818
5924
  fail("unsupported_reasoning", "Opaque or raw reasoning output cannot cross protocols", path);
5819
5925
  for (const rawPart of list(t.summary, "summary")) {
5820
5926
  const p = record(rawPart, "summary");
5821
- fields2(p, ["type", "text"], path, "unsupported_reasoning");
5927
+ fields(p, ["type", "text"], path, "unsupported_reasoning");
5822
5928
  if (p.type !== "summary_text")
5823
5929
  fail("unsupported_reasoning", "Unknown reasoning summary type", path);
5824
5930
  string(p.text, "summary");
@@ -5961,7 +6067,7 @@ class GeminiCanonicalDecoder {
5961
6067
  const events = [];
5962
6068
  if (b.promptFeedback !== undefined) {
5963
6069
  const p = record(b.promptFeedback, "promptFeedback");
5964
- fields2(p, ["blockReason", "blockReasonMessage", "safetyRatings"], "promptFeedback", "unsupported_response");
6070
+ fields(p, ["blockReason", "blockReasonMessage", "safetyRatings"], "promptFeedback", "unsupported_response");
5965
6071
  if (p.blockReason !== undefined && p.blockReason !== "BLOCK_REASON_UNSPECIFIED") {
5966
6072
  this.ended = true;
5967
6073
  events.push(...this.encoder.push({ choices: [{ delta: {}, finish_reason: "content_filter" }] }));
@@ -5976,7 +6082,7 @@ class GeminiCanonicalDecoder {
5976
6082
  fail("unsupported_response", "Only candidate index zero is supported", "candidates.index");
5977
6083
  if (c.content !== undefined && c.content !== null) {
5978
6084
  const content = record(c.content, "content");
5979
- fields2(content, ["role", "parts"], "candidates.content", "unsupported_content");
6085
+ fields(content, ["role", "parts"], "candidates.content", "unsupported_content");
5980
6086
  if (content.role !== undefined && content.role !== "model")
5981
6087
  fail("unsupported_response", "Response role must be model", "candidates.content.role");
5982
6088
  const parts = list(content.parts ?? [], "parts");
@@ -5984,14 +6090,14 @@ class GeminiCanonicalDecoder {
5984
6090
  fail("invalid_stream", "Content arrived after Gemini terminal");
5985
6091
  for (const [i, rawPart] of parts.entries()) {
5986
6092
  const p = record(rawPart, "part");
5987
- fields2(p, ["text", "thought", "functionCall", "thoughtSignature"], "candidates.content.parts", "unsupported_content");
6093
+ fields(p, ["text", "thought", "functionCall", "thoughtSignature"], "candidates.content.parts", "unsupported_content");
5988
6094
  if (p.thoughtSignature !== undefined && this.context.sourceProtocol !== "responses")
5989
6095
  fail("unsupported_reasoning", "Thought signatures cannot cross protocols", "candidates.content.parts.thoughtSignature");
5990
6096
  if (p.functionCall !== undefined) {
5991
6097
  if (p.text !== undefined || p.thought !== undefined)
5992
6098
  fail("unsupported_content", "Mixed Gemini part kinds", "candidates.content.parts");
5993
6099
  const f = record(p.functionCall, "functionCall");
5994
- fields2(f, ["id", "name", "args"], "functionCall", "unsupported_tool");
6100
+ fields(f, ["id", "name", "args"], "functionCall", "unsupported_tool");
5995
6101
  const index = this.serial++, originalId = f.id === undefined ? `call_gemini_${crypto.randomUUID().replaceAll("-", "")}` : string(f.id, "functionCall.id", true);
5996
6102
  if (this.ids.has(originalId))
5997
6103
  fail("invalid_tool_arguments", "Duplicate Gemini call id", "functionCall.id");
@@ -6145,7 +6251,7 @@ class CanonicalStreamValidator {
6145
6251
  this.sequence = n;
6146
6252
  }
6147
6253
  if (["response.created", "response.in_progress", "response.completed", "response.incomplete", "response.failed"].includes(type)) {
6148
- fields2(e, [...common, "response"], "", "unsupported_response");
6254
+ fields(e, [...common, "response"], "", "unsupported_response");
6149
6255
  const r = record(e.response, "response");
6150
6256
  const id = string(r.id, "response.id", true);
6151
6257
  if (this.responseId !== undefined && this.responseId !== id)
@@ -6202,7 +6308,7 @@ class CanonicalStreamValidator {
6202
6308
  ];
6203
6309
  if (!known.includes(type))
6204
6310
  fail("unsupported_response", "Unknown Responses stream event", "type");
6205
- 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");
6206
6312
  if (e.response_id !== undefined && e.response_id !== this.responseId)
6207
6313
  fail("invalid_stream", "Event response id changed", "response_id");
6208
6314
  const index = integer(e.output_index, "output_index");
@@ -6296,7 +6402,7 @@ class CanonicalStreamValidator {
6296
6402
  fail("unsupported_content", "Unknown content part type", "part.type");
6297
6403
  if (summary ? p.type !== "summary_text" : p.type === "summary_text")
6298
6404
  fail("invalid_stream", "Part kind differs from its output item", "part.type");
6299
- 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");
6300
6406
  if (p.annotations !== undefined && Array.isArray(p.annotations) && p.annotations.length)
6301
6407
  fail("unsupported_content", "Annotations cannot cross protocols", "part.annotations");
6302
6408
  const initial = string(p[p.type === "refusal" ? "refusal" : "text"], "part text");
@@ -6321,7 +6427,7 @@ class CanonicalStreamValidator {
6321
6427
  if (!p.textDone)
6322
6428
  fail("invalid_stream", "Part done before text done");
6323
6429
  const v = record(e.part, "part");
6324
- 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");
6325
6431
  if (v.annotations !== undefined && (!Array.isArray(v.annotations) || v.annotations.length))
6326
6432
  fail("unsupported_content", "Annotations cannot cross protocols", "part.annotations");
6327
6433
  if (v.type !== p.kind || v[p.kind === "refusal" ? "refusal" : "text"] !== p.text)
@@ -6475,7 +6581,7 @@ class CanonicalStreamRenderer {
6475
6581
  var LLM_PROTOCOLS = ["responses", "chat_completions", "anthropic_messages", "gemini_generate_content"];
6476
6582
 
6477
6583
  // src/protocol-session/index.ts
6478
- var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.5";
6584
+ var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.6";
6479
6585
  function describeProtocolConversion() {
6480
6586
  return {
6481
6587
  rulesVersion: PROTOCOL_CONVERSION_RULES_VERSION,
@@ -6684,9 +6790,9 @@ function validateStreamEnvelope(raw, protocol) {
6684
6790
  if (Array.isArray(d.tool_calls))
6685
6791
  for (const rawCall of d.tool_calls) {
6686
6792
  const t = record(rawCall, "tool call");
6687
- fields2(t, ["index", "id", "type", "function"], "tool_calls", "unsupported_tool");
6793
+ fields(t, ["index", "id", "type", "function"], "tool_calls", "unsupported_tool");
6688
6794
  if (t.function !== undefined)
6689
- 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");
6690
6796
  }
6691
6797
  }
6692
6798
  validateUsage(e.usage, protocol);
@@ -6695,12 +6801,12 @@ function validateStreamEnvelope(raw, protocol) {
6695
6801
  validateAnthropicBlock(record(e.content_block, "block"), "content_block");
6696
6802
  if (e.type === "content_block_delta") {
6697
6803
  const d = record(e.delta, "delta");
6698
- 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");
6699
6805
  if (d.type === "signature_delta" || d.signature !== undefined)
6700
6806
  fail("unsupported_reasoning", "Signed provider reasoning cannot cross protocols", "delta.signature");
6701
6807
  }
6702
6808
  if (e.type === "message_delta")
6703
- 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");
6704
6810
  if (e.type === "message_start") {
6705
6811
  const m = record(e.message, "message");
6706
6812
  validateUsage(m.usage, protocol);