@jeffusion/bungee-core 6.15.0 → 6.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2857,6 +2857,240 @@ function validateEncryptedFunctionArgs(item, delivery, path) {
2857
2857
  fail("unsupported_content", "Encrypted function arguments cannot cross protocols", param);
2858
2858
  }
2859
2859
 
2860
+ // packages/llms/src/protocol-session/gemini.ts
2861
+ import { createHash } from "crypto";
2862
+
2863
+ // packages/llms/src/protocol-session/validation.ts
2864
+ function fields(value, allowed, path, code = "unsupported_request") {
2865
+ for (const key of Object.keys(value))
2866
+ if (!allowed.includes(key))
2867
+ fail(code, "Field cannot be represented by the target protocol", path ? `${path}.${key}` : key);
2868
+ }
2869
+ function bool(value, path) {
2870
+ if (typeof value !== "boolean")
2871
+ fail("invalid_payload", "Expected a boolean", path);
2872
+ return value;
2873
+ }
2874
+ function integer(value, path, min = 0) {
2875
+ if (!Number.isSafeInteger(value) || value < min)
2876
+ fail("invalid_payload", "Expected an integer in the supported range", path);
2877
+ return value;
2878
+ }
2879
+ function textParts(raw, path, style, role) {
2880
+ if (typeof raw === "string")
2881
+ return [{ type: "input_text", text: raw }];
2882
+ return list(raw, path).map((rawPart, index) => {
2883
+ const p = record(rawPart, path), at = `${path}[${index}]`;
2884
+ if (style === "gemini") {
2885
+ fields(p, ["text", "thought"], at, "unsupported_content");
2886
+ if (p.thought === true)
2887
+ fail("unsupported_reasoning", "Reasoning must be represented as a separate history item", at);
2888
+ return { type: "input_text", text: string(p.text, at) };
2889
+ }
2890
+ if (style === "chat" && p.type === "image_url" && role === "user") {
2891
+ fields(p, ["type", "image_url"], at, "unsupported_content");
2892
+ const image = record(p.image_url, at);
2893
+ fields(image, ["url", "detail"], `${at}.image_url`, "unsupported_content");
2894
+ return { type: "input_image", image_url: string(image.url, at, true), ...image.detail !== undefined ? { detail: image.detail } : {} };
2895
+ }
2896
+ if (style === "chat" && p.type === "refusal" && role === "assistant") {
2897
+ fields(p, ["type", "refusal"], at, "unsupported_content");
2898
+ return { type: "refusal", refusal: string(p.refusal, at) };
2899
+ }
2900
+ if (p.type !== "text")
2901
+ fail("unsupported_content", "Content block cannot be represented by the target protocol", at);
2902
+ fields(p, ["type", "text"], at, "unsupported_content");
2903
+ return { type: "input_text", text: string(p.text, at) };
2904
+ });
2905
+ }
2906
+
2907
+ // packages/llms/src/protocol-session/gemini.ts
2908
+ var signatureSeparator = "__thought__";
2909
+ function geminiInlineImage(image, path, budget) {
2910
+ const param = `${path}.image_url`;
2911
+ const url = bounded(string(image.url, "image URL", true), budget.maxRequestBytes, param);
2912
+ const match = /^data:([^;,]+);base64,([\s\S]*)$/.exec(url);
2913
+ if (!match || !["image/png", "image/jpeg", "image/webp"].includes(match[1]))
2914
+ fail("unsupported_content", "Gemini images require inline PNG, JPEG or WebP data", param);
2915
+ const data = match[2];
2916
+ 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(/=+$/, ""))
2917
+ fail("invalid_payload", "Invalid image Base64 encoding", param);
2918
+ return { mimeType: match[1], data };
2919
+ }
2920
+ function geminiToolResponse(content, path, budget, diagnostics) {
2921
+ if (!Array.isArray(content) || !content.some((part) => part.type === "image_url"))
2922
+ return { response: { output: content } };
2923
+ if (content.length > budget.maxItems)
2924
+ fail("resource_limit", "Too many tool output parts", path);
2925
+ const parts = [];
2926
+ const output = content.map((part, index) => atParam(`${path}[${index}]`, () => {
2927
+ if (part.type === "text")
2928
+ return part;
2929
+ if (part.type !== "image_url")
2930
+ fail("unsupported_content", "Unsupported Gemini tool result content");
2931
+ const image = record(part.image_url, "tool image");
2932
+ const inlineData = geminiInlineImage(image, `${path}[${index}]`, budget);
2933
+ const displayName = `tool-image-${index}.${inlineData.mimeType.slice("image/".length)}`;
2934
+ parts.push({ inlineData: { ...inlineData, displayName } });
2935
+ if (image.detail !== undefined)
2936
+ diagnostics.push({ param: `${path}[${index}].detail`, action: "omitted", reason: "gemini_tool_image_detail_unavailable" });
2937
+ return { $ref: displayName };
2938
+ }));
2939
+ return { response: { output }, parts };
2940
+ }
2941
+ function checkedSignature(value, maxBytes) {
2942
+ const signature = bounded(string(value, "thoughtSignature", true), maxBytes, "thoughtSignature");
2943
+ 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(/=+$/, ""))
2944
+ fail("invalid_tool_arguments", "Invalid Gemini thought signature encoding", "thoughtSignature");
2945
+ return signature;
2946
+ }
2947
+ var envelopePrefix = "bungee_gemini:";
2948
+ var isGeminiSignatureCarrier = (value) => typeof value === "string" && value.startsWith(envelopePrefix);
2949
+ var geminiEnvelopeBytes = (payloadBytes) => envelopePrefix.length + Math.ceil(payloadBytes * 4 / 3);
2950
+ var geminiTextHash = (text) => createHash("sha256").update(text).digest("base64url");
2951
+ function geminiSignatureItem(items, budget) {
2952
+ const payload = serialized({ version: 1, items }, budget.maxArgumentBytes, "Gemini signatures");
2953
+ return {
2954
+ type: "reasoning",
2955
+ id: `rs_gemini_${crypto.randomUUID().replaceAll("-", "")}`,
2956
+ summary: [],
2957
+ encrypted_content: bounded(envelopePrefix + Buffer.from(payload).toString("base64url"), budget.maxArgumentBytes, "Gemini signatures")
2958
+ };
2959
+ }
2960
+ function readGeminiSignatures(item, budget) {
2961
+ fields(item, ["type", "id", "summary", "encrypted_content", "status"], "Gemini signatures", "unsupported_reasoning");
2962
+ if (item.type !== "reasoning" || list(item.summary, "summary").length)
2963
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier");
2964
+ string(item.id, "signature item id", true);
2965
+ const opaque = bounded(string(item.encrypted_content, "encrypted_content", true), budget.maxArgumentBytes, "Gemini signatures");
2966
+ if (!isGeminiSignatureCarrier(opaque))
2967
+ fail("unsupported_reasoning", "Native encrypted reasoning cannot be restored to Gemini");
2968
+ const encoded = opaque.slice(envelopePrefix.length), bytes = Buffer.from(encoded, "base64url");
2969
+ if (!encoded || bytes.toString("base64url") !== encoded)
2970
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier encoding");
2971
+ let raw;
2972
+ try {
2973
+ raw = JSON.parse(bytes.toString("utf8"));
2974
+ } catch {
2975
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier JSON");
2976
+ }
2977
+ const body = record(raw, "Gemini signatures");
2978
+ fields(body, ["version", "items"], "Gemini signatures", "unsupported_reasoning");
2979
+ if (body.version !== 1)
2980
+ fail("unsupported_reasoning", "Unknown Gemini signature format");
2981
+ const ids = new Set;
2982
+ let partCount = 0;
2983
+ const result = list(body.items, "signature items").map((raw) => {
2984
+ const item = record(raw, "signature item");
2985
+ fields(item, ["id", "thought", "parts"], "signature item", "unsupported_reasoning");
2986
+ const id = string(item.id, "signed item id", true);
2987
+ if (ids.has(id) || typeof item.thought !== "boolean")
2988
+ fail("unsupported_reasoning", "Invalid signed item identity");
2989
+ ids.add(id);
2990
+ const parts = list(item.parts, "signed parts").map((raw) => {
2991
+ if (++partCount > budget.maxItems)
2992
+ fail("resource_limit", "Too many signed Gemini parts");
2993
+ const part = record(raw, "signed part");
2994
+ fields(part, ["length", "hash", "signature", "textAbsent"], "signed part", "unsupported_reasoning");
2995
+ const length = integer(part.length, "signed part length"), hash = string(part.hash, "signed part hash", true);
2996
+ if (!/^[A-Za-z0-9_-]{43}$/.test(hash))
2997
+ fail("unsupported_reasoning", "Invalid signed part hash");
2998
+ const signature = part.signature === undefined ? undefined : checkedSignature(part.signature, budget.maxArgumentBytes);
2999
+ if (part.textAbsent !== undefined && (part.textAbsent !== true || length !== 0 || signature === undefined))
3000
+ fail("unsupported_reasoning", "Invalid empty signed part");
3001
+ return { length, hash, ...signature === undefined ? {} : { signature }, ...part.textAbsent ? { textAbsent: true } : {} };
3002
+ });
3003
+ if (!parts.some((p) => p.signature !== undefined))
3004
+ fail("unsupported_reasoning", "Signature carrier has no signature");
3005
+ return { id, thought: item.thought, parts };
3006
+ });
3007
+ if (!result.length || result.length > budget.maxItems)
3008
+ fail("unsupported_reasoning", "Invalid signature item count");
3009
+ return result;
3010
+ }
3011
+ function restoreGeminiHistory(input, budget) {
3012
+ const original = typeof input === "string" ? [] : list(input, "input").map((raw) => record(raw, "input item"));
3013
+ if (original.length > budget.maxItems)
3014
+ fail("resource_limit", "Too many input items", "input");
3015
+ const retained = new Map, parts = new Map, ids = new Map;
3016
+ original.forEach((item, i) => {
3017
+ if (typeof item.id === "string") {
3018
+ if (ids.has(item.id))
3019
+ fail("invalid_tool_history", "Duplicate history item id", "input.id");
3020
+ ids.set(item.id, i);
3021
+ }
3022
+ });
3023
+ original.forEach((carrier, index) => {
3024
+ if (carrier.type === "configuration_update") {
3025
+ retained.set(carrier, carrier);
3026
+ return;
3027
+ }
3028
+ if (carrier.encrypted_content == null)
3029
+ return;
3030
+ const { content, internal_chat_message_metadata_passthrough: metadata, ...normalized } = carrier;
3031
+ if (content !== undefined && content !== null)
3032
+ fail("unsupported_reasoning", "Gemini signature carriers cannot contain reasoning content", `input[${index}].content`);
3033
+ if (metadata !== undefined)
3034
+ atParam(`input[${index}].internal_chat_message_metadata_passthrough`, () => record(metadata, "message metadata"));
3035
+ const signed = readGeminiSignatures(normalized, budget);
3036
+ retained.set(carrier, normalized);
3037
+ let previous = -1;
3038
+ for (const item of signed) {
3039
+ const at = ids.get(item.id);
3040
+ if (at === undefined || at >= index || at <= previous || parts.has(item.id))
3041
+ fail("unsupported_reasoning", "Signed history reference is missing or ambiguous");
3042
+ previous = at;
3043
+ const source = original[at];
3044
+ if (item.thought ? source.type !== "reasoning" || source.encrypted_content != null : source.role !== "assistant" || source.type !== undefined && source.type !== "message")
3045
+ fail("unsupported_reasoning", "Signed history item kind changed");
3046
+ const content = item.thought ? list(source.summary, "summary") : typeof source.content === "string" ? [{ type: "output_text", text: source.content }] : list(source.content, "content");
3047
+ const text = content.map((raw) => {
3048
+ const p = record(raw, "signed text");
3049
+ if (p.type !== (item.thought ? "summary_text" : "output_text") && !(p.type === "input_text" && !item.thought))
3050
+ fail("unsupported_reasoning", "Signed history content kind changed");
3051
+ return string(p.text, "signed text");
3052
+ }).join("");
3053
+ let offset = 0;
3054
+ const restored = item.parts.map((part) => {
3055
+ const value = text.slice(offset, offset + part.length);
3056
+ offset += part.length;
3057
+ if (value.length !== part.length || geminiTextHash(value) !== part.hash)
3058
+ fail("unsupported_reasoning", "Signed history text changed");
3059
+ return { ...part.textAbsent ? {} : { text: value }, ...item.thought ? { thought: true } : {}, ...part.signature === undefined ? {} : { thoughtSignature: part.signature } };
3060
+ });
3061
+ if (offset !== text.length)
3062
+ fail("unsupported_reasoning", "Signed history text was not fully consumed");
3063
+ parts.set(item.id, restored);
3064
+ }
3065
+ });
3066
+ const positions = original.flatMap((item, index) => retained.has(item) ? [] : [index]);
3067
+ return {
3068
+ input: typeof input === "string" ? input : positions.map((index) => original[index]),
3069
+ parts,
3070
+ sourceParam(param) {
3071
+ return param.replace(/^input\[(\d+)\]/, (match, index) => positions[Number(index)] === undefined ? match : `input[${positions[Number(index)]}]`);
3072
+ },
3073
+ canonicalHistory(decoded) {
3074
+ if (!retained.size)
3075
+ return decoded;
3076
+ let next = 0;
3077
+ return original.filter((item) => item.type !== "additional_tools").map((item) => retained.get(item) ?? decoded[next++]);
3078
+ }
3079
+ };
3080
+ }
3081
+ function encodeGeminiCallId(id, signature, maxBytes) {
3082
+ if (id.includes(signatureSeparator))
3083
+ fail("invalid_tool_arguments", "Gemini call id contains the signature separator", "functionCall.id");
3084
+ return signature === undefined ? id : `${id}${signatureSeparator}${checkedSignature(signature, maxBytes)}`;
3085
+ }
3086
+ function decodeGeminiCallId(value, maxBytes) {
3087
+ const separator = value.indexOf(signatureSeparator);
3088
+ if (separator < 0)
3089
+ return { id: value };
3090
+ const id = string(value.slice(0, separator), "functionCall.id", true);
3091
+ return { id, thoughtSignature: checkedSignature(value.slice(separator + signatureSeparator.length), maxBytes) };
3092
+ }
3093
+
2860
3094
  // packages/llms/src/providers/openai/protocol-conversion.ts
2861
3095
  var THINKING_TAG_PATTERN = /<thinking>([\s\S]*?)<\/thinking>/gi;
2862
3096
  var TOOL_CALL_CONTENT_TYPES = new Set([
@@ -3437,7 +3671,7 @@ class OpenAIProtocolConversion {
3437
3671
  }
3438
3672
 
3439
3673
  // packages/llms/src/responses-codec/request-preferences.ts
3440
- function fields(value, allowed, path) {
3674
+ function fields2(value, allowed, path) {
3441
3675
  for (const key of Object.keys(value))
3442
3676
  if (!allowed.includes(key)) {
3443
3677
  fail("unsupported_request", "Unrecognized request option", `${path}.${key}`);
@@ -3448,7 +3682,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
3448
3682
  if (body.stream_options !== undefined)
3449
3683
  atParam("stream_options", () => {
3450
3684
  const options = record(body.stream_options, "stream_options");
3451
- fields(options, ["include_usage", "reasoning_summary_delivery"], "stream_options");
3685
+ fields2(options, ["include_usage", "reasoning_summary_delivery"], "stream_options");
3452
3686
  if (options.include_usage !== undefined) {
3453
3687
  if (typeof options.include_usage !== "boolean")
3454
3688
  fail("invalid_payload", "Usage preference must be boolean", "stream_options.include_usage");
@@ -3463,7 +3697,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
3463
3697
  if (body.access_programs !== undefined)
3464
3698
  atParam("access_programs", () => {
3465
3699
  const programs = record(body.access_programs, "access_programs");
3466
- fields(programs, ["cyber"], "access_programs");
3700
+ fields2(programs, ["cyber"], "access_programs");
3467
3701
  if (programs.cyber !== undefined && programs.cyber !== "standard") {
3468
3702
  if (programs.cyber === "daybreak_blue" || programs.cyber === "daybreak_red") {
3469
3703
  fail("unsupported_access_program", "Selected access program cannot be represented by the target protocol", "access_programs.cyber");
@@ -3475,7 +3709,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
3475
3709
  if (body.reasoning !== undefined)
3476
3710
  atParam("reasoning", () => {
3477
3711
  const reasoning = record(body.reasoning, "reasoning");
3478
- fields(reasoning, ["effort", "summary", "context"], "reasoning");
3712
+ fields2(reasoning, ["effort", "summary", "context"], "reasoning");
3479
3713
  if (reasoning.summary !== undefined) {
3480
3714
  if (typeof reasoning.summary !== "string" || !["none", "auto", "concise", "detailed"].includes(reasoning.summary))
3481
3715
  fail("invalid_payload", "Invalid reasoning summary preference", "reasoning.summary");
@@ -3506,7 +3740,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
3506
3740
  if (body.text !== undefined)
3507
3741
  atParam("text", () => {
3508
3742
  const text = record(body.text, "text");
3509
- fields(text, ["verbosity", "format"], "text");
3743
+ fields2(text, ["verbosity", "format"], "text");
3510
3744
  if (text.verbosity !== undefined) {
3511
3745
  if (typeof text.verbosity !== "string" || !["low", "medium", "high"].includes(text.verbosity))
3512
3746
  fail("invalid_payload", "Invalid text verbosity preference", "text.verbosity");
@@ -3569,6 +3803,7 @@ function definitionKey(value) {
3569
3803
  }
3570
3804
  function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {}) {
3571
3805
  const body = record(raw, "Responses request");
3806
+ const allowLossyContinuation = protocol === "chat_completions" && options.allowLossyContinuation === true;
3572
3807
  if (capabilities.agentMessageDelivery !== undefined && capabilities.agentMessageDelivery !== "plaintext")
3573
3808
  fail("invalid_payload", "Unknown agent message delivery policy", "agentMessageDelivery");
3574
3809
  const budget = limits(capabilities.limits);
@@ -3637,6 +3872,7 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3637
3872
  const byOriginal = new Map;
3638
3873
  const definitions = new Map;
3639
3874
  let examinedTools = 0;
3875
+ let hasCompaction = false;
3640
3876
  const tools = [];
3641
3877
  const identity = (name, namespace) => JSON.stringify([namespace ?? null, name]);
3642
3878
  const register = (name, namespace, custom) => {
@@ -3734,6 +3970,31 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3734
3970
  for (const [index, rawItem] of input.entries())
3735
3971
  atParam(`input[${index}]`, () => {
3736
3972
  const item = record(rawItem, "input item");
3973
+ if (Object.hasOwn(item, "phase")) {
3974
+ const param = `input[${index}].phase`;
3975
+ if (!allowLossyContinuation || item.type !== undefined && item.type !== "message" || item.role !== "assistant")
3976
+ fail("unsupported_content", "Message phase requires opted-in Chat assistant history", param);
3977
+ if (item.phase !== null && item.phase !== "commentary" && item.phase !== "final_answer")
3978
+ fail("invalid_payload", "Invalid assistant message phase", param);
3979
+ diagnostics.push({ param, action: "omitted", reason: "chat_assistant_phase_unavailable" });
3980
+ }
3981
+ if (allowLossyContinuation && item.type === "compaction") {
3982
+ const path = `input[${index}]`;
3983
+ for (const key of Object.keys(item))
3984
+ if (!["type", "id", "created_by", "encrypted_content", "internal_chat_message_metadata_passthrough"].includes(key))
3985
+ fail("unsupported_content", "Unknown compaction field", `${path}.${key}`);
3986
+ const param = `${path}.encrypted_content`;
3987
+ const encryptedContent = atParam(param, () => string(item.encrypted_content, "compaction encrypted content", true));
3988
+ if (!encryptedContent.trim())
3989
+ fail("invalid_payload", "Compaction encrypted content must be non-empty", param);
3990
+ if (isGeminiSignatureCarrier(encryptedContent))
3991
+ fail("unsupported_content", "Gemini signature carriers cannot cross into Chat", param);
3992
+ if (item.id != null)
3993
+ atParam(`${path}.id`, () => string(item.id, "compaction id", true));
3994
+ if (item.created_by !== undefined)
3995
+ atParam(`${path}.created_by`, () => string(item.created_by, "compaction created_by", true));
3996
+ hasCompaction = true;
3997
+ }
3737
3998
  if (item.type !== "additional_tools") {
3738
3999
  if (item.internal_chat_message_metadata_passthrough !== undefined) {
3739
4000
  record(item.internal_chat_message_metadata_passthrough, "message metadata");
@@ -3769,6 +4030,12 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3769
4030
  const partPath = `${path}[${index}]`;
3770
4031
  atParam(partPath, () => {
3771
4032
  const part = record(rawPart, "content part");
4033
+ if (Object.hasOwn(part, "logprobs")) {
4034
+ const param = `${partPath}.logprobs`;
4035
+ if (!allowLossyContinuation || role !== "assistant" || part.type !== "output_text" || !Array.isArray(part.logprobs) || part.logprobs.length !== 0)
4036
+ fail("unsupported_content", "Only empty assistant output log probabilities can be omitted", param);
4037
+ diagnostics.push({ param, action: "omitted", reason: "chat_empty_output_logprobs" });
4038
+ }
3772
4039
  if (part.type === "input_text" || part.type === "output_text" || part.type === "text")
3773
4040
  string(part.text, "content text");
3774
4041
  else if (part.type === "refusal" && role === "assistant") {
@@ -3818,6 +4085,8 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3818
4085
  let messageParam = "instructions";
3819
4086
  const callIds = new Set;
3820
4087
  const callToolNames = new Map;
4088
+ const callsAwaitingResult = new Map;
4089
+ let encryptedToolBatch;
3821
4090
  const answered = new Set;
3822
4091
  const deferredInstructions = [];
3823
4092
  const normalizeChatHistory = protocol === "chat_completions" && !options.preserveContentOrder;
@@ -3836,18 +4105,43 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3836
4105
  addMessage({ role: "user", content: [{ type: "text", text: `Images returned by tool ${JSON.stringify(name)} (call ${JSON.stringify(callId)}):` }, ...images] });
3837
4106
  projectedToolImages.length = 0;
3838
4107
  };
4108
+ const checkPendingToolHistory = (item, toolOutput) => {
4109
+ const message = item.type === undefined || item.type === "message";
4110
+ const instruction = message && (item.role === "system" || item.role === "developer");
4111
+ const toolCall = item.type === "function_call" || item.type === "custom_tool_call";
4112
+ if (hasCompaction && toolOutput && callsAwaitingResult.size && pendingReasoning)
4113
+ fail("invalid_tool_history", "Attach the reasoning summary before the Chat tool results", messageParam);
4114
+ if (toolOutput || instruction)
4115
+ return;
4116
+ if (deferredInstructions.length)
4117
+ fail("invalid_tool_history", "Only instructions and tool results may follow a deferred instruction until all tool results arrive", messageParam);
4118
+ if (encryptedToolBatch && !(toolCall && chat.at(-1)?.role === "assistant"))
4119
+ fail("invalid_tool_history", "Complete the encrypted tool batch before another turn or reasoning item", messageParam);
4120
+ if (hasCompaction && callsAwaitingResult.size && !(normalizeChatHistory && chat.at(-1)?.role === "assistant" && (toolCall || item.type === "reasoning" || message && item.role === "assistant")))
4121
+ fail("invalid_tool_history", "Complete the Chat tool batch before another message", messageParam);
4122
+ };
3839
4123
  if (body.instructions !== undefined)
3840
4124
  addMessage({ role: "system", content: string(body.instructions, "instructions") });
3841
4125
  for (const [inputIndex, rawItem] of input.entries())
3842
4126
  atParam(`input[${inputIndex}]`, () => {
3843
4127
  messageParam = `input[${inputIndex}]`;
3844
4128
  const item = record(rawItem, "input item");
3845
- if (item.type !== "function_call_output" && item.type !== "custom_tool_call_output")
4129
+ const toolOutput = item.type === "function_call_output" || item.type === "custom_tool_call_output";
4130
+ if (!toolOutput)
3846
4131
  flushToolImages();
3847
- if (item.type === "additional_tools")
4132
+ if (item.type === "additional_tools" || allowLossyContinuation && item.type === "configuration_update" && options.chatConfigurationUpdates?.has(item))
3848
4133
  return;
3849
- 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")))
3850
- fail("invalid_tool_history", "Only instructions and tool results may follow a deferred instruction until all tool results arrive", messageParam);
4134
+ if (item.type !== "reasoning")
4135
+ checkPendingToolHistory(item, toolOutput);
4136
+ if (allowLossyContinuation && item.type === "compaction") {
4137
+ if (callIds.size !== answered.size)
4138
+ fail("invalid_tool_history", "Compaction cannot split a Chat tool batch", messageParam);
4139
+ if (pendingReasoning)
4140
+ fail("unsupported_reasoning", "Reasoning must precede an assistant item", messageParam);
4141
+ addMessage({ role: "user", content: "[Earlier conversation context was compacted and is unavailable. Continue from the visible messages and ask for any details you need.]" });
4142
+ diagnostics.push({ param: messageParam, action: "mapped", reason: "chat_compaction_placeholder" });
4143
+ return;
4144
+ }
3851
4145
  if (item.type === "agent_message") {
3852
4146
  validateAgentMessage(item, messageParam, capabilities.limits);
3853
4147
  if (capabilities.agentMessageDelivery !== "plaintext")
@@ -3859,24 +4153,34 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3859
4153
  diagnostics.push({ param: messageParam, action: "mapped", reason: "agent_message_plaintext_delivery" });
3860
4154
  return;
3861
4155
  }
3862
- if (item.encrypted_content != null)
3863
- fail("unsupported_content", "Encrypted content cannot cross protocols", `${messageParam}.encrypted_content`);
4156
+ const encrypted = item.encrypted_content != null;
4157
+ if (encrypted) {
4158
+ const param = `${messageParam}.encrypted_content`;
4159
+ if (!allowLossyContinuation || item.type !== "reasoning" && item.type !== "function_call")
4160
+ fail("unsupported_content", "Encrypted content cannot cross protocols", param);
4161
+ atParam(param, () => string(item.encrypted_content, "encrypted content", true));
4162
+ diagnostics.push({ param, action: "omitted", reason: "chat_opaque_history_content_unavailable" });
4163
+ }
3864
4164
  if (item.type === "compaction")
3865
4165
  fail("unsupported_content", "Encrypted reasoning and compaction cannot be restored");
3866
4166
  if (item.type === "item_reference")
3867
4167
  fail("unresolved_reference", "Input item references must be resolved before conversion");
3868
4168
  if (item.type === "reasoning") {
3869
- if (protocol !== "chat_completions" || !(capabilities.reasoningHistory || capabilities.reasoningEffort))
3870
- fail("unsupported_reasoning", "Reasoning history requires an explicit compatible reasoning capability");
3871
- if (item.content != null)
4169
+ if (item.content != null && !(encrypted && Array.isArray(item.content) && !item.content.length))
3872
4170
  fail("unsupported_reasoning", "Reasoning content requires an explicit history mapping", `${messageParam}.content`);
3873
- const summary = list(item.summary, "reasoning summary");
3874
- const text = summary.map((part) => {
4171
+ const summaryParam = `${messageParam}.summary`;
4172
+ const summary = encrypted && item.summary === undefined ? [] : atParam(summaryParam, () => list(item.summary, "reasoning summary"));
4173
+ const text = summary.map((part, index) => atParam(`${summaryParam}[${index}]`, () => {
3875
4174
  const p = record(part, "reasoning summary");
3876
4175
  if (p.type !== "summary_text")
3877
4176
  fail("unsupported_reasoning", "Unknown reasoning summary");
3878
4177
  return string(p.text, "summary text");
3879
- }).join("");
4178
+ })).join("");
4179
+ if (encrypted && !text)
4180
+ return;
4181
+ checkPendingToolHistory(item, false);
4182
+ if (protocol !== "chat_completions" || !(capabilities.reasoningHistory || capabilities.reasoningEffort))
4183
+ fail("unsupported_reasoning", "Reasoning history requires an explicit compatible reasoning capability");
3880
4184
  if (options.preserveContentOrder)
3881
4185
  addMessage({ role: "assistant", content: null, reasoning_content: text, ...item.id === undefined ? {} : { id: string(item.id, "item.id", true) } });
3882
4186
  else
@@ -3886,16 +4190,30 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3886
4190
  if (item.type === "function_call" || item.type === "custom_tool_call") {
3887
4191
  const custom = item.type === "custom_tool_call";
3888
4192
  validateEncryptedFunctionArgs(item, capabilities.agentMessageDelivery, messageParam);
4193
+ if (encrypted && item.status !== undefined && item.status !== "completed")
4194
+ fail("invalid_tool_history", "Encrypted tool history requires a completed function call", `${messageParam}.status`);
3889
4195
  const id = string(item.call_id, "call_id", true);
3890
4196
  if (callIds.has(id))
3891
4197
  fail("invalid_tool_history", "Duplicate tool call identifier");
4198
+ const previous = chat.at(-1);
4199
+ if (encrypted && callIds.size !== answered.size) {
4200
+ const adjacent = previous?.role === "assistant" ? previous.tool_calls?.length ?? 0 : 0;
4201
+ if (adjacent !== callIds.size - answered.size)
4202
+ fail("invalid_tool_history", "Encrypted function call cannot join a split tool batch", `${messageParam}.call_id`);
4203
+ }
3892
4204
  callIds.add(id);
3893
- const args = custom ? JSON.stringify({ input: string(item.input, "custom input") }) : string(item.arguments, "arguments");
3894
- bounded(args, budget.maxArgumentBytes, "arguments");
3895
- argumentObject(args);
4205
+ if (hasCompaction || encrypted)
4206
+ callsAwaitingResult.set(id, { param: `${messageParam}.call_id`, outputType: custom ? "custom_tool_call_output" : "function_call_output" });
4207
+ if (encrypted)
4208
+ encryptedToolBatch ??= `${messageParam}.call_id`;
4209
+ const args = atParam(encrypted ? `${messageParam}.arguments` : messageParam, () => {
4210
+ const text = custom ? JSON.stringify({ input: string(item.input, "custom input") }) : string(item.arguments, "arguments");
4211
+ bounded(text, budget.maxArgumentBytes, "arguments");
4212
+ argumentObject(text);
4213
+ return text;
4214
+ });
3896
4215
  const call = { id, type: "function", function: { name: resolve(item, custom), arguments: args } };
3897
4216
  callToolNames.set(id, String(item.name));
3898
- const previous = chat.at(-1);
3899
4217
  if (previous?.role === "assistant" && !options.preserveContentOrder) {
3900
4218
  previous.tool_calls = [...previous.tool_calls ?? [], call];
3901
4219
  if (pendingReasoning)
@@ -3909,6 +4227,10 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3909
4227
  const id = string(item.call_id, "call_id", true);
3910
4228
  if (!callIds.has(id) || answered.has(id))
3911
4229
  fail("invalid_tool_history", "Unmatched or duplicate tool result");
4230
+ const pending = callsAwaitingResult.get(id);
4231
+ if (pending && item.type !== pending.outputType)
4232
+ fail("invalid_tool_history", "Tool result type must match the corresponding call", `${messageParam}.type`);
4233
+ callsAwaitingResult.delete(id);
3912
4234
  answered.add(id);
3913
4235
  if (Array.isArray(item.output) && item.output.length > budget.maxItems && item.output.some((part) => part && typeof part === "object" && part.type === "input_image"))
3914
4236
  fail("resource_limit", "Too many tool output content parts", `${messageParam}.output`);
@@ -3927,6 +4249,7 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3927
4249
  }
3928
4250
  addMessage({ role: "tool", tool_call_id: id, content: output, ...item.is_error === true ? { is_error: true } : {} });
3929
4251
  if (callIds.size === answered.size) {
4252
+ encryptedToolBatch = undefined;
3930
4253
  for (const instruction of deferredInstructions) {
3931
4254
  messageParam = instruction.param;
3932
4255
  addMessage(instruction.message);
@@ -3965,6 +4288,11 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3965
4288
  }
3966
4289
  addMessage(message);
3967
4290
  });
4291
+ const missingResult = callsAwaitingResult.values().next().value;
4292
+ if (missingResult)
4293
+ fail("invalid_tool_history", "Tool call requires a matching result", missingResult.param);
4294
+ if (encryptedToolBatch)
4295
+ fail("invalid_tool_history", "All calls in the encrypted tool batch require matching results", encryptedToolBatch);
3968
4296
  if (pendingReasoning)
3969
4297
  fail("unsupported_reasoning", "Orphan reasoning history cannot be represented");
3970
4298
  if (deferredInstructions.length)
@@ -4519,251 +4847,12 @@ function encodeResponsesResult(raw, protocol, model, toolNames = new Map, config
4519
4847
  fail("missing_terminal", "JSON response has no terminal result");
4520
4848
  return record(end.response, "Responses result");
4521
4849
  }
4522
- // packages/llms/src/protocol-session/gemini.ts
4523
- import { createHash } from "crypto";
4524
-
4525
- // packages/llms/src/protocol-session/validation.ts
4526
- function fields2(value, allowed, path, code = "unsupported_request") {
4527
- for (const key of Object.keys(value))
4528
- if (!allowed.includes(key))
4529
- fail(code, "Field cannot be represented by the target protocol", path ? `${path}.${key}` : key);
4530
- }
4531
- function bool(value, path) {
4532
- if (typeof value !== "boolean")
4533
- fail("invalid_payload", "Expected a boolean", path);
4534
- return value;
4535
- }
4536
- function integer(value, path, min = 0) {
4537
- if (!Number.isSafeInteger(value) || value < min)
4538
- fail("invalid_payload", "Expected an integer in the supported range", path);
4539
- return value;
4540
- }
4541
- function textParts(raw, path, style, role) {
4542
- if (typeof raw === "string")
4543
- return [{ type: "input_text", text: raw }];
4544
- return list(raw, path).map((rawPart, index) => {
4545
- const p = record(rawPart, path), at = `${path}[${index}]`;
4546
- if (style === "gemini") {
4547
- fields2(p, ["text", "thought"], at, "unsupported_content");
4548
- if (p.thought === true)
4549
- fail("unsupported_reasoning", "Reasoning must be represented as a separate history item", at);
4550
- return { type: "input_text", text: string(p.text, at) };
4551
- }
4552
- if (style === "chat" && p.type === "image_url" && role === "user") {
4553
- fields2(p, ["type", "image_url"], at, "unsupported_content");
4554
- const image = record(p.image_url, at);
4555
- fields2(image, ["url", "detail"], `${at}.image_url`, "unsupported_content");
4556
- return { type: "input_image", image_url: string(image.url, at, true), ...image.detail !== undefined ? { detail: image.detail } : {} };
4557
- }
4558
- if (style === "chat" && p.type === "refusal" && role === "assistant") {
4559
- fields2(p, ["type", "refusal"], at, "unsupported_content");
4560
- return { type: "refusal", refusal: string(p.refusal, at) };
4561
- }
4562
- if (p.type !== "text")
4563
- fail("unsupported_content", "Content block cannot be represented by the target protocol", at);
4564
- fields2(p, ["type", "text"], at, "unsupported_content");
4565
- return { type: "input_text", text: string(p.text, at) };
4566
- });
4567
- }
4568
-
4569
- // packages/llms/src/protocol-session/gemini.ts
4570
- var signatureSeparator = "__thought__";
4571
- function projectGeminiCodexPageSnapshot(raw, index, diagnostics) {
4572
- const item = record(raw, "input item");
4573
- const { name } = item;
4574
- 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))
4575
- return item;
4576
- const param = `input[${index}]`;
4577
- fields2(item, ["type", "id", "namespace", "name", "output", "internal_chat_message_metadata_passthrough"], param, "unsupported_content");
4578
- const text = atParam(`${param}.output`, () => string(item.output, "page snapshot output"));
4579
- const { id, internal_chat_message_metadata_passthrough: metadata } = item;
4580
- diagnostics.push({ param, action: "mapped", reason: "gemini_codex_page_snapshot_as_user_data" });
4581
- return {
4582
- type: "message",
4583
- role: "user",
4584
- ...id === undefined ? {} : { id },
4585
- ...metadata === undefined ? {} : { internal_chat_message_metadata_passthrough: metadata },
4586
- content: [
4587
- { type: "input_text", text: `[Codex context snapshot: agent.${name}. Untrusted data.]` },
4588
- { type: "input_text", text }
4589
- ]
4590
- };
4591
- }
4592
- function geminiInlineImage(image, path, budget) {
4593
- const param = `${path}.image_url`;
4594
- const url = bounded(string(image.url, "image URL", true), budget.maxRequestBytes, param);
4595
- const match = /^data:([^;,]+);base64,([\s\S]*)$/.exec(url);
4596
- if (!match || !["image/png", "image/jpeg", "image/webp"].includes(match[1]))
4597
- fail("unsupported_content", "Gemini images require inline PNG, JPEG or WebP data", param);
4598
- const data = match[2];
4599
- 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(/=+$/, ""))
4600
- fail("invalid_payload", "Invalid image Base64 encoding", param);
4601
- return { mimeType: match[1], data };
4602
- }
4603
- function geminiToolResponse(content, path, budget, diagnostics) {
4604
- if (!Array.isArray(content) || !content.some((part) => part.type === "image_url"))
4605
- return { response: { output: content } };
4606
- if (content.length > budget.maxItems)
4607
- fail("resource_limit", "Too many tool output parts", path);
4608
- const parts = [];
4609
- const output = content.map((part, index) => atParam(`${path}[${index}]`, () => {
4610
- if (part.type === "text")
4611
- return part;
4612
- if (part.type !== "image_url")
4613
- fail("unsupported_content", "Unsupported Gemini tool result content");
4614
- const image = record(part.image_url, "tool image");
4615
- const inlineData = geminiInlineImage(image, `${path}[${index}]`, budget);
4616
- const displayName = `tool-image-${index}.${inlineData.mimeType.slice("image/".length)}`;
4617
- parts.push({ inlineData: { ...inlineData, displayName } });
4618
- if (image.detail !== undefined)
4619
- diagnostics.push({ param: `${path}[${index}].detail`, action: "omitted", reason: "gemini_tool_image_detail_unavailable" });
4620
- return { $ref: displayName };
4621
- }));
4622
- return { response: { output }, parts };
4623
- }
4624
- function checkedSignature(value, maxBytes) {
4625
- const signature = bounded(string(value, "thoughtSignature", true), maxBytes, "thoughtSignature");
4626
- 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(/=+$/, ""))
4627
- fail("invalid_tool_arguments", "Invalid Gemini thought signature encoding", "thoughtSignature");
4628
- return signature;
4629
- }
4630
- var envelopePrefix = "bungee_gemini:";
4631
- var geminiEnvelopeBytes = (payloadBytes) => envelopePrefix.length + Math.ceil(payloadBytes * 4 / 3);
4632
- var geminiTextHash = (text) => createHash("sha256").update(text).digest("base64url");
4633
- function geminiSignatureItem(items, budget) {
4634
- const payload = serialized({ version: 1, items }, budget.maxArgumentBytes, "Gemini signatures");
4635
- return {
4636
- type: "reasoning",
4637
- id: `rs_gemini_${crypto.randomUUID().replaceAll("-", "")}`,
4638
- summary: [],
4639
- encrypted_content: bounded(envelopePrefix + Buffer.from(payload).toString("base64url"), budget.maxArgumentBytes, "Gemini signatures")
4640
- };
4641
- }
4642
- function readGeminiSignatures(item, budget) {
4643
- fields2(item, ["type", "id", "summary", "encrypted_content", "status"], "Gemini signatures", "unsupported_reasoning");
4644
- if (item.type !== "reasoning" || list(item.summary, "summary").length)
4645
- fail("unsupported_reasoning", "Invalid Gemini signature carrier");
4646
- string(item.id, "signature item id", true);
4647
- const opaque = bounded(string(item.encrypted_content, "encrypted_content", true), budget.maxArgumentBytes, "Gemini signatures");
4648
- if (!opaque.startsWith(envelopePrefix))
4649
- fail("unsupported_reasoning", "Native encrypted reasoning cannot be restored to Gemini");
4650
- const encoded = opaque.slice(envelopePrefix.length), bytes = Buffer.from(encoded, "base64url");
4651
- if (!encoded || bytes.toString("base64url") !== encoded)
4652
- fail("unsupported_reasoning", "Invalid Gemini signature carrier encoding");
4653
- let raw;
4654
- try {
4655
- raw = JSON.parse(bytes.toString("utf8"));
4656
- } catch {
4657
- fail("unsupported_reasoning", "Invalid Gemini signature carrier JSON");
4658
- }
4659
- const body = record(raw, "Gemini signatures");
4660
- fields2(body, ["version", "items"], "Gemini signatures", "unsupported_reasoning");
4661
- if (body.version !== 1)
4662
- fail("unsupported_reasoning", "Unknown Gemini signature format");
4663
- const ids = new Set;
4664
- let partCount = 0;
4665
- const result = list(body.items, "signature items").map((raw) => {
4666
- const item = record(raw, "signature item");
4667
- fields2(item, ["id", "thought", "parts"], "signature item", "unsupported_reasoning");
4668
- const id = string(item.id, "signed item id", true);
4669
- if (ids.has(id) || typeof item.thought !== "boolean")
4670
- fail("unsupported_reasoning", "Invalid signed item identity");
4671
- ids.add(id);
4672
- const parts = list(item.parts, "signed parts").map((raw) => {
4673
- if (++partCount > budget.maxItems)
4674
- fail("resource_limit", "Too many signed Gemini parts");
4675
- const part = record(raw, "signed part");
4676
- fields2(part, ["length", "hash", "signature", "textAbsent"], "signed part", "unsupported_reasoning");
4677
- const length = integer(part.length, "signed part length"), hash = string(part.hash, "signed part hash", true);
4678
- if (!/^[A-Za-z0-9_-]{43}$/.test(hash))
4679
- fail("unsupported_reasoning", "Invalid signed part hash");
4680
- const signature = part.signature === undefined ? undefined : checkedSignature(part.signature, budget.maxArgumentBytes);
4681
- if (part.textAbsent !== undefined && (part.textAbsent !== true || length !== 0 || signature === undefined))
4682
- fail("unsupported_reasoning", "Invalid empty signed part");
4683
- return { length, hash, ...signature === undefined ? {} : { signature }, ...part.textAbsent ? { textAbsent: true } : {} };
4684
- });
4685
- if (!parts.some((p) => p.signature !== undefined))
4686
- fail("unsupported_reasoning", "Signature carrier has no signature");
4687
- return { id, thought: item.thought, parts };
4688
- });
4689
- if (!result.length || result.length > budget.maxItems)
4690
- fail("unsupported_reasoning", "Invalid signature item count");
4691
- return result;
4692
- }
4693
- function restoreGeminiHistory(input, budget) {
4694
- const original = typeof input === "string" ? [] : list(input, "input").map((raw) => record(raw, "input item"));
4695
- const carriers = new Set, parts = new Map, ids = new Map;
4696
- original.forEach((item, i) => {
4697
- if (typeof item.id === "string") {
4698
- if (ids.has(item.id))
4699
- fail("invalid_tool_history", "Duplicate history item id", "input.id");
4700
- ids.set(item.id, i);
4701
- }
4702
- });
4703
- original.forEach((carrier, index) => {
4704
- if (carrier.encrypted_content == null)
4705
- return;
4706
- const signed = readGeminiSignatures(carrier, budget);
4707
- carriers.add(carrier);
4708
- let previous = -1;
4709
- for (const item of signed) {
4710
- const at = ids.get(item.id);
4711
- if (at === undefined || at >= index || at <= previous || parts.has(item.id))
4712
- fail("unsupported_reasoning", "Signed history reference is missing or ambiguous");
4713
- previous = at;
4714
- const source = original[at];
4715
- if (item.thought ? source.type !== "reasoning" || source.encrypted_content != null : source.role !== "assistant" || source.type !== undefined && source.type !== "message")
4716
- fail("unsupported_reasoning", "Signed history item kind changed");
4717
- const content = item.thought ? list(source.summary, "summary") : typeof source.content === "string" ? [{ type: "output_text", text: source.content }] : list(source.content, "content");
4718
- const text = content.map((raw) => {
4719
- const p = record(raw, "signed text");
4720
- if (p.type !== (item.thought ? "summary_text" : "output_text") && !(p.type === "input_text" && !item.thought))
4721
- fail("unsupported_reasoning", "Signed history content kind changed");
4722
- return string(p.text, "signed text");
4723
- }).join("");
4724
- let offset = 0;
4725
- const restored = item.parts.map((part) => {
4726
- const value = text.slice(offset, offset + part.length);
4727
- offset += part.length;
4728
- if (value.length !== part.length || geminiTextHash(value) !== part.hash)
4729
- fail("unsupported_reasoning", "Signed history text changed");
4730
- return { ...part.textAbsent ? {} : { text: value }, ...item.thought ? { thought: true } : {}, ...part.signature === undefined ? {} : { thoughtSignature: part.signature } };
4731
- });
4732
- if (offset !== text.length)
4733
- fail("unsupported_reasoning", "Signed history text was not fully consumed");
4734
- parts.set(item.id, restored);
4735
- }
4736
- });
4737
- return {
4738
- input: typeof input === "string" ? input : original.filter((item) => !carriers.has(item)),
4739
- parts,
4740
- canonicalHistory(decoded) {
4741
- if (!carriers.size)
4742
- return decoded;
4743
- let next = 0;
4744
- return original.flatMap((item) => carriers.has(item) ? [item] : item.type === "additional_tools" ? [] : [decoded[next++]]);
4745
- }
4746
- };
4747
- }
4748
- function encodeGeminiCallId(id, signature, maxBytes) {
4749
- if (id.includes(signatureSeparator))
4750
- fail("invalid_tool_arguments", "Gemini call id contains the signature separator", "functionCall.id");
4751
- return signature === undefined ? id : `${id}${signatureSeparator}${checkedSignature(signature, maxBytes)}`;
4752
- }
4753
- function decodeGeminiCallId(value, maxBytes) {
4754
- const separator = value.indexOf(signatureSeparator);
4755
- if (separator < 0)
4756
- return { id: value };
4757
- const id = string(value.slice(0, separator), "functionCall.id", true);
4758
- return { id, thoughtSignature: checkedSignature(value.slice(separator + signatureSeparator.length), maxBytes) };
4759
- }
4760
-
4761
4850
  // packages/llms/src/protocol-session/schema.ts
4762
4851
  function geminiSchemaToJson(raw, path, code = "unsupported_request", depth = 0) {
4763
4852
  if (depth > 64)
4764
4853
  fail("resource_limit", "Schema nesting exceeds the conversion limit", path);
4765
4854
  const s = record(raw, path);
4766
- 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);
4855
+ 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);
4767
4856
  const out = {};
4768
4857
  if (s.type !== undefined) {
4769
4858
  const types = { STRING: "string", NUMBER: "number", INTEGER: "integer", BOOLEAN: "boolean", ARRAY: "array", OBJECT: "object", NULL: "null" };
@@ -4803,19 +4892,19 @@ function message(input, role, content, style, path) {
4803
4892
  function toolDefinition(raw, style, path) {
4804
4893
  const t = record(raw, path);
4805
4894
  if (style === "chat") {
4806
- fields2(t, t.type === "custom" ? ["type", "custom"] : ["type", "function"], path, "unsupported_tool");
4895
+ fields(t, t.type === "custom" ? ["type", "custom"] : ["type", "function"], path, "unsupported_tool");
4807
4896
  if (t.type === "custom") {
4808
4897
  const custom = record(t.custom, `${path}.custom`);
4809
- fields2(custom, ["name", "description", "format"], `${path}.custom`, "unsupported_tool");
4898
+ fields(custom, ["name", "description", "format"], `${path}.custom`, "unsupported_tool");
4810
4899
  return { type: "custom", ...custom };
4811
4900
  }
4812
4901
  if (t.type !== "function")
4813
4902
  fail("unsupported_tool", "Unsupported tool kind", `${path}.type`);
4814
4903
  const fn = record(t.function, path);
4815
- fields2(fn, ["name", "description", "parameters", "strict"], `${path}.function`, "unsupported_tool");
4904
+ fields(fn, ["name", "description", "parameters", "strict"], `${path}.function`, "unsupported_tool");
4816
4905
  return { type: "function", ...fn };
4817
4906
  }
4818
- fields2(t, style === "anthropic" ? ["name", "description", "input_schema", "strict"] : ["name", "description", "parametersJsonSchema", "parameters"], path, "unsupported_tool");
4907
+ fields(t, style === "anthropic" ? ["name", "description", "input_schema", "strict"] : ["name", "description", "parametersJsonSchema", "parameters"], path, "unsupported_tool");
4819
4908
  if (t.parameters !== undefined && t.parametersJsonSchema !== undefined)
4820
4909
  fail("unsupported_tool", "Ambiguous schema dialect", path);
4821
4910
  return {
@@ -4838,13 +4927,13 @@ function canonicalRequest(raw, protocol, model) {
4838
4927
  };
4839
4928
  if (protocol === "chat_completions") {
4840
4929
  const callKinds = new Map;
4841
- 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"], "");
4930
+ 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"], "");
4842
4931
  if (b.max_tokens !== undefined && b.max_completion_tokens !== undefined)
4843
4932
  fail("unsupported_request", "Ambiguous token limits", "max_tokens");
4844
4933
  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" });
4845
4934
  for (const [index, rawMessage] of list(b.messages, "messages").entries()) {
4846
4935
  const m = record(rawMessage, "message"), path = `messages[${index}]`;
4847
- fields2(m, ["role", "content", "tool_calls", "tool_call_id", "reasoning_content", "reasoning", "refusal", "name"], path, "unsupported_content");
4936
+ fields(m, ["role", "content", "tool_calls", "tool_call_id", "reasoning_content", "reasoning", "refusal", "name"], path, "unsupported_content");
4848
4937
  if (m.name !== undefined)
4849
4938
  fail("unsupported_content", "Named messages cannot be represented faithfully", `${path}.name`);
4850
4939
  const role = string(m.role, "role", true);
@@ -4879,12 +4968,12 @@ function canonicalRequest(raw, protocol, model) {
4879
4968
  fail("invalid_tool_history", "Tool calls require assistant role", path);
4880
4969
  for (const [j, rawCall] of list(m.tool_calls, "tool_calls").entries()) {
4881
4970
  const c = record(rawCall, "tool call"), at = `${path}.tool_calls[${j}]`;
4882
- fields2(c, ["id", "type", "function", "custom"], at, "unsupported_tool");
4971
+ fields(c, ["id", "type", "function", "custom"], at, "unsupported_tool");
4883
4972
  const custom = c.type === "custom";
4884
4973
  if (!custom && c.type !== "function")
4885
4974
  fail("unsupported_tool", "Unknown call type", at);
4886
4975
  const fn = record(custom ? c.custom : c.function, "tool call");
4887
- fields2(fn, custom ? ["name", "input"] : ["name", "arguments"], at, "unsupported_tool");
4976
+ fields(fn, custom ? ["name", "input"] : ["name", "arguments"], at, "unsupported_tool");
4888
4977
  callKinds.set(string(c.id, "id", true), custom);
4889
4978
  input.push({
4890
4979
  type: custom ? "custom_tool_call" : "function_call",
@@ -4903,9 +4992,9 @@ function canonicalRequest(raw, protocol, model) {
4903
4992
  out.tool_choice = c;
4904
4993
  else {
4905
4994
  const choice = record(c, "tool_choice");
4906
- fields2(choice, ["type", "function", "custom"], "tool_choice");
4995
+ fields(choice, ["type", "function", "custom"], "tool_choice");
4907
4996
  const fn = record(choice.function ?? choice.custom, "tool_choice");
4908
- fields2(fn, ["name"], "tool_choice.function");
4997
+ fields(fn, ["name"], "tool_choice.function");
4909
4998
  out.tool_choice = { type: choice.type, name: fn.name };
4910
4999
  }
4911
5000
  }
@@ -4913,19 +5002,19 @@ function canonicalRequest(raw, protocol, model) {
4913
5002
  out.reasoning = { effort: b.reasoning_effort };
4914
5003
  if (b.response_format !== undefined) {
4915
5004
  const format = record(b.response_format, "response_format");
4916
- fields2(format, ["type", "json_schema"], "response_format");
5005
+ fields(format, ["type", "json_schema"], "response_format");
4917
5006
  out.text = { format: format.type === "json_schema" ? { type: "json_schema", ...record(format.json_schema, "json_schema") } : format };
4918
5007
  }
4919
5008
  return out;
4920
5009
  }
4921
5010
  if (protocol === "anthropic_messages") {
4922
- fields2(b, ["model", "messages", "system", "tools", "tool_choice", "stream", "temperature", "top_p", "max_tokens", "metadata", "stop_sequences", "thinking", "output_config"], "");
5011
+ fields(b, ["model", "messages", "system", "tools", "tool_choice", "stream", "temperature", "top_p", "max_tokens", "metadata", "stop_sequences", "thinking", "output_config"], "");
4923
5012
  copy({ stream: "stream", temperature: "temperature", top_p: "top_p", max_tokens: "max_output_tokens", metadata: "metadata", stop_sequences: "stop" });
4924
5013
  if (b.system !== undefined)
4925
5014
  message(input, "system", b.system, "anthropic", "system");
4926
5015
  for (const [index, rawMessage] of list(b.messages, "messages").entries()) {
4927
5016
  const m = record(rawMessage, "message"), path = `messages[${index}]`;
4928
- fields2(m, ["role", "content"], path, "unsupported_content");
5017
+ fields(m, ["role", "content"], path, "unsupported_content");
4929
5018
  if (m.role !== "user" && m.role !== "assistant")
4930
5019
  fail("unsupported_content", "Anthropic messages require user or assistant role", `${path}.role`);
4931
5020
  if (typeof m.content === "string") {
@@ -4937,15 +5026,15 @@ function canonicalRequest(raw, protocol, model) {
4937
5026
  if (p.type === "tool_use") {
4938
5027
  if (m.role !== "assistant")
4939
5028
  fail("invalid_tool_history", "Tool calls require assistant role", at);
4940
- fields2(p, ["type", "id", "name", "input"], at, "unsupported_content");
5029
+ fields(p, ["type", "id", "name", "input"], at, "unsupported_content");
4941
5030
  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)) });
4942
5031
  } else if (p.type === "tool_result") {
4943
5032
  if (m.role !== "user")
4944
5033
  fail("invalid_tool_history", "Tool results require user role", at);
4945
- fields2(p, ["type", "tool_use_id", "content", "is_error"], at, "unsupported_content");
5034
+ fields(p, ["type", "tool_use_id", "content", "is_error"], at, "unsupported_content");
4946
5035
  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) } : {} });
4947
5036
  } else if (p.type === "thinking") {
4948
- fields2(p, ["type", "thinking", "signature"], at, "unsupported_reasoning");
5037
+ fields(p, ["type", "thinking", "signature"], at, "unsupported_reasoning");
4949
5038
  if (p.signature != null)
4950
5039
  fail("unsupported_reasoning", "Provider-bound reasoning signatures cannot cross protocols", `${at}.signature`);
4951
5040
  if (m.role !== "assistant")
@@ -4959,7 +5048,7 @@ function canonicalRequest(raw, protocol, model) {
4959
5048
  out.tools = list(b.tools, "tools").map((t, i) => toolDefinition(t, "anthropic", `tools[${i}]`));
4960
5049
  if (b.tool_choice !== undefined) {
4961
5050
  const c = record(b.tool_choice, "tool_choice");
4962
- fields2(c, ["type", "name", "disable_parallel_tool_use"], "tool_choice");
5051
+ fields(c, ["type", "name", "disable_parallel_tool_use"], "tool_choice");
4963
5052
  if (c.type === "tool")
4964
5053
  out.tool_choice = { type: "function", name: c.name };
4965
5054
  else if (["auto", "none", "any"].includes(String(c.type)))
@@ -4971,7 +5060,7 @@ function canonicalRequest(raw, protocol, model) {
4971
5060
  }
4972
5061
  if (b.thinking !== undefined) {
4973
5062
  const t = record(b.thinking, "thinking");
4974
- fields2(t, ["type", "budget_tokens"], "thinking", "unsupported_reasoning");
5063
+ fields(t, ["type", "budget_tokens"], "thinking", "unsupported_reasoning");
4975
5064
  if (!["enabled", "adaptive", "disabled"].includes(String(t.type)))
4976
5065
  fail("unsupported_reasoning", "Unknown thinking mode", "thinking.type");
4977
5066
  if (t.type === "enabled")
@@ -4982,12 +5071,12 @@ function canonicalRequest(raw, protocol, model) {
4982
5071
  }
4983
5072
  if (b.output_config !== undefined) {
4984
5073
  const c = record(b.output_config, "output_config");
4985
- fields2(c, ["effort", "format"], "output_config");
5074
+ fields(c, ["effort", "format"], "output_config");
4986
5075
  if (c.effort !== undefined)
4987
5076
  out.reasoning = { effort: c.effort };
4988
5077
  if (c.format !== undefined) {
4989
5078
  const f = record(c.format, "format");
4990
- fields2(f, ["type", "schema"], "output_config.format");
5079
+ fields(f, ["type", "schema"], "output_config.format");
4991
5080
  if (f.type !== "json_schema")
4992
5081
  fail("unsupported_request", "Unknown structured output type", "output_config.format.type");
4993
5082
  out.text = { format: { type: "json_schema", name: "response", schema: f.schema } };
@@ -4995,12 +5084,12 @@ function canonicalRequest(raw, protocol, model) {
4995
5084
  }
4996
5085
  return out;
4997
5086
  }
4998
- fields2(b, ["contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "model", "stream"], "");
5087
+ fields(b, ["contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "model", "stream"], "");
4999
5088
  if (b.stream !== undefined)
5000
5089
  out.stream = b.stream;
5001
5090
  if (b.systemInstruction !== undefined) {
5002
5091
  const s = record(b.systemInstruction, "systemInstruction");
5003
- fields2(s, ["role", "parts"], "systemInstruction");
5092
+ fields(s, ["role", "parts"], "systemInstruction");
5004
5093
  if (s.role !== undefined && s.role !== "system")
5005
5094
  fail("unsupported_content", "Invalid system role", "systemInstruction.role");
5006
5095
  message(input, "system", s.parts, "gemini", "systemInstruction");
@@ -5010,12 +5099,12 @@ function canonicalRequest(raw, protocol, model) {
5010
5099
  for (const [index, rawContent] of list(b.contents, "contents").entries()) {
5011
5100
  const original = record(rawContent, "content"), path = `contents[${index}]`;
5012
5101
  const c = { ...original, role: original.role ?? "user" };
5013
- fields2(c, ["role", "parts"], path, "unsupported_content");
5102
+ fields(c, ["role", "parts"], path, "unsupported_content");
5014
5103
  if (c.role !== "user" && c.role !== "model")
5015
5104
  fail("unsupported_content", "Gemini contents require user or model role", `${path}.role`);
5016
5105
  for (const [j, rawPart] of list(c.parts, "parts").entries()) {
5017
5106
  const p = record(rawPart, "part"), at = `${path}.parts[${j}]`;
5018
- fields2(p, ["text", "thought", "functionCall", "functionResponse", "thoughtSignature"], at, "unsupported_content");
5107
+ fields(p, ["text", "thought", "functionCall", "functionResponse", "thoughtSignature"], at, "unsupported_content");
5019
5108
  if (p.thoughtSignature !== undefined)
5020
5109
  fail("unsupported_reasoning", "Provider-bound thought signatures cannot cross protocols", `${at}.thoughtSignature`);
5021
5110
  if ([p.text, p.functionCall, p.functionResponse].filter((v) => v !== undefined).length !== 1)
@@ -5024,7 +5113,7 @@ function canonicalRequest(raw, protocol, model) {
5024
5113
  if (c.role !== "model")
5025
5114
  fail("invalid_tool_history", "Function calls require model role", at);
5026
5115
  const f = record(p.functionCall, at);
5027
- fields2(f, ["name", "args", "id"], `${at}.functionCall`, "unsupported_tool");
5116
+ fields(f, ["name", "args", "id"], `${at}.functionCall`, "unsupported_tool");
5028
5117
  const name = string(f.name, at, true), id = f.id === undefined ? `call_gemini_${serial++}` : string(f.id, at, true);
5029
5118
  if (calls.has(id))
5030
5119
  fail("invalid_tool_history", "Duplicate tool call id", at);
@@ -5034,7 +5123,7 @@ function canonicalRequest(raw, protocol, model) {
5034
5123
  if (c.role !== "user")
5035
5124
  fail("invalid_tool_history", "Function results require user role", at);
5036
5125
  const f = record(p.functionResponse, at);
5037
- fields2(f, ["name", "response", "id"], `${at}.functionResponse`, "unsupported_tool");
5126
+ fields(f, ["name", "response", "id"], `${at}.functionResponse`, "unsupported_tool");
5038
5127
  const matches = [...calls.values()].filter((v) => v.name === f.name);
5039
5128
  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);
5040
5129
  if (calls.get(id)?.name !== f.name)
@@ -5053,7 +5142,7 @@ function canonicalRequest(raw, protocol, model) {
5053
5142
  const tools = [];
5054
5143
  for (const [i, rawTool] of list(b.tools, "tools").entries()) {
5055
5144
  const t = record(rawTool, "tool");
5056
- fields2(t, ["functionDeclarations"], `tools[${i}]`, "unsupported_tool");
5145
+ fields(t, ["functionDeclarations"], `tools[${i}]`, "unsupported_tool");
5057
5146
  for (const [j, f] of list(t.functionDeclarations, "functionDeclarations").entries())
5058
5147
  tools.push(toolDefinition(f, "gemini", `tools[${i}].functionDeclarations[${j}]`));
5059
5148
  }
@@ -5061,9 +5150,9 @@ function canonicalRequest(raw, protocol, model) {
5061
5150
  }
5062
5151
  if (b.toolConfig !== undefined) {
5063
5152
  const config = record(b.toolConfig, "toolConfig");
5064
- fields2(config, ["functionCallingConfig"], "toolConfig");
5153
+ fields(config, ["functionCallingConfig"], "toolConfig");
5065
5154
  const c = record(config.functionCallingConfig, "functionCallingConfig");
5066
- fields2(c, ["mode", "allowedFunctionNames"], "toolConfig.functionCallingConfig");
5155
+ fields(c, ["mode", "allowedFunctionNames"], "toolConfig.functionCallingConfig");
5067
5156
  if (!["AUTO", "NONE", "ANY"].includes(String(c.mode)))
5068
5157
  fail("unsupported_tool_choice", "Unknown function calling mode", "toolConfig.functionCallingConfig.mode");
5069
5158
  if (c.allowedFunctionNames !== undefined) {
@@ -5076,7 +5165,7 @@ function canonicalRequest(raw, protocol, model) {
5076
5165
  }
5077
5166
  if (b.generationConfig !== undefined) {
5078
5167
  const c = record(b.generationConfig, "generationConfig");
5079
- fields2(c, ["temperature", "topP", "maxOutputTokens", "stopSequences", "candidateCount", "responseMimeType", "responseJsonSchema", "responseSchema", "thinkingConfig"], "generationConfig");
5168
+ fields(c, ["temperature", "topP", "maxOutputTokens", "stopSequences", "candidateCount", "responseMimeType", "responseJsonSchema", "responseSchema", "thinkingConfig"], "generationConfig");
5080
5169
  for (const [from, to] of Object.entries({ temperature: "temperature", topP: "top_p", maxOutputTokens: "max_output_tokens", stopSequences: "stop", candidateCount: "n" }))
5081
5170
  if (c[from] !== undefined)
5082
5171
  out[to] = c[from];
@@ -5094,7 +5183,7 @@ function canonicalRequest(raw, protocol, model) {
5094
5183
  }
5095
5184
  if (c.thinkingConfig !== undefined) {
5096
5185
  const t = record(c.thinkingConfig, "thinkingConfig");
5097
- fields2(t, ["thinkingBudget", "thinkingLevel", "includeThoughts"], "generationConfig.thinkingConfig", "unsupported_reasoning");
5186
+ fields(t, ["thinkingBudget", "thinkingLevel", "includeThoughts"], "generationConfig.thinkingConfig", "unsupported_reasoning");
5098
5187
  if (t.thinkingBudget !== undefined)
5099
5188
  integer(t.thinkingBudget, "generationConfig.thinkingConfig.thinkingBudget", -1);
5100
5189
  if (t.thinkingLevel !== undefined)
@@ -5106,7 +5195,10 @@ function canonicalRequest(raw, protocol, model) {
5106
5195
  }
5107
5196
  return out;
5108
5197
  }
5109
- function validateCanonical(b, context) {
5198
+ function validateCanonical(b, context, chatConfigurationUpdates) {
5199
+ const responsesToGemini = context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content";
5200
+ const allowLossyContinuation = chatConfigurationUpdates !== undefined;
5201
+ let configuration;
5110
5202
  for (const key of ["stream", "parallel_tool_calls", "store", "background"])
5111
5203
  if (b[key] !== undefined)
5112
5204
  bool(b[key], key);
@@ -5114,13 +5206,13 @@ function validateCanonical(b, context) {
5114
5206
  if (b[key] !== undefined && (typeof b[key] !== "number" || !Number.isFinite(b[key])))
5115
5207
  fail("invalid_payload", "Sampling value must be finite", key);
5116
5208
  if (b.tool_choice !== undefined && typeof b.tool_choice !== "string")
5117
- fields2(record(b.tool_choice, "tool_choice"), ["type", "name", "namespace"], "tool_choice", "unsupported_tool_choice");
5209
+ fields(record(b.tool_choice, "tool_choice"), ["type", "name", "namespace"], "tool_choice", "unsupported_tool_choice");
5118
5210
  if (b.text !== undefined) {
5119
5211
  const text = record(b.text, "text");
5120
- fields2(text, ["format", "verbosity"], "text");
5212
+ fields(text, ["format", "verbosity"], "text");
5121
5213
  if (text.format !== undefined) {
5122
5214
  const f = record(text.format, "text.format");
5123
- fields2(f, f.type === "json_schema" ? ["type", "name", "schema", "strict", "description"] : ["type"], "text.format");
5215
+ fields(f, f.type === "json_schema" ? ["type", "name", "schema", "strict", "description"] : ["type"], "text.format");
5124
5216
  if (!["text", "json_object", "json_schema"].includes(String(f.type)))
5125
5217
  fail("unsupported_request", "Unknown structured output format", "text.format.type");
5126
5218
  if (f.type === "json_schema") {
@@ -5136,21 +5228,40 @@ function validateCanonical(b, context) {
5136
5228
  const input = typeof b.input === "string" ? [] : list(b.input, "input");
5137
5229
  for (const [i, raw] of input.entries()) {
5138
5230
  const t = record(raw, "input item"), p = `input[${i}]`;
5231
+ if ((responsesToGemini || allowLossyContinuation) && t.type === "configuration_update") {
5232
+ fields(t, ["type", "reasoning"], p, "unsupported_content");
5233
+ const reasoning = atParam(`${p}.reasoning`, () => record(t.reasoning, "configuration reasoning"));
5234
+ fields(reasoning, ["effort"], `${p}.reasoning`, "unsupported_reasoning");
5235
+ const param = `${p}.reasoning.effort`;
5236
+ const effort = atParam(param, () => string(reasoning.effort, "configuration effort", true));
5237
+ const map = context.reasoningPolicy?.effortMap;
5238
+ const level = map && Object.hasOwn(map, effort) ? map[effort] : undefined;
5239
+ if (typeof level !== "string" || !level || responsesToGemini && !["minimal", "low", "medium", "high"].includes(level))
5240
+ fail("unsupported_reasoning", responsesToGemini ? "Configuration update requires an explicit Gemini level mapping" : "Configuration update requires an explicit Chat effort mapping", param);
5241
+ configuration = { effort, level, param };
5242
+ chatConfigurationUpdates?.add(t);
5243
+ continue;
5244
+ }
5139
5245
  if (t.type === "agent_message") {
5140
5246
  validateAgentMessage(t, p, context.capabilities?.limits);
5141
5247
  continue;
5142
5248
  }
5143
- 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"];
5144
- fields2(t, [...allowed, "internal_chat_message_metadata_passthrough"], p, "unsupported_content");
5249
+ if (allowLossyContinuation && isGeminiSignatureCarrier(t.encrypted_content))
5250
+ fail("unsupported_content", "Gemini signature carriers cannot cross into Chat", `${p}.encrypted_content`);
5251
+ if (allowLossyContinuation && t.type === "compaction")
5252
+ continue;
5253
+ 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"];
5254
+ const assistantPhase = allowLossyContinuation && (t.type === undefined || t.type === "message") && t.role === "assistant";
5255
+ fields(t, [...allowed, "internal_chat_message_metadata_passthrough", ...assistantPhase ? ["phase"] : []], p, "unsupported_content");
5145
5256
  if (t.is_error !== undefined)
5146
5257
  bool(t.is_error, `${p}.is_error`);
5147
- if (t.type === "reasoning")
5148
- for (const [j, part] of list(t.summary, "summary").entries())
5149
- fields2(record(part, "summary"), ["type", "text"], `${p}.summary[${j}]`, "unsupported_reasoning");
5258
+ if (t.type === "reasoning" && !(allowLossyContinuation && t.encrypted_content != null && t.summary === undefined))
5259
+ for (const [j, part] of atParam(`${p}.summary`, () => list(t.summary, "summary")).entries())
5260
+ atParam(`${p}.summary[${j}]`, () => fields(record(part, "summary"), ["type", "text"], `${p}.summary[${j}]`, "unsupported_reasoning"));
5150
5261
  if (Array.isArray(t.content))
5151
5262
  for (const [j, part] of t.content.entries()) {
5152
5263
  const c = record(part, "part");
5153
- fields2(c, c.type === "input_image" ? ["type", "image_url", "detail"] : c.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], `${p}.content[${j}]`, "unsupported_content");
5264
+ 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");
5154
5265
  if (context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content" && t.role === "user" && c.type === "input_image") {
5155
5266
  atParam(`${p}.content[${j}].image_url`, () => string(c.image_url, "image URL", true));
5156
5267
  if (c.detail !== undefined && (typeof c.detail !== "string" || !["auto", "low", "high"].includes(c.detail)))
@@ -5161,7 +5272,7 @@ function validateCanonical(b, context) {
5161
5272
  for (const [j, part] of t.output.entries())
5162
5273
  atParam(`${p}.output[${j}]`, () => {
5163
5274
  const c = record(part, "tool output part");
5164
- fields2(c, c.type === "input_image" ? ["type", "image_url", "detail"] : ["type", "text", "annotations"], `${p}.output[${j}]`, "unsupported_content");
5275
+ fields(c, c.type === "input_image" ? ["type", "image_url", "detail"] : ["type", "text", "annotations"], `${p}.output[${j}]`, "unsupported_content");
5165
5276
  if (c.type === "input_image") {
5166
5277
  atParam(`${p}.output[${j}].image_url`, () => string(c.image_url, "image URL", true));
5167
5278
  if (c.detail !== undefined && (typeof c.detail !== "string" || !["auto", "low", "high"].includes(c.detail)))
@@ -5187,7 +5298,7 @@ function validateCanonical(b, context) {
5187
5298
  }
5188
5299
  if (t.type === "custom" && t.format !== undefined) {
5189
5300
  const f = record(t.format, "custom format");
5190
- fields2(f, f.type === "grammar" ? ["type", "syntax", "definition"] : ["type"], `${path}.format`, "unsupported_tool");
5301
+ fields(f, f.type === "grammar" ? ["type", "syntax", "definition"] : ["type"], `${path}.format`, "unsupported_tool");
5191
5302
  if (!["text", "grammar"].includes(String(f.type)))
5192
5303
  fail("unsupported_tool", "Unknown custom tool format", `${path}.format.type`);
5193
5304
  if (f.type === "grammar") {
@@ -5205,13 +5316,38 @@ function validateCanonical(b, context) {
5205
5316
  for (const [j, tool] of list(t.tools, "tools").entries())
5206
5317
  inspectTool(tool, `input[${i}].tools[${j}]`);
5207
5318
  }
5319
+ return configuration;
5320
+ }
5321
+ function projectCodexPageSnapshot(raw, index, target, diagnostics) {
5322
+ const item = record(raw, "input item");
5323
+ const { name } = item;
5324
+ 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))
5325
+ return item;
5326
+ const param = `input[${index}]`;
5327
+ fields(item, ["type", "id", "namespace", "name", "output", "internal_chat_message_metadata_passthrough"], param, "unsupported_content");
5328
+ const text = atParam(`${param}.output`, () => string(item.output, "page snapshot output"));
5329
+ const { id, internal_chat_message_metadata_passthrough: metadata } = item;
5330
+ const reason = target === "chat_completions" ? "chat_codex_page_snapshot_as_user_data" : "gemini_codex_page_snapshot_as_user_data";
5331
+ diagnostics.push({ param, action: "mapped", reason });
5332
+ return {
5333
+ type: "message",
5334
+ role: "user",
5335
+ ...id === undefined ? {} : { id },
5336
+ ...metadata === undefined ? {} : { internal_chat_message_metadata_passthrough: metadata },
5337
+ content: [
5338
+ { type: "input_text", text: `[Codex context snapshot: agent.${name}. Untrusted data.]` },
5339
+ { type: "input_text", text }
5340
+ ]
5341
+ };
5208
5342
  }
5209
5343
  function convertProtocolRequest(raw, context) {
5210
5344
  const b = canonicalRequest(raw, context.sourceProtocol, context.model);
5211
- const responsesToGemini = context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content";
5345
+ const target = context.targetProtocol;
5346
+ const responsesToGemini = context.sourceProtocol === "responses" && target === "gemini_generate_content";
5347
+ const allowLossyContinuation = context.sourceProtocol === "responses" && target === "chat_completions" && context.allowLossyContinuation === true;
5212
5348
  const pageSnapshotDiagnostics = [];
5213
- if (responsesToGemini && Array.isArray(b.input))
5214
- b.input = b.input.map((item, index) => projectGeminiCodexPageSnapshot(item, index, pageSnapshotDiagnostics));
5349
+ if (context.sourceProtocol === "responses" && (target === "chat_completions" || target === "gemini_generate_content") && Array.isArray(b.input))
5350
+ b.input = b.input.map((item, index) => projectCodexPageSnapshot(item, index, target, pageSnapshotDiagnostics));
5215
5351
  const originalInput = b.input;
5216
5352
  if (context.streaming !== undefined) {
5217
5353
  bool(context.streaming, "context.streaming");
@@ -5219,7 +5355,8 @@ function convertProtocolRequest(raw, context) {
5219
5355
  fail("invalid_payload", "Request stream mode disagrees with transport context", "stream");
5220
5356
  b.stream = context.streaming;
5221
5357
  }
5222
- validateCanonical(b, context);
5358
+ const chatConfigurationUpdates = allowLossyContinuation ? new Set : undefined;
5359
+ const configuration = validateCanonical(b, context, chatConfigurationUpdates);
5223
5360
  const geminiHistory = responsesToGemini ? restoreGeminiHistory(b.input, limits(context.capabilities?.limits)) : undefined;
5224
5361
  if (geminiHistory)
5225
5362
  b.input = geminiHistory.input;
@@ -5238,16 +5375,19 @@ function convertProtocolRequest(raw, context) {
5238
5375
  fail("unsupported_reasoning", "Thinking mode requires an explicit target wire policy", "thinking");
5239
5376
  let mappedEffort;
5240
5377
  if (reasoning?.effort !== undefined) {
5241
- const effort = string(reasoning.effort, "reasoning.effort", true);
5242
- mappedEffort = policy?.effortMap?.[effort];
5243
- if (mappedEffort === undefined && policy?.anthropicThinkingBudget === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
5244
- fail("unsupported_reasoning", "Reasoning effort requires an explicit verified wire mapping", "reasoning.effort");
5245
- if (mappedEffort !== undefined)
5246
- string(mappedEffort, "reasoningPolicy.effortMap", true);
5378
+ const effort = atParam("reasoning.effort", () => string(reasoning.effort, "reasoning.effort", true));
5379
+ if (!allowLossyContinuation || !configuration) {
5380
+ mappedEffort = policy?.effortMap?.[effort];
5381
+ if (mappedEffort === undefined && policy?.anthropicThinkingBudget === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
5382
+ fail("unsupported_reasoning", "Reasoning effort requires an explicit verified wire mapping", "reasoning.effort");
5383
+ if (mappedEffort !== undefined)
5384
+ string(mappedEffort, "reasoningPolicy.effortMap", true);
5385
+ }
5247
5386
  }
5387
+ if (configuration)
5388
+ mappedEffort = configuration.level;
5248
5389
  if (sourceThinking !== undefined && reasoning?.effort === undefined && policy?.targetEffort !== undefined)
5249
5390
  mappedEffort = string(policy.targetEffort, "reasoningPolicy.targetEffort", true);
5250
- const target = context.targetProtocol;
5251
5391
  if (target === "gemini_generate_content" && reasoning?.effort !== undefined && mappedEffort === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
5252
5392
  fail("unsupported_reasoning", "Gemini requires an explicit thinking budget or level", "reasoning.effort");
5253
5393
  if (sourceThinking !== undefined) {
@@ -5286,7 +5426,7 @@ function convertProtocolRequest(raw, context) {
5286
5426
  }
5287
5427
  if (b.metadata !== undefined) {
5288
5428
  const metadata = record(b.metadata, "metadata");
5289
- fields2(metadata, ["user_id"], "metadata");
5429
+ fields(metadata, ["user_id"], "metadata");
5290
5430
  if (metadata.user_id !== undefined)
5291
5431
  string(metadata.user_id, "metadata.user_id");
5292
5432
  }
@@ -5298,7 +5438,7 @@ function convertProtocolRequest(raw, context) {
5298
5438
  } else if (target === "chat_completions") {
5299
5439
  if (reasoning?.effort !== undefined || mappedEffort !== undefined) {
5300
5440
  if (!cap.reasoningEffort)
5301
- fail("unsupported_reasoning", "Target effort capability is required", "reasoning.effort");
5441
+ fail("unsupported_reasoning", "Target effort capability is required", configuration?.param ?? "reasoning.effort");
5302
5442
  b.reasoning = { ...reasoning, effort: mappedEffort };
5303
5443
  if (mappedEffort === undefined)
5304
5444
  fail("unsupported_reasoning", "Chat requires a target effort mapping", "reasoning.effort");
@@ -5310,9 +5450,21 @@ function convertProtocolRequest(raw, context) {
5310
5450
  const decodingTarget = target === "gemini_generate_content" ? "chat_completions" : target;
5311
5451
  if (target === "gemini_generate_content" && reasoning)
5312
5452
  b.reasoning = { ...reasoning, effort: undefined };
5313
- const decoded = decodeResponsesRequest(b, decodingTarget, { ...cap, reasoningHistory: target !== "anthropic_messages" && cap.reasoningHistory === true, reasoningEffort: target === "chat_completions" && cap.reasoningEffort === true, anthropicThinkingBudget: undefined }, { preserveContentOrder: target === "gemini_generate_content", toolOutputImages: responsesToGemini });
5453
+ let decoded;
5454
+ try {
5455
+ 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 });
5456
+ } catch (error) {
5457
+ if (geminiHistory && error instanceof ResponsesCodecError && error.param !== undefined)
5458
+ throw new ResponsesCodecError(error.code, error.message, geminiHistory.sourceParam(error.param));
5459
+ throw error;
5460
+ }
5314
5461
  const diagnostics = decoded.diagnostics;
5462
+ if (geminiHistory)
5463
+ for (const diagnostic of diagnostics)
5464
+ diagnostic.param = geminiHistory.sourceParam(diagnostic.param);
5315
5465
  diagnostics.push(...pageSnapshotDiagnostics);
5466
+ if (configuration)
5467
+ diagnostics.push({ param: configuration.param, action: "mapped", reason: responsesToGemini ? "gemini_configuration_effort_update" : "chat_configuration_effort_update" });
5316
5468
  if (target === "gemini_generate_content" && decoded.body.parallel_tool_calls === true) {
5317
5469
  delete decoded.body.parallel_tool_calls;
5318
5470
  diagnostics.push({ param: "parallel_tool_calls", action: "omitted", reason: "gemini_parallel_tool_calls_allowed" });
@@ -5342,17 +5494,24 @@ function convertProtocolRequest(raw, context) {
5342
5494
  if (target === "gemini_generate_content" && (mappedEffort !== undefined || policy?.geminiThinkingBudget !== undefined || policy?.geminiThinkingLevel !== undefined)) {
5343
5495
  const level = policy?.geminiThinkingLevel ?? mappedEffort;
5344
5496
  if (policy?.geminiThinkingBudget !== undefined && level !== undefined)
5345
- fail("unsupported_reasoning", "Choose one Gemini thinking policy", "reasoningPolicy");
5497
+ fail("unsupported_reasoning", "Choose one Gemini thinking policy", configuration?.param ?? "reasoningPolicy");
5346
5498
  if (level !== undefined && !["minimal", "low", "medium", "high"].includes(level))
5347
5499
  fail("unsupported_reasoning", "Unknown Gemini thinking level", "reasoning.effort");
5348
5500
  if (mappedEffort !== undefined && policy?.geminiThinkingLevel !== undefined && mappedEffort !== policy.geminiThinkingLevel)
5349
- fail("unsupported_reasoning", "Conflicting Gemini thinking levels", "reasoning.effort");
5501
+ fail("unsupported_reasoning", "Conflicting Gemini thinking levels", configuration?.param ?? "reasoning.effort");
5350
5502
  const thinkingConfig = policy?.geminiThinkingBudget !== undefined ? { thinkingBudget: integer(policy.geminiThinkingBudget, "reasoningPolicy.geminiThinkingBudget", -1) } : { thinkingLevel: string(level, "reasoningPolicy.geminiThinkingLevel", true) };
5351
5503
  body.generationConfig = { ...record(body.generationConfig ?? {}, "generationConfig"), thinkingConfig };
5352
5504
  }
5353
5505
  if (mappedEffort !== undefined || sourceThinking !== undefined || policy?.anthropicThinkingBudget !== undefined)
5354
5506
  diagnostics.push({ param: "reasoning", action: "mapped", reason: "explicit_verified_wire_policy" });
5355
- return { body, canonicalHistory: geminiHistory?.canonicalHistory(decoded.canonicalInput) ?? decoded.canonicalInput, diagnostics, toolNames: decoded.toolNames, streaming: b.stream === true };
5507
+ return {
5508
+ body,
5509
+ canonicalHistory: geminiHistory?.canonicalHistory(decoded.canonicalInput) ?? decoded.canonicalInput,
5510
+ diagnostics,
5511
+ toolNames: decoded.toolNames,
5512
+ streaming: b.stream === true,
5513
+ ...configuration ? { effectiveReasoningEffort: configuration.effort } : {}
5514
+ };
5356
5515
  }
5357
5516
  function renderGemini(chat, context, input, signedParts, diagnostics) {
5358
5517
  const result = { contents: [] }, contents = result.contents, system = [], calls = new Map;
@@ -5500,11 +5659,11 @@ function validateUsage(raw, protocol) {
5500
5659
  return;
5501
5660
  }
5502
5661
  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"];
5503
- fields2(u, keys, "usage", "unsupported_response");
5662
+ fields(u, keys, "usage", "unsupported_response");
5504
5663
  for (const [key, value] of Object.entries(u)) {
5505
5664
  if (key.endsWith("_details")) {
5506
5665
  const d = record(value, "usage details");
5507
- fields2(d, key.includes("output") || key.includes("completion") ? ["reasoning_tokens"] : ["cached_tokens", "cache_creation_tokens"], `usage.${key}`, "unsupported_response");
5666
+ fields(d, key.includes("output") || key.includes("completion") ? ["reasoning_tokens"] : ["cached_tokens", "cache_creation_tokens"], `usage.${key}`, "unsupported_response");
5508
5667
  for (const [k, v] of Object.entries(d))
5509
5668
  integer(v, `usage.${key}.${k}`);
5510
5669
  } else
@@ -5525,10 +5684,10 @@ function validateProviderResponse(raw, protocol) {
5525
5684
  const m = record(c.message, "message");
5526
5685
  for (const [callIndex, rawCall] of (m.tool_calls == null ? [] : list(m.tool_calls, "tool_calls")).entries()) {
5527
5686
  const call = record(rawCall, "call");
5528
- fields2(call, ["id", "type", "function", "index"], "tool_calls", "unsupported_tool");
5687
+ fields(call, ["id", "type", "function", "index"], "tool_calls", "unsupported_tool");
5529
5688
  if (call.index !== undefined && integer(call.index, `tool_calls[${callIndex}].index`) !== callIndex)
5530
5689
  fail("invalid_payload", "Tool call index must match its array position", `tool_calls[${callIndex}].index`);
5531
- fields2(record(call.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
5690
+ fields(record(call.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
5532
5691
  }
5533
5692
  }
5534
5693
  validateUsage(b.usage, protocol);
@@ -5542,14 +5701,14 @@ function validateProviderResponse(raw, protocol) {
5542
5701
  return b;
5543
5702
  }
5544
5703
  function validateAnthropicBlock(b, path) {
5545
- fields2(b, b.type === "text" ? ["type", "text"] : b.type === "thinking" ? ["type", "thinking", "signature"] : ["type", "id", "name", "input"], path, "unsupported_content");
5704
+ fields(b, b.type === "text" ? ["type", "text"] : b.type === "thinking" ? ["type", "thinking", "signature"] : ["type", "id", "name", "input"], path, "unsupported_content");
5546
5705
  if (b.signature !== undefined)
5547
5706
  fail("unsupported_reasoning", "Signed provider reasoning cannot cross protocols", `${path}.signature`);
5548
5707
  }
5549
5708
  function validateCanonicalResponse(raw, context, itemOnly = false) {
5550
5709
  const b = record(raw, "response");
5551
5710
  serialized(b, limits(context.capabilities?.limits).maxOutputBytes, "response");
5552
- 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");
5711
+ 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");
5553
5712
  if (!itemOnly) {
5554
5713
  string(b.id, "response.id", true);
5555
5714
  integer(b.created_at, "response.created_at");
@@ -5560,7 +5719,7 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
5560
5719
  fail("missing_terminal", "Response has no explicit supported terminal", "status");
5561
5720
  if (b.status === "incomplete") {
5562
5721
  const d = record(b.incomplete_details, "incomplete_details");
5563
- fields2(d, ["reason"], "incomplete_details", "unsupported_response");
5722
+ fields(d, ["reason"], "incomplete_details", "unsupported_response");
5564
5723
  if (!["max_output_tokens", "content_filter"].includes(String(d.reason)))
5565
5724
  fail("unknown_terminal", "Unknown incomplete reason", "incomplete_details.reason");
5566
5725
  }
@@ -5575,13 +5734,13 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
5575
5734
  fail("unsupported_response", "Unknown item status", `${path}.status`);
5576
5735
  if (b.status === "completed" && t.status !== undefined && t.status !== "completed")
5577
5736
  fail("invalid_stream", "Completed response contains an unfinished item", `${path}.status`);
5578
- 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");
5737
+ 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");
5579
5738
  if (t.type === "message") {
5580
5739
  if (t.role !== "assistant")
5581
5740
  fail("unsupported_content", "Output message must be assistant", `${path}.role`);
5582
5741
  for (const [j, rawPart] of list(t.content, "content").entries()) {
5583
5742
  const p = record(rawPart, "part");
5584
- fields2(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], `${path}.content[${j}]`, "unsupported_content");
5743
+ fields(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], `${path}.content[${j}]`, "unsupported_content");
5585
5744
  if (p.type === "output_text")
5586
5745
  string(p.text, "text");
5587
5746
  else if (p.type === "refusal")
@@ -5600,7 +5759,7 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
5600
5759
  fail("unsupported_reasoning", "Opaque or raw reasoning output cannot cross protocols", path);
5601
5760
  for (const rawPart of list(t.summary, "summary")) {
5602
5761
  const p = record(rawPart, "summary");
5603
- fields2(p, ["type", "text"], path, "unsupported_reasoning");
5762
+ fields(p, ["type", "text"], path, "unsupported_reasoning");
5604
5763
  if (p.type !== "summary_text")
5605
5764
  fail("unsupported_reasoning", "Unknown reasoning summary type", path);
5606
5765
  string(p.text, "summary");
@@ -5743,7 +5902,7 @@ class GeminiCanonicalDecoder {
5743
5902
  const events = [];
5744
5903
  if (b.promptFeedback !== undefined) {
5745
5904
  const p = record(b.promptFeedback, "promptFeedback");
5746
- fields2(p, ["blockReason", "blockReasonMessage", "safetyRatings"], "promptFeedback", "unsupported_response");
5905
+ fields(p, ["blockReason", "blockReasonMessage", "safetyRatings"], "promptFeedback", "unsupported_response");
5747
5906
  if (p.blockReason !== undefined && p.blockReason !== "BLOCK_REASON_UNSPECIFIED") {
5748
5907
  this.ended = true;
5749
5908
  events.push(...this.encoder.push({ choices: [{ delta: {}, finish_reason: "content_filter" }] }));
@@ -5758,7 +5917,7 @@ class GeminiCanonicalDecoder {
5758
5917
  fail("unsupported_response", "Only candidate index zero is supported", "candidates.index");
5759
5918
  if (c.content !== undefined && c.content !== null) {
5760
5919
  const content = record(c.content, "content");
5761
- fields2(content, ["role", "parts"], "candidates.content", "unsupported_content");
5920
+ fields(content, ["role", "parts"], "candidates.content", "unsupported_content");
5762
5921
  if (content.role !== undefined && content.role !== "model")
5763
5922
  fail("unsupported_response", "Response role must be model", "candidates.content.role");
5764
5923
  const parts = list(content.parts ?? [], "parts");
@@ -5766,14 +5925,14 @@ class GeminiCanonicalDecoder {
5766
5925
  fail("invalid_stream", "Content arrived after Gemini terminal");
5767
5926
  for (const [i, rawPart] of parts.entries()) {
5768
5927
  const p = record(rawPart, "part");
5769
- fields2(p, ["text", "thought", "functionCall", "thoughtSignature"], "candidates.content.parts", "unsupported_content");
5928
+ fields(p, ["text", "thought", "functionCall", "thoughtSignature"], "candidates.content.parts", "unsupported_content");
5770
5929
  if (p.thoughtSignature !== undefined && this.context.sourceProtocol !== "responses")
5771
5930
  fail("unsupported_reasoning", "Thought signatures cannot cross protocols", "candidates.content.parts.thoughtSignature");
5772
5931
  if (p.functionCall !== undefined) {
5773
5932
  if (p.text !== undefined || p.thought !== undefined)
5774
5933
  fail("unsupported_content", "Mixed Gemini part kinds", "candidates.content.parts");
5775
5934
  const f = record(p.functionCall, "functionCall");
5776
- fields2(f, ["id", "name", "args"], "functionCall", "unsupported_tool");
5935
+ fields(f, ["id", "name", "args"], "functionCall", "unsupported_tool");
5777
5936
  const index = this.serial++, originalId = f.id === undefined ? `call_gemini_${crypto.randomUUID().replaceAll("-", "")}` : string(f.id, "functionCall.id", true);
5778
5937
  if (this.ids.has(originalId))
5779
5938
  fail("invalid_tool_arguments", "Duplicate Gemini call id", "functionCall.id");
@@ -5927,7 +6086,7 @@ class CanonicalStreamValidator {
5927
6086
  this.sequence = n;
5928
6087
  }
5929
6088
  if (["response.created", "response.in_progress", "response.completed", "response.incomplete", "response.failed"].includes(type)) {
5930
- fields2(e, [...common, "response"], "", "unsupported_response");
6089
+ fields(e, [...common, "response"], "", "unsupported_response");
5931
6090
  const r = record(e.response, "response");
5932
6091
  const id = string(r.id, "response.id", true);
5933
6092
  if (this.responseId !== undefined && this.responseId !== id)
@@ -5984,7 +6143,7 @@ class CanonicalStreamValidator {
5984
6143
  ];
5985
6144
  if (!known.includes(type))
5986
6145
  fail("unsupported_response", "Unknown Responses stream event", "type");
5987
- 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");
6146
+ 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");
5988
6147
  if (e.response_id !== undefined && e.response_id !== this.responseId)
5989
6148
  fail("invalid_stream", "Event response id changed", "response_id");
5990
6149
  const index = integer(e.output_index, "output_index");
@@ -6078,7 +6237,7 @@ class CanonicalStreamValidator {
6078
6237
  fail("unsupported_content", "Unknown content part type", "part.type");
6079
6238
  if (summary ? p.type !== "summary_text" : p.type === "summary_text")
6080
6239
  fail("invalid_stream", "Part kind differs from its output item", "part.type");
6081
- fields2(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
6240
+ fields(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
6082
6241
  if (p.annotations !== undefined && Array.isArray(p.annotations) && p.annotations.length)
6083
6242
  fail("unsupported_content", "Annotations cannot cross protocols", "part.annotations");
6084
6243
  const initial = string(p[p.type === "refusal" ? "refusal" : "text"], "part text");
@@ -6103,7 +6262,7 @@ class CanonicalStreamValidator {
6103
6262
  if (!p.textDone)
6104
6263
  fail("invalid_stream", "Part done before text done");
6105
6264
  const v = record(e.part, "part");
6106
- fields2(v, p.kind === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
6265
+ fields(v, p.kind === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
6107
6266
  if (v.annotations !== undefined && (!Array.isArray(v.annotations) || v.annotations.length))
6108
6267
  fail("unsupported_content", "Annotations cannot cross protocols", "part.annotations");
6109
6268
  if (v.type !== p.kind || v[p.kind === "refusal" ? "refusal" : "text"] !== p.text)
@@ -6257,7 +6416,7 @@ class CanonicalStreamRenderer {
6257
6416
  var LLM_PROTOCOLS = ["responses", "chat_completions", "anthropic_messages", "gemini_generate_content"];
6258
6417
 
6259
6418
  // packages/llms/src/protocol-session/index.ts
6260
- var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.4";
6419
+ var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.6";
6261
6420
  function describeProtocolConversion() {
6262
6421
  return {
6263
6422
  rulesVersion: PROTOCOL_CONVERSION_RULES_VERSION,
@@ -6466,9 +6625,9 @@ function validateStreamEnvelope(raw, protocol) {
6466
6625
  if (Array.isArray(d.tool_calls))
6467
6626
  for (const rawCall of d.tool_calls) {
6468
6627
  const t = record(rawCall, "tool call");
6469
- fields2(t, ["index", "id", "type", "function"], "tool_calls", "unsupported_tool");
6628
+ fields(t, ["index", "id", "type", "function"], "tool_calls", "unsupported_tool");
6470
6629
  if (t.function !== undefined)
6471
- fields2(record(t.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
6630
+ fields(record(t.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
6472
6631
  }
6473
6632
  }
6474
6633
  validateUsage(e.usage, protocol);
@@ -6477,12 +6636,12 @@ function validateStreamEnvelope(raw, protocol) {
6477
6636
  validateAnthropicBlock(record(e.content_block, "block"), "content_block");
6478
6637
  if (e.type === "content_block_delta") {
6479
6638
  const d = record(e.delta, "delta");
6480
- 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");
6639
+ 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");
6481
6640
  if (d.type === "signature_delta" || d.signature !== undefined)
6482
6641
  fail("unsupported_reasoning", "Signed provider reasoning cannot cross protocols", "delta.signature");
6483
6642
  }
6484
6643
  if (e.type === "message_delta")
6485
- fields2(record(e.delta, "delta"), ["stop_reason", "stop_sequence"], "delta", "unsupported_response");
6644
+ fields(record(e.delta, "delta"), ["stop_reason", "stop_sequence"], "delta", "unsupported_response");
6486
6645
  if (e.type === "message_start") {
6487
6646
  const m = record(e.message, "message");
6488
6647
  validateUsage(m.usage, protocol);
@@ -6974,7 +7133,7 @@ class AgentRelay {
6974
7133
  }
6975
7134
 
6976
7135
  // plugins/llm-protocol-adapter/server/service.ts
6977
- var REASONING_RULES_VERSION = "2026-10-27.1";
7136
+ var REASONING_RULES_VERSION = "2026-11-11.2";
6978
7137
  var concrete = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
6979
7138
  var effortProtocols = new Set(["responses", "chat_completions", "anthropic_messages", "gemini_generate_content"]);
6980
7139
  var geminiEfforts = new Set(["minimal", "low", "medium", "high"]);
@@ -7073,7 +7232,8 @@ function conversionService(catalog, worker, history, runBackground) {
7073
7232
  let catalogVersion = profile?.catalogVersion ?? null;
7074
7233
  let selected = context.selectedEffort, rewrittenDeveloper = false;
7075
7234
  const passthrough = context.sourceProtocol === context.targetProtocol;
7076
- if (!passthrough && selected !== undefined && (!profile || !profile.supportedEfforts.includes(selected)))
7235
+ const lossyChat = context.sourceProtocol === "responses" && context.targetProtocol === "chat_completions" && context.allowLossyContinuation === true;
7236
+ if (!passthrough && !lossyChat && selected !== undefined && (!profile || !profile.supportedEfforts.includes(selected)))
7077
7237
  fail2("reasoning.effort");
7078
7238
  const engine = createProtocolSession({
7079
7239
  ...context,
@@ -7086,11 +7246,17 @@ function conversionService(catalog, worker, history, runBackground) {
7086
7246
  convertRequest(raw) {
7087
7247
  const effort = wireEffort(raw, context.sourceProtocol);
7088
7248
  if (effort !== undefined) {
7089
- if (typeof effort !== "string" || !passthrough && !profile?.supportedEfforts.includes(effort) || selected !== undefined && selected !== effort)
7249
+ if (typeof effort !== "string" || !passthrough && !lossyChat && !profile?.supportedEfforts.includes(effort) || selected !== undefined && selected !== effort)
7090
7250
  fail2("reasoning.effort");
7091
7251
  selected = effort;
7092
7252
  }
7093
7253
  const result = engine.convertRequest(raw);
7254
+ if (result.effectiveReasoningEffort !== undefined) {
7255
+ if (!profile?.supportedEfforts.includes(result.effectiveReasoningEffort))
7256
+ fail2("reasoning.effort");
7257
+ selected = result.effectiveReasoningEffort;
7258
+ } else if (lossyChat && selected !== undefined && !profile?.supportedEfforts.includes(selected))
7259
+ fail2("reasoning.effort");
7094
7260
  rewrittenDeveloper = false;
7095
7261
  if (deepseekChat) {
7096
7262
  for (const message of chatMessages(result.body))
@@ -7623,4 +7789,4 @@ export {
7623
7789
  targetPath
7624
7790
  };
7625
7791
 
7626
- //# debugId=8E8291BBC094BF9D64756E2164756E21
7792
+ //# debugId=A4568E1586A3370764756E2164756E21