@jeffusion/bungee-llms 6.15.1 → 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.
@@ -2062,6 +2062,240 @@ function validateEncryptedFunctionArgs(item, delivery, path) {
2062
2062
  fail("unsupported_content", "Encrypted function arguments cannot cross protocols", param);
2063
2063
  }
2064
2064
 
2065
+ // src/protocol-session/gemini.ts
2066
+ import { createHash } from "crypto";
2067
+
2068
+ // src/protocol-session/validation.ts
2069
+ function fields(value, allowed, path, code = "unsupported_request") {
2070
+ for (const key of Object.keys(value))
2071
+ if (!allowed.includes(key))
2072
+ fail(code, "Field cannot be represented by the target protocol", path ? `${path}.${key}` : key);
2073
+ }
2074
+ function bool(value, path) {
2075
+ if (typeof value !== "boolean")
2076
+ fail("invalid_payload", "Expected a boolean", path);
2077
+ return value;
2078
+ }
2079
+ function integer(value, path, min = 0) {
2080
+ if (!Number.isSafeInteger(value) || value < min)
2081
+ fail("invalid_payload", "Expected an integer in the supported range", path);
2082
+ return value;
2083
+ }
2084
+ function textParts(raw, path, style, role) {
2085
+ if (typeof raw === "string")
2086
+ return [{ type: "input_text", text: raw }];
2087
+ return list(raw, path).map((rawPart, index) => {
2088
+ const p = record(rawPart, path), at = `${path}[${index}]`;
2089
+ if (style === "gemini") {
2090
+ fields(p, ["text", "thought"], at, "unsupported_content");
2091
+ if (p.thought === true)
2092
+ fail("unsupported_reasoning", "Reasoning must be represented as a separate history item", at);
2093
+ return { type: "input_text", text: string(p.text, at) };
2094
+ }
2095
+ if (style === "chat" && p.type === "image_url" && role === "user") {
2096
+ fields(p, ["type", "image_url"], at, "unsupported_content");
2097
+ const image = record(p.image_url, at);
2098
+ fields(image, ["url", "detail"], `${at}.image_url`, "unsupported_content");
2099
+ return { type: "input_image", image_url: string(image.url, at, true), ...image.detail !== undefined ? { detail: image.detail } : {} };
2100
+ }
2101
+ if (style === "chat" && p.type === "refusal" && role === "assistant") {
2102
+ fields(p, ["type", "refusal"], at, "unsupported_content");
2103
+ return { type: "refusal", refusal: string(p.refusal, at) };
2104
+ }
2105
+ if (p.type !== "text")
2106
+ fail("unsupported_content", "Content block cannot be represented by the target protocol", at);
2107
+ fields(p, ["type", "text"], at, "unsupported_content");
2108
+ return { type: "input_text", text: string(p.text, at) };
2109
+ });
2110
+ }
2111
+
2112
+ // src/protocol-session/gemini.ts
2113
+ var signatureSeparator = "__thought__";
2114
+ function geminiInlineImage(image, path, budget) {
2115
+ const param = `${path}.image_url`;
2116
+ const url = bounded(string(image.url, "image URL", true), budget.maxRequestBytes, param);
2117
+ const match = /^data:([^;,]+);base64,([\s\S]*)$/.exec(url);
2118
+ if (!match || !["image/png", "image/jpeg", "image/webp"].includes(match[1]))
2119
+ fail("unsupported_content", "Gemini images require inline PNG, JPEG or WebP data", param);
2120
+ const data = match[2];
2121
+ 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(/=+$/, ""))
2122
+ fail("invalid_payload", "Invalid image Base64 encoding", param);
2123
+ return { mimeType: match[1], data };
2124
+ }
2125
+ function geminiToolResponse(content, path, budget, diagnostics) {
2126
+ if (!Array.isArray(content) || !content.some((part) => part.type === "image_url"))
2127
+ return { response: { output: content } };
2128
+ if (content.length > budget.maxItems)
2129
+ fail("resource_limit", "Too many tool output parts", path);
2130
+ const parts = [];
2131
+ const output = content.map((part, index) => atParam(`${path}[${index}]`, () => {
2132
+ if (part.type === "text")
2133
+ return part;
2134
+ if (part.type !== "image_url")
2135
+ fail("unsupported_content", "Unsupported Gemini tool result content");
2136
+ const image = record(part.image_url, "tool image");
2137
+ const inlineData = geminiInlineImage(image, `${path}[${index}]`, budget);
2138
+ const displayName = `tool-image-${index}.${inlineData.mimeType.slice("image/".length)}`;
2139
+ parts.push({ inlineData: { ...inlineData, displayName } });
2140
+ if (image.detail !== undefined)
2141
+ diagnostics.push({ param: `${path}[${index}].detail`, action: "omitted", reason: "gemini_tool_image_detail_unavailable" });
2142
+ return { $ref: displayName };
2143
+ }));
2144
+ return { response: { output }, parts };
2145
+ }
2146
+ function checkedSignature(value, maxBytes) {
2147
+ const signature = bounded(string(value, "thoughtSignature", true), maxBytes, "thoughtSignature");
2148
+ 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(/=+$/, ""))
2149
+ fail("invalid_tool_arguments", "Invalid Gemini thought signature encoding", "thoughtSignature");
2150
+ return signature;
2151
+ }
2152
+ var envelopePrefix = "bungee_gemini:";
2153
+ var isGeminiSignatureCarrier = (value) => typeof value === "string" && value.startsWith(envelopePrefix);
2154
+ var geminiEnvelopeBytes = (payloadBytes) => envelopePrefix.length + Math.ceil(payloadBytes * 4 / 3);
2155
+ var geminiTextHash = (text) => createHash("sha256").update(text).digest("base64url");
2156
+ function geminiSignatureItem(items, budget) {
2157
+ const payload = serialized({ version: 1, items }, budget.maxArgumentBytes, "Gemini signatures");
2158
+ return {
2159
+ type: "reasoning",
2160
+ id: `rs_gemini_${crypto.randomUUID().replaceAll("-", "")}`,
2161
+ summary: [],
2162
+ encrypted_content: bounded(envelopePrefix + Buffer.from(payload).toString("base64url"), budget.maxArgumentBytes, "Gemini signatures")
2163
+ };
2164
+ }
2165
+ function readGeminiSignatures(item, budget) {
2166
+ fields(item, ["type", "id", "summary", "encrypted_content", "status"], "Gemini signatures", "unsupported_reasoning");
2167
+ if (item.type !== "reasoning" || list(item.summary, "summary").length)
2168
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier");
2169
+ string(item.id, "signature item id", true);
2170
+ const opaque = bounded(string(item.encrypted_content, "encrypted_content", true), budget.maxArgumentBytes, "Gemini signatures");
2171
+ if (!isGeminiSignatureCarrier(opaque))
2172
+ fail("unsupported_reasoning", "Native encrypted reasoning cannot be restored to Gemini");
2173
+ const encoded = opaque.slice(envelopePrefix.length), bytes = Buffer.from(encoded, "base64url");
2174
+ if (!encoded || bytes.toString("base64url") !== encoded)
2175
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier encoding");
2176
+ let raw;
2177
+ try {
2178
+ raw = JSON.parse(bytes.toString("utf8"));
2179
+ } catch {
2180
+ fail("unsupported_reasoning", "Invalid Gemini signature carrier JSON");
2181
+ }
2182
+ const body = record(raw, "Gemini signatures");
2183
+ fields(body, ["version", "items"], "Gemini signatures", "unsupported_reasoning");
2184
+ if (body.version !== 1)
2185
+ fail("unsupported_reasoning", "Unknown Gemini signature format");
2186
+ const ids = new Set;
2187
+ let partCount = 0;
2188
+ const result = list(body.items, "signature items").map((raw) => {
2189
+ const item = record(raw, "signature item");
2190
+ fields(item, ["id", "thought", "parts"], "signature item", "unsupported_reasoning");
2191
+ const id = string(item.id, "signed item id", true);
2192
+ if (ids.has(id) || typeof item.thought !== "boolean")
2193
+ fail("unsupported_reasoning", "Invalid signed item identity");
2194
+ ids.add(id);
2195
+ const parts = list(item.parts, "signed parts").map((raw) => {
2196
+ if (++partCount > budget.maxItems)
2197
+ fail("resource_limit", "Too many signed Gemini parts");
2198
+ const part = record(raw, "signed part");
2199
+ fields(part, ["length", "hash", "signature", "textAbsent"], "signed part", "unsupported_reasoning");
2200
+ const length = integer(part.length, "signed part length"), hash = string(part.hash, "signed part hash", true);
2201
+ if (!/^[A-Za-z0-9_-]{43}$/.test(hash))
2202
+ fail("unsupported_reasoning", "Invalid signed part hash");
2203
+ const signature = part.signature === undefined ? undefined : checkedSignature(part.signature, budget.maxArgumentBytes);
2204
+ if (part.textAbsent !== undefined && (part.textAbsent !== true || length !== 0 || signature === undefined))
2205
+ fail("unsupported_reasoning", "Invalid empty signed part");
2206
+ return { length, hash, ...signature === undefined ? {} : { signature }, ...part.textAbsent ? { textAbsent: true } : {} };
2207
+ });
2208
+ if (!parts.some((p) => p.signature !== undefined))
2209
+ fail("unsupported_reasoning", "Signature carrier has no signature");
2210
+ return { id, thought: item.thought, parts };
2211
+ });
2212
+ if (!result.length || result.length > budget.maxItems)
2213
+ fail("unsupported_reasoning", "Invalid signature item count");
2214
+ return result;
2215
+ }
2216
+ function restoreGeminiHistory(input, budget) {
2217
+ const original = typeof input === "string" ? [] : list(input, "input").map((raw) => record(raw, "input item"));
2218
+ if (original.length > budget.maxItems)
2219
+ fail("resource_limit", "Too many input items", "input");
2220
+ const retained = new Map, parts = new Map, ids = new Map;
2221
+ original.forEach((item, i) => {
2222
+ if (typeof item.id === "string") {
2223
+ if (ids.has(item.id))
2224
+ fail("invalid_tool_history", "Duplicate history item id", "input.id");
2225
+ ids.set(item.id, i);
2226
+ }
2227
+ });
2228
+ original.forEach((carrier, index) => {
2229
+ if (carrier.type === "configuration_update") {
2230
+ retained.set(carrier, carrier);
2231
+ return;
2232
+ }
2233
+ if (carrier.encrypted_content == null)
2234
+ return;
2235
+ const { content, internal_chat_message_metadata_passthrough: metadata, ...normalized } = carrier;
2236
+ if (content !== undefined && content !== null)
2237
+ fail("unsupported_reasoning", "Gemini signature carriers cannot contain reasoning content", `input[${index}].content`);
2238
+ if (metadata !== undefined)
2239
+ atParam(`input[${index}].internal_chat_message_metadata_passthrough`, () => record(metadata, "message metadata"));
2240
+ const signed = readGeminiSignatures(normalized, budget);
2241
+ retained.set(carrier, normalized);
2242
+ let previous = -1;
2243
+ for (const item of signed) {
2244
+ const at = ids.get(item.id);
2245
+ if (at === undefined || at >= index || at <= previous || parts.has(item.id))
2246
+ fail("unsupported_reasoning", "Signed history reference is missing or ambiguous");
2247
+ previous = at;
2248
+ const source = original[at];
2249
+ if (item.thought ? source.type !== "reasoning" || source.encrypted_content != null : source.role !== "assistant" || source.type !== undefined && source.type !== "message")
2250
+ fail("unsupported_reasoning", "Signed history item kind changed");
2251
+ const content = item.thought ? list(source.summary, "summary") : typeof source.content === "string" ? [{ type: "output_text", text: source.content }] : list(source.content, "content");
2252
+ const text = content.map((raw) => {
2253
+ const p = record(raw, "signed text");
2254
+ if (p.type !== (item.thought ? "summary_text" : "output_text") && !(p.type === "input_text" && !item.thought))
2255
+ fail("unsupported_reasoning", "Signed history content kind changed");
2256
+ return string(p.text, "signed text");
2257
+ }).join("");
2258
+ let offset = 0;
2259
+ const restored = item.parts.map((part) => {
2260
+ const value = text.slice(offset, offset + part.length);
2261
+ offset += part.length;
2262
+ if (value.length !== part.length || geminiTextHash(value) !== part.hash)
2263
+ fail("unsupported_reasoning", "Signed history text changed");
2264
+ return { ...part.textAbsent ? {} : { text: value }, ...item.thought ? { thought: true } : {}, ...part.signature === undefined ? {} : { thoughtSignature: part.signature } };
2265
+ });
2266
+ if (offset !== text.length)
2267
+ fail("unsupported_reasoning", "Signed history text was not fully consumed");
2268
+ parts.set(item.id, restored);
2269
+ }
2270
+ });
2271
+ const positions = original.flatMap((item, index) => retained.has(item) ? [] : [index]);
2272
+ return {
2273
+ input: typeof input === "string" ? input : positions.map((index) => original[index]),
2274
+ parts,
2275
+ sourceParam(param) {
2276
+ return param.replace(/^input\[(\d+)\]/, (match, index) => positions[Number(index)] === undefined ? match : `input[${positions[Number(index)]}]`);
2277
+ },
2278
+ canonicalHistory(decoded) {
2279
+ if (!retained.size)
2280
+ return decoded;
2281
+ let next = 0;
2282
+ return original.filter((item) => item.type !== "additional_tools").map((item) => retained.get(item) ?? decoded[next++]);
2283
+ }
2284
+ };
2285
+ }
2286
+ function encodeGeminiCallId(id, signature, maxBytes) {
2287
+ if (id.includes(signatureSeparator))
2288
+ fail("invalid_tool_arguments", "Gemini call id contains the signature separator", "functionCall.id");
2289
+ return signature === undefined ? id : `${id}${signatureSeparator}${checkedSignature(signature, maxBytes)}`;
2290
+ }
2291
+ function decodeGeminiCallId(value, maxBytes) {
2292
+ const separator = value.indexOf(signatureSeparator);
2293
+ if (separator < 0)
2294
+ return { id: value };
2295
+ const id = string(value.slice(0, separator), "functionCall.id", true);
2296
+ return { id, thoughtSignature: checkedSignature(value.slice(separator + signatureSeparator.length), maxBytes) };
2297
+ }
2298
+
2065
2299
  // src/providers/openai/protocol-conversion.ts
2066
2300
  var THINKING_TAG_PATTERN = /<thinking>([\s\S]*?)<\/thinking>/gi;
2067
2301
  var TOOL_CALL_CONTENT_TYPES = new Set([
@@ -2642,7 +2876,7 @@ class OpenAIProtocolConversion {
2642
2876
  }
2643
2877
 
2644
2878
  // src/responses-codec/request-preferences.ts
2645
- function fields(value, allowed, path) {
2879
+ function fields2(value, allowed, path) {
2646
2880
  for (const key of Object.keys(value))
2647
2881
  if (!allowed.includes(key)) {
2648
2882
  fail("unsupported_request", "Unrecognized request option", `${path}.${key}`);
@@ -2653,7 +2887,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
2653
2887
  if (body.stream_options !== undefined)
2654
2888
  atParam("stream_options", () => {
2655
2889
  const options = record(body.stream_options, "stream_options");
2656
- fields(options, ["include_usage", "reasoning_summary_delivery"], "stream_options");
2890
+ fields2(options, ["include_usage", "reasoning_summary_delivery"], "stream_options");
2657
2891
  if (options.include_usage !== undefined) {
2658
2892
  if (typeof options.include_usage !== "boolean")
2659
2893
  fail("invalid_payload", "Usage preference must be boolean", "stream_options.include_usage");
@@ -2668,7 +2902,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
2668
2902
  if (body.access_programs !== undefined)
2669
2903
  atParam("access_programs", () => {
2670
2904
  const programs = record(body.access_programs, "access_programs");
2671
- fields(programs, ["cyber"], "access_programs");
2905
+ fields2(programs, ["cyber"], "access_programs");
2672
2906
  if (programs.cyber !== undefined && programs.cyber !== "standard") {
2673
2907
  if (programs.cyber === "daybreak_blue" || programs.cyber === "daybreak_red") {
2674
2908
  fail("unsupported_access_program", "Selected access program cannot be represented by the target protocol", "access_programs.cyber");
@@ -2680,7 +2914,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
2680
2914
  if (body.reasoning !== undefined)
2681
2915
  atParam("reasoning", () => {
2682
2916
  const reasoning = record(body.reasoning, "reasoning");
2683
- fields(reasoning, ["effort", "summary", "context"], "reasoning");
2917
+ fields2(reasoning, ["effort", "summary", "context"], "reasoning");
2684
2918
  if (reasoning.summary !== undefined) {
2685
2919
  if (typeof reasoning.summary !== "string" || !["none", "auto", "concise", "detailed"].includes(reasoning.summary))
2686
2920
  fail("invalid_payload", "Invalid reasoning summary preference", "reasoning.summary");
@@ -2711,7 +2945,7 @@ function applyResponsesPreferences(body, result, protocol, capabilities, maxToke
2711
2945
  if (body.text !== undefined)
2712
2946
  atParam("text", () => {
2713
2947
  const text = record(body.text, "text");
2714
- fields(text, ["verbosity", "format"], "text");
2948
+ fields2(text, ["verbosity", "format"], "text");
2715
2949
  if (text.verbosity !== undefined) {
2716
2950
  if (typeof text.verbosity !== "string" || !["low", "medium", "high"].includes(text.verbosity))
2717
2951
  fail("invalid_payload", "Invalid text verbosity preference", "text.verbosity");
@@ -2774,6 +3008,7 @@ function definitionKey(value) {
2774
3008
  }
2775
3009
  function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {}) {
2776
3010
  const body = record(raw, "Responses request");
3011
+ const allowLossyContinuation = protocol === "chat_completions" && options.allowLossyContinuation === true;
2777
3012
  if (capabilities.agentMessageDelivery !== undefined && capabilities.agentMessageDelivery !== "plaintext")
2778
3013
  fail("invalid_payload", "Unknown agent message delivery policy", "agentMessageDelivery");
2779
3014
  const budget = limits(capabilities.limits);
@@ -2842,6 +3077,7 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
2842
3077
  const byOriginal = new Map;
2843
3078
  const definitions = new Map;
2844
3079
  let examinedTools = 0;
3080
+ let hasCompaction = false;
2845
3081
  const tools = [];
2846
3082
  const identity = (name, namespace) => JSON.stringify([namespace ?? null, name]);
2847
3083
  const register = (name, namespace, custom) => {
@@ -2939,6 +3175,31 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
2939
3175
  for (const [index, rawItem] of input.entries())
2940
3176
  atParam(`input[${index}]`, () => {
2941
3177
  const item = record(rawItem, "input item");
3178
+ if (Object.hasOwn(item, "phase")) {
3179
+ const param = `input[${index}].phase`;
3180
+ if (!allowLossyContinuation || item.type !== undefined && item.type !== "message" || item.role !== "assistant")
3181
+ fail("unsupported_content", "Message phase requires opted-in Chat assistant history", param);
3182
+ if (item.phase !== null && item.phase !== "commentary" && item.phase !== "final_answer")
3183
+ fail("invalid_payload", "Invalid assistant message phase", param);
3184
+ diagnostics.push({ param, action: "omitted", reason: "chat_assistant_phase_unavailable" });
3185
+ }
3186
+ if (allowLossyContinuation && item.type === "compaction") {
3187
+ const path = `input[${index}]`;
3188
+ for (const key of Object.keys(item))
3189
+ if (!["type", "id", "created_by", "encrypted_content", "internal_chat_message_metadata_passthrough"].includes(key))
3190
+ fail("unsupported_content", "Unknown compaction field", `${path}.${key}`);
3191
+ const param = `${path}.encrypted_content`;
3192
+ const encryptedContent = atParam(param, () => string(item.encrypted_content, "compaction encrypted content", true));
3193
+ if (!encryptedContent.trim())
3194
+ fail("invalid_payload", "Compaction encrypted content must be non-empty", param);
3195
+ if (isGeminiSignatureCarrier(encryptedContent))
3196
+ fail("unsupported_content", "Gemini signature carriers cannot cross into Chat", param);
3197
+ if (item.id != null)
3198
+ atParam(`${path}.id`, () => string(item.id, "compaction id", true));
3199
+ if (item.created_by !== undefined)
3200
+ atParam(`${path}.created_by`, () => string(item.created_by, "compaction created_by", true));
3201
+ hasCompaction = true;
3202
+ }
2942
3203
  if (item.type !== "additional_tools") {
2943
3204
  if (item.internal_chat_message_metadata_passthrough !== undefined) {
2944
3205
  record(item.internal_chat_message_metadata_passthrough, "message metadata");
@@ -2974,6 +3235,12 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
2974
3235
  const partPath = `${path}[${index}]`;
2975
3236
  atParam(partPath, () => {
2976
3237
  const part = record(rawPart, "content part");
3238
+ if (Object.hasOwn(part, "logprobs")) {
3239
+ const param = `${partPath}.logprobs`;
3240
+ if (!allowLossyContinuation || role !== "assistant" || part.type !== "output_text" || !Array.isArray(part.logprobs) || part.logprobs.length !== 0)
3241
+ fail("unsupported_content", "Only empty assistant output log probabilities can be omitted", param);
3242
+ diagnostics.push({ param, action: "omitted", reason: "chat_empty_output_logprobs" });
3243
+ }
2977
3244
  if (part.type === "input_text" || part.type === "output_text" || part.type === "text")
2978
3245
  string(part.text, "content text");
2979
3246
  else if (part.type === "refusal" && role === "assistant") {
@@ -3023,6 +3290,8 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3023
3290
  let messageParam = "instructions";
3024
3291
  const callIds = new Set;
3025
3292
  const callToolNames = new Map;
3293
+ const callsAwaitingResult = new Map;
3294
+ let encryptedToolBatch;
3026
3295
  const answered = new Set;
3027
3296
  const deferredInstructions = [];
3028
3297
  const normalizeChatHistory = protocol === "chat_completions" && !options.preserveContentOrder;
@@ -3041,18 +3310,43 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3041
3310
  addMessage({ role: "user", content: [{ type: "text", text: `Images returned by tool ${JSON.stringify(name)} (call ${JSON.stringify(callId)}):` }, ...images] });
3042
3311
  projectedToolImages.length = 0;
3043
3312
  };
3313
+ const checkPendingToolHistory = (item, toolOutput) => {
3314
+ const message = item.type === undefined || item.type === "message";
3315
+ const instruction = message && (item.role === "system" || item.role === "developer");
3316
+ const toolCall = item.type === "function_call" || item.type === "custom_tool_call";
3317
+ if (hasCompaction && toolOutput && callsAwaitingResult.size && pendingReasoning)
3318
+ fail("invalid_tool_history", "Attach the reasoning summary before the Chat tool results", messageParam);
3319
+ if (toolOutput || instruction)
3320
+ return;
3321
+ if (deferredInstructions.length)
3322
+ fail("invalid_tool_history", "Only instructions and tool results may follow a deferred instruction until all tool results arrive", messageParam);
3323
+ if (encryptedToolBatch && !(toolCall && chat.at(-1)?.role === "assistant"))
3324
+ fail("invalid_tool_history", "Complete the encrypted tool batch before another turn or reasoning item", messageParam);
3325
+ if (hasCompaction && callsAwaitingResult.size && !(normalizeChatHistory && chat.at(-1)?.role === "assistant" && (toolCall || item.type === "reasoning" || message && item.role === "assistant")))
3326
+ fail("invalid_tool_history", "Complete the Chat tool batch before another message", messageParam);
3327
+ };
3044
3328
  if (body.instructions !== undefined)
3045
3329
  addMessage({ role: "system", content: string(body.instructions, "instructions") });
3046
3330
  for (const [inputIndex, rawItem] of input.entries())
3047
3331
  atParam(`input[${inputIndex}]`, () => {
3048
3332
  messageParam = `input[${inputIndex}]`;
3049
3333
  const item = record(rawItem, "input item");
3050
- if (item.type !== "function_call_output" && item.type !== "custom_tool_call_output")
3334
+ const toolOutput = item.type === "function_call_output" || item.type === "custom_tool_call_output";
3335
+ if (!toolOutput)
3051
3336
  flushToolImages();
3052
- if (item.type === "additional_tools")
3337
+ if (item.type === "additional_tools" || allowLossyContinuation && item.type === "configuration_update" && options.chatConfigurationUpdates?.has(item))
3053
3338
  return;
3054
- 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")))
3055
- fail("invalid_tool_history", "Only instructions and tool results may follow a deferred instruction until all tool results arrive", messageParam);
3339
+ if (item.type !== "reasoning")
3340
+ checkPendingToolHistory(item, toolOutput);
3341
+ if (allowLossyContinuation && item.type === "compaction") {
3342
+ if (callIds.size !== answered.size)
3343
+ fail("invalid_tool_history", "Compaction cannot split a Chat tool batch", messageParam);
3344
+ if (pendingReasoning)
3345
+ fail("unsupported_reasoning", "Reasoning must precede an assistant item", messageParam);
3346
+ addMessage({ role: "user", content: "[Earlier conversation context was compacted and is unavailable. Continue from the visible messages and ask for any details you need.]" });
3347
+ diagnostics.push({ param: messageParam, action: "mapped", reason: "chat_compaction_placeholder" });
3348
+ return;
3349
+ }
3056
3350
  if (item.type === "agent_message") {
3057
3351
  validateAgentMessage(item, messageParam, capabilities.limits);
3058
3352
  if (capabilities.agentMessageDelivery !== "plaintext")
@@ -3064,24 +3358,34 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3064
3358
  diagnostics.push({ param: messageParam, action: "mapped", reason: "agent_message_plaintext_delivery" });
3065
3359
  return;
3066
3360
  }
3067
- if (item.encrypted_content != null)
3068
- fail("unsupported_content", "Encrypted content cannot cross protocols", `${messageParam}.encrypted_content`);
3361
+ const encrypted = item.encrypted_content != null;
3362
+ if (encrypted) {
3363
+ const param = `${messageParam}.encrypted_content`;
3364
+ if (!allowLossyContinuation || item.type !== "reasoning" && item.type !== "function_call")
3365
+ fail("unsupported_content", "Encrypted content cannot cross protocols", param);
3366
+ atParam(param, () => string(item.encrypted_content, "encrypted content", true));
3367
+ diagnostics.push({ param, action: "omitted", reason: "chat_opaque_history_content_unavailable" });
3368
+ }
3069
3369
  if (item.type === "compaction")
3070
3370
  fail("unsupported_content", "Encrypted reasoning and compaction cannot be restored");
3071
3371
  if (item.type === "item_reference")
3072
3372
  fail("unresolved_reference", "Input item references must be resolved before conversion");
3073
3373
  if (item.type === "reasoning") {
3074
- if (protocol !== "chat_completions" || !(capabilities.reasoningHistory || capabilities.reasoningEffort))
3075
- fail("unsupported_reasoning", "Reasoning history requires an explicit compatible reasoning capability");
3076
- if (item.content != null)
3374
+ if (item.content != null && !(encrypted && Array.isArray(item.content) && !item.content.length))
3077
3375
  fail("unsupported_reasoning", "Reasoning content requires an explicit history mapping", `${messageParam}.content`);
3078
- const summary = list(item.summary, "reasoning summary");
3079
- const text = summary.map((part) => {
3376
+ const summaryParam = `${messageParam}.summary`;
3377
+ const summary = encrypted && item.summary === undefined ? [] : atParam(summaryParam, () => list(item.summary, "reasoning summary"));
3378
+ const text = summary.map((part, index) => atParam(`${summaryParam}[${index}]`, () => {
3080
3379
  const p = record(part, "reasoning summary");
3081
3380
  if (p.type !== "summary_text")
3082
3381
  fail("unsupported_reasoning", "Unknown reasoning summary");
3083
3382
  return string(p.text, "summary text");
3084
- }).join("");
3383
+ })).join("");
3384
+ if (encrypted && !text)
3385
+ return;
3386
+ checkPendingToolHistory(item, false);
3387
+ if (protocol !== "chat_completions" || !(capabilities.reasoningHistory || capabilities.reasoningEffort))
3388
+ fail("unsupported_reasoning", "Reasoning history requires an explicit compatible reasoning capability");
3085
3389
  if (options.preserveContentOrder)
3086
3390
  addMessage({ role: "assistant", content: null, reasoning_content: text, ...item.id === undefined ? {} : { id: string(item.id, "item.id", true) } });
3087
3391
  else
@@ -3091,16 +3395,30 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3091
3395
  if (item.type === "function_call" || item.type === "custom_tool_call") {
3092
3396
  const custom = item.type === "custom_tool_call";
3093
3397
  validateEncryptedFunctionArgs(item, capabilities.agentMessageDelivery, messageParam);
3398
+ if (encrypted && item.status !== undefined && item.status !== "completed")
3399
+ fail("invalid_tool_history", "Encrypted tool history requires a completed function call", `${messageParam}.status`);
3094
3400
  const id = string(item.call_id, "call_id", true);
3095
3401
  if (callIds.has(id))
3096
3402
  fail("invalid_tool_history", "Duplicate tool call identifier");
3403
+ const previous = chat.at(-1);
3404
+ if (encrypted && callIds.size !== answered.size) {
3405
+ const adjacent = previous?.role === "assistant" ? previous.tool_calls?.length ?? 0 : 0;
3406
+ if (adjacent !== callIds.size - answered.size)
3407
+ fail("invalid_tool_history", "Encrypted function call cannot join a split tool batch", `${messageParam}.call_id`);
3408
+ }
3097
3409
  callIds.add(id);
3098
- const args = custom ? JSON.stringify({ input: string(item.input, "custom input") }) : string(item.arguments, "arguments");
3099
- bounded(args, budget.maxArgumentBytes, "arguments");
3100
- argumentObject(args);
3410
+ if (hasCompaction || encrypted)
3411
+ callsAwaitingResult.set(id, { param: `${messageParam}.call_id`, outputType: custom ? "custom_tool_call_output" : "function_call_output" });
3412
+ if (encrypted)
3413
+ encryptedToolBatch ??= `${messageParam}.call_id`;
3414
+ const args = atParam(encrypted ? `${messageParam}.arguments` : messageParam, () => {
3415
+ const text = custom ? JSON.stringify({ input: string(item.input, "custom input") }) : string(item.arguments, "arguments");
3416
+ bounded(text, budget.maxArgumentBytes, "arguments");
3417
+ argumentObject(text);
3418
+ return text;
3419
+ });
3101
3420
  const call = { id, type: "function", function: { name: resolve(item, custom), arguments: args } };
3102
3421
  callToolNames.set(id, String(item.name));
3103
- const previous = chat.at(-1);
3104
3422
  if (previous?.role === "assistant" && !options.preserveContentOrder) {
3105
3423
  previous.tool_calls = [...previous.tool_calls ?? [], call];
3106
3424
  if (pendingReasoning)
@@ -3114,6 +3432,10 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3114
3432
  const id = string(item.call_id, "call_id", true);
3115
3433
  if (!callIds.has(id) || answered.has(id))
3116
3434
  fail("invalid_tool_history", "Unmatched or duplicate tool result");
3435
+ const pending = callsAwaitingResult.get(id);
3436
+ if (pending && item.type !== pending.outputType)
3437
+ fail("invalid_tool_history", "Tool result type must match the corresponding call", `${messageParam}.type`);
3438
+ callsAwaitingResult.delete(id);
3117
3439
  answered.add(id);
3118
3440
  if (Array.isArray(item.output) && item.output.length > budget.maxItems && item.output.some((part) => part && typeof part === "object" && part.type === "input_image"))
3119
3441
  fail("resource_limit", "Too many tool output content parts", `${messageParam}.output`);
@@ -3132,6 +3454,7 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3132
3454
  }
3133
3455
  addMessage({ role: "tool", tool_call_id: id, content: output, ...item.is_error === true ? { is_error: true } : {} });
3134
3456
  if (callIds.size === answered.size) {
3457
+ encryptedToolBatch = undefined;
3135
3458
  for (const instruction of deferredInstructions) {
3136
3459
  messageParam = instruction.param;
3137
3460
  addMessage(instruction.message);
@@ -3170,6 +3493,11 @@ function decodeResponsesRequest(raw, protocol, capabilities = {}, options = {})
3170
3493
  }
3171
3494
  addMessage(message);
3172
3495
  });
3496
+ const missingResult = callsAwaitingResult.values().next().value;
3497
+ if (missingResult)
3498
+ fail("invalid_tool_history", "Tool call requires a matching result", missingResult.param);
3499
+ if (encryptedToolBatch)
3500
+ fail("invalid_tool_history", "All calls in the encrypted tool batch require matching results", encryptedToolBatch);
3173
3501
  if (pendingReasoning)
3174
3502
  fail("unsupported_reasoning", "Orphan reasoning history cannot be represented");
3175
3503
  if (deferredInstructions.length)
@@ -3724,245 +4052,12 @@ function encodeResponsesResult(raw, protocol, model, toolNames = new Map, config
3724
4052
  fail("missing_terminal", "JSON response has no terminal result");
3725
4053
  return record(end.response, "Responses result");
3726
4054
  }
3727
- // src/protocol-session/gemini.ts
3728
- import { createHash } from "crypto";
3729
-
3730
- // src/protocol-session/validation.ts
3731
- function fields2(value, allowed, path, code = "unsupported_request") {
3732
- for (const key of Object.keys(value))
3733
- if (!allowed.includes(key))
3734
- fail(code, "Field cannot be represented by the target protocol", path ? `${path}.${key}` : key);
3735
- }
3736
- function bool(value, path) {
3737
- if (typeof value !== "boolean")
3738
- fail("invalid_payload", "Expected a boolean", path);
3739
- return value;
3740
- }
3741
- function integer(value, path, min = 0) {
3742
- if (!Number.isSafeInteger(value) || value < min)
3743
- fail("invalid_payload", "Expected an integer in the supported range", path);
3744
- return value;
3745
- }
3746
- function textParts(raw, path, style, role) {
3747
- if (typeof raw === "string")
3748
- return [{ type: "input_text", text: raw }];
3749
- return list(raw, path).map((rawPart, index) => {
3750
- const p = record(rawPart, path), at = `${path}[${index}]`;
3751
- if (style === "gemini") {
3752
- fields2(p, ["text", "thought"], at, "unsupported_content");
3753
- if (p.thought === true)
3754
- fail("unsupported_reasoning", "Reasoning must be represented as a separate history item", at);
3755
- return { type: "input_text", text: string(p.text, at) };
3756
- }
3757
- if (style === "chat" && p.type === "image_url" && role === "user") {
3758
- fields2(p, ["type", "image_url"], at, "unsupported_content");
3759
- const image = record(p.image_url, at);
3760
- fields2(image, ["url", "detail"], `${at}.image_url`, "unsupported_content");
3761
- return { type: "input_image", image_url: string(image.url, at, true), ...image.detail !== undefined ? { detail: image.detail } : {} };
3762
- }
3763
- if (style === "chat" && p.type === "refusal" && role === "assistant") {
3764
- fields2(p, ["type", "refusal"], at, "unsupported_content");
3765
- return { type: "refusal", refusal: string(p.refusal, at) };
3766
- }
3767
- if (p.type !== "text")
3768
- fail("unsupported_content", "Content block cannot be represented by the target protocol", at);
3769
- fields2(p, ["type", "text"], at, "unsupported_content");
3770
- return { type: "input_text", text: string(p.text, at) };
3771
- });
3772
- }
3773
-
3774
- // src/protocol-session/gemini.ts
3775
- var signatureSeparator = "__thought__";
3776
- function geminiInlineImage(image, path, budget) {
3777
- const param = `${path}.image_url`;
3778
- const url = bounded(string(image.url, "image URL", true), budget.maxRequestBytes, param);
3779
- const match = /^data:([^;,]+);base64,([\s\S]*)$/.exec(url);
3780
- if (!match || !["image/png", "image/jpeg", "image/webp"].includes(match[1]))
3781
- fail("unsupported_content", "Gemini images require inline PNG, JPEG or WebP data", param);
3782
- const data = match[2];
3783
- 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(/=+$/, ""))
3784
- fail("invalid_payload", "Invalid image Base64 encoding", param);
3785
- return { mimeType: match[1], data };
3786
- }
3787
- function geminiToolResponse(content, path, budget, diagnostics) {
3788
- if (!Array.isArray(content) || !content.some((part) => part.type === "image_url"))
3789
- return { response: { output: content } };
3790
- if (content.length > budget.maxItems)
3791
- fail("resource_limit", "Too many tool output parts", path);
3792
- const parts = [];
3793
- const output = content.map((part, index) => atParam(`${path}[${index}]`, () => {
3794
- if (part.type === "text")
3795
- return part;
3796
- if (part.type !== "image_url")
3797
- fail("unsupported_content", "Unsupported Gemini tool result content");
3798
- const image = record(part.image_url, "tool image");
3799
- const inlineData = geminiInlineImage(image, `${path}[${index}]`, budget);
3800
- const displayName = `tool-image-${index}.${inlineData.mimeType.slice("image/".length)}`;
3801
- parts.push({ inlineData: { ...inlineData, displayName } });
3802
- if (image.detail !== undefined)
3803
- diagnostics.push({ param: `${path}[${index}].detail`, action: "omitted", reason: "gemini_tool_image_detail_unavailable" });
3804
- return { $ref: displayName };
3805
- }));
3806
- return { response: { output }, parts };
3807
- }
3808
- function checkedSignature(value, maxBytes) {
3809
- const signature = bounded(string(value, "thoughtSignature", true), maxBytes, "thoughtSignature");
3810
- 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(/=+$/, ""))
3811
- fail("invalid_tool_arguments", "Invalid Gemini thought signature encoding", "thoughtSignature");
3812
- return signature;
3813
- }
3814
- var envelopePrefix = "bungee_gemini:";
3815
- var geminiEnvelopeBytes = (payloadBytes) => envelopePrefix.length + Math.ceil(payloadBytes * 4 / 3);
3816
- var geminiTextHash = (text) => createHash("sha256").update(text).digest("base64url");
3817
- function geminiSignatureItem(items, budget) {
3818
- const payload = serialized({ version: 1, items }, budget.maxArgumentBytes, "Gemini signatures");
3819
- return {
3820
- type: "reasoning",
3821
- id: `rs_gemini_${crypto.randomUUID().replaceAll("-", "")}`,
3822
- summary: [],
3823
- encrypted_content: bounded(envelopePrefix + Buffer.from(payload).toString("base64url"), budget.maxArgumentBytes, "Gemini signatures")
3824
- };
3825
- }
3826
- function readGeminiSignatures(item, budget) {
3827
- fields2(item, ["type", "id", "summary", "encrypted_content", "status"], "Gemini signatures", "unsupported_reasoning");
3828
- if (item.type !== "reasoning" || list(item.summary, "summary").length)
3829
- fail("unsupported_reasoning", "Invalid Gemini signature carrier");
3830
- string(item.id, "signature item id", true);
3831
- const opaque = bounded(string(item.encrypted_content, "encrypted_content", true), budget.maxArgumentBytes, "Gemini signatures");
3832
- if (!opaque.startsWith(envelopePrefix))
3833
- fail("unsupported_reasoning", "Native encrypted reasoning cannot be restored to Gemini");
3834
- const encoded = opaque.slice(envelopePrefix.length), bytes = Buffer.from(encoded, "base64url");
3835
- if (!encoded || bytes.toString("base64url") !== encoded)
3836
- fail("unsupported_reasoning", "Invalid Gemini signature carrier encoding");
3837
- let raw;
3838
- try {
3839
- raw = JSON.parse(bytes.toString("utf8"));
3840
- } catch {
3841
- fail("unsupported_reasoning", "Invalid Gemini signature carrier JSON");
3842
- }
3843
- const body = record(raw, "Gemini signatures");
3844
- fields2(body, ["version", "items"], "Gemini signatures", "unsupported_reasoning");
3845
- if (body.version !== 1)
3846
- fail("unsupported_reasoning", "Unknown Gemini signature format");
3847
- const ids = new Set;
3848
- let partCount = 0;
3849
- const result = list(body.items, "signature items").map((raw) => {
3850
- const item = record(raw, "signature item");
3851
- fields2(item, ["id", "thought", "parts"], "signature item", "unsupported_reasoning");
3852
- const id = string(item.id, "signed item id", true);
3853
- if (ids.has(id) || typeof item.thought !== "boolean")
3854
- fail("unsupported_reasoning", "Invalid signed item identity");
3855
- ids.add(id);
3856
- const parts = list(item.parts, "signed parts").map((raw) => {
3857
- if (++partCount > budget.maxItems)
3858
- fail("resource_limit", "Too many signed Gemini parts");
3859
- const part = record(raw, "signed part");
3860
- fields2(part, ["length", "hash", "signature", "textAbsent"], "signed part", "unsupported_reasoning");
3861
- const length = integer(part.length, "signed part length"), hash = string(part.hash, "signed part hash", true);
3862
- if (!/^[A-Za-z0-9_-]{43}$/.test(hash))
3863
- fail("unsupported_reasoning", "Invalid signed part hash");
3864
- const signature = part.signature === undefined ? undefined : checkedSignature(part.signature, budget.maxArgumentBytes);
3865
- if (part.textAbsent !== undefined && (part.textAbsent !== true || length !== 0 || signature === undefined))
3866
- fail("unsupported_reasoning", "Invalid empty signed part");
3867
- return { length, hash, ...signature === undefined ? {} : { signature }, ...part.textAbsent ? { textAbsent: true } : {} };
3868
- });
3869
- if (!parts.some((p) => p.signature !== undefined))
3870
- fail("unsupported_reasoning", "Signature carrier has no signature");
3871
- return { id, thought: item.thought, parts };
3872
- });
3873
- if (!result.length || result.length > budget.maxItems)
3874
- fail("unsupported_reasoning", "Invalid signature item count");
3875
- return result;
3876
- }
3877
- function restoreGeminiHistory(input, budget) {
3878
- const original = typeof input === "string" ? [] : list(input, "input").map((raw) => record(raw, "input item"));
3879
- if (original.length > budget.maxItems)
3880
- fail("resource_limit", "Too many input items", "input");
3881
- const retained = new Map, parts = new Map, ids = new Map;
3882
- original.forEach((item, i) => {
3883
- if (typeof item.id === "string") {
3884
- if (ids.has(item.id))
3885
- fail("invalid_tool_history", "Duplicate history item id", "input.id");
3886
- ids.set(item.id, i);
3887
- }
3888
- });
3889
- original.forEach((carrier, index) => {
3890
- if (carrier.type === "configuration_update") {
3891
- retained.set(carrier, carrier);
3892
- return;
3893
- }
3894
- if (carrier.encrypted_content == null)
3895
- return;
3896
- const { content, internal_chat_message_metadata_passthrough: metadata, ...normalized } = carrier;
3897
- if (content !== undefined && content !== null)
3898
- fail("unsupported_reasoning", "Gemini signature carriers cannot contain reasoning content", `input[${index}].content`);
3899
- if (metadata !== undefined)
3900
- atParam(`input[${index}].internal_chat_message_metadata_passthrough`, () => record(metadata, "message metadata"));
3901
- const signed = readGeminiSignatures(normalized, budget);
3902
- retained.set(carrier, normalized);
3903
- let previous = -1;
3904
- for (const item of signed) {
3905
- const at = ids.get(item.id);
3906
- if (at === undefined || at >= index || at <= previous || parts.has(item.id))
3907
- fail("unsupported_reasoning", "Signed history reference is missing or ambiguous");
3908
- previous = at;
3909
- const source = original[at];
3910
- if (item.thought ? source.type !== "reasoning" || source.encrypted_content != null : source.role !== "assistant" || source.type !== undefined && source.type !== "message")
3911
- fail("unsupported_reasoning", "Signed history item kind changed");
3912
- const content = item.thought ? list(source.summary, "summary") : typeof source.content === "string" ? [{ type: "output_text", text: source.content }] : list(source.content, "content");
3913
- const text = content.map((raw) => {
3914
- const p = record(raw, "signed text");
3915
- if (p.type !== (item.thought ? "summary_text" : "output_text") && !(p.type === "input_text" && !item.thought))
3916
- fail("unsupported_reasoning", "Signed history content kind changed");
3917
- return string(p.text, "signed text");
3918
- }).join("");
3919
- let offset = 0;
3920
- const restored = item.parts.map((part) => {
3921
- const value = text.slice(offset, offset + part.length);
3922
- offset += part.length;
3923
- if (value.length !== part.length || geminiTextHash(value) !== part.hash)
3924
- fail("unsupported_reasoning", "Signed history text changed");
3925
- return { ...part.textAbsent ? {} : { text: value }, ...item.thought ? { thought: true } : {}, ...part.signature === undefined ? {} : { thoughtSignature: part.signature } };
3926
- });
3927
- if (offset !== text.length)
3928
- fail("unsupported_reasoning", "Signed history text was not fully consumed");
3929
- parts.set(item.id, restored);
3930
- }
3931
- });
3932
- const positions = original.flatMap((item, index) => retained.has(item) ? [] : [index]);
3933
- return {
3934
- input: typeof input === "string" ? input : positions.map((index) => original[index]),
3935
- parts,
3936
- sourceParam(param) {
3937
- return param.replace(/^input\[(\d+)\]/, (match, index) => positions[Number(index)] === undefined ? match : `input[${positions[Number(index)]}]`);
3938
- },
3939
- canonicalHistory(decoded) {
3940
- if (!retained.size)
3941
- return decoded;
3942
- let next = 0;
3943
- return original.filter((item) => item.type !== "additional_tools").map((item) => retained.get(item) ?? decoded[next++]);
3944
- }
3945
- };
3946
- }
3947
- function encodeGeminiCallId(id, signature, maxBytes) {
3948
- if (id.includes(signatureSeparator))
3949
- fail("invalid_tool_arguments", "Gemini call id contains the signature separator", "functionCall.id");
3950
- return signature === undefined ? id : `${id}${signatureSeparator}${checkedSignature(signature, maxBytes)}`;
3951
- }
3952
- function decodeGeminiCallId(value, maxBytes) {
3953
- const separator = value.indexOf(signatureSeparator);
3954
- if (separator < 0)
3955
- return { id: value };
3956
- const id = string(value.slice(0, separator), "functionCall.id", true);
3957
- return { id, thoughtSignature: checkedSignature(value.slice(separator + signatureSeparator.length), maxBytes) };
3958
- }
3959
-
3960
4055
  // src/protocol-session/schema.ts
3961
4056
  function geminiSchemaToJson(raw, path, code = "unsupported_request", depth = 0) {
3962
4057
  if (depth > 64)
3963
4058
  fail("resource_limit", "Schema nesting exceeds the conversion limit", path);
3964
4059
  const s = record(raw, path);
3965
- 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);
4060
+ 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);
3966
4061
  const out = {};
3967
4062
  if (s.type !== undefined) {
3968
4063
  const types = { STRING: "string", NUMBER: "number", INTEGER: "integer", BOOLEAN: "boolean", ARRAY: "array", OBJECT: "object", NULL: "null" };
@@ -4002,19 +4097,19 @@ function message(input, role, content, style, path) {
4002
4097
  function toolDefinition(raw, style, path) {
4003
4098
  const t = record(raw, path);
4004
4099
  if (style === "chat") {
4005
- fields2(t, t.type === "custom" ? ["type", "custom"] : ["type", "function"], path, "unsupported_tool");
4100
+ fields(t, t.type === "custom" ? ["type", "custom"] : ["type", "function"], path, "unsupported_tool");
4006
4101
  if (t.type === "custom") {
4007
4102
  const custom = record(t.custom, `${path}.custom`);
4008
- fields2(custom, ["name", "description", "format"], `${path}.custom`, "unsupported_tool");
4103
+ fields(custom, ["name", "description", "format"], `${path}.custom`, "unsupported_tool");
4009
4104
  return { type: "custom", ...custom };
4010
4105
  }
4011
4106
  if (t.type !== "function")
4012
4107
  fail("unsupported_tool", "Unsupported tool kind", `${path}.type`);
4013
4108
  const fn = record(t.function, path);
4014
- fields2(fn, ["name", "description", "parameters", "strict"], `${path}.function`, "unsupported_tool");
4109
+ fields(fn, ["name", "description", "parameters", "strict"], `${path}.function`, "unsupported_tool");
4015
4110
  return { type: "function", ...fn };
4016
4111
  }
4017
- fields2(t, style === "anthropic" ? ["name", "description", "input_schema", "strict"] : ["name", "description", "parametersJsonSchema", "parameters"], path, "unsupported_tool");
4112
+ fields(t, style === "anthropic" ? ["name", "description", "input_schema", "strict"] : ["name", "description", "parametersJsonSchema", "parameters"], path, "unsupported_tool");
4018
4113
  if (t.parameters !== undefined && t.parametersJsonSchema !== undefined)
4019
4114
  fail("unsupported_tool", "Ambiguous schema dialect", path);
4020
4115
  return {
@@ -4037,13 +4132,13 @@ function canonicalRequest(raw, protocol, model) {
4037
4132
  };
4038
4133
  if (protocol === "chat_completions") {
4039
4134
  const callKinds = new Map;
4040
- 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"], "");
4135
+ 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"], "");
4041
4136
  if (b.max_tokens !== undefined && b.max_completion_tokens !== undefined)
4042
4137
  fail("unsupported_request", "Ambiguous token limits", "max_tokens");
4043
4138
  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" });
4044
4139
  for (const [index, rawMessage] of list(b.messages, "messages").entries()) {
4045
4140
  const m = record(rawMessage, "message"), path = `messages[${index}]`;
4046
- fields2(m, ["role", "content", "tool_calls", "tool_call_id", "reasoning_content", "reasoning", "refusal", "name"], path, "unsupported_content");
4141
+ fields(m, ["role", "content", "tool_calls", "tool_call_id", "reasoning_content", "reasoning", "refusal", "name"], path, "unsupported_content");
4047
4142
  if (m.name !== undefined)
4048
4143
  fail("unsupported_content", "Named messages cannot be represented faithfully", `${path}.name`);
4049
4144
  const role = string(m.role, "role", true);
@@ -4078,12 +4173,12 @@ function canonicalRequest(raw, protocol, model) {
4078
4173
  fail("invalid_tool_history", "Tool calls require assistant role", path);
4079
4174
  for (const [j, rawCall] of list(m.tool_calls, "tool_calls").entries()) {
4080
4175
  const c = record(rawCall, "tool call"), at = `${path}.tool_calls[${j}]`;
4081
- fields2(c, ["id", "type", "function", "custom"], at, "unsupported_tool");
4176
+ fields(c, ["id", "type", "function", "custom"], at, "unsupported_tool");
4082
4177
  const custom = c.type === "custom";
4083
4178
  if (!custom && c.type !== "function")
4084
4179
  fail("unsupported_tool", "Unknown call type", at);
4085
4180
  const fn = record(custom ? c.custom : c.function, "tool call");
4086
- fields2(fn, custom ? ["name", "input"] : ["name", "arguments"], at, "unsupported_tool");
4181
+ fields(fn, custom ? ["name", "input"] : ["name", "arguments"], at, "unsupported_tool");
4087
4182
  callKinds.set(string(c.id, "id", true), custom);
4088
4183
  input.push({
4089
4184
  type: custom ? "custom_tool_call" : "function_call",
@@ -4102,9 +4197,9 @@ function canonicalRequest(raw, protocol, model) {
4102
4197
  out.tool_choice = c;
4103
4198
  else {
4104
4199
  const choice = record(c, "tool_choice");
4105
- fields2(choice, ["type", "function", "custom"], "tool_choice");
4200
+ fields(choice, ["type", "function", "custom"], "tool_choice");
4106
4201
  const fn = record(choice.function ?? choice.custom, "tool_choice");
4107
- fields2(fn, ["name"], "tool_choice.function");
4202
+ fields(fn, ["name"], "tool_choice.function");
4108
4203
  out.tool_choice = { type: choice.type, name: fn.name };
4109
4204
  }
4110
4205
  }
@@ -4112,19 +4207,19 @@ function canonicalRequest(raw, protocol, model) {
4112
4207
  out.reasoning = { effort: b.reasoning_effort };
4113
4208
  if (b.response_format !== undefined) {
4114
4209
  const format = record(b.response_format, "response_format");
4115
- fields2(format, ["type", "json_schema"], "response_format");
4210
+ fields(format, ["type", "json_schema"], "response_format");
4116
4211
  out.text = { format: format.type === "json_schema" ? { type: "json_schema", ...record(format.json_schema, "json_schema") } : format };
4117
4212
  }
4118
4213
  return out;
4119
4214
  }
4120
4215
  if (protocol === "anthropic_messages") {
4121
- fields2(b, ["model", "messages", "system", "tools", "tool_choice", "stream", "temperature", "top_p", "max_tokens", "metadata", "stop_sequences", "thinking", "output_config"], "");
4216
+ fields(b, ["model", "messages", "system", "tools", "tool_choice", "stream", "temperature", "top_p", "max_tokens", "metadata", "stop_sequences", "thinking", "output_config"], "");
4122
4217
  copy({ stream: "stream", temperature: "temperature", top_p: "top_p", max_tokens: "max_output_tokens", metadata: "metadata", stop_sequences: "stop" });
4123
4218
  if (b.system !== undefined)
4124
4219
  message(input, "system", b.system, "anthropic", "system");
4125
4220
  for (const [index, rawMessage] of list(b.messages, "messages").entries()) {
4126
4221
  const m = record(rawMessage, "message"), path = `messages[${index}]`;
4127
- fields2(m, ["role", "content"], path, "unsupported_content");
4222
+ fields(m, ["role", "content"], path, "unsupported_content");
4128
4223
  if (m.role !== "user" && m.role !== "assistant")
4129
4224
  fail("unsupported_content", "Anthropic messages require user or assistant role", `${path}.role`);
4130
4225
  if (typeof m.content === "string") {
@@ -4136,15 +4231,15 @@ function canonicalRequest(raw, protocol, model) {
4136
4231
  if (p.type === "tool_use") {
4137
4232
  if (m.role !== "assistant")
4138
4233
  fail("invalid_tool_history", "Tool calls require assistant role", at);
4139
- fields2(p, ["type", "id", "name", "input"], at, "unsupported_content");
4234
+ fields(p, ["type", "id", "name", "input"], at, "unsupported_content");
4140
4235
  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)) });
4141
4236
  } else if (p.type === "tool_result") {
4142
4237
  if (m.role !== "user")
4143
4238
  fail("invalid_tool_history", "Tool results require user role", at);
4144
- fields2(p, ["type", "tool_use_id", "content", "is_error"], at, "unsupported_content");
4239
+ fields(p, ["type", "tool_use_id", "content", "is_error"], at, "unsupported_content");
4145
4240
  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) } : {} });
4146
4241
  } else if (p.type === "thinking") {
4147
- fields2(p, ["type", "thinking", "signature"], at, "unsupported_reasoning");
4242
+ fields(p, ["type", "thinking", "signature"], at, "unsupported_reasoning");
4148
4243
  if (p.signature != null)
4149
4244
  fail("unsupported_reasoning", "Provider-bound reasoning signatures cannot cross protocols", `${at}.signature`);
4150
4245
  if (m.role !== "assistant")
@@ -4158,7 +4253,7 @@ function canonicalRequest(raw, protocol, model) {
4158
4253
  out.tools = list(b.tools, "tools").map((t, i) => toolDefinition(t, "anthropic", `tools[${i}]`));
4159
4254
  if (b.tool_choice !== undefined) {
4160
4255
  const c = record(b.tool_choice, "tool_choice");
4161
- fields2(c, ["type", "name", "disable_parallel_tool_use"], "tool_choice");
4256
+ fields(c, ["type", "name", "disable_parallel_tool_use"], "tool_choice");
4162
4257
  if (c.type === "tool")
4163
4258
  out.tool_choice = { type: "function", name: c.name };
4164
4259
  else if (["auto", "none", "any"].includes(String(c.type)))
@@ -4170,7 +4265,7 @@ function canonicalRequest(raw, protocol, model) {
4170
4265
  }
4171
4266
  if (b.thinking !== undefined) {
4172
4267
  const t = record(b.thinking, "thinking");
4173
- fields2(t, ["type", "budget_tokens"], "thinking", "unsupported_reasoning");
4268
+ fields(t, ["type", "budget_tokens"], "thinking", "unsupported_reasoning");
4174
4269
  if (!["enabled", "adaptive", "disabled"].includes(String(t.type)))
4175
4270
  fail("unsupported_reasoning", "Unknown thinking mode", "thinking.type");
4176
4271
  if (t.type === "enabled")
@@ -4181,12 +4276,12 @@ function canonicalRequest(raw, protocol, model) {
4181
4276
  }
4182
4277
  if (b.output_config !== undefined) {
4183
4278
  const c = record(b.output_config, "output_config");
4184
- fields2(c, ["effort", "format"], "output_config");
4279
+ fields(c, ["effort", "format"], "output_config");
4185
4280
  if (c.effort !== undefined)
4186
4281
  out.reasoning = { effort: c.effort };
4187
4282
  if (c.format !== undefined) {
4188
4283
  const f = record(c.format, "format");
4189
- fields2(f, ["type", "schema"], "output_config.format");
4284
+ fields(f, ["type", "schema"], "output_config.format");
4190
4285
  if (f.type !== "json_schema")
4191
4286
  fail("unsupported_request", "Unknown structured output type", "output_config.format.type");
4192
4287
  out.text = { format: { type: "json_schema", name: "response", schema: f.schema } };
@@ -4194,12 +4289,12 @@ function canonicalRequest(raw, protocol, model) {
4194
4289
  }
4195
4290
  return out;
4196
4291
  }
4197
- fields2(b, ["contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "model", "stream"], "");
4292
+ fields(b, ["contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "model", "stream"], "");
4198
4293
  if (b.stream !== undefined)
4199
4294
  out.stream = b.stream;
4200
4295
  if (b.systemInstruction !== undefined) {
4201
4296
  const s = record(b.systemInstruction, "systemInstruction");
4202
- fields2(s, ["role", "parts"], "systemInstruction");
4297
+ fields(s, ["role", "parts"], "systemInstruction");
4203
4298
  if (s.role !== undefined && s.role !== "system")
4204
4299
  fail("unsupported_content", "Invalid system role", "systemInstruction.role");
4205
4300
  message(input, "system", s.parts, "gemini", "systemInstruction");
@@ -4209,12 +4304,12 @@ function canonicalRequest(raw, protocol, model) {
4209
4304
  for (const [index, rawContent] of list(b.contents, "contents").entries()) {
4210
4305
  const original = record(rawContent, "content"), path = `contents[${index}]`;
4211
4306
  const c = { ...original, role: original.role ?? "user" };
4212
- fields2(c, ["role", "parts"], path, "unsupported_content");
4307
+ fields(c, ["role", "parts"], path, "unsupported_content");
4213
4308
  if (c.role !== "user" && c.role !== "model")
4214
4309
  fail("unsupported_content", "Gemini contents require user or model role", `${path}.role`);
4215
4310
  for (const [j, rawPart] of list(c.parts, "parts").entries()) {
4216
4311
  const p = record(rawPart, "part"), at = `${path}.parts[${j}]`;
4217
- fields2(p, ["text", "thought", "functionCall", "functionResponse", "thoughtSignature"], at, "unsupported_content");
4312
+ fields(p, ["text", "thought", "functionCall", "functionResponse", "thoughtSignature"], at, "unsupported_content");
4218
4313
  if (p.thoughtSignature !== undefined)
4219
4314
  fail("unsupported_reasoning", "Provider-bound thought signatures cannot cross protocols", `${at}.thoughtSignature`);
4220
4315
  if ([p.text, p.functionCall, p.functionResponse].filter((v) => v !== undefined).length !== 1)
@@ -4223,7 +4318,7 @@ function canonicalRequest(raw, protocol, model) {
4223
4318
  if (c.role !== "model")
4224
4319
  fail("invalid_tool_history", "Function calls require model role", at);
4225
4320
  const f = record(p.functionCall, at);
4226
- fields2(f, ["name", "args", "id"], `${at}.functionCall`, "unsupported_tool");
4321
+ fields(f, ["name", "args", "id"], `${at}.functionCall`, "unsupported_tool");
4227
4322
  const name = string(f.name, at, true), id = f.id === undefined ? `call_gemini_${serial++}` : string(f.id, at, true);
4228
4323
  if (calls.has(id))
4229
4324
  fail("invalid_tool_history", "Duplicate tool call id", at);
@@ -4233,7 +4328,7 @@ function canonicalRequest(raw, protocol, model) {
4233
4328
  if (c.role !== "user")
4234
4329
  fail("invalid_tool_history", "Function results require user role", at);
4235
4330
  const f = record(p.functionResponse, at);
4236
- fields2(f, ["name", "response", "id"], `${at}.functionResponse`, "unsupported_tool");
4331
+ fields(f, ["name", "response", "id"], `${at}.functionResponse`, "unsupported_tool");
4237
4332
  const matches = [...calls.values()].filter((v) => v.name === f.name);
4238
4333
  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);
4239
4334
  if (calls.get(id)?.name !== f.name)
@@ -4252,7 +4347,7 @@ function canonicalRequest(raw, protocol, model) {
4252
4347
  const tools = [];
4253
4348
  for (const [i, rawTool] of list(b.tools, "tools").entries()) {
4254
4349
  const t = record(rawTool, "tool");
4255
- fields2(t, ["functionDeclarations"], `tools[${i}]`, "unsupported_tool");
4350
+ fields(t, ["functionDeclarations"], `tools[${i}]`, "unsupported_tool");
4256
4351
  for (const [j, f] of list(t.functionDeclarations, "functionDeclarations").entries())
4257
4352
  tools.push(toolDefinition(f, "gemini", `tools[${i}].functionDeclarations[${j}]`));
4258
4353
  }
@@ -4260,9 +4355,9 @@ function canonicalRequest(raw, protocol, model) {
4260
4355
  }
4261
4356
  if (b.toolConfig !== undefined) {
4262
4357
  const config = record(b.toolConfig, "toolConfig");
4263
- fields2(config, ["functionCallingConfig"], "toolConfig");
4358
+ fields(config, ["functionCallingConfig"], "toolConfig");
4264
4359
  const c = record(config.functionCallingConfig, "functionCallingConfig");
4265
- fields2(c, ["mode", "allowedFunctionNames"], "toolConfig.functionCallingConfig");
4360
+ fields(c, ["mode", "allowedFunctionNames"], "toolConfig.functionCallingConfig");
4266
4361
  if (!["AUTO", "NONE", "ANY"].includes(String(c.mode)))
4267
4362
  fail("unsupported_tool_choice", "Unknown function calling mode", "toolConfig.functionCallingConfig.mode");
4268
4363
  if (c.allowedFunctionNames !== undefined) {
@@ -4275,7 +4370,7 @@ function canonicalRequest(raw, protocol, model) {
4275
4370
  }
4276
4371
  if (b.generationConfig !== undefined) {
4277
4372
  const c = record(b.generationConfig, "generationConfig");
4278
- fields2(c, ["temperature", "topP", "maxOutputTokens", "stopSequences", "candidateCount", "responseMimeType", "responseJsonSchema", "responseSchema", "thinkingConfig"], "generationConfig");
4373
+ fields(c, ["temperature", "topP", "maxOutputTokens", "stopSequences", "candidateCount", "responseMimeType", "responseJsonSchema", "responseSchema", "thinkingConfig"], "generationConfig");
4279
4374
  for (const [from, to] of Object.entries({ temperature: "temperature", topP: "top_p", maxOutputTokens: "max_output_tokens", stopSequences: "stop", candidateCount: "n" }))
4280
4375
  if (c[from] !== undefined)
4281
4376
  out[to] = c[from];
@@ -4293,7 +4388,7 @@ function canonicalRequest(raw, protocol, model) {
4293
4388
  }
4294
4389
  if (c.thinkingConfig !== undefined) {
4295
4390
  const t = record(c.thinkingConfig, "thinkingConfig");
4296
- fields2(t, ["thinkingBudget", "thinkingLevel", "includeThoughts"], "generationConfig.thinkingConfig", "unsupported_reasoning");
4391
+ fields(t, ["thinkingBudget", "thinkingLevel", "includeThoughts"], "generationConfig.thinkingConfig", "unsupported_reasoning");
4297
4392
  if (t.thinkingBudget !== undefined)
4298
4393
  integer(t.thinkingBudget, "generationConfig.thinkingConfig.thinkingBudget", -1);
4299
4394
  if (t.thinkingLevel !== undefined)
@@ -4305,8 +4400,9 @@ function canonicalRequest(raw, protocol, model) {
4305
4400
  }
4306
4401
  return out;
4307
4402
  }
4308
- function validateCanonical(b, context) {
4403
+ function validateCanonical(b, context, chatConfigurationUpdates) {
4309
4404
  const responsesToGemini = context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content";
4405
+ const allowLossyContinuation = chatConfigurationUpdates !== undefined;
4310
4406
  let configuration;
4311
4407
  for (const key of ["stream", "parallel_tool_calls", "store", "background"])
4312
4408
  if (b[key] !== undefined)
@@ -4315,13 +4411,13 @@ function validateCanonical(b, context) {
4315
4411
  if (b[key] !== undefined && (typeof b[key] !== "number" || !Number.isFinite(b[key])))
4316
4412
  fail("invalid_payload", "Sampling value must be finite", key);
4317
4413
  if (b.tool_choice !== undefined && typeof b.tool_choice !== "string")
4318
- fields2(record(b.tool_choice, "tool_choice"), ["type", "name", "namespace"], "tool_choice", "unsupported_tool_choice");
4414
+ fields(record(b.tool_choice, "tool_choice"), ["type", "name", "namespace"], "tool_choice", "unsupported_tool_choice");
4319
4415
  if (b.text !== undefined) {
4320
4416
  const text = record(b.text, "text");
4321
- fields2(text, ["format", "verbosity"], "text");
4417
+ fields(text, ["format", "verbosity"], "text");
4322
4418
  if (text.format !== undefined) {
4323
4419
  const f = record(text.format, "text.format");
4324
- fields2(f, f.type === "json_schema" ? ["type", "name", "schema", "strict", "description"] : ["type"], "text.format");
4420
+ fields(f, f.type === "json_schema" ? ["type", "name", "schema", "strict", "description"] : ["type"], "text.format");
4325
4421
  if (!["text", "json_object", "json_schema"].includes(String(f.type)))
4326
4422
  fail("unsupported_request", "Unknown structured output format", "text.format.type");
4327
4423
  if (f.type === "json_schema") {
@@ -4337,34 +4433,40 @@ function validateCanonical(b, context) {
4337
4433
  const input = typeof b.input === "string" ? [] : list(b.input, "input");
4338
4434
  for (const [i, raw] of input.entries()) {
4339
4435
  const t = record(raw, "input item"), p = `input[${i}]`;
4340
- if (responsesToGemini && t.type === "configuration_update") {
4341
- fields2(t, ["type", "reasoning"], p, "unsupported_content");
4436
+ if ((responsesToGemini || allowLossyContinuation) && t.type === "configuration_update") {
4437
+ fields(t, ["type", "reasoning"], p, "unsupported_content");
4342
4438
  const reasoning = atParam(`${p}.reasoning`, () => record(t.reasoning, "configuration reasoning"));
4343
- fields2(reasoning, ["effort"], `${p}.reasoning`, "unsupported_reasoning");
4439
+ fields(reasoning, ["effort"], `${p}.reasoning`, "unsupported_reasoning");
4344
4440
  const param = `${p}.reasoning.effort`;
4345
4441
  const effort = atParam(param, () => string(reasoning.effort, "configuration effort", true));
4346
4442
  const map = context.reasoningPolicy?.effortMap;
4347
4443
  const level = map && Object.hasOwn(map, effort) ? map[effort] : undefined;
4348
- if (level === undefined || !["minimal", "low", "medium", "high"].includes(level))
4349
- fail("unsupported_reasoning", "Configuration update requires an explicit Gemini level mapping", param);
4444
+ if (typeof level !== "string" || !level || responsesToGemini && !["minimal", "low", "medium", "high"].includes(level))
4445
+ fail("unsupported_reasoning", responsesToGemini ? "Configuration update requires an explicit Gemini level mapping" : "Configuration update requires an explicit Chat effort mapping", param);
4350
4446
  configuration = { effort, level, param };
4447
+ chatConfigurationUpdates?.add(t);
4351
4448
  continue;
4352
4449
  }
4353
4450
  if (t.type === "agent_message") {
4354
4451
  validateAgentMessage(t, p, context.capabilities?.limits);
4355
4452
  continue;
4356
4453
  }
4357
- 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"];
4358
- fields2(t, [...allowed, "internal_chat_message_metadata_passthrough"], p, "unsupported_content");
4454
+ if (allowLossyContinuation && isGeminiSignatureCarrier(t.encrypted_content))
4455
+ fail("unsupported_content", "Gemini signature carriers cannot cross into Chat", `${p}.encrypted_content`);
4456
+ if (allowLossyContinuation && t.type === "compaction")
4457
+ continue;
4458
+ 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"];
4459
+ const assistantPhase = allowLossyContinuation && (t.type === undefined || t.type === "message") && t.role === "assistant";
4460
+ fields(t, [...allowed, "internal_chat_message_metadata_passthrough", ...assistantPhase ? ["phase"] : []], p, "unsupported_content");
4359
4461
  if (t.is_error !== undefined)
4360
4462
  bool(t.is_error, `${p}.is_error`);
4361
- if (t.type === "reasoning")
4362
- for (const [j, part] of list(t.summary, "summary").entries())
4363
- fields2(record(part, "summary"), ["type", "text"], `${p}.summary[${j}]`, "unsupported_reasoning");
4463
+ if (t.type === "reasoning" && !(allowLossyContinuation && t.encrypted_content != null && t.summary === undefined))
4464
+ for (const [j, part] of atParam(`${p}.summary`, () => list(t.summary, "summary")).entries())
4465
+ atParam(`${p}.summary[${j}]`, () => fields(record(part, "summary"), ["type", "text"], `${p}.summary[${j}]`, "unsupported_reasoning"));
4364
4466
  if (Array.isArray(t.content))
4365
4467
  for (const [j, part] of t.content.entries()) {
4366
4468
  const c = record(part, "part");
4367
- fields2(c, c.type === "input_image" ? ["type", "image_url", "detail"] : c.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], `${p}.content[${j}]`, "unsupported_content");
4469
+ 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");
4368
4470
  if (context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content" && t.role === "user" && c.type === "input_image") {
4369
4471
  atParam(`${p}.content[${j}].image_url`, () => string(c.image_url, "image URL", true));
4370
4472
  if (c.detail !== undefined && (typeof c.detail !== "string" || !["auto", "low", "high"].includes(c.detail)))
@@ -4375,7 +4477,7 @@ function validateCanonical(b, context) {
4375
4477
  for (const [j, part] of t.output.entries())
4376
4478
  atParam(`${p}.output[${j}]`, () => {
4377
4479
  const c = record(part, "tool output part");
4378
- fields2(c, c.type === "input_image" ? ["type", "image_url", "detail"] : ["type", "text", "annotations"], `${p}.output[${j}]`, "unsupported_content");
4480
+ fields(c, c.type === "input_image" ? ["type", "image_url", "detail"] : ["type", "text", "annotations"], `${p}.output[${j}]`, "unsupported_content");
4379
4481
  if (c.type === "input_image") {
4380
4482
  atParam(`${p}.output[${j}].image_url`, () => string(c.image_url, "image URL", true));
4381
4483
  if (c.detail !== undefined && (typeof c.detail !== "string" || !["auto", "low", "high"].includes(c.detail)))
@@ -4401,7 +4503,7 @@ function validateCanonical(b, context) {
4401
4503
  }
4402
4504
  if (t.type === "custom" && t.format !== undefined) {
4403
4505
  const f = record(t.format, "custom format");
4404
- fields2(f, f.type === "grammar" ? ["type", "syntax", "definition"] : ["type"], `${path}.format`, "unsupported_tool");
4506
+ fields(f, f.type === "grammar" ? ["type", "syntax", "definition"] : ["type"], `${path}.format`, "unsupported_tool");
4405
4507
  if (!["text", "grammar"].includes(String(f.type)))
4406
4508
  fail("unsupported_tool", "Unknown custom tool format", `${path}.format.type`);
4407
4509
  if (f.type === "grammar") {
@@ -4427,7 +4529,7 @@ function projectCodexPageSnapshot(raw, index, target, diagnostics) {
4427
4529
  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))
4428
4530
  return item;
4429
4531
  const param = `input[${index}]`;
4430
- fields2(item, ["type", "id", "namespace", "name", "output", "internal_chat_message_metadata_passthrough"], param, "unsupported_content");
4532
+ fields(item, ["type", "id", "namespace", "name", "output", "internal_chat_message_metadata_passthrough"], param, "unsupported_content");
4431
4533
  const text = atParam(`${param}.output`, () => string(item.output, "page snapshot output"));
4432
4534
  const { id, internal_chat_message_metadata_passthrough: metadata } = item;
4433
4535
  const reason = target === "chat_completions" ? "chat_codex_page_snapshot_as_user_data" : "gemini_codex_page_snapshot_as_user_data";
@@ -4447,6 +4549,7 @@ function convertProtocolRequest(raw, context) {
4447
4549
  const b = canonicalRequest(raw, context.sourceProtocol, context.model);
4448
4550
  const target = context.targetProtocol;
4449
4551
  const responsesToGemini = context.sourceProtocol === "responses" && target === "gemini_generate_content";
4552
+ const allowLossyContinuation = context.sourceProtocol === "responses" && target === "chat_completions" && context.allowLossyContinuation === true;
4450
4553
  const pageSnapshotDiagnostics = [];
4451
4554
  if (context.sourceProtocol === "responses" && (target === "chat_completions" || target === "gemini_generate_content") && Array.isArray(b.input))
4452
4555
  b.input = b.input.map((item, index) => projectCodexPageSnapshot(item, index, target, pageSnapshotDiagnostics));
@@ -4457,7 +4560,8 @@ function convertProtocolRequest(raw, context) {
4457
4560
  fail("invalid_payload", "Request stream mode disagrees with transport context", "stream");
4458
4561
  b.stream = context.streaming;
4459
4562
  }
4460
- const configuration = validateCanonical(b, context);
4563
+ const chatConfigurationUpdates = allowLossyContinuation ? new Set : undefined;
4564
+ const configuration = validateCanonical(b, context, chatConfigurationUpdates);
4461
4565
  const geminiHistory = responsesToGemini ? restoreGeminiHistory(b.input, limits(context.capabilities?.limits)) : undefined;
4462
4566
  if (geminiHistory)
4463
4567
  b.input = geminiHistory.input;
@@ -4476,12 +4580,14 @@ function convertProtocolRequest(raw, context) {
4476
4580
  fail("unsupported_reasoning", "Thinking mode requires an explicit target wire policy", "thinking");
4477
4581
  let mappedEffort;
4478
4582
  if (reasoning?.effort !== undefined) {
4479
- const effort = string(reasoning.effort, "reasoning.effort", true);
4480
- mappedEffort = policy?.effortMap?.[effort];
4481
- if (mappedEffort === undefined && policy?.anthropicThinkingBudget === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
4482
- fail("unsupported_reasoning", "Reasoning effort requires an explicit verified wire mapping", "reasoning.effort");
4483
- if (mappedEffort !== undefined)
4484
- string(mappedEffort, "reasoningPolicy.effortMap", true);
4583
+ const effort = atParam("reasoning.effort", () => string(reasoning.effort, "reasoning.effort", true));
4584
+ if (!allowLossyContinuation || !configuration) {
4585
+ mappedEffort = policy?.effortMap?.[effort];
4586
+ if (mappedEffort === undefined && policy?.anthropicThinkingBudget === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
4587
+ fail("unsupported_reasoning", "Reasoning effort requires an explicit verified wire mapping", "reasoning.effort");
4588
+ if (mappedEffort !== undefined)
4589
+ string(mappedEffort, "reasoningPolicy.effortMap", true);
4590
+ }
4485
4591
  }
4486
4592
  if (configuration)
4487
4593
  mappedEffort = configuration.level;
@@ -4525,7 +4631,7 @@ function convertProtocolRequest(raw, context) {
4525
4631
  }
4526
4632
  if (b.metadata !== undefined) {
4527
4633
  const metadata = record(b.metadata, "metadata");
4528
- fields2(metadata, ["user_id"], "metadata");
4634
+ fields(metadata, ["user_id"], "metadata");
4529
4635
  if (metadata.user_id !== undefined)
4530
4636
  string(metadata.user_id, "metadata.user_id");
4531
4637
  }
@@ -4537,7 +4643,7 @@ function convertProtocolRequest(raw, context) {
4537
4643
  } else if (target === "chat_completions") {
4538
4644
  if (reasoning?.effort !== undefined || mappedEffort !== undefined) {
4539
4645
  if (!cap.reasoningEffort)
4540
- fail("unsupported_reasoning", "Target effort capability is required", "reasoning.effort");
4646
+ fail("unsupported_reasoning", "Target effort capability is required", configuration?.param ?? "reasoning.effort");
4541
4647
  b.reasoning = { ...reasoning, effort: mappedEffort };
4542
4648
  if (mappedEffort === undefined)
4543
4649
  fail("unsupported_reasoning", "Chat requires a target effort mapping", "reasoning.effort");
@@ -4551,7 +4657,7 @@ function convertProtocolRequest(raw, context) {
4551
4657
  b.reasoning = { ...reasoning, effort: undefined };
4552
4658
  let decoded;
4553
4659
  try {
4554
- 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 });
4660
+ 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 });
4555
4661
  } catch (error) {
4556
4662
  if (geminiHistory && error instanceof ResponsesCodecError && error.param !== undefined)
4557
4663
  throw new ResponsesCodecError(error.code, error.message, geminiHistory.sourceParam(error.param));
@@ -4563,7 +4669,7 @@ function convertProtocolRequest(raw, context) {
4563
4669
  diagnostic.param = geminiHistory.sourceParam(diagnostic.param);
4564
4670
  diagnostics.push(...pageSnapshotDiagnostics);
4565
4671
  if (configuration)
4566
- diagnostics.push({ param: configuration.param, action: "mapped", reason: "gemini_configuration_effort_update" });
4672
+ diagnostics.push({ param: configuration.param, action: "mapped", reason: responsesToGemini ? "gemini_configuration_effort_update" : "chat_configuration_effort_update" });
4567
4673
  if (target === "gemini_generate_content" && decoded.body.parallel_tool_calls === true) {
4568
4674
  delete decoded.body.parallel_tool_calls;
4569
4675
  diagnostics.push({ param: "parallel_tool_calls", action: "omitted", reason: "gemini_parallel_tool_calls_allowed" });
@@ -4758,11 +4864,11 @@ function validateUsage(raw, protocol) {
4758
4864
  return;
4759
4865
  }
4760
4866
  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"];
4761
- fields2(u, keys, "usage", "unsupported_response");
4867
+ fields(u, keys, "usage", "unsupported_response");
4762
4868
  for (const [key, value] of Object.entries(u)) {
4763
4869
  if (key.endsWith("_details")) {
4764
4870
  const d = record(value, "usage details");
4765
- fields2(d, key.includes("output") || key.includes("completion") ? ["reasoning_tokens"] : ["cached_tokens", "cache_creation_tokens"], `usage.${key}`, "unsupported_response");
4871
+ fields(d, key.includes("output") || key.includes("completion") ? ["reasoning_tokens"] : ["cached_tokens", "cache_creation_tokens"], `usage.${key}`, "unsupported_response");
4766
4872
  for (const [k, v] of Object.entries(d))
4767
4873
  integer(v, `usage.${key}.${k}`);
4768
4874
  } else
@@ -4783,10 +4889,10 @@ function validateProviderResponse(raw, protocol) {
4783
4889
  const m = record(c.message, "message");
4784
4890
  for (const [callIndex, rawCall] of (m.tool_calls == null ? [] : list(m.tool_calls, "tool_calls")).entries()) {
4785
4891
  const call = record(rawCall, "call");
4786
- fields2(call, ["id", "type", "function", "index"], "tool_calls", "unsupported_tool");
4892
+ fields(call, ["id", "type", "function", "index"], "tool_calls", "unsupported_tool");
4787
4893
  if (call.index !== undefined && integer(call.index, `tool_calls[${callIndex}].index`) !== callIndex)
4788
4894
  fail("invalid_payload", "Tool call index must match its array position", `tool_calls[${callIndex}].index`);
4789
- fields2(record(call.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
4895
+ fields(record(call.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
4790
4896
  }
4791
4897
  }
4792
4898
  validateUsage(b.usage, protocol);
@@ -4800,14 +4906,14 @@ function validateProviderResponse(raw, protocol) {
4800
4906
  return b;
4801
4907
  }
4802
4908
  function validateAnthropicBlock(b, path) {
4803
- fields2(b, b.type === "text" ? ["type", "text"] : b.type === "thinking" ? ["type", "thinking", "signature"] : ["type", "id", "name", "input"], path, "unsupported_content");
4909
+ fields(b, b.type === "text" ? ["type", "text"] : b.type === "thinking" ? ["type", "thinking", "signature"] : ["type", "id", "name", "input"], path, "unsupported_content");
4804
4910
  if (b.signature !== undefined)
4805
4911
  fail("unsupported_reasoning", "Signed provider reasoning cannot cross protocols", `${path}.signature`);
4806
4912
  }
4807
4913
  function validateCanonicalResponse(raw, context, itemOnly = false) {
4808
4914
  const b = record(raw, "response");
4809
4915
  serialized(b, limits(context.capabilities?.limits).maxOutputBytes, "response");
4810
- 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");
4916
+ 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");
4811
4917
  if (!itemOnly) {
4812
4918
  string(b.id, "response.id", true);
4813
4919
  integer(b.created_at, "response.created_at");
@@ -4818,7 +4924,7 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
4818
4924
  fail("missing_terminal", "Response has no explicit supported terminal", "status");
4819
4925
  if (b.status === "incomplete") {
4820
4926
  const d = record(b.incomplete_details, "incomplete_details");
4821
- fields2(d, ["reason"], "incomplete_details", "unsupported_response");
4927
+ fields(d, ["reason"], "incomplete_details", "unsupported_response");
4822
4928
  if (!["max_output_tokens", "content_filter"].includes(String(d.reason)))
4823
4929
  fail("unknown_terminal", "Unknown incomplete reason", "incomplete_details.reason");
4824
4930
  }
@@ -4833,13 +4939,13 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
4833
4939
  fail("unsupported_response", "Unknown item status", `${path}.status`);
4834
4940
  if (b.status === "completed" && t.status !== undefined && t.status !== "completed")
4835
4941
  fail("invalid_stream", "Completed response contains an unfinished item", `${path}.status`);
4836
- 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");
4942
+ 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");
4837
4943
  if (t.type === "message") {
4838
4944
  if (t.role !== "assistant")
4839
4945
  fail("unsupported_content", "Output message must be assistant", `${path}.role`);
4840
4946
  for (const [j, rawPart] of list(t.content, "content").entries()) {
4841
4947
  const p = record(rawPart, "part");
4842
- fields2(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], `${path}.content[${j}]`, "unsupported_content");
4948
+ fields(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], `${path}.content[${j}]`, "unsupported_content");
4843
4949
  if (p.type === "output_text")
4844
4950
  string(p.text, "text");
4845
4951
  else if (p.type === "refusal")
@@ -4858,7 +4964,7 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
4858
4964
  fail("unsupported_reasoning", "Opaque or raw reasoning output cannot cross protocols", path);
4859
4965
  for (const rawPart of list(t.summary, "summary")) {
4860
4966
  const p = record(rawPart, "summary");
4861
- fields2(p, ["type", "text"], path, "unsupported_reasoning");
4967
+ fields(p, ["type", "text"], path, "unsupported_reasoning");
4862
4968
  if (p.type !== "summary_text")
4863
4969
  fail("unsupported_reasoning", "Unknown reasoning summary type", path);
4864
4970
  string(p.text, "summary");
@@ -5001,7 +5107,7 @@ class GeminiCanonicalDecoder {
5001
5107
  const events = [];
5002
5108
  if (b.promptFeedback !== undefined) {
5003
5109
  const p = record(b.promptFeedback, "promptFeedback");
5004
- fields2(p, ["blockReason", "blockReasonMessage", "safetyRatings"], "promptFeedback", "unsupported_response");
5110
+ fields(p, ["blockReason", "blockReasonMessage", "safetyRatings"], "promptFeedback", "unsupported_response");
5005
5111
  if (p.blockReason !== undefined && p.blockReason !== "BLOCK_REASON_UNSPECIFIED") {
5006
5112
  this.ended = true;
5007
5113
  events.push(...this.encoder.push({ choices: [{ delta: {}, finish_reason: "content_filter" }] }));
@@ -5016,7 +5122,7 @@ class GeminiCanonicalDecoder {
5016
5122
  fail("unsupported_response", "Only candidate index zero is supported", "candidates.index");
5017
5123
  if (c.content !== undefined && c.content !== null) {
5018
5124
  const content = record(c.content, "content");
5019
- fields2(content, ["role", "parts"], "candidates.content", "unsupported_content");
5125
+ fields(content, ["role", "parts"], "candidates.content", "unsupported_content");
5020
5126
  if (content.role !== undefined && content.role !== "model")
5021
5127
  fail("unsupported_response", "Response role must be model", "candidates.content.role");
5022
5128
  const parts = list(content.parts ?? [], "parts");
@@ -5024,14 +5130,14 @@ class GeminiCanonicalDecoder {
5024
5130
  fail("invalid_stream", "Content arrived after Gemini terminal");
5025
5131
  for (const [i, rawPart] of parts.entries()) {
5026
5132
  const p = record(rawPart, "part");
5027
- fields2(p, ["text", "thought", "functionCall", "thoughtSignature"], "candidates.content.parts", "unsupported_content");
5133
+ fields(p, ["text", "thought", "functionCall", "thoughtSignature"], "candidates.content.parts", "unsupported_content");
5028
5134
  if (p.thoughtSignature !== undefined && this.context.sourceProtocol !== "responses")
5029
5135
  fail("unsupported_reasoning", "Thought signatures cannot cross protocols", "candidates.content.parts.thoughtSignature");
5030
5136
  if (p.functionCall !== undefined) {
5031
5137
  if (p.text !== undefined || p.thought !== undefined)
5032
5138
  fail("unsupported_content", "Mixed Gemini part kinds", "candidates.content.parts");
5033
5139
  const f = record(p.functionCall, "functionCall");
5034
- fields2(f, ["id", "name", "args"], "functionCall", "unsupported_tool");
5140
+ fields(f, ["id", "name", "args"], "functionCall", "unsupported_tool");
5035
5141
  const index = this.serial++, originalId = f.id === undefined ? `call_gemini_${crypto.randomUUID().replaceAll("-", "")}` : string(f.id, "functionCall.id", true);
5036
5142
  if (this.ids.has(originalId))
5037
5143
  fail("invalid_tool_arguments", "Duplicate Gemini call id", "functionCall.id");
@@ -5185,7 +5291,7 @@ class CanonicalStreamValidator {
5185
5291
  this.sequence = n;
5186
5292
  }
5187
5293
  if (["response.created", "response.in_progress", "response.completed", "response.incomplete", "response.failed"].includes(type)) {
5188
- fields2(e, [...common, "response"], "", "unsupported_response");
5294
+ fields(e, [...common, "response"], "", "unsupported_response");
5189
5295
  const r = record(e.response, "response");
5190
5296
  const id = string(r.id, "response.id", true);
5191
5297
  if (this.responseId !== undefined && this.responseId !== id)
@@ -5242,7 +5348,7 @@ class CanonicalStreamValidator {
5242
5348
  ];
5243
5349
  if (!known.includes(type))
5244
5350
  fail("unsupported_response", "Unknown Responses stream event", "type");
5245
- 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");
5351
+ 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");
5246
5352
  if (e.response_id !== undefined && e.response_id !== this.responseId)
5247
5353
  fail("invalid_stream", "Event response id changed", "response_id");
5248
5354
  const index = integer(e.output_index, "output_index");
@@ -5336,7 +5442,7 @@ class CanonicalStreamValidator {
5336
5442
  fail("unsupported_content", "Unknown content part type", "part.type");
5337
5443
  if (summary ? p.type !== "summary_text" : p.type === "summary_text")
5338
5444
  fail("invalid_stream", "Part kind differs from its output item", "part.type");
5339
- fields2(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
5445
+ fields(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
5340
5446
  if (p.annotations !== undefined && Array.isArray(p.annotations) && p.annotations.length)
5341
5447
  fail("unsupported_content", "Annotations cannot cross protocols", "part.annotations");
5342
5448
  const initial = string(p[p.type === "refusal" ? "refusal" : "text"], "part text");
@@ -5361,7 +5467,7 @@ class CanonicalStreamValidator {
5361
5467
  if (!p.textDone)
5362
5468
  fail("invalid_stream", "Part done before text done");
5363
5469
  const v = record(e.part, "part");
5364
- fields2(v, p.kind === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
5470
+ fields(v, p.kind === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
5365
5471
  if (v.annotations !== undefined && (!Array.isArray(v.annotations) || v.annotations.length))
5366
5472
  fail("unsupported_content", "Annotations cannot cross protocols", "part.annotations");
5367
5473
  if (v.type !== p.kind || v[p.kind === "refusal" ? "refusal" : "text"] !== p.text)
@@ -5515,7 +5621,7 @@ class CanonicalStreamRenderer {
5515
5621
  var LLM_PROTOCOLS = ["responses", "chat_completions", "anthropic_messages", "gemini_generate_content"];
5516
5622
 
5517
5623
  // src/protocol-session/index.ts
5518
- var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.5";
5624
+ var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.6";
5519
5625
  function describeProtocolConversion() {
5520
5626
  return {
5521
5627
  rulesVersion: PROTOCOL_CONVERSION_RULES_VERSION,
@@ -5724,9 +5830,9 @@ function validateStreamEnvelope(raw, protocol) {
5724
5830
  if (Array.isArray(d.tool_calls))
5725
5831
  for (const rawCall of d.tool_calls) {
5726
5832
  const t = record(rawCall, "tool call");
5727
- fields2(t, ["index", "id", "type", "function"], "tool_calls", "unsupported_tool");
5833
+ fields(t, ["index", "id", "type", "function"], "tool_calls", "unsupported_tool");
5728
5834
  if (t.function !== undefined)
5729
- fields2(record(t.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
5835
+ fields(record(t.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
5730
5836
  }
5731
5837
  }
5732
5838
  validateUsage(e.usage, protocol);
@@ -5735,12 +5841,12 @@ function validateStreamEnvelope(raw, protocol) {
5735
5841
  validateAnthropicBlock(record(e.content_block, "block"), "content_block");
5736
5842
  if (e.type === "content_block_delta") {
5737
5843
  const d = record(e.delta, "delta");
5738
- 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");
5844
+ 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");
5739
5845
  if (d.type === "signature_delta" || d.signature !== undefined)
5740
5846
  fail("unsupported_reasoning", "Signed provider reasoning cannot cross protocols", "delta.signature");
5741
5847
  }
5742
5848
  if (e.type === "message_delta")
5743
- fields2(record(e.delta, "delta"), ["stop_reason", "stop_sequence"], "delta", "unsupported_response");
5849
+ fields(record(e.delta, "delta"), ["stop_reason", "stop_sequence"], "delta", "unsupported_response");
5744
5850
  if (e.type === "message_start") {
5745
5851
  const m = record(e.message, "message");
5746
5852
  validateUsage(m.usage, protocol);