@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.
@@ -2669,6 +2669,240 @@ function validateEncryptedFunctionArgs(item, delivery, path) {
2669
2669
  fail("unsupported_content", "Encrypted function arguments cannot cross protocols", param);
2670
2670
  }
2671
2671
 
2672
+ // packages/llms/src/protocol-session/gemini.ts
2673
+ import { createHash } from "crypto";
2674
+
2675
+ // packages/llms/src/protocol-session/validation.ts
2676
+ function fields(value, allowed, path, code = "unsupported_request") {
2677
+ for (const key of Object.keys(value))
2678
+ if (!allowed.includes(key))
2679
+ fail(code, "Field cannot be represented by the target protocol", path ? `${path}.${key}` : key);
2680
+ }
2681
+ function bool(value, path) {
2682
+ if (typeof value !== "boolean")
2683
+ fail("invalid_payload", "Expected a boolean", path);
2684
+ return value;
2685
+ }
2686
+ function integer(value, path, min = 0) {
2687
+ if (!Number.isSafeInteger(value) || value < min)
2688
+ fail("invalid_payload", "Expected an integer in the supported range", path);
2689
+ return value;
2690
+ }
2691
+ function textParts(raw, path, style, role) {
2692
+ if (typeof raw === "string")
2693
+ return [{ type: "input_text", text: raw }];
2694
+ return list(raw, path).map((rawPart, index) => {
2695
+ const p = record(rawPart, path), at = `${path}[${index}]`;
2696
+ if (style === "gemini") {
2697
+ fields(p, ["text", "thought"], at, "unsupported_content");
2698
+ if (p.thought === true)
2699
+ fail("unsupported_reasoning", "Reasoning must be represented as a separate history item", at);
2700
+ return { type: "input_text", text: string(p.text, at) };
2701
+ }
2702
+ if (style === "chat" && p.type === "image_url" && role === "user") {
2703
+ fields(p, ["type", "image_url"], at, "unsupported_content");
2704
+ const image = record(p.image_url, at);
2705
+ fields(image, ["url", "detail"], `${at}.image_url`, "unsupported_content");
2706
+ return { type: "input_image", image_url: string(image.url, at, true), ...image.detail !== undefined ? { detail: image.detail } : {} };
2707
+ }
2708
+ if (style === "chat" && p.type === "refusal" && role === "assistant") {
2709
+ fields(p, ["type", "refusal"], at, "unsupported_content");
2710
+ return { type: "refusal", refusal: string(p.refusal, at) };
2711
+ }
2712
+ if (p.type !== "text")
2713
+ fail("unsupported_content", "Content block cannot be represented by the target protocol", at);
2714
+ fields(p, ["type", "text"], at, "unsupported_content");
2715
+ return { type: "input_text", text: string(p.text, at) };
2716
+ });
2717
+ }
2718
+
2719
+ // packages/llms/src/protocol-session/gemini.ts
2720
+ var signatureSeparator = "__thought__";
2721
+ function geminiInlineImage(image, path, budget) {
2722
+ const param = `${path}.image_url`;
2723
+ const url = bounded(string(image.url, "image URL", true), budget.maxRequestBytes, param);
2724
+ const match = /^data:([^;,]+);base64,([\s\S]*)$/.exec(url);
2725
+ if (!match || !["image/png", "image/jpeg", "image/webp"].includes(match[1]))
2726
+ fail("unsupported_content", "Gemini images require inline PNG, JPEG or WebP data", param);
2727
+ const data = match[2];
2728
+ 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(/=+$/, ""))
2729
+ fail("invalid_payload", "Invalid image Base64 encoding", param);
2730
+ return { mimeType: match[1], data };
2731
+ }
2732
+ function geminiToolResponse(content, path, budget, diagnostics) {
2733
+ if (!Array.isArray(content) || !content.some((part) => part.type === "image_url"))
2734
+ return { response: { output: content } };
2735
+ if (content.length > budget.maxItems)
2736
+ fail("resource_limit", "Too many tool output parts", path);
2737
+ const parts = [];
2738
+ const output = content.map((part, index) => atParam(`${path}[${index}]`, () => {
2739
+ if (part.type === "text")
2740
+ return part;
2741
+ if (part.type !== "image_url")
2742
+ fail("unsupported_content", "Unsupported Gemini tool result content");
2743
+ const image = record(part.image_url, "tool image");
2744
+ const inlineData = geminiInlineImage(image, `${path}[${index}]`, budget);
2745
+ const displayName = `tool-image-${index}.${inlineData.mimeType.slice("image/".length)}`;
2746
+ parts.push({ inlineData: { ...inlineData, displayName } });
2747
+ if (image.detail !== undefined)
2748
+ diagnostics.push({ param: `${path}[${index}].detail`, action: "omitted", reason: "gemini_tool_image_detail_unavailable" });
2749
+ return { $ref: displayName };
2750
+ }));
2751
+ return { response: { output }, parts };
2752
+ }
2753
+ function checkedSignature(value, maxBytes) {
2754
+ const signature = bounded(string(value, "thoughtSignature", true), maxBytes, "thoughtSignature");
2755
+ 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(/=+$/, ""))
2756
+ fail("invalid_tool_arguments", "Invalid Gemini thought signature encoding", "thoughtSignature");
2757
+ return signature;
2758
+ }
2759
+ var envelopePrefix = "bungee_gemini:";
2760
+ var isGeminiSignatureCarrier = (value) => typeof value === "string" && value.startsWith(envelopePrefix);
2761
+ var geminiEnvelopeBytes = (payloadBytes) => envelopePrefix.length + Math.ceil(payloadBytes * 4 / 3);
2762
+ var geminiTextHash = (text) => createHash("sha256").update(text).digest("base64url");
2763
+ function geminiSignatureItem(items, budget) {
2764
+ const payload = serialized({ version: 1, items }, budget.maxArgumentBytes, "Gemini signatures");
2765
+ return {
2766
+ type: "reasoning",
2767
+ id: `rs_gemini_${crypto.randomUUID().replaceAll("-", "")}`,
2768
+ summary: [],
2769
+ encrypted_content: bounded(envelopePrefix + Buffer.from(payload).toString("base64url"), budget.maxArgumentBytes, "Gemini signatures")
2770
+ };
2771
+ }
2772
+ function readGeminiSignatures(item, budget) {
2773
+ fields(item, ["type", "id", "summary", "encrypted_content", "status"], "Gemini signatures", "unsupported_reasoning");
2774
+ if (item.type !== "reasoning" || list(item.summary, "summary").length)
2775
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier");
2776
+ string(item.id, "signature item id", true);
2777
+ const opaque = bounded(string(item.encrypted_content, "encrypted_content", true), budget.maxArgumentBytes, "Gemini signatures");
2778
+ if (!isGeminiSignatureCarrier(opaque))
2779
+ fail("unsupported_reasoning", "Native encrypted reasoning cannot be restored to Gemini");
2780
+ const encoded = opaque.slice(envelopePrefix.length), bytes = Buffer.from(encoded, "base64url");
2781
+ if (!encoded || bytes.toString("base64url") !== encoded)
2782
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier encoding");
2783
+ let raw;
2784
+ try {
2785
+ raw = JSON.parse(bytes.toString("utf8"));
2786
+ } catch {
2787
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier JSON");
2788
+ }
2789
+ const body = record(raw, "Gemini signatures");
2790
+ fields(body, ["version", "items"], "Gemini signatures", "unsupported_reasoning");
2791
+ if (body.version !== 1)
2792
+ fail("unsupported_reasoning", "Unknown Gemini signature format");
2793
+ const ids = new Set;
2794
+ let partCount = 0;
2795
+ const result = list(body.items, "signature items").map((raw) => {
2796
+ const item = record(raw, "signature item");
2797
+ fields(item, ["id", "thought", "parts"], "signature item", "unsupported_reasoning");
2798
+ const id = string(item.id, "signed item id", true);
2799
+ if (ids.has(id) || typeof item.thought !== "boolean")
2800
+ fail("unsupported_reasoning", "Invalid signed item identity");
2801
+ ids.add(id);
2802
+ const parts = list(item.parts, "signed parts").map((raw) => {
2803
+ if (++partCount > budget.maxItems)
2804
+ fail("resource_limit", "Too many signed Gemini parts");
2805
+ const part = record(raw, "signed part");
2806
+ fields(part, ["length", "hash", "signature", "textAbsent"], "signed part", "unsupported_reasoning");
2807
+ const length = integer(part.length, "signed part length"), hash = string(part.hash, "signed part hash", true);
2808
+ if (!/^[A-Za-z0-9_-]{43}$/.test(hash))
2809
+ fail("unsupported_reasoning", "Invalid signed part hash");
2810
+ const signature = part.signature === undefined ? undefined : checkedSignature(part.signature, budget.maxArgumentBytes);
2811
+ if (part.textAbsent !== undefined && (part.textAbsent !== true || length !== 0 || signature === undefined))
2812
+ fail("unsupported_reasoning", "Invalid empty signed part");
2813
+ return { length, hash, ...signature === undefined ? {} : { signature }, ...part.textAbsent ? { textAbsent: true } : {} };
2814
+ });
2815
+ if (!parts.some((p) => p.signature !== undefined))
2816
+ fail("unsupported_reasoning", "Signature carrier has no signature");
2817
+ return { id, thought: item.thought, parts };
2818
+ });
2819
+ if (!result.length || result.length > budget.maxItems)
2820
+ fail("unsupported_reasoning", "Invalid signature item count");
2821
+ return result;
2822
+ }
2823
+ function restoreGeminiHistory(input, budget) {
2824
+ const original = typeof input === "string" ? [] : list(input, "input").map((raw) => record(raw, "input item"));
2825
+ if (original.length > budget.maxItems)
2826
+ fail("resource_limit", "Too many input items", "input");
2827
+ const retained = new Map, parts = new Map, ids = new Map;
2828
+ original.forEach((item, i) => {
2829
+ if (typeof item.id === "string") {
2830
+ if (ids.has(item.id))
2831
+ fail("invalid_tool_history", "Duplicate history item id", "input.id");
2832
+ ids.set(item.id, i);
2833
+ }
2834
+ });
2835
+ original.forEach((carrier, index) => {
2836
+ if (carrier.type === "configuration_update") {
2837
+ retained.set(carrier, carrier);
2838
+ return;
2839
+ }
2840
+ if (carrier.encrypted_content == null)
2841
+ return;
2842
+ const { content, internal_chat_message_metadata_passthrough: metadata, ...normalized } = carrier;
2843
+ if (content !== undefined && content !== null)
2844
+ fail("unsupported_reasoning", "Gemini signature carriers cannot contain reasoning content", `input[${index}].content`);
2845
+ if (metadata !== undefined)
2846
+ atParam(`input[${index}].internal_chat_message_metadata_passthrough`, () => record(metadata, "message metadata"));
2847
+ const signed = readGeminiSignatures(normalized, budget);
2848
+ retained.set(carrier, normalized);
2849
+ let previous = -1;
2850
+ for (const item of signed) {
2851
+ const at = ids.get(item.id);
2852
+ if (at === undefined || at >= index || at <= previous || parts.has(item.id))
2853
+ fail("unsupported_reasoning", "Signed history reference is missing or ambiguous");
2854
+ previous = at;
2855
+ const source = original[at];
2856
+ if (item.thought ? source.type !== "reasoning" || source.encrypted_content != null : source.role !== "assistant" || source.type !== undefined && source.type !== "message")
2857
+ fail("unsupported_reasoning", "Signed history item kind changed");
2858
+ const content = item.thought ? list(source.summary, "summary") : typeof source.content === "string" ? [{ type: "output_text", text: source.content }] : list(source.content, "content");
2859
+ const text = content.map((raw) => {
2860
+ const p = record(raw, "signed text");
2861
+ if (p.type !== (item.thought ? "summary_text" : "output_text") && !(p.type === "input_text" && !item.thought))
2862
+ fail("unsupported_reasoning", "Signed history content kind changed");
2863
+ return string(p.text, "signed text");
2864
+ }).join("");
2865
+ let offset = 0;
2866
+ const restored = item.parts.map((part) => {
2867
+ const value = text.slice(offset, offset + part.length);
2868
+ offset += part.length;
2869
+ if (value.length !== part.length || geminiTextHash(value) !== part.hash)
2870
+ fail("unsupported_reasoning", "Signed history text changed");
2871
+ return { ...part.textAbsent ? {} : { text: value }, ...item.thought ? { thought: true } : {}, ...part.signature === undefined ? {} : { thoughtSignature: part.signature } };
2872
+ });
2873
+ if (offset !== text.length)
2874
+ fail("unsupported_reasoning", "Signed history text was not fully consumed");
2875
+ parts.set(item.id, restored);
2876
+ }
2877
+ });
2878
+ const positions = original.flatMap((item, index) => retained.has(item) ? [] : [index]);
2879
+ return {
2880
+ input: typeof input === "string" ? input : positions.map((index) => original[index]),
2881
+ parts,
2882
+ sourceParam(param) {
2883
+ return param.replace(/^input\[(\d+)\]/, (match, index) => positions[Number(index)] === undefined ? match : `input[${positions[Number(index)]}]`);
2884
+ },
2885
+ canonicalHistory(decoded) {
2886
+ if (!retained.size)
2887
+ return decoded;
2888
+ let next = 0;
2889
+ return original.filter((item) => item.type !== "additional_tools").map((item) => retained.get(item) ?? decoded[next++]);
2890
+ }
2891
+ };
2892
+ }
2893
+ function encodeGeminiCallId(id, signature, maxBytes) {
2894
+ if (id.includes(signatureSeparator))
2895
+ fail("invalid_tool_arguments", "Gemini call id contains the signature separator", "functionCall.id");
2896
+ return signature === undefined ? id : `${id}${signatureSeparator}${checkedSignature(signature, maxBytes)}`;
2897
+ }
2898
+ function decodeGeminiCallId(value, maxBytes) {
2899
+ const separator = value.indexOf(signatureSeparator);
2900
+ if (separator < 0)
2901
+ return { id: value };
2902
+ const id = string(value.slice(0, separator), "functionCall.id", true);
2903
+ return { id, thoughtSignature: checkedSignature(value.slice(separator + signatureSeparator.length), maxBytes) };
2904
+ }
2905
+
2672
2906
  // packages/llms/src/providers/openai/protocol-conversion.ts
2673
2907
  var THINKING_TAG_PATTERN = /<thinking>([\s\S]*?)<\/thinking>/gi;
2674
2908
  var TOOL_CALL_CONTENT_TYPES = new Set([
@@ -3249,7 +3483,7 @@ class OpenAIProtocolConversion {
3249
3483
  }
3250
3484
 
3251
3485
  // packages/llms/src/responses-codec/request-preferences.ts
3252
- function fields(value, allowed, path) {
3486
+ function fields2(value, allowed, path) {
3253
3487
  for (const key of Object.keys(value))
3254
3488
  if (!allowed.includes(key)) {
3255
3489
  fail("unsupported_request", "Unrecognized request option", `${path}.${key}`);
@@ -3260,7 +3494,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
3260
3494
  if (body.stream_options !== undefined)
3261
3495
  atParam("stream_options", () => {
3262
3496
  const options = record(body.stream_options, "stream_options");
3263
- fields(options, ["include_usage", "reasoning_summary_delivery"], "stream_options");
3497
+ fields2(options, ["include_usage", "reasoning_summary_delivery"], "stream_options");
3264
3498
  if (options.include_usage !== undefined) {
3265
3499
  if (typeof options.include_usage !== "boolean")
3266
3500
  fail("invalid_payload", "Usage preference must be boolean", "stream_options.include_usage");
@@ -3275,7 +3509,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
3275
3509
  if (body.access_programs !== undefined)
3276
3510
  atParam("access_programs", () => {
3277
3511
  const programs = record(body.access_programs, "access_programs");
3278
- fields(programs, ["cyber"], "access_programs");
3512
+ fields2(programs, ["cyber"], "access_programs");
3279
3513
  if (programs.cyber !== undefined && programs.cyber !== "standard") {
3280
3514
  if (programs.cyber === "daybreak_blue" || programs.cyber === "daybreak_red") {
3281
3515
  fail("unsupported_access_program", "Selected access program cannot be represented by the target protocol", "access_programs.cyber");
@@ -3287,7 +3521,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
3287
3521
  if (body.reasoning !== undefined)
3288
3522
  atParam("reasoning", () => {
3289
3523
  const reasoning = record(body.reasoning, "reasoning");
3290
- fields(reasoning, ["effort", "summary", "context"], "reasoning");
3524
+ fields2(reasoning, ["effort", "summary", "context"], "reasoning");
3291
3525
  if (reasoning.summary !== undefined) {
3292
3526
  if (typeof reasoning.summary !== "string" || !["none", "auto", "concise", "detailed"].includes(reasoning.summary))
3293
3527
  fail("invalid_payload", "Invalid reasoning summary preference", "reasoning.summary");
@@ -3318,7 +3552,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
3318
3552
  if (body.text !== undefined)
3319
3553
  atParam("text", () => {
3320
3554
  const text = record(body.text, "text");
3321
- fields(text, ["verbosity", "format"], "text");
3555
+ fields2(text, ["verbosity", "format"], "text");
3322
3556
  if (text.verbosity !== undefined) {
3323
3557
  if (typeof text.verbosity !== "string" || !["low", "medium", "high"].includes(text.verbosity))
3324
3558
  fail("invalid_payload", "Invalid text verbosity preference", "text.verbosity");
@@ -3381,6 +3615,7 @@ function definitionKey(value) {
3381
3615
  }
3382
3616
  function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {}) {
3383
3617
  const body = record(raw, "Responses request");
3618
+ const allowLossyContinuation = protocol === "chat_completions" && options.allowLossyContinuation === true;
3384
3619
  if (capabilities.agentMessageDelivery !== undefined && capabilities.agentMessageDelivery !== "plaintext")
3385
3620
  fail("invalid_payload", "Unknown agent message delivery policy", "agentMessageDelivery");
3386
3621
  const budget = limits(capabilities.limits);
@@ -3449,6 +3684,7 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3449
3684
  const byOriginal = new Map;
3450
3685
  const definitions = new Map;
3451
3686
  let examinedTools = 0;
3687
+ let hasCompaction = false;
3452
3688
  const tools = [];
3453
3689
  const identity = (name, namespace) => JSON.stringify([namespace ?? null, name]);
3454
3690
  const register = (name, namespace, custom) => {
@@ -3546,6 +3782,31 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3546
3782
  for (const [index, rawItem] of input.entries())
3547
3783
  atParam(`input[${index}]`, () => {
3548
3784
  const item = record(rawItem, "input item");
3785
+ if (Object.hasOwn(item, "phase")) {
3786
+ const param = `input[${index}].phase`;
3787
+ if (!allowLossyContinuation || item.type !== undefined && item.type !== "message" || item.role !== "assistant")
3788
+ fail("unsupported_content", "Message phase requires opted-in Chat assistant history", param);
3789
+ if (item.phase !== null && item.phase !== "commentary" && item.phase !== "final_answer")
3790
+ fail("invalid_payload", "Invalid assistant message phase", param);
3791
+ diagnostics.push({ param, action: "omitted", reason: "chat_assistant_phase_unavailable" });
3792
+ }
3793
+ if (allowLossyContinuation && item.type === "compaction") {
3794
+ const path = `input[${index}]`;
3795
+ for (const key of Object.keys(item))
3796
+ if (!["type", "id", "created_by", "encrypted_content", "internal_chat_message_metadata_passthrough"].includes(key))
3797
+ fail("unsupported_content", "Unknown compaction field", `${path}.${key}`);
3798
+ const param = `${path}.encrypted_content`;
3799
+ const encryptedContent = atParam(param, () => string(item.encrypted_content, "compaction encrypted content", true));
3800
+ if (!encryptedContent.trim())
3801
+ fail("invalid_payload", "Compaction encrypted content must be non-empty", param);
3802
+ if (isGeminiSignatureCarrier(encryptedContent))
3803
+ fail("unsupported_content", "Gemini signature carriers cannot cross into Chat", param);
3804
+ if (item.id != null)
3805
+ atParam(`${path}.id`, () => string(item.id, "compaction id", true));
3806
+ if (item.created_by !== undefined)
3807
+ atParam(`${path}.created_by`, () => string(item.created_by, "compaction created_by", true));
3808
+ hasCompaction = true;
3809
+ }
3549
3810
  if (item.type !== "additional_tools") {
3550
3811
  if (item.internal_chat_message_metadata_passthrough !== undefined) {
3551
3812
  record(item.internal_chat_message_metadata_passthrough, "message metadata");
@@ -3581,6 +3842,12 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3581
3842
  const partPath = `${path}[${index}]`;
3582
3843
  atParam(partPath, () => {
3583
3844
  const part = record(rawPart, "content part");
3845
+ if (Object.hasOwn(part, "logprobs")) {
3846
+ const param = `${partPath}.logprobs`;
3847
+ if (!allowLossyContinuation || role !== "assistant" || part.type !== "output_text" || !Array.isArray(part.logprobs) || part.logprobs.length !== 0)
3848
+ fail("unsupported_content", "Only empty assistant output log probabilities can be omitted", param);
3849
+ diagnostics.push({ param, action: "omitted", reason: "chat_empty_output_logprobs" });
3850
+ }
3584
3851
  if (part.type === "input_text" || part.type === "output_text" || part.type === "text")
3585
3852
  string(part.text, "content text");
3586
3853
  else if (part.type === "refusal" && role === "assistant") {
@@ -3630,6 +3897,8 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3630
3897
  let messageParam = "instructions";
3631
3898
  const callIds = new Set;
3632
3899
  const callToolNames = new Map;
3900
+ const callsAwaitingResult = new Map;
3901
+ let encryptedToolBatch;
3633
3902
  const answered = new Set;
3634
3903
  const deferredInstructions = [];
3635
3904
  const normalizeChatHistory = protocol === "chat_completions" && !options.preserveContentOrder;
@@ -3648,18 +3917,43 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3648
3917
  addMessage({ role: "user", content: [{ type: "text", text: `Images returned by tool ${JSON.stringify(name)} (call ${JSON.stringify(callId)}):` }, ...images] });
3649
3918
  projectedToolImages.length = 0;
3650
3919
  };
3920
+ const checkPendingToolHistory = (item, toolOutput) => {
3921
+ const message = item.type === undefined || item.type === "message";
3922
+ const instruction = message && (item.role === "system" || item.role === "developer");
3923
+ const toolCall = item.type === "function_call" || item.type === "custom_tool_call";
3924
+ if (hasCompaction && toolOutput && callsAwaitingResult.size && pendingReasoning)
3925
+ fail("invalid_tool_history", "Attach the reasoning summary before the Chat tool results", messageParam);
3926
+ if (toolOutput || instruction)
3927
+ return;
3928
+ if (deferredInstructions.length)
3929
+ fail("invalid_tool_history", "Only instructions and tool results may follow a deferred instruction until all tool results arrive", messageParam);
3930
+ if (encryptedToolBatch && !(toolCall && chat.at(-1)?.role === "assistant"))
3931
+ fail("invalid_tool_history", "Complete the encrypted tool batch before another turn or reasoning item", messageParam);
3932
+ if (hasCompaction && callsAwaitingResult.size && !(normalizeChatHistory && chat.at(-1)?.role === "assistant" && (toolCall || item.type === "reasoning" || message && item.role === "assistant")))
3933
+ fail("invalid_tool_history", "Complete the Chat tool batch before another message", messageParam);
3934
+ };
3651
3935
  if (body.instructions !== undefined)
3652
3936
  addMessage({ role: "system", content: string(body.instructions, "instructions") });
3653
3937
  for (const [inputIndex, rawItem] of input.entries())
3654
3938
  atParam(`input[${inputIndex}]`, () => {
3655
3939
  messageParam = `input[${inputIndex}]`;
3656
3940
  const item = record(rawItem, "input item");
3657
- if (item.type !== "function_call_output" && item.type !== "custom_tool_call_output")
3941
+ const toolOutput = item.type === "function_call_output" || item.type === "custom_tool_call_output";
3942
+ if (!toolOutput)
3658
3943
  flushToolImages();
3659
- if (item.type === "additional_tools")
3944
+ if (item.type === "additional_tools" || allowLossyContinuation && item.type === "configuration_update" && options.chatConfigurationUpdates?.has(item))
3660
3945
  return;
3661
- 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")))
3662
- fail("invalid_tool_history", "Only instructions and tool results may follow a deferred instruction until all tool results arrive", messageParam);
3946
+ if (item.type !== "reasoning")
3947
+ checkPendingToolHistory(item, toolOutput);
3948
+ if (allowLossyContinuation && item.type === "compaction") {
3949
+ if (callIds.size !== answered.size)
3950
+ fail("invalid_tool_history", "Compaction cannot split a Chat tool batch", messageParam);
3951
+ if (pendingReasoning)
3952
+ fail("unsupported_reasoning", "Reasoning must precede an assistant item", messageParam);
3953
+ addMessage({ role: "user", content: "[Earlier conversation context was compacted and is unavailable. Continue from the visible messages and ask for any details you need.]" });
3954
+ diagnostics.push({ param: messageParam, action: "mapped", reason: "chat_compaction_placeholder" });
3955
+ return;
3956
+ }
3663
3957
  if (item.type === "agent_message") {
3664
3958
  validateAgentMessage(item, messageParam, capabilities.limits);
3665
3959
  if (capabilities.agentMessageDelivery !== "plaintext")
@@ -3671,24 +3965,34 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3671
3965
  diagnostics.push({ param: messageParam, action: "mapped", reason: "agent_message_plaintext_delivery" });
3672
3966
  return;
3673
3967
  }
3674
- if (item.encrypted_content != null)
3675
- fail("unsupported_content", "Encrypted content cannot cross protocols", `${messageParam}.encrypted_content`);
3968
+ const encrypted = item.encrypted_content != null;
3969
+ if (encrypted) {
3970
+ const param = `${messageParam}.encrypted_content`;
3971
+ if (!allowLossyContinuation || item.type !== "reasoning" && item.type !== "function_call")
3972
+ fail("unsupported_content", "Encrypted content cannot cross protocols", param);
3973
+ atParam(param, () => string(item.encrypted_content, "encrypted content", true));
3974
+ diagnostics.push({ param, action: "omitted", reason: "chat_opaque_history_content_unavailable" });
3975
+ }
3676
3976
  if (item.type === "compaction")
3677
3977
  fail("unsupported_content", "Encrypted reasoning and compaction cannot be restored");
3678
3978
  if (item.type === "item_reference")
3679
3979
  fail("unresolved_reference", "Input item references must be resolved before conversion");
3680
3980
  if (item.type === "reasoning") {
3681
- if (protocol !== "chat_completions" || !(capabilities.reasoningHistory || capabilities.reasoningEffort))
3682
- fail("unsupported_reasoning", "Reasoning history requires an explicit compatible reasoning capability");
3683
- if (item.content != null)
3981
+ if (item.content != null && !(encrypted && Array.isArray(item.content) && !item.content.length))
3684
3982
  fail("unsupported_reasoning", "Reasoning content requires an explicit history mapping", `${messageParam}.content`);
3685
- const summary = list(item.summary, "reasoning summary");
3686
- const text = summary.map((part) => {
3983
+ const summaryParam = `${messageParam}.summary`;
3984
+ const summary = encrypted && item.summary === undefined ? [] : atParam(summaryParam, () => list(item.summary, "reasoning summary"));
3985
+ const text = summary.map((part, index) => atParam(`${summaryParam}[${index}]`, () => {
3687
3986
  const p = record(part, "reasoning summary");
3688
3987
  if (p.type !== "summary_text")
3689
3988
  fail("unsupported_reasoning", "Unknown reasoning summary");
3690
3989
  return string(p.text, "summary text");
3691
- }).join("");
3990
+ })).join("");
3991
+ if (encrypted && !text)
3992
+ return;
3993
+ checkPendingToolHistory(item, false);
3994
+ if (protocol !== "chat_completions" || !(capabilities.reasoningHistory || capabilities.reasoningEffort))
3995
+ fail("unsupported_reasoning", "Reasoning history requires an explicit compatible reasoning capability");
3692
3996
  if (options.preserveContentOrder)
3693
3997
  addMessage({ role: "assistant", content: null, reasoning_content: text, ...item.id === undefined ? {} : { id: string(item.id, "item.id", true) } });
3694
3998
  else
@@ -3698,16 +4002,30 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3698
4002
  if (item.type === "function_call" || item.type === "custom_tool_call") {
3699
4003
  const custom = item.type === "custom_tool_call";
3700
4004
  validateEncryptedFunctionArgs(item, capabilities.agentMessageDelivery, messageParam);
4005
+ if (encrypted && item.status !== undefined && item.status !== "completed")
4006
+ fail("invalid_tool_history", "Encrypted tool history requires a completed function call", `${messageParam}.status`);
3701
4007
  const id = string(item.call_id, "call_id", true);
3702
4008
  if (callIds.has(id))
3703
4009
  fail("invalid_tool_history", "Duplicate tool call identifier");
4010
+ const previous = chat.at(-1);
4011
+ if (encrypted && callIds.size !== answered.size) {
4012
+ const adjacent = previous?.role === "assistant" ? previous.tool_calls?.length ?? 0 : 0;
4013
+ if (adjacent !== callIds.size - answered.size)
4014
+ fail("invalid_tool_history", "Encrypted function call cannot join a split tool batch", `${messageParam}.call_id`);
4015
+ }
3704
4016
  callIds.add(id);
3705
- const args = custom ? JSON.stringify({ input: string(item.input, "custom input") }) : string(item.arguments, "arguments");
3706
- bounded(args, budget.maxArgumentBytes, "arguments");
3707
- argumentObject(args);
4017
+ if (hasCompaction || encrypted)
4018
+ callsAwaitingResult.set(id, { param: `${messageParam}.call_id`, outputType: custom ? "custom_tool_call_output" : "function_call_output" });
4019
+ if (encrypted)
4020
+ encryptedToolBatch ??= `${messageParam}.call_id`;
4021
+ const args = atParam(encrypted ? `${messageParam}.arguments` : messageParam, () => {
4022
+ const text = custom ? JSON.stringify({ input: string(item.input, "custom input") }) : string(item.arguments, "arguments");
4023
+ bounded(text, budget.maxArgumentBytes, "arguments");
4024
+ argumentObject(text);
4025
+ return text;
4026
+ });
3708
4027
  const call = { id, type: "function", function: { name: resolve(item, custom), arguments: args } };
3709
4028
  callToolNames.set(id, String(item.name));
3710
- const previous = chat.at(-1);
3711
4029
  if (previous?.role === "assistant" && !options.preserveContentOrder) {
3712
4030
  previous.tool_calls = [...previous.tool_calls ?? [], call];
3713
4031
  if (pendingReasoning)
@@ -3721,6 +4039,10 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3721
4039
  const id = string(item.call_id, "call_id", true);
3722
4040
  if (!callIds.has(id) || answered.has(id))
3723
4041
  fail("invalid_tool_history", "Unmatched or duplicate tool result");
4042
+ const pending = callsAwaitingResult.get(id);
4043
+ if (pending && item.type !== pending.outputType)
4044
+ fail("invalid_tool_history", "Tool result type must match the corresponding call", `${messageParam}.type`);
4045
+ callsAwaitingResult.delete(id);
3724
4046
  answered.add(id);
3725
4047
  if (Array.isArray(item.output) && item.output.length > budget.maxItems && item.output.some((part) => part && typeof part === "object" && part.type === "input_image"))
3726
4048
  fail("resource_limit", "Too many tool output content parts", `${messageParam}.output`);
@@ -3739,6 +4061,7 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3739
4061
  }
3740
4062
  addMessage({ role: "tool", tool_call_id: id, content: output, ...item.is_error === true ? { is_error: true } : {} });
3741
4063
  if (callIds.size === answered.size) {
4064
+ encryptedToolBatch = undefined;
3742
4065
  for (const instruction of deferredInstructions) {
3743
4066
  messageParam = instruction.param;
3744
4067
  addMessage(instruction.message);
@@ -3777,6 +4100,11 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3777
4100
  }
3778
4101
  addMessage(message);
3779
4102
  });
4103
+ const missingResult = callsAwaitingResult.values().next().value;
4104
+ if (missingResult)
4105
+ fail("invalid_tool_history", "Tool call requires a matching result", missingResult.param);
4106
+ if (encryptedToolBatch)
4107
+ fail("invalid_tool_history", "All calls in the encrypted tool batch require matching results", encryptedToolBatch);
3780
4108
  if (pendingReasoning)
3781
4109
  fail("unsupported_reasoning", "Orphan reasoning history cannot be represented");
3782
4110
  if (deferredInstructions.length)
@@ -4331,251 +4659,12 @@ function encodeResponsesResult(raw, protocol, model, toolNames = new Map, config
4331
4659
  fail("missing_terminal", "JSON response has no terminal result");
4332
4660
  return record(end.response, "Responses result");
4333
4661
  }
4334
- // packages/llms/src/protocol-session/gemini.ts
4335
- import { createHash } from "crypto";
4336
-
4337
- // packages/llms/src/protocol-session/validation.ts
4338
- function fields2(value, allowed, path, code = "unsupported_request") {
4339
- for (const key of Object.keys(value))
4340
- if (!allowed.includes(key))
4341
- fail(code, "Field cannot be represented by the target protocol", path ? `${path}.${key}` : key);
4342
- }
4343
- function bool(value, path) {
4344
- if (typeof value !== "boolean")
4345
- fail("invalid_payload", "Expected a boolean", path);
4346
- return value;
4347
- }
4348
- function integer(value, path, min = 0) {
4349
- if (!Number.isSafeInteger(value) || value < min)
4350
- fail("invalid_payload", "Expected an integer in the supported range", path);
4351
- return value;
4352
- }
4353
- function textParts(raw, path, style, role) {
4354
- if (typeof raw === "string")
4355
- return [{ type: "input_text", text: raw }];
4356
- return list(raw, path).map((rawPart, index) => {
4357
- const p = record(rawPart, path), at = `${path}[${index}]`;
4358
- if (style === "gemini") {
4359
- fields2(p, ["text", "thought"], at, "unsupported_content");
4360
- if (p.thought === true)
4361
- fail("unsupported_reasoning", "Reasoning must be represented as a separate history item", at);
4362
- return { type: "input_text", text: string(p.text, at) };
4363
- }
4364
- if (style === "chat" && p.type === "image_url" && role === "user") {
4365
- fields2(p, ["type", "image_url"], at, "unsupported_content");
4366
- const image = record(p.image_url, at);
4367
- fields2(image, ["url", "detail"], `${at}.image_url`, "unsupported_content");
4368
- return { type: "input_image", image_url: string(image.url, at, true), ...image.detail !== undefined ? { detail: image.detail } : {} };
4369
- }
4370
- if (style === "chat" && p.type === "refusal" && role === "assistant") {
4371
- fields2(p, ["type", "refusal"], at, "unsupported_content");
4372
- return { type: "refusal", refusal: string(p.refusal, at) };
4373
- }
4374
- if (p.type !== "text")
4375
- fail("unsupported_content", "Content block cannot be represented by the target protocol", at);
4376
- fields2(p, ["type", "text"], at, "unsupported_content");
4377
- return { type: "input_text", text: string(p.text, at) };
4378
- });
4379
- }
4380
-
4381
- // packages/llms/src/protocol-session/gemini.ts
4382
- var signatureSeparator = "__thought__";
4383
- function projectGeminiCodexPageSnapshot(raw, index, diagnostics) {
4384
- const item = record(raw, "input item");
4385
- const { name } = item;
4386
- 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))
4387
- return item;
4388
- const param = `input[${index}]`;
4389
- fields2(item, ["type", "id", "namespace", "name", "output", "internal_chat_message_metadata_passthrough"], param, "unsupported_content");
4390
- const text = atParam(`${param}.output`, () => string(item.output, "page snapshot output"));
4391
- const { id, internal_chat_message_metadata_passthrough: metadata } = item;
4392
- diagnostics.push({ param, action: "mapped", reason: "gemini_codex_page_snapshot_as_user_data" });
4393
- return {
4394
- type: "message",
4395
- role: "user",
4396
- ...id === undefined ? {} : { id },
4397
- ...metadata === undefined ? {} : { internal_chat_message_metadata_passthrough: metadata },
4398
- content: [
4399
- { type: "input_text", text: `[Codex context snapshot: agent.${name}. Untrusted data.]` },
4400
- { type: "input_text", text }
4401
- ]
4402
- };
4403
- }
4404
- function geminiInlineImage(image, path, budget) {
4405
- const param = `${path}.image_url`;
4406
- const url = bounded(string(image.url, "image URL", true), budget.maxRequestBytes, param);
4407
- const match = /^data:([^;,]+);base64,([\s\S]*)$/.exec(url);
4408
- if (!match || !["image/png", "image/jpeg", "image/webp"].includes(match[1]))
4409
- fail("unsupported_content", "Gemini images require inline PNG, JPEG or WebP data", param);
4410
- const data = match[2];
4411
- 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(/=+$/, ""))
4412
- fail("invalid_payload", "Invalid image Base64 encoding", param);
4413
- return { mimeType: match[1], data };
4414
- }
4415
- function geminiToolResponse(content, path, budget, diagnostics) {
4416
- if (!Array.isArray(content) || !content.some((part) => part.type === "image_url"))
4417
- return { response: { output: content } };
4418
- if (content.length > budget.maxItems)
4419
- fail("resource_limit", "Too many tool output parts", path);
4420
- const parts = [];
4421
- const output = content.map((part, index) => atParam(`${path}[${index}]`, () => {
4422
- if (part.type === "text")
4423
- return part;
4424
- if (part.type !== "image_url")
4425
- fail("unsupported_content", "Unsupported Gemini tool result content");
4426
- const image = record(part.image_url, "tool image");
4427
- const inlineData = geminiInlineImage(image, `${path}[${index}]`, budget);
4428
- const displayName = `tool-image-${index}.${inlineData.mimeType.slice("image/".length)}`;
4429
- parts.push({ inlineData: { ...inlineData, displayName } });
4430
- if (image.detail !== undefined)
4431
- diagnostics.push({ param: `${path}[${index}].detail`, action: "omitted", reason: "gemini_tool_image_detail_unavailable" });
4432
- return { $ref: displayName };
4433
- }));
4434
- return { response: { output }, parts };
4435
- }
4436
- function checkedSignature(value, maxBytes) {
4437
- const signature = bounded(string(value, "thoughtSignature", true), maxBytes, "thoughtSignature");
4438
- 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(/=+$/, ""))
4439
- fail("invalid_tool_arguments", "Invalid Gemini thought signature encoding", "thoughtSignature");
4440
- return signature;
4441
- }
4442
- var envelopePrefix = "bungee_gemini:";
4443
- var geminiEnvelopeBytes = (payloadBytes) => envelopePrefix.length + Math.ceil(payloadBytes * 4 / 3);
4444
- var geminiTextHash = (text) => createHash("sha256").update(text).digest("base64url");
4445
- function geminiSignatureItem(items, budget) {
4446
- const payload = serialized({ version: 1, items }, budget.maxArgumentBytes, "Gemini signatures");
4447
- return {
4448
- type: "reasoning",
4449
- id: `rs_gemini_${crypto.randomUUID().replaceAll("-", "")}`,
4450
- summary: [],
4451
- encrypted_content: bounded(envelopePrefix + Buffer.from(payload).toString("base64url"), budget.maxArgumentBytes, "Gemini signatures")
4452
- };
4453
- }
4454
- function readGeminiSignatures(item, budget) {
4455
- fields2(item, ["type", "id", "summary", "encrypted_content", "status"], "Gemini signatures", "unsupported_reasoning");
4456
- if (item.type !== "reasoning" || list(item.summary, "summary").length)
4457
- fail("unsupported_reasoning", "Invalid Gemini signature carrier");
4458
- string(item.id, "signature item id", true);
4459
- const opaque = bounded(string(item.encrypted_content, "encrypted_content", true), budget.maxArgumentBytes, "Gemini signatures");
4460
- if (!opaque.startsWith(envelopePrefix))
4461
- fail("unsupported_reasoning", "Native encrypted reasoning cannot be restored to Gemini");
4462
- const encoded = opaque.slice(envelopePrefix.length), bytes = Buffer.from(encoded, "base64url");
4463
- if (!encoded || bytes.toString("base64url") !== encoded)
4464
- fail("unsupported_reasoning", "Invalid Gemini signature carrier encoding");
4465
- let raw;
4466
- try {
4467
- raw = JSON.parse(bytes.toString("utf8"));
4468
- } catch {
4469
- fail("unsupported_reasoning", "Invalid Gemini signature carrier JSON");
4470
- }
4471
- const body = record(raw, "Gemini signatures");
4472
- fields2(body, ["version", "items"], "Gemini signatures", "unsupported_reasoning");
4473
- if (body.version !== 1)
4474
- fail("unsupported_reasoning", "Unknown Gemini signature format");
4475
- const ids = new Set;
4476
- let partCount = 0;
4477
- const result = list(body.items, "signature items").map((raw) => {
4478
- const item = record(raw, "signature item");
4479
- fields2(item, ["id", "thought", "parts"], "signature item", "unsupported_reasoning");
4480
- const id = string(item.id, "signed item id", true);
4481
- if (ids.has(id) || typeof item.thought !== "boolean")
4482
- fail("unsupported_reasoning", "Invalid signed item identity");
4483
- ids.add(id);
4484
- const parts = list(item.parts, "signed parts").map((raw) => {
4485
- if (++partCount > budget.maxItems)
4486
- fail("resource_limit", "Too many signed Gemini parts");
4487
- const part = record(raw, "signed part");
4488
- fields2(part, ["length", "hash", "signature", "textAbsent"], "signed part", "unsupported_reasoning");
4489
- const length = integer(part.length, "signed part length"), hash = string(part.hash, "signed part hash", true);
4490
- if (!/^[A-Za-z0-9_-]{43}$/.test(hash))
4491
- fail("unsupported_reasoning", "Invalid signed part hash");
4492
- const signature = part.signature === undefined ? undefined : checkedSignature(part.signature, budget.maxArgumentBytes);
4493
- if (part.textAbsent !== undefined && (part.textAbsent !== true || length !== 0 || signature === undefined))
4494
- fail("unsupported_reasoning", "Invalid empty signed part");
4495
- return { length, hash, ...signature === undefined ? {} : { signature }, ...part.textAbsent ? { textAbsent: true } : {} };
4496
- });
4497
- if (!parts.some((p) => p.signature !== undefined))
4498
- fail("unsupported_reasoning", "Signature carrier has no signature");
4499
- return { id, thought: item.thought, parts };
4500
- });
4501
- if (!result.length || result.length > budget.maxItems)
4502
- fail("unsupported_reasoning", "Invalid signature item count");
4503
- return result;
4504
- }
4505
- function restoreGeminiHistory(input, budget) {
4506
- const original = typeof input === "string" ? [] : list(input, "input").map((raw) => record(raw, "input item"));
4507
- const carriers = new Set, parts = new Map, ids = new Map;
4508
- original.forEach((item, i) => {
4509
- if (typeof item.id === "string") {
4510
- if (ids.has(item.id))
4511
- fail("invalid_tool_history", "Duplicate history item id", "input.id");
4512
- ids.set(item.id, i);
4513
- }
4514
- });
4515
- original.forEach((carrier, index) => {
4516
- if (carrier.encrypted_content == null)
4517
- return;
4518
- const signed = readGeminiSignatures(carrier, budget);
4519
- carriers.add(carrier);
4520
- let previous = -1;
4521
- for (const item of signed) {
4522
- const at = ids.get(item.id);
4523
- if (at === undefined || at >= index || at <= previous || parts.has(item.id))
4524
- fail("unsupported_reasoning", "Signed history reference is missing or ambiguous");
4525
- previous = at;
4526
- const source = original[at];
4527
- if (item.thought ? source.type !== "reasoning" || source.encrypted_content != null : source.role !== "assistant" || source.type !== undefined && source.type !== "message")
4528
- fail("unsupported_reasoning", "Signed history item kind changed");
4529
- const content = item.thought ? list(source.summary, "summary") : typeof source.content === "string" ? [{ type: "output_text", text: source.content }] : list(source.content, "content");
4530
- const text = content.map((raw) => {
4531
- const p = record(raw, "signed text");
4532
- if (p.type !== (item.thought ? "summary_text" : "output_text") && !(p.type === "input_text" && !item.thought))
4533
- fail("unsupported_reasoning", "Signed history content kind changed");
4534
- return string(p.text, "signed text");
4535
- }).join("");
4536
- let offset = 0;
4537
- const restored = item.parts.map((part) => {
4538
- const value = text.slice(offset, offset + part.length);
4539
- offset += part.length;
4540
- if (value.length !== part.length || geminiTextHash(value) !== part.hash)
4541
- fail("unsupported_reasoning", "Signed history text changed");
4542
- return { ...part.textAbsent ? {} : { text: value }, ...item.thought ? { thought: true } : {}, ...part.signature === undefined ? {} : { thoughtSignature: part.signature } };
4543
- });
4544
- if (offset !== text.length)
4545
- fail("unsupported_reasoning", "Signed history text was not fully consumed");
4546
- parts.set(item.id, restored);
4547
- }
4548
- });
4549
- return {
4550
- input: typeof input === "string" ? input : original.filter((item) => !carriers.has(item)),
4551
- parts,
4552
- canonicalHistory(decoded) {
4553
- if (!carriers.size)
4554
- return decoded;
4555
- let next = 0;
4556
- return original.flatMap((item) => carriers.has(item) ? [item] : item.type === "additional_tools" ? [] : [decoded[next++]]);
4557
- }
4558
- };
4559
- }
4560
- function encodeGeminiCallId(id, signature, maxBytes) {
4561
- if (id.includes(signatureSeparator))
4562
- fail("invalid_tool_arguments", "Gemini call id contains the signature separator", "functionCall.id");
4563
- return signature === undefined ? id : `${id}${signatureSeparator}${checkedSignature(signature, maxBytes)}`;
4564
- }
4565
- function decodeGeminiCallId(value, maxBytes) {
4566
- const separator = value.indexOf(signatureSeparator);
4567
- if (separator < 0)
4568
- return { id: value };
4569
- const id = string(value.slice(0, separator), "functionCall.id", true);
4570
- return { id, thoughtSignature: checkedSignature(value.slice(separator + signatureSeparator.length), maxBytes) };
4571
- }
4572
-
4573
4662
  // packages/llms/src/protocol-session/schema.ts
4574
4663
  function geminiSchemaToJson(raw, path, code = "unsupported_request", depth = 0) {
4575
4664
  if (depth > 64)
4576
4665
  fail("resource_limit", "Schema nesting exceeds the conversion limit", path);
4577
4666
  const s = record(raw, path);
4578
- 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);
4667
+ 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);
4579
4668
  const out = {};
4580
4669
  if (s.type !== undefined) {
4581
4670
  const types = { STRING: "string", NUMBER: "number", INTEGER: "integer", BOOLEAN: "boolean", ARRAY: "array", OBJECT: "object", NULL: "null" };
@@ -4615,19 +4704,19 @@ function message(input, role, content, style, path) {
4615
4704
  function toolDefinition(raw, style, path) {
4616
4705
  const t = record(raw, path);
4617
4706
  if (style === "chat") {
4618
- fields2(t, t.type === "custom" ? ["type", "custom"] : ["type", "function"], path, "unsupported_tool");
4707
+ fields(t, t.type === "custom" ? ["type", "custom"] : ["type", "function"], path, "unsupported_tool");
4619
4708
  if (t.type === "custom") {
4620
4709
  const custom = record(t.custom, `${path}.custom`);
4621
- fields2(custom, ["name", "description", "format"], `${path}.custom`, "unsupported_tool");
4710
+ fields(custom, ["name", "description", "format"], `${path}.custom`, "unsupported_tool");
4622
4711
  return { type: "custom", ...custom };
4623
4712
  }
4624
4713
  if (t.type !== "function")
4625
4714
  fail("unsupported_tool", "Unsupported tool kind", `${path}.type`);
4626
4715
  const fn = record(t.function, path);
4627
- fields2(fn, ["name", "description", "parameters", "strict"], `${path}.function`, "unsupported_tool");
4716
+ fields(fn, ["name", "description", "parameters", "strict"], `${path}.function`, "unsupported_tool");
4628
4717
  return { type: "function", ...fn };
4629
4718
  }
4630
- fields2(t, style === "anthropic" ? ["name", "description", "input_schema", "strict"] : ["name", "description", "parametersJsonSchema", "parameters"], path, "unsupported_tool");
4719
+ fields(t, style === "anthropic" ? ["name", "description", "input_schema", "strict"] : ["name", "description", "parametersJsonSchema", "parameters"], path, "unsupported_tool");
4631
4720
  if (t.parameters !== undefined && t.parametersJsonSchema !== undefined)
4632
4721
  fail("unsupported_tool", "Ambiguous schema dialect", path);
4633
4722
  return {
@@ -4650,13 +4739,13 @@ function canonicalRequest(raw, protocol, model) {
4650
4739
  };
4651
4740
  if (protocol === "chat_completions") {
4652
4741
  const callKinds = new Map;
4653
- 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"], "");
4742
+ 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"], "");
4654
4743
  if (b.max_tokens !== undefined && b.max_completion_tokens !== undefined)
4655
4744
  fail("unsupported_request", "Ambiguous token limits", "max_tokens");
4656
4745
  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" });
4657
4746
  for (const [index, rawMessage] of list(b.messages, "messages").entries()) {
4658
4747
  const m = record(rawMessage, "message"), path = `messages[${index}]`;
4659
- fields2(m, ["role", "content", "tool_calls", "tool_call_id", "reasoning_content", "reasoning", "refusal", "name"], path, "unsupported_content");
4748
+ fields(m, ["role", "content", "tool_calls", "tool_call_id", "reasoning_content", "reasoning", "refusal", "name"], path, "unsupported_content");
4660
4749
  if (m.name !== undefined)
4661
4750
  fail("unsupported_content", "Named messages cannot be represented faithfully", `${path}.name`);
4662
4751
  const role = string(m.role, "role", true);
@@ -4691,12 +4780,12 @@ function canonicalRequest(raw, protocol, model) {
4691
4780
  fail("invalid_tool_history", "Tool calls require assistant role", path);
4692
4781
  for (const [j, rawCall] of list(m.tool_calls, "tool_calls").entries()) {
4693
4782
  const c = record(rawCall, "tool call"), at = `${path}.tool_calls[${j}]`;
4694
- fields2(c, ["id", "type", "function", "custom"], at, "unsupported_tool");
4783
+ fields(c, ["id", "type", "function", "custom"], at, "unsupported_tool");
4695
4784
  const custom = c.type === "custom";
4696
4785
  if (!custom && c.type !== "function")
4697
4786
  fail("unsupported_tool", "Unknown call type", at);
4698
4787
  const fn = record(custom ? c.custom : c.function, "tool call");
4699
- fields2(fn, custom ? ["name", "input"] : ["name", "arguments"], at, "unsupported_tool");
4788
+ fields(fn, custom ? ["name", "input"] : ["name", "arguments"], at, "unsupported_tool");
4700
4789
  callKinds.set(string(c.id, "id", true), custom);
4701
4790
  input.push({
4702
4791
  type: custom ? "custom_tool_call" : "function_call",
@@ -4715,9 +4804,9 @@ function canonicalRequest(raw, protocol, model) {
4715
4804
  out.tool_choice = c;
4716
4805
  else {
4717
4806
  const choice = record(c, "tool_choice");
4718
- fields2(choice, ["type", "function", "custom"], "tool_choice");
4807
+ fields(choice, ["type", "function", "custom"], "tool_choice");
4719
4808
  const fn = record(choice.function ?? choice.custom, "tool_choice");
4720
- fields2(fn, ["name"], "tool_choice.function");
4809
+ fields(fn, ["name"], "tool_choice.function");
4721
4810
  out.tool_choice = { type: choice.type, name: fn.name };
4722
4811
  }
4723
4812
  }
@@ -4725,19 +4814,19 @@ function canonicalRequest(raw, protocol, model) {
4725
4814
  out.reasoning = { effort: b.reasoning_effort };
4726
4815
  if (b.response_format !== undefined) {
4727
4816
  const format = record(b.response_format, "response_format");
4728
- fields2(format, ["type", "json_schema"], "response_format");
4817
+ fields(format, ["type", "json_schema"], "response_format");
4729
4818
  out.text = { format: format.type === "json_schema" ? { type: "json_schema", ...record(format.json_schema, "json_schema") } : format };
4730
4819
  }
4731
4820
  return out;
4732
4821
  }
4733
4822
  if (protocol === "anthropic_messages") {
4734
- fields2(b, ["model", "messages", "system", "tools", "tool_choice", "stream", "temperature", "top_p", "max_tokens", "metadata", "stop_sequences", "thinking", "output_config"], "");
4823
+ fields(b, ["model", "messages", "system", "tools", "tool_choice", "stream", "temperature", "top_p", "max_tokens", "metadata", "stop_sequences", "thinking", "output_config"], "");
4735
4824
  copy({ stream: "stream", temperature: "temperature", top_p: "top_p", max_tokens: "max_output_tokens", metadata: "metadata", stop_sequences: "stop" });
4736
4825
  if (b.system !== undefined)
4737
4826
  message(input, "system", b.system, "anthropic", "system");
4738
4827
  for (const [index, rawMessage] of list(b.messages, "messages").entries()) {
4739
4828
  const m = record(rawMessage, "message"), path = `messages[${index}]`;
4740
- fields2(m, ["role", "content"], path, "unsupported_content");
4829
+ fields(m, ["role", "content"], path, "unsupported_content");
4741
4830
  if (m.role !== "user" && m.role !== "assistant")
4742
4831
  fail("unsupported_content", "Anthropic messages require user or assistant role", `${path}.role`);
4743
4832
  if (typeof m.content === "string") {
@@ -4749,15 +4838,15 @@ function canonicalRequest(raw, protocol, model) {
4749
4838
  if (p.type === "tool_use") {
4750
4839
  if (m.role !== "assistant")
4751
4840
  fail("invalid_tool_history", "Tool calls require assistant role", at);
4752
- fields2(p, ["type", "id", "name", "input"], at, "unsupported_content");
4841
+ fields(p, ["type", "id", "name", "input"], at, "unsupported_content");
4753
4842
  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)) });
4754
4843
  } else if (p.type === "tool_result") {
4755
4844
  if (m.role !== "user")
4756
4845
  fail("invalid_tool_history", "Tool results require user role", at);
4757
- fields2(p, ["type", "tool_use_id", "content", "is_error"], at, "unsupported_content");
4846
+ fields(p, ["type", "tool_use_id", "content", "is_error"], at, "unsupported_content");
4758
4847
  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) } : {} });
4759
4848
  } else if (p.type === "thinking") {
4760
- fields2(p, ["type", "thinking", "signature"], at, "unsupported_reasoning");
4849
+ fields(p, ["type", "thinking", "signature"], at, "unsupported_reasoning");
4761
4850
  if (p.signature != null)
4762
4851
  fail("unsupported_reasoning", "Provider-bound reasoning signatures cannot cross protocols", `${at}.signature`);
4763
4852
  if (m.role !== "assistant")
@@ -4771,7 +4860,7 @@ function canonicalRequest(raw, protocol, model) {
4771
4860
  out.tools = list(b.tools, "tools").map((t, i) => toolDefinition(t, "anthropic", `tools[${i}]`));
4772
4861
  if (b.tool_choice !== undefined) {
4773
4862
  const c = record(b.tool_choice, "tool_choice");
4774
- fields2(c, ["type", "name", "disable_parallel_tool_use"], "tool_choice");
4863
+ fields(c, ["type", "name", "disable_parallel_tool_use"], "tool_choice");
4775
4864
  if (c.type === "tool")
4776
4865
  out.tool_choice = { type: "function", name: c.name };
4777
4866
  else if (["auto", "none", "any"].includes(String(c.type)))
@@ -4783,7 +4872,7 @@ function canonicalRequest(raw, protocol, model) {
4783
4872
  }
4784
4873
  if (b.thinking !== undefined) {
4785
4874
  const t = record(b.thinking, "thinking");
4786
- fields2(t, ["type", "budget_tokens"], "thinking", "unsupported_reasoning");
4875
+ fields(t, ["type", "budget_tokens"], "thinking", "unsupported_reasoning");
4787
4876
  if (!["enabled", "adaptive", "disabled"].includes(String(t.type)))
4788
4877
  fail("unsupported_reasoning", "Unknown thinking mode", "thinking.type");
4789
4878
  if (t.type === "enabled")
@@ -4794,12 +4883,12 @@ function canonicalRequest(raw, protocol, model) {
4794
4883
  }
4795
4884
  if (b.output_config !== undefined) {
4796
4885
  const c = record(b.output_config, "output_config");
4797
- fields2(c, ["effort", "format"], "output_config");
4886
+ fields(c, ["effort", "format"], "output_config");
4798
4887
  if (c.effort !== undefined)
4799
4888
  out.reasoning = { effort: c.effort };
4800
4889
  if (c.format !== undefined) {
4801
4890
  const f = record(c.format, "format");
4802
- fields2(f, ["type", "schema"], "output_config.format");
4891
+ fields(f, ["type", "schema"], "output_config.format");
4803
4892
  if (f.type !== "json_schema")
4804
4893
  fail("unsupported_request", "Unknown structured output type", "output_config.format.type");
4805
4894
  out.text = { format: { type: "json_schema", name: "response", schema: f.schema } };
@@ -4807,12 +4896,12 @@ function canonicalRequest(raw, protocol, model) {
4807
4896
  }
4808
4897
  return out;
4809
4898
  }
4810
- fields2(b, ["contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "model", "stream"], "");
4899
+ fields(b, ["contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "model", "stream"], "");
4811
4900
  if (b.stream !== undefined)
4812
4901
  out.stream = b.stream;
4813
4902
  if (b.systemInstruction !== undefined) {
4814
4903
  const s = record(b.systemInstruction, "systemInstruction");
4815
- fields2(s, ["role", "parts"], "systemInstruction");
4904
+ fields(s, ["role", "parts"], "systemInstruction");
4816
4905
  if (s.role !== undefined && s.role !== "system")
4817
4906
  fail("unsupported_content", "Invalid system role", "systemInstruction.role");
4818
4907
  message(input, "system", s.parts, "gemini", "systemInstruction");
@@ -4822,12 +4911,12 @@ function canonicalRequest(raw, protocol, model) {
4822
4911
  for (const [index, rawContent] of list(b.contents, "contents").entries()) {
4823
4912
  const original = record(rawContent, "content"), path = `contents[${index}]`;
4824
4913
  const c = { ...original, role: original.role ?? "user" };
4825
- fields2(c, ["role", "parts"], path, "unsupported_content");
4914
+ fields(c, ["role", "parts"], path, "unsupported_content");
4826
4915
  if (c.role !== "user" && c.role !== "model")
4827
4916
  fail("unsupported_content", "Gemini contents require user or model role", `${path}.role`);
4828
4917
  for (const [j, rawPart] of list(c.parts, "parts").entries()) {
4829
4918
  const p = record(rawPart, "part"), at = `${path}.parts[${j}]`;
4830
- fields2(p, ["text", "thought", "functionCall", "functionResponse", "thoughtSignature"], at, "unsupported_content");
4919
+ fields(p, ["text", "thought", "functionCall", "functionResponse", "thoughtSignature"], at, "unsupported_content");
4831
4920
  if (p.thoughtSignature !== undefined)
4832
4921
  fail("unsupported_reasoning", "Provider-bound thought signatures cannot cross protocols", `${at}.thoughtSignature`);
4833
4922
  if ([p.text, p.functionCall, p.functionResponse].filter((v) => v !== undefined).length !== 1)
@@ -4836,7 +4925,7 @@ function canonicalRequest(raw, protocol, model) {
4836
4925
  if (c.role !== "model")
4837
4926
  fail("invalid_tool_history", "Function calls require model role", at);
4838
4927
  const f = record(p.functionCall, at);
4839
- fields2(f, ["name", "args", "id"], `${at}.functionCall`, "unsupported_tool");
4928
+ fields(f, ["name", "args", "id"], `${at}.functionCall`, "unsupported_tool");
4840
4929
  const name = string(f.name, at, true), id = f.id === undefined ? `call_gemini_${serial++}` : string(f.id, at, true);
4841
4930
  if (calls.has(id))
4842
4931
  fail("invalid_tool_history", "Duplicate tool call id", at);
@@ -4846,7 +4935,7 @@ function canonicalRequest(raw, protocol, model) {
4846
4935
  if (c.role !== "user")
4847
4936
  fail("invalid_tool_history", "Function results require user role", at);
4848
4937
  const f = record(p.functionResponse, at);
4849
- fields2(f, ["name", "response", "id"], `${at}.functionResponse`, "unsupported_tool");
4938
+ fields(f, ["name", "response", "id"], `${at}.functionResponse`, "unsupported_tool");
4850
4939
  const matches = [...calls.values()].filter((v) => v.name === f.name);
4851
4940
  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);
4852
4941
  if (calls.get(id)?.name !== f.name)
@@ -4865,7 +4954,7 @@ function canonicalRequest(raw, protocol, model) {
4865
4954
  const tools = [];
4866
4955
  for (const [i, rawTool] of list(b.tools, "tools").entries()) {
4867
4956
  const t = record(rawTool, "tool");
4868
- fields2(t, ["functionDeclarations"], `tools[${i}]`, "unsupported_tool");
4957
+ fields(t, ["functionDeclarations"], `tools[${i}]`, "unsupported_tool");
4869
4958
  for (const [j, f] of list(t.functionDeclarations, "functionDeclarations").entries())
4870
4959
  tools.push(toolDefinition(f, "gemini", `tools[${i}].functionDeclarations[${j}]`));
4871
4960
  }
@@ -4873,9 +4962,9 @@ function canonicalRequest(raw, protocol, model) {
4873
4962
  }
4874
4963
  if (b.toolConfig !== undefined) {
4875
4964
  const config = record(b.toolConfig, "toolConfig");
4876
- fields2(config, ["functionCallingConfig"], "toolConfig");
4965
+ fields(config, ["functionCallingConfig"], "toolConfig");
4877
4966
  const c = record(config.functionCallingConfig, "functionCallingConfig");
4878
- fields2(c, ["mode", "allowedFunctionNames"], "toolConfig.functionCallingConfig");
4967
+ fields(c, ["mode", "allowedFunctionNames"], "toolConfig.functionCallingConfig");
4879
4968
  if (!["AUTO", "NONE", "ANY"].includes(String(c.mode)))
4880
4969
  fail("unsupported_tool_choice", "Unknown function calling mode", "toolConfig.functionCallingConfig.mode");
4881
4970
  if (c.allowedFunctionNames !== undefined) {
@@ -4888,7 +4977,7 @@ function canonicalRequest(raw, protocol, model) {
4888
4977
  }
4889
4978
  if (b.generationConfig !== undefined) {
4890
4979
  const c = record(b.generationConfig, "generationConfig");
4891
- fields2(c, ["temperature", "topP", "maxOutputTokens", "stopSequences", "candidateCount", "responseMimeType", "responseJsonSchema", "responseSchema", "thinkingConfig"], "generationConfig");
4980
+ fields(c, ["temperature", "topP", "maxOutputTokens", "stopSequences", "candidateCount", "responseMimeType", "responseJsonSchema", "responseSchema", "thinkingConfig"], "generationConfig");
4892
4981
  for (const [from, to] of Object.entries({ temperature: "temperature", topP: "top_p", maxOutputTokens: "max_output_tokens", stopSequences: "stop", candidateCount: "n" }))
4893
4982
  if (c[from] !== undefined)
4894
4983
  out[to] = c[from];
@@ -4906,7 +4995,7 @@ function canonicalRequest(raw, protocol, model) {
4906
4995
  }
4907
4996
  if (c.thinkingConfig !== undefined) {
4908
4997
  const t = record(c.thinkingConfig, "thinkingConfig");
4909
- fields2(t, ["thinkingBudget", "thinkingLevel", "includeThoughts"], "generationConfig.thinkingConfig", "unsupported_reasoning");
4998
+ fields(t, ["thinkingBudget", "thinkingLevel", "includeThoughts"], "generationConfig.thinkingConfig", "unsupported_reasoning");
4910
4999
  if (t.thinkingBudget !== undefined)
4911
5000
  integer(t.thinkingBudget, "generationConfig.thinkingConfig.thinkingBudget", -1);
4912
5001
  if (t.thinkingLevel !== undefined)
@@ -4918,7 +5007,10 @@ function canonicalRequest(raw, protocol, model) {
4918
5007
  }
4919
5008
  return out;
4920
5009
  }
4921
- function validateCanonical(b, context) {
5010
+ function validateCanonical(b, context, chatConfigurationUpdates) {
5011
+ const responsesToGemini = context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content";
5012
+ const allowLossyContinuation = chatConfigurationUpdates !== undefined;
5013
+ let configuration;
4922
5014
  for (const key of ["stream", "parallel_tool_calls", "store", "background"])
4923
5015
  if (b[key] !== undefined)
4924
5016
  bool(b[key], key);
@@ -4926,13 +5018,13 @@ function validateCanonical(b, context) {
4926
5018
  if (b[key] !== undefined && (typeof b[key] !== "number" || !Number.isFinite(b[key])))
4927
5019
  fail("invalid_payload", "Sampling value must be finite", key);
4928
5020
  if (b.tool_choice !== undefined && typeof b.tool_choice !== "string")
4929
- fields2(record(b.tool_choice, "tool_choice"), ["type", "name", "namespace"], "tool_choice", "unsupported_tool_choice");
5021
+ fields(record(b.tool_choice, "tool_choice"), ["type", "name", "namespace"], "tool_choice", "unsupported_tool_choice");
4930
5022
  if (b.text !== undefined) {
4931
5023
  const text = record(b.text, "text");
4932
- fields2(text, ["format", "verbosity"], "text");
5024
+ fields(text, ["format", "verbosity"], "text");
4933
5025
  if (text.format !== undefined) {
4934
5026
  const f = record(text.format, "text.format");
4935
- fields2(f, f.type === "json_schema" ? ["type", "name", "schema", "strict", "description"] : ["type"], "text.format");
5027
+ fields(f, f.type === "json_schema" ? ["type", "name", "schema", "strict", "description"] : ["type"], "text.format");
4936
5028
  if (!["text", "json_object", "json_schema"].includes(String(f.type)))
4937
5029
  fail("unsupported_request", "Unknown structured output format", "text.format.type");
4938
5030
  if (f.type === "json_schema") {
@@ -4948,21 +5040,40 @@ function validateCanonical(b, context) {
4948
5040
  const input = typeof b.input === "string" ? [] : list(b.input, "input");
4949
5041
  for (const [i, raw] of input.entries()) {
4950
5042
  const t = record(raw, "input item"), p = `input[${i}]`;
5043
+ if ((responsesToGemini || allowLossyContinuation) && t.type === "configuration_update") {
5044
+ fields(t, ["type", "reasoning"], p, "unsupported_content");
5045
+ const reasoning = atParam(`${p}.reasoning`, () => record(t.reasoning, "configuration reasoning"));
5046
+ fields(reasoning, ["effort"], `${p}.reasoning`, "unsupported_reasoning");
5047
+ const param = `${p}.reasoning.effort`;
5048
+ const effort = atParam(param, () => string(reasoning.effort, "configuration effort", true));
5049
+ const map = context.reasoningPolicy?.effortMap;
5050
+ const level = map && Object.hasOwn(map, effort) ? map[effort] : undefined;
5051
+ if (typeof level !== "string" || !level || responsesToGemini && !["minimal", "low", "medium", "high"].includes(level))
5052
+ fail("unsupported_reasoning", responsesToGemini ? "Configuration update requires an explicit Gemini level mapping" : "Configuration update requires an explicit Chat effort mapping", param);
5053
+ configuration = { effort, level, param };
5054
+ chatConfigurationUpdates?.add(t);
5055
+ continue;
5056
+ }
4951
5057
  if (t.type === "agent_message") {
4952
5058
  validateAgentMessage(t, p, context.capabilities?.limits);
4953
5059
  continue;
4954
5060
  }
4955
- 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"];
4956
- fields2(t, [...allowed, "internal_chat_message_metadata_passthrough"], p, "unsupported_content");
5061
+ if (allowLossyContinuation && isGeminiSignatureCarrier(t.encrypted_content))
5062
+ fail("unsupported_content", "Gemini signature carriers cannot cross into Chat", `${p}.encrypted_content`);
5063
+ if (allowLossyContinuation && t.type === "compaction")
5064
+ continue;
5065
+ 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"];
5066
+ const assistantPhase = allowLossyContinuation && (t.type === undefined || t.type === "message") && t.role === "assistant";
5067
+ fields(t, [...allowed, "internal_chat_message_metadata_passthrough", ...assistantPhase ? ["phase"] : []], p, "unsupported_content");
4957
5068
  if (t.is_error !== undefined)
4958
5069
  bool(t.is_error, `${p}.is_error`);
4959
- if (t.type === "reasoning")
4960
- for (const [j, part] of list(t.summary, "summary").entries())
4961
- fields2(record(part, "summary"), ["type", "text"], `${p}.summary[${j}]`, "unsupported_reasoning");
5070
+ if (t.type === "reasoning" && !(allowLossyContinuation && t.encrypted_content != null && t.summary === undefined))
5071
+ for (const [j, part] of atParam(`${p}.summary`, () => list(t.summary, "summary")).entries())
5072
+ atParam(`${p}.summary[${j}]`, () => fields(record(part, "summary"), ["type", "text"], `${p}.summary[${j}]`, "unsupported_reasoning"));
4962
5073
  if (Array.isArray(t.content))
4963
5074
  for (const [j, part] of t.content.entries()) {
4964
5075
  const c = record(part, "part");
4965
- fields2(c, c.type === "input_image" ? ["type", "image_url", "detail"] : c.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], `${p}.content[${j}]`, "unsupported_content");
5076
+ 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");
4966
5077
  if (context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content" && t.role === "user" && c.type === "input_image") {
4967
5078
  atParam(`${p}.content[${j}].image_url`, () => string(c.image_url, "image URL", true));
4968
5079
  if (c.detail !== undefined && (typeof c.detail !== "string" || !["auto", "low", "high"].includes(c.detail)))
@@ -4973,7 +5084,7 @@ function validateCanonical(b, context) {
4973
5084
  for (const [j, part] of t.output.entries())
4974
5085
  atParam(`${p}.output[${j}]`, () => {
4975
5086
  const c = record(part, "tool output part");
4976
- fields2(c, c.type === "input_image" ? ["type", "image_url", "detail"] : ["type", "text", "annotations"], `${p}.output[${j}]`, "unsupported_content");
5087
+ fields(c, c.type === "input_image" ? ["type", "image_url", "detail"] : ["type", "text", "annotations"], `${p}.output[${j}]`, "unsupported_content");
4977
5088
  if (c.type === "input_image") {
4978
5089
  atParam(`${p}.output[${j}].image_url`, () => string(c.image_url, "image URL", true));
4979
5090
  if (c.detail !== undefined && (typeof c.detail !== "string" || !["auto", "low", "high"].includes(c.detail)))
@@ -4999,7 +5110,7 @@ function validateCanonical(b, context) {
4999
5110
  }
5000
5111
  if (t.type === "custom" && t.format !== undefined) {
5001
5112
  const f = record(t.format, "custom format");
5002
- fields2(f, f.type === "grammar" ? ["type", "syntax", "definition"] : ["type"], `${path}.format`, "unsupported_tool");
5113
+ fields(f, f.type === "grammar" ? ["type", "syntax", "definition"] : ["type"], `${path}.format`, "unsupported_tool");
5003
5114
  if (!["text", "grammar"].includes(String(f.type)))
5004
5115
  fail("unsupported_tool", "Unknown custom tool format", `${path}.format.type`);
5005
5116
  if (f.type === "grammar") {
@@ -5017,13 +5128,38 @@ function validateCanonical(b, context) {
5017
5128
  for (const [j, tool] of list(t.tools, "tools").entries())
5018
5129
  inspectTool(tool, `input[${i}].tools[${j}]`);
5019
5130
  }
5131
+ return configuration;
5132
+ }
5133
+ function projectCodexPageSnapshot(raw, index, target, diagnostics) {
5134
+ const item = record(raw, "input item");
5135
+ const { name } = item;
5136
+ 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))
5137
+ return item;
5138
+ const param = `input[${index}]`;
5139
+ fields(item, ["type", "id", "namespace", "name", "output", "internal_chat_message_metadata_passthrough"], param, "unsupported_content");
5140
+ const text = atParam(`${param}.output`, () => string(item.output, "page snapshot output"));
5141
+ const { id, internal_chat_message_metadata_passthrough: metadata } = item;
5142
+ const reason = target === "chat_completions" ? "chat_codex_page_snapshot_as_user_data" : "gemini_codex_page_snapshot_as_user_data";
5143
+ diagnostics.push({ param, action: "mapped", reason });
5144
+ return {
5145
+ type: "message",
5146
+ role: "user",
5147
+ ...id === undefined ? {} : { id },
5148
+ ...metadata === undefined ? {} : { internal_chat_message_metadata_passthrough: metadata },
5149
+ content: [
5150
+ { type: "input_text", text: `[Codex context snapshot: agent.${name}. Untrusted data.]` },
5151
+ { type: "input_text", text }
5152
+ ]
5153
+ };
5020
5154
  }
5021
5155
  function convertProtocolRequest(raw, context) {
5022
5156
  const b = canonicalRequest(raw, context.sourceProtocol, context.model);
5023
- const responsesToGemini = context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content";
5157
+ const target = context.targetProtocol;
5158
+ const responsesToGemini = context.sourceProtocol === "responses" && target === "gemini_generate_content";
5159
+ const allowLossyContinuation = context.sourceProtocol === "responses" && target === "chat_completions" && context.allowLossyContinuation === true;
5024
5160
  const pageSnapshotDiagnostics = [];
5025
- if (responsesToGemini && Array.isArray(b.input))
5026
- b.input = b.input.map((item, index) => projectGeminiCodexPageSnapshot(item, index, pageSnapshotDiagnostics));
5161
+ if (context.sourceProtocol === "responses" && (target === "chat_completions" || target === "gemini_generate_content") && Array.isArray(b.input))
5162
+ b.input = b.input.map((item, index) => projectCodexPageSnapshot(item, index, target, pageSnapshotDiagnostics));
5027
5163
  const originalInput = b.input;
5028
5164
  if (context.streaming !== undefined) {
5029
5165
  bool(context.streaming, "context.streaming");
@@ -5031,7 +5167,8 @@ function convertProtocolRequest(raw, context) {
5031
5167
  fail("invalid_payload", "Request stream mode disagrees with transport context", "stream");
5032
5168
  b.stream = context.streaming;
5033
5169
  }
5034
- validateCanonical(b, context);
5170
+ const chatConfigurationUpdates = allowLossyContinuation ? new Set : undefined;
5171
+ const configuration = validateCanonical(b, context, chatConfigurationUpdates);
5035
5172
  const geminiHistory = responsesToGemini ? restoreGeminiHistory(b.input, limits(context.capabilities?.limits)) : undefined;
5036
5173
  if (geminiHistory)
5037
5174
  b.input = geminiHistory.input;
@@ -5050,16 +5187,19 @@ function convertProtocolRequest(raw, context) {
5050
5187
  fail("unsupported_reasoning", "Thinking mode requires an explicit target wire policy", "thinking");
5051
5188
  let mappedEffort;
5052
5189
  if (reasoning?.effort !== undefined) {
5053
- const effort = string(reasoning.effort, "reasoning.effort", true);
5054
- mappedEffort = policy?.effortMap?.[effort];
5055
- if (mappedEffort === undefined && policy?.anthropicThinkingBudget === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
5056
- fail("unsupported_reasoning", "Reasoning effort requires an explicit verified wire mapping", "reasoning.effort");
5057
- if (mappedEffort !== undefined)
5058
- string(mappedEffort, "reasoningPolicy.effortMap", true);
5190
+ const effort = atParam("reasoning.effort", () => string(reasoning.effort, "reasoning.effort", true));
5191
+ if (!allowLossyContinuation || !configuration) {
5192
+ mappedEffort = policy?.effortMap?.[effort];
5193
+ if (mappedEffort === undefined && policy?.anthropicThinkingBudget === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
5194
+ fail("unsupported_reasoning", "Reasoning effort requires an explicit verified wire mapping", "reasoning.effort");
5195
+ if (mappedEffort !== undefined)
5196
+ string(mappedEffort, "reasoningPolicy.effortMap", true);
5197
+ }
5059
5198
  }
5199
+ if (configuration)
5200
+ mappedEffort = configuration.level;
5060
5201
  if (sourceThinking !== undefined && reasoning?.effort === undefined && policy?.targetEffort !== undefined)
5061
5202
  mappedEffort = string(policy.targetEffort, "reasoningPolicy.targetEffort", true);
5062
- const target = context.targetProtocol;
5063
5203
  if (target === "gemini_generate_content" && reasoning?.effort !== undefined && mappedEffort === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
5064
5204
  fail("unsupported_reasoning", "Gemini requires an explicit thinking budget or level", "reasoning.effort");
5065
5205
  if (sourceThinking !== undefined) {
@@ -5098,7 +5238,7 @@ function convertProtocolRequest(raw, context) {
5098
5238
  }
5099
5239
  if (b.metadata !== undefined) {
5100
5240
  const metadata = record(b.metadata, "metadata");
5101
- fields2(metadata, ["user_id"], "metadata");
5241
+ fields(metadata, ["user_id"], "metadata");
5102
5242
  if (metadata.user_id !== undefined)
5103
5243
  string(metadata.user_id, "metadata.user_id");
5104
5244
  }
@@ -5110,7 +5250,7 @@ function convertProtocolRequest(raw, context) {
5110
5250
  } else if (target === "chat_completions") {
5111
5251
  if (reasoning?.effort !== undefined || mappedEffort !== undefined) {
5112
5252
  if (!cap.reasoningEffort)
5113
- fail("unsupported_reasoning", "Target effort capability is required", "reasoning.effort");
5253
+ fail("unsupported_reasoning", "Target effort capability is required", configuration?.param ?? "reasoning.effort");
5114
5254
  b.reasoning = { ...reasoning, effort: mappedEffort };
5115
5255
  if (mappedEffort === undefined)
5116
5256
  fail("unsupported_reasoning", "Chat requires a target effort mapping", "reasoning.effort");
@@ -5122,9 +5262,21 @@ function convertProtocolRequest(raw, context) {
5122
5262
  const decodingTarget = target === "gemini_generate_content" ? "chat_completions" : target;
5123
5263
  if (target === "gemini_generate_content" && reasoning)
5124
5264
  b.reasoning = { ...reasoning, effort: undefined };
5125
- 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 });
5265
+ let decoded;
5266
+ try {
5267
+ 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 });
5268
+ } catch (error) {
5269
+ if (geminiHistory && error instanceof ResponsesCodecError && error.param !== undefined)
5270
+ throw new ResponsesCodecError(error.code, error.message, geminiHistory.sourceParam(error.param));
5271
+ throw error;
5272
+ }
5126
5273
  const diagnostics = decoded.diagnostics;
5274
+ if (geminiHistory)
5275
+ for (const diagnostic of diagnostics)
5276
+ diagnostic.param = geminiHistory.sourceParam(diagnostic.param);
5127
5277
  diagnostics.push(...pageSnapshotDiagnostics);
5278
+ if (configuration)
5279
+ diagnostics.push({ param: configuration.param, action: "mapped", reason: responsesToGemini ? "gemini_configuration_effort_update" : "chat_configuration_effort_update" });
5128
5280
  if (target === "gemini_generate_content" && decoded.body.parallel_tool_calls === true) {
5129
5281
  delete decoded.body.parallel_tool_calls;
5130
5282
  diagnostics.push({ param: "parallel_tool_calls", action: "omitted", reason: "gemini_parallel_tool_calls_allowed" });
@@ -5154,17 +5306,24 @@ function convertProtocolRequest(raw, context) {
5154
5306
  if (target === "gemini_generate_content" && (mappedEffort !== undefined || policy?.geminiThinkingBudget !== undefined || policy?.geminiThinkingLevel !== undefined)) {
5155
5307
  const level = policy?.geminiThinkingLevel ?? mappedEffort;
5156
5308
  if (policy?.geminiThinkingBudget !== undefined && level !== undefined)
5157
- fail("unsupported_reasoning", "Choose one Gemini thinking policy", "reasoningPolicy");
5309
+ fail("unsupported_reasoning", "Choose one Gemini thinking policy", configuration?.param ?? "reasoningPolicy");
5158
5310
  if (level !== undefined && !["minimal", "low", "medium", "high"].includes(level))
5159
5311
  fail("unsupported_reasoning", "Unknown Gemini thinking level", "reasoning.effort");
5160
5312
  if (mappedEffort !== undefined && policy?.geminiThinkingLevel !== undefined && mappedEffort !== policy.geminiThinkingLevel)
5161
- fail("unsupported_reasoning", "Conflicting Gemini thinking levels", "reasoning.effort");
5313
+ fail("unsupported_reasoning", "Conflicting Gemini thinking levels", configuration?.param ?? "reasoning.effort");
5162
5314
  const thinkingConfig = policy?.geminiThinkingBudget !== undefined ? { thinkingBudget: integer(policy.geminiThinkingBudget, "reasoningPolicy.geminiThinkingBudget", -1) } : { thinkingLevel: string(level, "reasoningPolicy.geminiThinkingLevel", true) };
5163
5315
  body.generationConfig = { ...record(body.generationConfig ?? {}, "generationConfig"), thinkingConfig };
5164
5316
  }
5165
5317
  if (mappedEffort !== undefined || sourceThinking !== undefined || policy?.anthropicThinkingBudget !== undefined)
5166
5318
  diagnostics.push({ param: "reasoning", action: "mapped", reason: "explicit_verified_wire_policy" });
5167
- return { body, canonicalHistory: geminiHistory?.canonicalHistory(decoded.canonicalInput) ?? decoded.canonicalInput, diagnostics, toolNames: decoded.toolNames, streaming: b.stream === true };
5319
+ return {
5320
+ body,
5321
+ canonicalHistory: geminiHistory?.canonicalHistory(decoded.canonicalInput) ?? decoded.canonicalInput,
5322
+ diagnostics,
5323
+ toolNames: decoded.toolNames,
5324
+ streaming: b.stream === true,
5325
+ ...configuration ? { effectiveReasoningEffort: configuration.effort } : {}
5326
+ };
5168
5327
  }
5169
5328
  function renderGemini(chat, context, input, signedParts, diagnostics) {
5170
5329
  const result = { contents: [] }, contents = result.contents, system = [], calls = new Map;
@@ -5312,11 +5471,11 @@ function validateUsage(raw, protocol) {
5312
5471
  return;
5313
5472
  }
5314
5473
  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"];
5315
- fields2(u, keys, "usage", "unsupported_response");
5474
+ fields(u, keys, "usage", "unsupported_response");
5316
5475
  for (const [key, value] of Object.entries(u)) {
5317
5476
  if (key.endsWith("_details")) {
5318
5477
  const d = record(value, "usage details");
5319
- fields2(d, key.includes("output") || key.includes("completion") ? ["reasoning_tokens"] : ["cached_tokens", "cache_creation_tokens"], `usage.${key}`, "unsupported_response");
5478
+ fields(d, key.includes("output") || key.includes("completion") ? ["reasoning_tokens"] : ["cached_tokens", "cache_creation_tokens"], `usage.${key}`, "unsupported_response");
5320
5479
  for (const [k, v] of Object.entries(d))
5321
5480
  integer(v, `usage.${key}.${k}`);
5322
5481
  } else
@@ -5337,10 +5496,10 @@ function validateProviderResponse(raw, protocol) {
5337
5496
  const m = record(c.message, "message");
5338
5497
  for (const [callIndex, rawCall] of (m.tool_calls == null ? [] : list(m.tool_calls, "tool_calls")).entries()) {
5339
5498
  const call = record(rawCall, "call");
5340
- fields2(call, ["id", "type", "function", "index"], "tool_calls", "unsupported_tool");
5499
+ fields(call, ["id", "type", "function", "index"], "tool_calls", "unsupported_tool");
5341
5500
  if (call.index !== undefined && integer(call.index, `tool_calls[${callIndex}].index`) !== callIndex)
5342
5501
  fail("invalid_payload", "Tool call index must match its array position", `tool_calls[${callIndex}].index`);
5343
- fields2(record(call.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
5502
+ fields(record(call.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
5344
5503
  }
5345
5504
  }
5346
5505
  validateUsage(b.usage, protocol);
@@ -5354,14 +5513,14 @@ function validateProviderResponse(raw, protocol) {
5354
5513
  return b;
5355
5514
  }
5356
5515
  function validateAnthropicBlock(b, path) {
5357
- fields2(b, b.type === "text" ? ["type", "text"] : b.type === "thinking" ? ["type", "thinking", "signature"] : ["type", "id", "name", "input"], path, "unsupported_content");
5516
+ fields(b, b.type === "text" ? ["type", "text"] : b.type === "thinking" ? ["type", "thinking", "signature"] : ["type", "id", "name", "input"], path, "unsupported_content");
5358
5517
  if (b.signature !== undefined)
5359
5518
  fail("unsupported_reasoning", "Signed provider reasoning cannot cross protocols", `${path}.signature`);
5360
5519
  }
5361
5520
  function validateCanonicalResponse(raw, context, itemOnly = false) {
5362
5521
  const b = record(raw, "response");
5363
5522
  serialized(b, limits(context.capabilities?.limits).maxOutputBytes, "response");
5364
- 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");
5523
+ 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");
5365
5524
  if (!itemOnly) {
5366
5525
  string(b.id, "response.id", true);
5367
5526
  integer(b.created_at, "response.created_at");
@@ -5372,7 +5531,7 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
5372
5531
  fail("missing_terminal", "Response has no explicit supported terminal", "status");
5373
5532
  if (b.status === "incomplete") {
5374
5533
  const d = record(b.incomplete_details, "incomplete_details");
5375
- fields2(d, ["reason"], "incomplete_details", "unsupported_response");
5534
+ fields(d, ["reason"], "incomplete_details", "unsupported_response");
5376
5535
  if (!["max_output_tokens", "content_filter"].includes(String(d.reason)))
5377
5536
  fail("unknown_terminal", "Unknown incomplete reason", "incomplete_details.reason");
5378
5537
  }
@@ -5387,13 +5546,13 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
5387
5546
  fail("unsupported_response", "Unknown item status", `${path}.status`);
5388
5547
  if (b.status === "completed" && t.status !== undefined && t.status !== "completed")
5389
5548
  fail("invalid_stream", "Completed response contains an unfinished item", `${path}.status`);
5390
- 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");
5549
+ 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");
5391
5550
  if (t.type === "message") {
5392
5551
  if (t.role !== "assistant")
5393
5552
  fail("unsupported_content", "Output message must be assistant", `${path}.role`);
5394
5553
  for (const [j, rawPart] of list(t.content, "content").entries()) {
5395
5554
  const p = record(rawPart, "part");
5396
- fields2(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], `${path}.content[${j}]`, "unsupported_content");
5555
+ fields(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], `${path}.content[${j}]`, "unsupported_content");
5397
5556
  if (p.type === "output_text")
5398
5557
  string(p.text, "text");
5399
5558
  else if (p.type === "refusal")
@@ -5412,7 +5571,7 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
5412
5571
  fail("unsupported_reasoning", "Opaque or raw reasoning output cannot cross protocols", path);
5413
5572
  for (const rawPart of list(t.summary, "summary")) {
5414
5573
  const p = record(rawPart, "summary");
5415
- fields2(p, ["type", "text"], path, "unsupported_reasoning");
5574
+ fields(p, ["type", "text"], path, "unsupported_reasoning");
5416
5575
  if (p.type !== "summary_text")
5417
5576
  fail("unsupported_reasoning", "Unknown reasoning summary type", path);
5418
5577
  string(p.text, "summary");
@@ -5555,7 +5714,7 @@ class GeminiCanonicalDecoder {
5555
5714
  const events = [];
5556
5715
  if (b.promptFeedback !== undefined) {
5557
5716
  const p = record(b.promptFeedback, "promptFeedback");
5558
- fields2(p, ["blockReason", "blockReasonMessage", "safetyRatings"], "promptFeedback", "unsupported_response");
5717
+ fields(p, ["blockReason", "blockReasonMessage", "safetyRatings"], "promptFeedback", "unsupported_response");
5559
5718
  if (p.blockReason !== undefined && p.blockReason !== "BLOCK_REASON_UNSPECIFIED") {
5560
5719
  this.ended = true;
5561
5720
  events.push(...this.encoder.push({ choices: [{ delta: {}, finish_reason: "content_filter" }] }));
@@ -5570,7 +5729,7 @@ class GeminiCanonicalDecoder {
5570
5729
  fail("unsupported_response", "Only candidate index zero is supported", "candidates.index");
5571
5730
  if (c.content !== undefined && c.content !== null) {
5572
5731
  const content = record(c.content, "content");
5573
- fields2(content, ["role", "parts"], "candidates.content", "unsupported_content");
5732
+ fields(content, ["role", "parts"], "candidates.content", "unsupported_content");
5574
5733
  if (content.role !== undefined && content.role !== "model")
5575
5734
  fail("unsupported_response", "Response role must be model", "candidates.content.role");
5576
5735
  const parts = list(content.parts ?? [], "parts");
@@ -5578,14 +5737,14 @@ class GeminiCanonicalDecoder {
5578
5737
  fail("invalid_stream", "Content arrived after Gemini terminal");
5579
5738
  for (const [i, rawPart] of parts.entries()) {
5580
5739
  const p = record(rawPart, "part");
5581
- fields2(p, ["text", "thought", "functionCall", "thoughtSignature"], "candidates.content.parts", "unsupported_content");
5740
+ fields(p, ["text", "thought", "functionCall", "thoughtSignature"], "candidates.content.parts", "unsupported_content");
5582
5741
  if (p.thoughtSignature !== undefined && this.context.sourceProtocol !== "responses")
5583
5742
  fail("unsupported_reasoning", "Thought signatures cannot cross protocols", "candidates.content.parts.thoughtSignature");
5584
5743
  if (p.functionCall !== undefined) {
5585
5744
  if (p.text !== undefined || p.thought !== undefined)
5586
5745
  fail("unsupported_content", "Mixed Gemini part kinds", "candidates.content.parts");
5587
5746
  const f = record(p.functionCall, "functionCall");
5588
- fields2(f, ["id", "name", "args"], "functionCall", "unsupported_tool");
5747
+ fields(f, ["id", "name", "args"], "functionCall", "unsupported_tool");
5589
5748
  const index = this.serial++, originalId = f.id === undefined ? `call_gemini_${crypto.randomUUID().replaceAll("-", "")}` : string(f.id, "functionCall.id", true);
5590
5749
  if (this.ids.has(originalId))
5591
5750
  fail("invalid_tool_arguments", "Duplicate Gemini call id", "functionCall.id");
@@ -5739,7 +5898,7 @@ class CanonicalStreamValidator {
5739
5898
  this.sequence = n;
5740
5899
  }
5741
5900
  if (["response.created", "response.in_progress", "response.completed", "response.incomplete", "response.failed"].includes(type)) {
5742
- fields2(e, [...common, "response"], "", "unsupported_response");
5901
+ fields(e, [...common, "response"], "", "unsupported_response");
5743
5902
  const r = record(e.response, "response");
5744
5903
  const id = string(r.id, "response.id", true);
5745
5904
  if (this.responseId !== undefined && this.responseId !== id)
@@ -5796,7 +5955,7 @@ class CanonicalStreamValidator {
5796
5955
  ];
5797
5956
  if (!known.includes(type))
5798
5957
  fail("unsupported_response", "Unknown Responses stream event", "type");
5799
- 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");
5958
+ 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");
5800
5959
  if (e.response_id !== undefined && e.response_id !== this.responseId)
5801
5960
  fail("invalid_stream", "Event response id changed", "response_id");
5802
5961
  const index = integer(e.output_index, "output_index");
@@ -5890,7 +6049,7 @@ class CanonicalStreamValidator {
5890
6049
  fail("unsupported_content", "Unknown content part type", "part.type");
5891
6050
  if (summary ? p.type !== "summary_text" : p.type === "summary_text")
5892
6051
  fail("invalid_stream", "Part kind differs from its output item", "part.type");
5893
- fields2(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
6052
+ fields(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
5894
6053
  if (p.annotations !== undefined && Array.isArray(p.annotations) && p.annotations.length)
5895
6054
  fail("unsupported_content", "Annotations cannot cross protocols", "part.annotations");
5896
6055
  const initial = string(p[p.type === "refusal" ? "refusal" : "text"], "part text");
@@ -5915,7 +6074,7 @@ class CanonicalStreamValidator {
5915
6074
  if (!p.textDone)
5916
6075
  fail("invalid_stream", "Part done before text done");
5917
6076
  const v = record(e.part, "part");
5918
- fields2(v, p.kind === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
6077
+ fields(v, p.kind === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
5919
6078
  if (v.annotations !== undefined && (!Array.isArray(v.annotations) || v.annotations.length))
5920
6079
  fail("unsupported_content", "Annotations cannot cross protocols", "part.annotations");
5921
6080
  if (v.type !== p.kind || v[p.kind === "refusal" ? "refusal" : "text"] !== p.text)
@@ -6069,7 +6228,7 @@ class CanonicalStreamRenderer {
6069
6228
  var LLM_PROTOCOLS = ["responses", "chat_completions", "anthropic_messages", "gemini_generate_content"];
6070
6229
 
6071
6230
  // packages/llms/src/protocol-session/index.ts
6072
- var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.4";
6231
+ var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.6";
6073
6232
  function describeProtocolConversion() {
6074
6233
  return {
6075
6234
  rulesVersion: PROTOCOL_CONVERSION_RULES_VERSION,
@@ -6278,9 +6437,9 @@ function validateStreamEnvelope(raw, protocol) {
6278
6437
  if (Array.isArray(d.tool_calls))
6279
6438
  for (const rawCall of d.tool_calls) {
6280
6439
  const t = record(rawCall, "tool call");
6281
- fields2(t, ["index", "id", "type", "function"], "tool_calls", "unsupported_tool");
6440
+ fields(t, ["index", "id", "type", "function"], "tool_calls", "unsupported_tool");
6282
6441
  if (t.function !== undefined)
6283
- fields2(record(t.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
6442
+ fields(record(t.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
6284
6443
  }
6285
6444
  }
6286
6445
  validateUsage(e.usage, protocol);
@@ -6289,12 +6448,12 @@ function validateStreamEnvelope(raw, protocol) {
6289
6448
  validateAnthropicBlock(record(e.content_block, "block"), "content_block");
6290
6449
  if (e.type === "content_block_delta") {
6291
6450
  const d = record(e.delta, "delta");
6292
- 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");
6451
+ 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");
6293
6452
  if (d.type === "signature_delta" || d.signature !== undefined)
6294
6453
  fail("unsupported_reasoning", "Signed provider reasoning cannot cross protocols", "delta.signature");
6295
6454
  }
6296
6455
  if (e.type === "message_delta")
6297
- fields2(record(e.delta, "delta"), ["stop_reason", "stop_sequence"], "delta", "unsupported_response");
6456
+ fields(record(e.delta, "delta"), ["stop_reason", "stop_sequence"], "delta", "unsupported_response");
6298
6457
  if (e.type === "message_start") {
6299
6458
  const m = record(e.message, "message");
6300
6459
  validateUsage(m.usage, protocol);
@@ -6703,7 +6862,7 @@ class AgentRelay {
6703
6862
  }
6704
6863
 
6705
6864
  // plugins/llm-protocol-adapter/server/service.ts
6706
- var REASONING_RULES_VERSION = "2026-10-27.1";
6865
+ var REASONING_RULES_VERSION = "2026-11-11.2";
6707
6866
  var concrete = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
6708
6867
  var effortProtocols = new Set(["responses", "chat_completions", "anthropic_messages", "gemini_generate_content"]);
6709
6868
  var geminiEfforts = new Set(["minimal", "low", "medium", "high"]);
@@ -6802,7 +6961,8 @@ function conversionService(catalog, worker, history, runBackground) {
6802
6961
  let catalogVersion = profile?.catalogVersion ?? null;
6803
6962
  let selected = context.selectedEffort, rewrittenDeveloper = false;
6804
6963
  const passthrough = context.sourceProtocol === context.targetProtocol;
6805
- if (!passthrough && selected !== undefined && (!profile || !profile.supportedEfforts.includes(selected)))
6964
+ const lossyChat = context.sourceProtocol === "responses" && context.targetProtocol === "chat_completions" && context.allowLossyContinuation === true;
6965
+ if (!passthrough && !lossyChat && selected !== undefined && (!profile || !profile.supportedEfforts.includes(selected)))
6806
6966
  fail2("reasoning.effort");
6807
6967
  const engine = createProtocolSession({
6808
6968
  ...context,
@@ -6815,11 +6975,17 @@ function conversionService(catalog, worker, history, runBackground) {
6815
6975
  convertRequest(raw) {
6816
6976
  const effort = wireEffort(raw, context.sourceProtocol);
6817
6977
  if (effort !== undefined) {
6818
- if (typeof effort !== "string" || !passthrough && !profile?.supportedEfforts.includes(effort) || selected !== undefined && selected !== effort)
6978
+ if (typeof effort !== "string" || !passthrough && !lossyChat && !profile?.supportedEfforts.includes(effort) || selected !== undefined && selected !== effort)
6819
6979
  fail2("reasoning.effort");
6820
6980
  selected = effort;
6821
6981
  }
6822
6982
  const result = engine.convertRequest(raw);
6983
+ if (result.effectiveReasoningEffort !== undefined) {
6984
+ if (!profile?.supportedEfforts.includes(result.effectiveReasoningEffort))
6985
+ fail2("reasoning.effort");
6986
+ selected = result.effectiveReasoningEffort;
6987
+ } else if (lossyChat && selected !== undefined && !profile?.supportedEfforts.includes(selected))
6988
+ fail2("reasoning.effort");
6823
6989
  rewrittenDeveloper = false;
6824
6990
  if (deepseekChat) {
6825
6991
  for (const message of chatMessages(result.body))
@@ -6937,4 +7103,4 @@ export {
6937
7103
  control_default as default
6938
7104
  };
6939
7105
 
6940
- //# debugId=DF2F30C0215A142764756E2164756E21
7106
+ //# debugId=85BC5CA0BC5492CC64756E2164756E21