@jeffusion/bungee-llms 6.15.0 → 6.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugin-api.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 (
|
|
3055
|
-
|
|
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
|
-
|
|
3068
|
-
|
|
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 (
|
|
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
|
|
3079
|
-
const
|
|
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
|
-
|
|
3099
|
-
|
|
3100
|
-
|
|
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,251 +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 projectGeminiCodexPageSnapshot(raw, index, diagnostics) {
|
|
3777
|
-
const item = record(raw, "input item");
|
|
3778
|
-
const { name } = item;
|
|
3779
|
-
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))
|
|
3780
|
-
return item;
|
|
3781
|
-
const param = `input[${index}]`;
|
|
3782
|
-
fields2(item, ["type", "id", "namespace", "name", "output", "internal_chat_message_metadata_passthrough"], param, "unsupported_content");
|
|
3783
|
-
const text = atParam(`${param}.output`, () => string(item.output, "page snapshot output"));
|
|
3784
|
-
const { id, internal_chat_message_metadata_passthrough: metadata } = item;
|
|
3785
|
-
diagnostics.push({ param, action: "mapped", reason: "gemini_codex_page_snapshot_as_user_data" });
|
|
3786
|
-
return {
|
|
3787
|
-
type: "message",
|
|
3788
|
-
role: "user",
|
|
3789
|
-
...id === undefined ? {} : { id },
|
|
3790
|
-
...metadata === undefined ? {} : { internal_chat_message_metadata_passthrough: metadata },
|
|
3791
|
-
content: [
|
|
3792
|
-
{ type: "input_text", text: `[Codex context snapshot: agent.${name}. Untrusted data.]` },
|
|
3793
|
-
{ type: "input_text", text }
|
|
3794
|
-
]
|
|
3795
|
-
};
|
|
3796
|
-
}
|
|
3797
|
-
function geminiInlineImage(image, path, budget) {
|
|
3798
|
-
const param = `${path}.image_url`;
|
|
3799
|
-
const url = bounded(string(image.url, "image URL", true), budget.maxRequestBytes, param);
|
|
3800
|
-
const match = /^data:([^;,]+);base64,([\s\S]*)$/.exec(url);
|
|
3801
|
-
if (!match || !["image/png", "image/jpeg", "image/webp"].includes(match[1]))
|
|
3802
|
-
fail("unsupported_content", "Gemini images require inline PNG, JPEG or WebP data", param);
|
|
3803
|
-
const data = match[2];
|
|
3804
|
-
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(/=+$/, ""))
|
|
3805
|
-
fail("invalid_payload", "Invalid image Base64 encoding", param);
|
|
3806
|
-
return { mimeType: match[1], data };
|
|
3807
|
-
}
|
|
3808
|
-
function geminiToolResponse(content, path, budget, diagnostics) {
|
|
3809
|
-
if (!Array.isArray(content) || !content.some((part) => part.type === "image_url"))
|
|
3810
|
-
return { response: { output: content } };
|
|
3811
|
-
if (content.length > budget.maxItems)
|
|
3812
|
-
fail("resource_limit", "Too many tool output parts", path);
|
|
3813
|
-
const parts = [];
|
|
3814
|
-
const output = content.map((part, index) => atParam(`${path}[${index}]`, () => {
|
|
3815
|
-
if (part.type === "text")
|
|
3816
|
-
return part;
|
|
3817
|
-
if (part.type !== "image_url")
|
|
3818
|
-
fail("unsupported_content", "Unsupported Gemini tool result content");
|
|
3819
|
-
const image = record(part.image_url, "tool image");
|
|
3820
|
-
const inlineData = geminiInlineImage(image, `${path}[${index}]`, budget);
|
|
3821
|
-
const displayName = `tool-image-${index}.${inlineData.mimeType.slice("image/".length)}`;
|
|
3822
|
-
parts.push({ inlineData: { ...inlineData, displayName } });
|
|
3823
|
-
if (image.detail !== undefined)
|
|
3824
|
-
diagnostics.push({ param: `${path}[${index}].detail`, action: "omitted", reason: "gemini_tool_image_detail_unavailable" });
|
|
3825
|
-
return { $ref: displayName };
|
|
3826
|
-
}));
|
|
3827
|
-
return { response: { output }, parts };
|
|
3828
|
-
}
|
|
3829
|
-
function checkedSignature(value, maxBytes) {
|
|
3830
|
-
const signature = bounded(string(value, "thoughtSignature", true), maxBytes, "thoughtSignature");
|
|
3831
|
-
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(/=+$/, ""))
|
|
3832
|
-
fail("invalid_tool_arguments", "Invalid Gemini thought signature encoding", "thoughtSignature");
|
|
3833
|
-
return signature;
|
|
3834
|
-
}
|
|
3835
|
-
var envelopePrefix = "bungee_gemini:";
|
|
3836
|
-
var geminiEnvelopeBytes = (payloadBytes) => envelopePrefix.length + Math.ceil(payloadBytes * 4 / 3);
|
|
3837
|
-
var geminiTextHash = (text) => createHash("sha256").update(text).digest("base64url");
|
|
3838
|
-
function geminiSignatureItem(items, budget) {
|
|
3839
|
-
const payload = serialized({ version: 1, items }, budget.maxArgumentBytes, "Gemini signatures");
|
|
3840
|
-
return {
|
|
3841
|
-
type: "reasoning",
|
|
3842
|
-
id: `rs_gemini_${crypto.randomUUID().replaceAll("-", "")}`,
|
|
3843
|
-
summary: [],
|
|
3844
|
-
encrypted_content: bounded(envelopePrefix + Buffer.from(payload).toString("base64url"), budget.maxArgumentBytes, "Gemini signatures")
|
|
3845
|
-
};
|
|
3846
|
-
}
|
|
3847
|
-
function readGeminiSignatures(item, budget) {
|
|
3848
|
-
fields2(item, ["type", "id", "summary", "encrypted_content", "status"], "Gemini signatures", "unsupported_reasoning");
|
|
3849
|
-
if (item.type !== "reasoning" || list(item.summary, "summary").length)
|
|
3850
|
-
fail("unsupported_reasoning", "Invalid Gemini signature carrier");
|
|
3851
|
-
string(item.id, "signature item id", true);
|
|
3852
|
-
const opaque = bounded(string(item.encrypted_content, "encrypted_content", true), budget.maxArgumentBytes, "Gemini signatures");
|
|
3853
|
-
if (!opaque.startsWith(envelopePrefix))
|
|
3854
|
-
fail("unsupported_reasoning", "Native encrypted reasoning cannot be restored to Gemini");
|
|
3855
|
-
const encoded = opaque.slice(envelopePrefix.length), bytes = Buffer.from(encoded, "base64url");
|
|
3856
|
-
if (!encoded || bytes.toString("base64url") !== encoded)
|
|
3857
|
-
fail("unsupported_reasoning", "Invalid Gemini signature carrier encoding");
|
|
3858
|
-
let raw;
|
|
3859
|
-
try {
|
|
3860
|
-
raw = JSON.parse(bytes.toString("utf8"));
|
|
3861
|
-
} catch {
|
|
3862
|
-
fail("unsupported_reasoning", "Invalid Gemini signature carrier JSON");
|
|
3863
|
-
}
|
|
3864
|
-
const body = record(raw, "Gemini signatures");
|
|
3865
|
-
fields2(body, ["version", "items"], "Gemini signatures", "unsupported_reasoning");
|
|
3866
|
-
if (body.version !== 1)
|
|
3867
|
-
fail("unsupported_reasoning", "Unknown Gemini signature format");
|
|
3868
|
-
const ids = new Set;
|
|
3869
|
-
let partCount = 0;
|
|
3870
|
-
const result = list(body.items, "signature items").map((raw) => {
|
|
3871
|
-
const item = record(raw, "signature item");
|
|
3872
|
-
fields2(item, ["id", "thought", "parts"], "signature item", "unsupported_reasoning");
|
|
3873
|
-
const id = string(item.id, "signed item id", true);
|
|
3874
|
-
if (ids.has(id) || typeof item.thought !== "boolean")
|
|
3875
|
-
fail("unsupported_reasoning", "Invalid signed item identity");
|
|
3876
|
-
ids.add(id);
|
|
3877
|
-
const parts = list(item.parts, "signed parts").map((raw) => {
|
|
3878
|
-
if (++partCount > budget.maxItems)
|
|
3879
|
-
fail("resource_limit", "Too many signed Gemini parts");
|
|
3880
|
-
const part = record(raw, "signed part");
|
|
3881
|
-
fields2(part, ["length", "hash", "signature", "textAbsent"], "signed part", "unsupported_reasoning");
|
|
3882
|
-
const length = integer(part.length, "signed part length"), hash = string(part.hash, "signed part hash", true);
|
|
3883
|
-
if (!/^[A-Za-z0-9_-]{43}$/.test(hash))
|
|
3884
|
-
fail("unsupported_reasoning", "Invalid signed part hash");
|
|
3885
|
-
const signature = part.signature === undefined ? undefined : checkedSignature(part.signature, budget.maxArgumentBytes);
|
|
3886
|
-
if (part.textAbsent !== undefined && (part.textAbsent !== true || length !== 0 || signature === undefined))
|
|
3887
|
-
fail("unsupported_reasoning", "Invalid empty signed part");
|
|
3888
|
-
return { length, hash, ...signature === undefined ? {} : { signature }, ...part.textAbsent ? { textAbsent: true } : {} };
|
|
3889
|
-
});
|
|
3890
|
-
if (!parts.some((p) => p.signature !== undefined))
|
|
3891
|
-
fail("unsupported_reasoning", "Signature carrier has no signature");
|
|
3892
|
-
return { id, thought: item.thought, parts };
|
|
3893
|
-
});
|
|
3894
|
-
if (!result.length || result.length > budget.maxItems)
|
|
3895
|
-
fail("unsupported_reasoning", "Invalid signature item count");
|
|
3896
|
-
return result;
|
|
3897
|
-
}
|
|
3898
|
-
function restoreGeminiHistory(input, budget) {
|
|
3899
|
-
const original = typeof input === "string" ? [] : list(input, "input").map((raw) => record(raw, "input item"));
|
|
3900
|
-
const carriers = new Set, parts = new Map, ids = new Map;
|
|
3901
|
-
original.forEach((item, i) => {
|
|
3902
|
-
if (typeof item.id === "string") {
|
|
3903
|
-
if (ids.has(item.id))
|
|
3904
|
-
fail("invalid_tool_history", "Duplicate history item id", "input.id");
|
|
3905
|
-
ids.set(item.id, i);
|
|
3906
|
-
}
|
|
3907
|
-
});
|
|
3908
|
-
original.forEach((carrier, index) => {
|
|
3909
|
-
if (carrier.encrypted_content == null)
|
|
3910
|
-
return;
|
|
3911
|
-
const signed = readGeminiSignatures(carrier, budget);
|
|
3912
|
-
carriers.add(carrier);
|
|
3913
|
-
let previous = -1;
|
|
3914
|
-
for (const item of signed) {
|
|
3915
|
-
const at = ids.get(item.id);
|
|
3916
|
-
if (at === undefined || at >= index || at <= previous || parts.has(item.id))
|
|
3917
|
-
fail("unsupported_reasoning", "Signed history reference is missing or ambiguous");
|
|
3918
|
-
previous = at;
|
|
3919
|
-
const source = original[at];
|
|
3920
|
-
if (item.thought ? source.type !== "reasoning" || source.encrypted_content != null : source.role !== "assistant" || source.type !== undefined && source.type !== "message")
|
|
3921
|
-
fail("unsupported_reasoning", "Signed history item kind changed");
|
|
3922
|
-
const content = item.thought ? list(source.summary, "summary") : typeof source.content === "string" ? [{ type: "output_text", text: source.content }] : list(source.content, "content");
|
|
3923
|
-
const text = content.map((raw) => {
|
|
3924
|
-
const p = record(raw, "signed text");
|
|
3925
|
-
if (p.type !== (item.thought ? "summary_text" : "output_text") && !(p.type === "input_text" && !item.thought))
|
|
3926
|
-
fail("unsupported_reasoning", "Signed history content kind changed");
|
|
3927
|
-
return string(p.text, "signed text");
|
|
3928
|
-
}).join("");
|
|
3929
|
-
let offset = 0;
|
|
3930
|
-
const restored = item.parts.map((part) => {
|
|
3931
|
-
const value = text.slice(offset, offset + part.length);
|
|
3932
|
-
offset += part.length;
|
|
3933
|
-
if (value.length !== part.length || geminiTextHash(value) !== part.hash)
|
|
3934
|
-
fail("unsupported_reasoning", "Signed history text changed");
|
|
3935
|
-
return { ...part.textAbsent ? {} : { text: value }, ...item.thought ? { thought: true } : {}, ...part.signature === undefined ? {} : { thoughtSignature: part.signature } };
|
|
3936
|
-
});
|
|
3937
|
-
if (offset !== text.length)
|
|
3938
|
-
fail("unsupported_reasoning", "Signed history text was not fully consumed");
|
|
3939
|
-
parts.set(item.id, restored);
|
|
3940
|
-
}
|
|
3941
|
-
});
|
|
3942
|
-
return {
|
|
3943
|
-
input: typeof input === "string" ? input : original.filter((item) => !carriers.has(item)),
|
|
3944
|
-
parts,
|
|
3945
|
-
canonicalHistory(decoded) {
|
|
3946
|
-
if (!carriers.size)
|
|
3947
|
-
return decoded;
|
|
3948
|
-
let next = 0;
|
|
3949
|
-
return original.flatMap((item) => carriers.has(item) ? [item] : item.type === "additional_tools" ? [] : [decoded[next++]]);
|
|
3950
|
-
}
|
|
3951
|
-
};
|
|
3952
|
-
}
|
|
3953
|
-
function encodeGeminiCallId(id, signature, maxBytes) {
|
|
3954
|
-
if (id.includes(signatureSeparator))
|
|
3955
|
-
fail("invalid_tool_arguments", "Gemini call id contains the signature separator", "functionCall.id");
|
|
3956
|
-
return signature === undefined ? id : `${id}${signatureSeparator}${checkedSignature(signature, maxBytes)}`;
|
|
3957
|
-
}
|
|
3958
|
-
function decodeGeminiCallId(value, maxBytes) {
|
|
3959
|
-
const separator = value.indexOf(signatureSeparator);
|
|
3960
|
-
if (separator < 0)
|
|
3961
|
-
return { id: value };
|
|
3962
|
-
const id = string(value.slice(0, separator), "functionCall.id", true);
|
|
3963
|
-
return { id, thoughtSignature: checkedSignature(value.slice(separator + signatureSeparator.length), maxBytes) };
|
|
3964
|
-
}
|
|
3965
|
-
|
|
3966
4055
|
// src/protocol-session/schema.ts
|
|
3967
4056
|
function geminiSchemaToJson(raw, path, code = "unsupported_request", depth = 0) {
|
|
3968
4057
|
if (depth > 64)
|
|
3969
4058
|
fail("resource_limit", "Schema nesting exceeds the conversion limit", path);
|
|
3970
4059
|
const s = record(raw, path);
|
|
3971
|
-
|
|
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);
|
|
3972
4061
|
const out = {};
|
|
3973
4062
|
if (s.type !== undefined) {
|
|
3974
4063
|
const types = { STRING: "string", NUMBER: "number", INTEGER: "integer", BOOLEAN: "boolean", ARRAY: "array", OBJECT: "object", NULL: "null" };
|
|
@@ -4008,19 +4097,19 @@ function message(input, role, content, style, path) {
|
|
|
4008
4097
|
function toolDefinition(raw, style, path) {
|
|
4009
4098
|
const t = record(raw, path);
|
|
4010
4099
|
if (style === "chat") {
|
|
4011
|
-
|
|
4100
|
+
fields(t, t.type === "custom" ? ["type", "custom"] : ["type", "function"], path, "unsupported_tool");
|
|
4012
4101
|
if (t.type === "custom") {
|
|
4013
4102
|
const custom = record(t.custom, `${path}.custom`);
|
|
4014
|
-
|
|
4103
|
+
fields(custom, ["name", "description", "format"], `${path}.custom`, "unsupported_tool");
|
|
4015
4104
|
return { type: "custom", ...custom };
|
|
4016
4105
|
}
|
|
4017
4106
|
if (t.type !== "function")
|
|
4018
4107
|
fail("unsupported_tool", "Unsupported tool kind", `${path}.type`);
|
|
4019
4108
|
const fn = record(t.function, path);
|
|
4020
|
-
|
|
4109
|
+
fields(fn, ["name", "description", "parameters", "strict"], `${path}.function`, "unsupported_tool");
|
|
4021
4110
|
return { type: "function", ...fn };
|
|
4022
4111
|
}
|
|
4023
|
-
|
|
4112
|
+
fields(t, style === "anthropic" ? ["name", "description", "input_schema", "strict"] : ["name", "description", "parametersJsonSchema", "parameters"], path, "unsupported_tool");
|
|
4024
4113
|
if (t.parameters !== undefined && t.parametersJsonSchema !== undefined)
|
|
4025
4114
|
fail("unsupported_tool", "Ambiguous schema dialect", path);
|
|
4026
4115
|
return {
|
|
@@ -4043,13 +4132,13 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4043
4132
|
};
|
|
4044
4133
|
if (protocol === "chat_completions") {
|
|
4045
4134
|
const callKinds = new Map;
|
|
4046
|
-
|
|
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"], "");
|
|
4047
4136
|
if (b.max_tokens !== undefined && b.max_completion_tokens !== undefined)
|
|
4048
4137
|
fail("unsupported_request", "Ambiguous token limits", "max_tokens");
|
|
4049
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" });
|
|
4050
4139
|
for (const [index, rawMessage] of list(b.messages, "messages").entries()) {
|
|
4051
4140
|
const m = record(rawMessage, "message"), path = `messages[${index}]`;
|
|
4052
|
-
|
|
4141
|
+
fields(m, ["role", "content", "tool_calls", "tool_call_id", "reasoning_content", "reasoning", "refusal", "name"], path, "unsupported_content");
|
|
4053
4142
|
if (m.name !== undefined)
|
|
4054
4143
|
fail("unsupported_content", "Named messages cannot be represented faithfully", `${path}.name`);
|
|
4055
4144
|
const role = string(m.role, "role", true);
|
|
@@ -4084,12 +4173,12 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4084
4173
|
fail("invalid_tool_history", "Tool calls require assistant role", path);
|
|
4085
4174
|
for (const [j, rawCall] of list(m.tool_calls, "tool_calls").entries()) {
|
|
4086
4175
|
const c = record(rawCall, "tool call"), at = `${path}.tool_calls[${j}]`;
|
|
4087
|
-
|
|
4176
|
+
fields(c, ["id", "type", "function", "custom"], at, "unsupported_tool");
|
|
4088
4177
|
const custom = c.type === "custom";
|
|
4089
4178
|
if (!custom && c.type !== "function")
|
|
4090
4179
|
fail("unsupported_tool", "Unknown call type", at);
|
|
4091
4180
|
const fn = record(custom ? c.custom : c.function, "tool call");
|
|
4092
|
-
|
|
4181
|
+
fields(fn, custom ? ["name", "input"] : ["name", "arguments"], at, "unsupported_tool");
|
|
4093
4182
|
callKinds.set(string(c.id, "id", true), custom);
|
|
4094
4183
|
input.push({
|
|
4095
4184
|
type: custom ? "custom_tool_call" : "function_call",
|
|
@@ -4108,9 +4197,9 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4108
4197
|
out.tool_choice = c;
|
|
4109
4198
|
else {
|
|
4110
4199
|
const choice = record(c, "tool_choice");
|
|
4111
|
-
|
|
4200
|
+
fields(choice, ["type", "function", "custom"], "tool_choice");
|
|
4112
4201
|
const fn = record(choice.function ?? choice.custom, "tool_choice");
|
|
4113
|
-
|
|
4202
|
+
fields(fn, ["name"], "tool_choice.function");
|
|
4114
4203
|
out.tool_choice = { type: choice.type, name: fn.name };
|
|
4115
4204
|
}
|
|
4116
4205
|
}
|
|
@@ -4118,19 +4207,19 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4118
4207
|
out.reasoning = { effort: b.reasoning_effort };
|
|
4119
4208
|
if (b.response_format !== undefined) {
|
|
4120
4209
|
const format = record(b.response_format, "response_format");
|
|
4121
|
-
|
|
4210
|
+
fields(format, ["type", "json_schema"], "response_format");
|
|
4122
4211
|
out.text = { format: format.type === "json_schema" ? { type: "json_schema", ...record(format.json_schema, "json_schema") } : format };
|
|
4123
4212
|
}
|
|
4124
4213
|
return out;
|
|
4125
4214
|
}
|
|
4126
4215
|
if (protocol === "anthropic_messages") {
|
|
4127
|
-
|
|
4216
|
+
fields(b, ["model", "messages", "system", "tools", "tool_choice", "stream", "temperature", "top_p", "max_tokens", "metadata", "stop_sequences", "thinking", "output_config"], "");
|
|
4128
4217
|
copy({ stream: "stream", temperature: "temperature", top_p: "top_p", max_tokens: "max_output_tokens", metadata: "metadata", stop_sequences: "stop" });
|
|
4129
4218
|
if (b.system !== undefined)
|
|
4130
4219
|
message(input, "system", b.system, "anthropic", "system");
|
|
4131
4220
|
for (const [index, rawMessage] of list(b.messages, "messages").entries()) {
|
|
4132
4221
|
const m = record(rawMessage, "message"), path = `messages[${index}]`;
|
|
4133
|
-
|
|
4222
|
+
fields(m, ["role", "content"], path, "unsupported_content");
|
|
4134
4223
|
if (m.role !== "user" && m.role !== "assistant")
|
|
4135
4224
|
fail("unsupported_content", "Anthropic messages require user or assistant role", `${path}.role`);
|
|
4136
4225
|
if (typeof m.content === "string") {
|
|
@@ -4142,15 +4231,15 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4142
4231
|
if (p.type === "tool_use") {
|
|
4143
4232
|
if (m.role !== "assistant")
|
|
4144
4233
|
fail("invalid_tool_history", "Tool calls require assistant role", at);
|
|
4145
|
-
|
|
4234
|
+
fields(p, ["type", "id", "name", "input"], at, "unsupported_content");
|
|
4146
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)) });
|
|
4147
4236
|
} else if (p.type === "tool_result") {
|
|
4148
4237
|
if (m.role !== "user")
|
|
4149
4238
|
fail("invalid_tool_history", "Tool results require user role", at);
|
|
4150
|
-
|
|
4239
|
+
fields(p, ["type", "tool_use_id", "content", "is_error"], at, "unsupported_content");
|
|
4151
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) } : {} });
|
|
4152
4241
|
} else if (p.type === "thinking") {
|
|
4153
|
-
|
|
4242
|
+
fields(p, ["type", "thinking", "signature"], at, "unsupported_reasoning");
|
|
4154
4243
|
if (p.signature != null)
|
|
4155
4244
|
fail("unsupported_reasoning", "Provider-bound reasoning signatures cannot cross protocols", `${at}.signature`);
|
|
4156
4245
|
if (m.role !== "assistant")
|
|
@@ -4164,7 +4253,7 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4164
4253
|
out.tools = list(b.tools, "tools").map((t, i) => toolDefinition(t, "anthropic", `tools[${i}]`));
|
|
4165
4254
|
if (b.tool_choice !== undefined) {
|
|
4166
4255
|
const c = record(b.tool_choice, "tool_choice");
|
|
4167
|
-
|
|
4256
|
+
fields(c, ["type", "name", "disable_parallel_tool_use"], "tool_choice");
|
|
4168
4257
|
if (c.type === "tool")
|
|
4169
4258
|
out.tool_choice = { type: "function", name: c.name };
|
|
4170
4259
|
else if (["auto", "none", "any"].includes(String(c.type)))
|
|
@@ -4176,7 +4265,7 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4176
4265
|
}
|
|
4177
4266
|
if (b.thinking !== undefined) {
|
|
4178
4267
|
const t = record(b.thinking, "thinking");
|
|
4179
|
-
|
|
4268
|
+
fields(t, ["type", "budget_tokens"], "thinking", "unsupported_reasoning");
|
|
4180
4269
|
if (!["enabled", "adaptive", "disabled"].includes(String(t.type)))
|
|
4181
4270
|
fail("unsupported_reasoning", "Unknown thinking mode", "thinking.type");
|
|
4182
4271
|
if (t.type === "enabled")
|
|
@@ -4187,12 +4276,12 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4187
4276
|
}
|
|
4188
4277
|
if (b.output_config !== undefined) {
|
|
4189
4278
|
const c = record(b.output_config, "output_config");
|
|
4190
|
-
|
|
4279
|
+
fields(c, ["effort", "format"], "output_config");
|
|
4191
4280
|
if (c.effort !== undefined)
|
|
4192
4281
|
out.reasoning = { effort: c.effort };
|
|
4193
4282
|
if (c.format !== undefined) {
|
|
4194
4283
|
const f = record(c.format, "format");
|
|
4195
|
-
|
|
4284
|
+
fields(f, ["type", "schema"], "output_config.format");
|
|
4196
4285
|
if (f.type !== "json_schema")
|
|
4197
4286
|
fail("unsupported_request", "Unknown structured output type", "output_config.format.type");
|
|
4198
4287
|
out.text = { format: { type: "json_schema", name: "response", schema: f.schema } };
|
|
@@ -4200,12 +4289,12 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4200
4289
|
}
|
|
4201
4290
|
return out;
|
|
4202
4291
|
}
|
|
4203
|
-
|
|
4292
|
+
fields(b, ["contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "model", "stream"], "");
|
|
4204
4293
|
if (b.stream !== undefined)
|
|
4205
4294
|
out.stream = b.stream;
|
|
4206
4295
|
if (b.systemInstruction !== undefined) {
|
|
4207
4296
|
const s = record(b.systemInstruction, "systemInstruction");
|
|
4208
|
-
|
|
4297
|
+
fields(s, ["role", "parts"], "systemInstruction");
|
|
4209
4298
|
if (s.role !== undefined && s.role !== "system")
|
|
4210
4299
|
fail("unsupported_content", "Invalid system role", "systemInstruction.role");
|
|
4211
4300
|
message(input, "system", s.parts, "gemini", "systemInstruction");
|
|
@@ -4215,12 +4304,12 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4215
4304
|
for (const [index, rawContent] of list(b.contents, "contents").entries()) {
|
|
4216
4305
|
const original = record(rawContent, "content"), path = `contents[${index}]`;
|
|
4217
4306
|
const c = { ...original, role: original.role ?? "user" };
|
|
4218
|
-
|
|
4307
|
+
fields(c, ["role", "parts"], path, "unsupported_content");
|
|
4219
4308
|
if (c.role !== "user" && c.role !== "model")
|
|
4220
4309
|
fail("unsupported_content", "Gemini contents require user or model role", `${path}.role`);
|
|
4221
4310
|
for (const [j, rawPart] of list(c.parts, "parts").entries()) {
|
|
4222
4311
|
const p = record(rawPart, "part"), at = `${path}.parts[${j}]`;
|
|
4223
|
-
|
|
4312
|
+
fields(p, ["text", "thought", "functionCall", "functionResponse", "thoughtSignature"], at, "unsupported_content");
|
|
4224
4313
|
if (p.thoughtSignature !== undefined)
|
|
4225
4314
|
fail("unsupported_reasoning", "Provider-bound thought signatures cannot cross protocols", `${at}.thoughtSignature`);
|
|
4226
4315
|
if ([p.text, p.functionCall, p.functionResponse].filter((v) => v !== undefined).length !== 1)
|
|
@@ -4229,7 +4318,7 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4229
4318
|
if (c.role !== "model")
|
|
4230
4319
|
fail("invalid_tool_history", "Function calls require model role", at);
|
|
4231
4320
|
const f = record(p.functionCall, at);
|
|
4232
|
-
|
|
4321
|
+
fields(f, ["name", "args", "id"], `${at}.functionCall`, "unsupported_tool");
|
|
4233
4322
|
const name = string(f.name, at, true), id = f.id === undefined ? `call_gemini_${serial++}` : string(f.id, at, true);
|
|
4234
4323
|
if (calls.has(id))
|
|
4235
4324
|
fail("invalid_tool_history", "Duplicate tool call id", at);
|
|
@@ -4239,7 +4328,7 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4239
4328
|
if (c.role !== "user")
|
|
4240
4329
|
fail("invalid_tool_history", "Function results require user role", at);
|
|
4241
4330
|
const f = record(p.functionResponse, at);
|
|
4242
|
-
|
|
4331
|
+
fields(f, ["name", "response", "id"], `${at}.functionResponse`, "unsupported_tool");
|
|
4243
4332
|
const matches = [...calls.values()].filter((v) => v.name === f.name);
|
|
4244
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);
|
|
4245
4334
|
if (calls.get(id)?.name !== f.name)
|
|
@@ -4258,7 +4347,7 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4258
4347
|
const tools = [];
|
|
4259
4348
|
for (const [i, rawTool] of list(b.tools, "tools").entries()) {
|
|
4260
4349
|
const t = record(rawTool, "tool");
|
|
4261
|
-
|
|
4350
|
+
fields(t, ["functionDeclarations"], `tools[${i}]`, "unsupported_tool");
|
|
4262
4351
|
for (const [j, f] of list(t.functionDeclarations, "functionDeclarations").entries())
|
|
4263
4352
|
tools.push(toolDefinition(f, "gemini", `tools[${i}].functionDeclarations[${j}]`));
|
|
4264
4353
|
}
|
|
@@ -4266,9 +4355,9 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4266
4355
|
}
|
|
4267
4356
|
if (b.toolConfig !== undefined) {
|
|
4268
4357
|
const config = record(b.toolConfig, "toolConfig");
|
|
4269
|
-
|
|
4358
|
+
fields(config, ["functionCallingConfig"], "toolConfig");
|
|
4270
4359
|
const c = record(config.functionCallingConfig, "functionCallingConfig");
|
|
4271
|
-
|
|
4360
|
+
fields(c, ["mode", "allowedFunctionNames"], "toolConfig.functionCallingConfig");
|
|
4272
4361
|
if (!["AUTO", "NONE", "ANY"].includes(String(c.mode)))
|
|
4273
4362
|
fail("unsupported_tool_choice", "Unknown function calling mode", "toolConfig.functionCallingConfig.mode");
|
|
4274
4363
|
if (c.allowedFunctionNames !== undefined) {
|
|
@@ -4281,7 +4370,7 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4281
4370
|
}
|
|
4282
4371
|
if (b.generationConfig !== undefined) {
|
|
4283
4372
|
const c = record(b.generationConfig, "generationConfig");
|
|
4284
|
-
|
|
4373
|
+
fields(c, ["temperature", "topP", "maxOutputTokens", "stopSequences", "candidateCount", "responseMimeType", "responseJsonSchema", "responseSchema", "thinkingConfig"], "generationConfig");
|
|
4285
4374
|
for (const [from, to] of Object.entries({ temperature: "temperature", topP: "top_p", maxOutputTokens: "max_output_tokens", stopSequences: "stop", candidateCount: "n" }))
|
|
4286
4375
|
if (c[from] !== undefined)
|
|
4287
4376
|
out[to] = c[from];
|
|
@@ -4299,7 +4388,7 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4299
4388
|
}
|
|
4300
4389
|
if (c.thinkingConfig !== undefined) {
|
|
4301
4390
|
const t = record(c.thinkingConfig, "thinkingConfig");
|
|
4302
|
-
|
|
4391
|
+
fields(t, ["thinkingBudget", "thinkingLevel", "includeThoughts"], "generationConfig.thinkingConfig", "unsupported_reasoning");
|
|
4303
4392
|
if (t.thinkingBudget !== undefined)
|
|
4304
4393
|
integer(t.thinkingBudget, "generationConfig.thinkingConfig.thinkingBudget", -1);
|
|
4305
4394
|
if (t.thinkingLevel !== undefined)
|
|
@@ -4311,7 +4400,10 @@ function canonicalRequest(raw, protocol, model) {
|
|
|
4311
4400
|
}
|
|
4312
4401
|
return out;
|
|
4313
4402
|
}
|
|
4314
|
-
function validateCanonical(b, context) {
|
|
4403
|
+
function validateCanonical(b, context, chatConfigurationUpdates) {
|
|
4404
|
+
const responsesToGemini = context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content";
|
|
4405
|
+
const allowLossyContinuation = chatConfigurationUpdates !== undefined;
|
|
4406
|
+
let configuration;
|
|
4315
4407
|
for (const key of ["stream", "parallel_tool_calls", "store", "background"])
|
|
4316
4408
|
if (b[key] !== undefined)
|
|
4317
4409
|
bool(b[key], key);
|
|
@@ -4319,13 +4411,13 @@ function validateCanonical(b, context) {
|
|
|
4319
4411
|
if (b[key] !== undefined && (typeof b[key] !== "number" || !Number.isFinite(b[key])))
|
|
4320
4412
|
fail("invalid_payload", "Sampling value must be finite", key);
|
|
4321
4413
|
if (b.tool_choice !== undefined && typeof b.tool_choice !== "string")
|
|
4322
|
-
|
|
4414
|
+
fields(record(b.tool_choice, "tool_choice"), ["type", "name", "namespace"], "tool_choice", "unsupported_tool_choice");
|
|
4323
4415
|
if (b.text !== undefined) {
|
|
4324
4416
|
const text = record(b.text, "text");
|
|
4325
|
-
|
|
4417
|
+
fields(text, ["format", "verbosity"], "text");
|
|
4326
4418
|
if (text.format !== undefined) {
|
|
4327
4419
|
const f = record(text.format, "text.format");
|
|
4328
|
-
|
|
4420
|
+
fields(f, f.type === "json_schema" ? ["type", "name", "schema", "strict", "description"] : ["type"], "text.format");
|
|
4329
4421
|
if (!["text", "json_object", "json_schema"].includes(String(f.type)))
|
|
4330
4422
|
fail("unsupported_request", "Unknown structured output format", "text.format.type");
|
|
4331
4423
|
if (f.type === "json_schema") {
|
|
@@ -4341,21 +4433,40 @@ function validateCanonical(b, context) {
|
|
|
4341
4433
|
const input = typeof b.input === "string" ? [] : list(b.input, "input");
|
|
4342
4434
|
for (const [i, raw] of input.entries()) {
|
|
4343
4435
|
const t = record(raw, "input item"), p = `input[${i}]`;
|
|
4436
|
+
if ((responsesToGemini || allowLossyContinuation) && t.type === "configuration_update") {
|
|
4437
|
+
fields(t, ["type", "reasoning"], p, "unsupported_content");
|
|
4438
|
+
const reasoning = atParam(`${p}.reasoning`, () => record(t.reasoning, "configuration reasoning"));
|
|
4439
|
+
fields(reasoning, ["effort"], `${p}.reasoning`, "unsupported_reasoning");
|
|
4440
|
+
const param = `${p}.reasoning.effort`;
|
|
4441
|
+
const effort = atParam(param, () => string(reasoning.effort, "configuration effort", true));
|
|
4442
|
+
const map = context.reasoningPolicy?.effortMap;
|
|
4443
|
+
const level = map && Object.hasOwn(map, effort) ? map[effort] : undefined;
|
|
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);
|
|
4446
|
+
configuration = { effort, level, param };
|
|
4447
|
+
chatConfigurationUpdates?.add(t);
|
|
4448
|
+
continue;
|
|
4449
|
+
}
|
|
4344
4450
|
if (t.type === "agent_message") {
|
|
4345
4451
|
validateAgentMessage(t, p, context.capabilities?.limits);
|
|
4346
4452
|
continue;
|
|
4347
4453
|
}
|
|
4348
|
-
|
|
4349
|
-
|
|
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");
|
|
4350
4461
|
if (t.is_error !== undefined)
|
|
4351
4462
|
bool(t.is_error, `${p}.is_error`);
|
|
4352
|
-
if (t.type === "reasoning")
|
|
4353
|
-
for (const [j, part] of list(t.summary, "summary").entries())
|
|
4354
|
-
|
|
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"));
|
|
4355
4466
|
if (Array.isArray(t.content))
|
|
4356
4467
|
for (const [j, part] of t.content.entries()) {
|
|
4357
4468
|
const c = record(part, "part");
|
|
4358
|
-
|
|
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");
|
|
4359
4470
|
if (context.sourceProtocol === "responses" && context.targetProtocol === "gemini_generate_content" && t.role === "user" && c.type === "input_image") {
|
|
4360
4471
|
atParam(`${p}.content[${j}].image_url`, () => string(c.image_url, "image URL", true));
|
|
4361
4472
|
if (c.detail !== undefined && (typeof c.detail !== "string" || !["auto", "low", "high"].includes(c.detail)))
|
|
@@ -4366,7 +4477,7 @@ function validateCanonical(b, context) {
|
|
|
4366
4477
|
for (const [j, part] of t.output.entries())
|
|
4367
4478
|
atParam(`${p}.output[${j}]`, () => {
|
|
4368
4479
|
const c = record(part, "tool output part");
|
|
4369
|
-
|
|
4480
|
+
fields(c, c.type === "input_image" ? ["type", "image_url", "detail"] : ["type", "text", "annotations"], `${p}.output[${j}]`, "unsupported_content");
|
|
4370
4481
|
if (c.type === "input_image") {
|
|
4371
4482
|
atParam(`${p}.output[${j}].image_url`, () => string(c.image_url, "image URL", true));
|
|
4372
4483
|
if (c.detail !== undefined && (typeof c.detail !== "string" || !["auto", "low", "high"].includes(c.detail)))
|
|
@@ -4392,7 +4503,7 @@ function validateCanonical(b, context) {
|
|
|
4392
4503
|
}
|
|
4393
4504
|
if (t.type === "custom" && t.format !== undefined) {
|
|
4394
4505
|
const f = record(t.format, "custom format");
|
|
4395
|
-
|
|
4506
|
+
fields(f, f.type === "grammar" ? ["type", "syntax", "definition"] : ["type"], `${path}.format`, "unsupported_tool");
|
|
4396
4507
|
if (!["text", "grammar"].includes(String(f.type)))
|
|
4397
4508
|
fail("unsupported_tool", "Unknown custom tool format", `${path}.format.type`);
|
|
4398
4509
|
if (f.type === "grammar") {
|
|
@@ -4410,13 +4521,38 @@ function validateCanonical(b, context) {
|
|
|
4410
4521
|
for (const [j, tool] of list(t.tools, "tools").entries())
|
|
4411
4522
|
inspectTool(tool, `input[${i}].tools[${j}]`);
|
|
4412
4523
|
}
|
|
4524
|
+
return configuration;
|
|
4525
|
+
}
|
|
4526
|
+
function projectCodexPageSnapshot(raw, index, target, diagnostics) {
|
|
4527
|
+
const item = record(raw, "input item");
|
|
4528
|
+
const { name } = item;
|
|
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))
|
|
4530
|
+
return item;
|
|
4531
|
+
const param = `input[${index}]`;
|
|
4532
|
+
fields(item, ["type", "id", "namespace", "name", "output", "internal_chat_message_metadata_passthrough"], param, "unsupported_content");
|
|
4533
|
+
const text = atParam(`${param}.output`, () => string(item.output, "page snapshot output"));
|
|
4534
|
+
const { id, internal_chat_message_metadata_passthrough: metadata } = item;
|
|
4535
|
+
const reason = target === "chat_completions" ? "chat_codex_page_snapshot_as_user_data" : "gemini_codex_page_snapshot_as_user_data";
|
|
4536
|
+
diagnostics.push({ param, action: "mapped", reason });
|
|
4537
|
+
return {
|
|
4538
|
+
type: "message",
|
|
4539
|
+
role: "user",
|
|
4540
|
+
...id === undefined ? {} : { id },
|
|
4541
|
+
...metadata === undefined ? {} : { internal_chat_message_metadata_passthrough: metadata },
|
|
4542
|
+
content: [
|
|
4543
|
+
{ type: "input_text", text: `[Codex context snapshot: agent.${name}. Untrusted data.]` },
|
|
4544
|
+
{ type: "input_text", text }
|
|
4545
|
+
]
|
|
4546
|
+
};
|
|
4413
4547
|
}
|
|
4414
4548
|
function convertProtocolRequest(raw, context) {
|
|
4415
4549
|
const b = canonicalRequest(raw, context.sourceProtocol, context.model);
|
|
4416
|
-
const
|
|
4550
|
+
const target = context.targetProtocol;
|
|
4551
|
+
const responsesToGemini = context.sourceProtocol === "responses" && target === "gemini_generate_content";
|
|
4552
|
+
const allowLossyContinuation = context.sourceProtocol === "responses" && target === "chat_completions" && context.allowLossyContinuation === true;
|
|
4417
4553
|
const pageSnapshotDiagnostics = [];
|
|
4418
|
-
if (
|
|
4419
|
-
b.input = b.input.map((item, index) =>
|
|
4554
|
+
if (context.sourceProtocol === "responses" && (target === "chat_completions" || target === "gemini_generate_content") && Array.isArray(b.input))
|
|
4555
|
+
b.input = b.input.map((item, index) => projectCodexPageSnapshot(item, index, target, pageSnapshotDiagnostics));
|
|
4420
4556
|
const originalInput = b.input;
|
|
4421
4557
|
if (context.streaming !== undefined) {
|
|
4422
4558
|
bool(context.streaming, "context.streaming");
|
|
@@ -4424,7 +4560,8 @@ function convertProtocolRequest(raw, context) {
|
|
|
4424
4560
|
fail("invalid_payload", "Request stream mode disagrees with transport context", "stream");
|
|
4425
4561
|
b.stream = context.streaming;
|
|
4426
4562
|
}
|
|
4427
|
-
|
|
4563
|
+
const chatConfigurationUpdates = allowLossyContinuation ? new Set : undefined;
|
|
4564
|
+
const configuration = validateCanonical(b, context, chatConfigurationUpdates);
|
|
4428
4565
|
const geminiHistory = responsesToGemini ? restoreGeminiHistory(b.input, limits(context.capabilities?.limits)) : undefined;
|
|
4429
4566
|
if (geminiHistory)
|
|
4430
4567
|
b.input = geminiHistory.input;
|
|
@@ -4443,16 +4580,19 @@ function convertProtocolRequest(raw, context) {
|
|
|
4443
4580
|
fail("unsupported_reasoning", "Thinking mode requires an explicit target wire policy", "thinking");
|
|
4444
4581
|
let mappedEffort;
|
|
4445
4582
|
if (reasoning?.effort !== undefined) {
|
|
4446
|
-
const effort = string(reasoning.effort, "reasoning.effort", true);
|
|
4447
|
-
|
|
4448
|
-
|
|
4449
|
-
|
|
4450
|
-
|
|
4451
|
-
|
|
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
|
+
}
|
|
4452
4591
|
}
|
|
4592
|
+
if (configuration)
|
|
4593
|
+
mappedEffort = configuration.level;
|
|
4453
4594
|
if (sourceThinking !== undefined && reasoning?.effort === undefined && policy?.targetEffort !== undefined)
|
|
4454
4595
|
mappedEffort = string(policy.targetEffort, "reasoningPolicy.targetEffort", true);
|
|
4455
|
-
const target = context.targetProtocol;
|
|
4456
4596
|
if (target === "gemini_generate_content" && reasoning?.effort !== undefined && mappedEffort === undefined && policy?.geminiThinkingBudget === undefined && policy?.geminiThinkingLevel === undefined)
|
|
4457
4597
|
fail("unsupported_reasoning", "Gemini requires an explicit thinking budget or level", "reasoning.effort");
|
|
4458
4598
|
if (sourceThinking !== undefined) {
|
|
@@ -4491,7 +4631,7 @@ function convertProtocolRequest(raw, context) {
|
|
|
4491
4631
|
}
|
|
4492
4632
|
if (b.metadata !== undefined) {
|
|
4493
4633
|
const metadata = record(b.metadata, "metadata");
|
|
4494
|
-
|
|
4634
|
+
fields(metadata, ["user_id"], "metadata");
|
|
4495
4635
|
if (metadata.user_id !== undefined)
|
|
4496
4636
|
string(metadata.user_id, "metadata.user_id");
|
|
4497
4637
|
}
|
|
@@ -4503,7 +4643,7 @@ function convertProtocolRequest(raw, context) {
|
|
|
4503
4643
|
} else if (target === "chat_completions") {
|
|
4504
4644
|
if (reasoning?.effort !== undefined || mappedEffort !== undefined) {
|
|
4505
4645
|
if (!cap.reasoningEffort)
|
|
4506
|
-
fail("unsupported_reasoning", "Target effort capability is required", "reasoning.effort");
|
|
4646
|
+
fail("unsupported_reasoning", "Target effort capability is required", configuration?.param ?? "reasoning.effort");
|
|
4507
4647
|
b.reasoning = { ...reasoning, effort: mappedEffort };
|
|
4508
4648
|
if (mappedEffort === undefined)
|
|
4509
4649
|
fail("unsupported_reasoning", "Chat requires a target effort mapping", "reasoning.effort");
|
|
@@ -4515,9 +4655,21 @@ function convertProtocolRequest(raw, context) {
|
|
|
4515
4655
|
const decodingTarget = target === "gemini_generate_content" ? "chat_completions" : target;
|
|
4516
4656
|
if (target === "gemini_generate_content" && reasoning)
|
|
4517
4657
|
b.reasoning = { ...reasoning, effort: undefined };
|
|
4518
|
-
|
|
4658
|
+
let decoded;
|
|
4659
|
+
try {
|
|
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 });
|
|
4661
|
+
} catch (error) {
|
|
4662
|
+
if (geminiHistory && error instanceof ResponsesCodecError && error.param !== undefined)
|
|
4663
|
+
throw new ResponsesCodecError(error.code, error.message, geminiHistory.sourceParam(error.param));
|
|
4664
|
+
throw error;
|
|
4665
|
+
}
|
|
4519
4666
|
const diagnostics = decoded.diagnostics;
|
|
4667
|
+
if (geminiHistory)
|
|
4668
|
+
for (const diagnostic of diagnostics)
|
|
4669
|
+
diagnostic.param = geminiHistory.sourceParam(diagnostic.param);
|
|
4520
4670
|
diagnostics.push(...pageSnapshotDiagnostics);
|
|
4671
|
+
if (configuration)
|
|
4672
|
+
diagnostics.push({ param: configuration.param, action: "mapped", reason: responsesToGemini ? "gemini_configuration_effort_update" : "chat_configuration_effort_update" });
|
|
4521
4673
|
if (target === "gemini_generate_content" && decoded.body.parallel_tool_calls === true) {
|
|
4522
4674
|
delete decoded.body.parallel_tool_calls;
|
|
4523
4675
|
diagnostics.push({ param: "parallel_tool_calls", action: "omitted", reason: "gemini_parallel_tool_calls_allowed" });
|
|
@@ -4547,17 +4699,24 @@ function convertProtocolRequest(raw, context) {
|
|
|
4547
4699
|
if (target === "gemini_generate_content" && (mappedEffort !== undefined || policy?.geminiThinkingBudget !== undefined || policy?.geminiThinkingLevel !== undefined)) {
|
|
4548
4700
|
const level = policy?.geminiThinkingLevel ?? mappedEffort;
|
|
4549
4701
|
if (policy?.geminiThinkingBudget !== undefined && level !== undefined)
|
|
4550
|
-
fail("unsupported_reasoning", "Choose one Gemini thinking policy", "reasoningPolicy");
|
|
4702
|
+
fail("unsupported_reasoning", "Choose one Gemini thinking policy", configuration?.param ?? "reasoningPolicy");
|
|
4551
4703
|
if (level !== undefined && !["minimal", "low", "medium", "high"].includes(level))
|
|
4552
4704
|
fail("unsupported_reasoning", "Unknown Gemini thinking level", "reasoning.effort");
|
|
4553
4705
|
if (mappedEffort !== undefined && policy?.geminiThinkingLevel !== undefined && mappedEffort !== policy.geminiThinkingLevel)
|
|
4554
|
-
fail("unsupported_reasoning", "Conflicting Gemini thinking levels", "reasoning.effort");
|
|
4706
|
+
fail("unsupported_reasoning", "Conflicting Gemini thinking levels", configuration?.param ?? "reasoning.effort");
|
|
4555
4707
|
const thinkingConfig = policy?.geminiThinkingBudget !== undefined ? { thinkingBudget: integer(policy.geminiThinkingBudget, "reasoningPolicy.geminiThinkingBudget", -1) } : { thinkingLevel: string(level, "reasoningPolicy.geminiThinkingLevel", true) };
|
|
4556
4708
|
body.generationConfig = { ...record(body.generationConfig ?? {}, "generationConfig"), thinkingConfig };
|
|
4557
4709
|
}
|
|
4558
4710
|
if (mappedEffort !== undefined || sourceThinking !== undefined || policy?.anthropicThinkingBudget !== undefined)
|
|
4559
4711
|
diagnostics.push({ param: "reasoning", action: "mapped", reason: "explicit_verified_wire_policy" });
|
|
4560
|
-
return {
|
|
4712
|
+
return {
|
|
4713
|
+
body,
|
|
4714
|
+
canonicalHistory: geminiHistory?.canonicalHistory(decoded.canonicalInput) ?? decoded.canonicalInput,
|
|
4715
|
+
diagnostics,
|
|
4716
|
+
toolNames: decoded.toolNames,
|
|
4717
|
+
streaming: b.stream === true,
|
|
4718
|
+
...configuration ? { effectiveReasoningEffort: configuration.effort } : {}
|
|
4719
|
+
};
|
|
4561
4720
|
}
|
|
4562
4721
|
function renderGemini(chat, context, input, signedParts, diagnostics) {
|
|
4563
4722
|
const result = { contents: [] }, contents = result.contents, system = [], calls = new Map;
|
|
@@ -4705,11 +4864,11 @@ function validateUsage(raw, protocol) {
|
|
|
4705
4864
|
return;
|
|
4706
4865
|
}
|
|
4707
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"];
|
|
4708
|
-
|
|
4867
|
+
fields(u, keys, "usage", "unsupported_response");
|
|
4709
4868
|
for (const [key, value] of Object.entries(u)) {
|
|
4710
4869
|
if (key.endsWith("_details")) {
|
|
4711
4870
|
const d = record(value, "usage details");
|
|
4712
|
-
|
|
4871
|
+
fields(d, key.includes("output") || key.includes("completion") ? ["reasoning_tokens"] : ["cached_tokens", "cache_creation_tokens"], `usage.${key}`, "unsupported_response");
|
|
4713
4872
|
for (const [k, v] of Object.entries(d))
|
|
4714
4873
|
integer(v, `usage.${key}.${k}`);
|
|
4715
4874
|
} else
|
|
@@ -4730,10 +4889,10 @@ function validateProviderResponse(raw, protocol) {
|
|
|
4730
4889
|
const m = record(c.message, "message");
|
|
4731
4890
|
for (const [callIndex, rawCall] of (m.tool_calls == null ? [] : list(m.tool_calls, "tool_calls")).entries()) {
|
|
4732
4891
|
const call = record(rawCall, "call");
|
|
4733
|
-
|
|
4892
|
+
fields(call, ["id", "type", "function", "index"], "tool_calls", "unsupported_tool");
|
|
4734
4893
|
if (call.index !== undefined && integer(call.index, `tool_calls[${callIndex}].index`) !== callIndex)
|
|
4735
4894
|
fail("invalid_payload", "Tool call index must match its array position", `tool_calls[${callIndex}].index`);
|
|
4736
|
-
|
|
4895
|
+
fields(record(call.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
|
|
4737
4896
|
}
|
|
4738
4897
|
}
|
|
4739
4898
|
validateUsage(b.usage, protocol);
|
|
@@ -4747,14 +4906,14 @@ function validateProviderResponse(raw, protocol) {
|
|
|
4747
4906
|
return b;
|
|
4748
4907
|
}
|
|
4749
4908
|
function validateAnthropicBlock(b, path) {
|
|
4750
|
-
|
|
4909
|
+
fields(b, b.type === "text" ? ["type", "text"] : b.type === "thinking" ? ["type", "thinking", "signature"] : ["type", "id", "name", "input"], path, "unsupported_content");
|
|
4751
4910
|
if (b.signature !== undefined)
|
|
4752
4911
|
fail("unsupported_reasoning", "Signed provider reasoning cannot cross protocols", `${path}.signature`);
|
|
4753
4912
|
}
|
|
4754
4913
|
function validateCanonicalResponse(raw, context, itemOnly = false) {
|
|
4755
4914
|
const b = record(raw, "response");
|
|
4756
4915
|
serialized(b, limits(context.capabilities?.limits).maxOutputBytes, "response");
|
|
4757
|
-
|
|
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");
|
|
4758
4917
|
if (!itemOnly) {
|
|
4759
4918
|
string(b.id, "response.id", true);
|
|
4760
4919
|
integer(b.created_at, "response.created_at");
|
|
@@ -4765,7 +4924,7 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
|
|
|
4765
4924
|
fail("missing_terminal", "Response has no explicit supported terminal", "status");
|
|
4766
4925
|
if (b.status === "incomplete") {
|
|
4767
4926
|
const d = record(b.incomplete_details, "incomplete_details");
|
|
4768
|
-
|
|
4927
|
+
fields(d, ["reason"], "incomplete_details", "unsupported_response");
|
|
4769
4928
|
if (!["max_output_tokens", "content_filter"].includes(String(d.reason)))
|
|
4770
4929
|
fail("unknown_terminal", "Unknown incomplete reason", "incomplete_details.reason");
|
|
4771
4930
|
}
|
|
@@ -4780,13 +4939,13 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
|
|
|
4780
4939
|
fail("unsupported_response", "Unknown item status", `${path}.status`);
|
|
4781
4940
|
if (b.status === "completed" && t.status !== undefined && t.status !== "completed")
|
|
4782
4941
|
fail("invalid_stream", "Completed response contains an unfinished item", `${path}.status`);
|
|
4783
|
-
|
|
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");
|
|
4784
4943
|
if (t.type === "message") {
|
|
4785
4944
|
if (t.role !== "assistant")
|
|
4786
4945
|
fail("unsupported_content", "Output message must be assistant", `${path}.role`);
|
|
4787
4946
|
for (const [j, rawPart] of list(t.content, "content").entries()) {
|
|
4788
4947
|
const p = record(rawPart, "part");
|
|
4789
|
-
|
|
4948
|
+
fields(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], `${path}.content[${j}]`, "unsupported_content");
|
|
4790
4949
|
if (p.type === "output_text")
|
|
4791
4950
|
string(p.text, "text");
|
|
4792
4951
|
else if (p.type === "refusal")
|
|
@@ -4805,7 +4964,7 @@ function validateCanonicalResponse(raw, context, itemOnly = false) {
|
|
|
4805
4964
|
fail("unsupported_reasoning", "Opaque or raw reasoning output cannot cross protocols", path);
|
|
4806
4965
|
for (const rawPart of list(t.summary, "summary")) {
|
|
4807
4966
|
const p = record(rawPart, "summary");
|
|
4808
|
-
|
|
4967
|
+
fields(p, ["type", "text"], path, "unsupported_reasoning");
|
|
4809
4968
|
if (p.type !== "summary_text")
|
|
4810
4969
|
fail("unsupported_reasoning", "Unknown reasoning summary type", path);
|
|
4811
4970
|
string(p.text, "summary");
|
|
@@ -4948,7 +5107,7 @@ class GeminiCanonicalDecoder {
|
|
|
4948
5107
|
const events = [];
|
|
4949
5108
|
if (b.promptFeedback !== undefined) {
|
|
4950
5109
|
const p = record(b.promptFeedback, "promptFeedback");
|
|
4951
|
-
|
|
5110
|
+
fields(p, ["blockReason", "blockReasonMessage", "safetyRatings"], "promptFeedback", "unsupported_response");
|
|
4952
5111
|
if (p.blockReason !== undefined && p.blockReason !== "BLOCK_REASON_UNSPECIFIED") {
|
|
4953
5112
|
this.ended = true;
|
|
4954
5113
|
events.push(...this.encoder.push({ choices: [{ delta: {}, finish_reason: "content_filter" }] }));
|
|
@@ -4963,7 +5122,7 @@ class GeminiCanonicalDecoder {
|
|
|
4963
5122
|
fail("unsupported_response", "Only candidate index zero is supported", "candidates.index");
|
|
4964
5123
|
if (c.content !== undefined && c.content !== null) {
|
|
4965
5124
|
const content = record(c.content, "content");
|
|
4966
|
-
|
|
5125
|
+
fields(content, ["role", "parts"], "candidates.content", "unsupported_content");
|
|
4967
5126
|
if (content.role !== undefined && content.role !== "model")
|
|
4968
5127
|
fail("unsupported_response", "Response role must be model", "candidates.content.role");
|
|
4969
5128
|
const parts = list(content.parts ?? [], "parts");
|
|
@@ -4971,14 +5130,14 @@ class GeminiCanonicalDecoder {
|
|
|
4971
5130
|
fail("invalid_stream", "Content arrived after Gemini terminal");
|
|
4972
5131
|
for (const [i, rawPart] of parts.entries()) {
|
|
4973
5132
|
const p = record(rawPart, "part");
|
|
4974
|
-
|
|
5133
|
+
fields(p, ["text", "thought", "functionCall", "thoughtSignature"], "candidates.content.parts", "unsupported_content");
|
|
4975
5134
|
if (p.thoughtSignature !== undefined && this.context.sourceProtocol !== "responses")
|
|
4976
5135
|
fail("unsupported_reasoning", "Thought signatures cannot cross protocols", "candidates.content.parts.thoughtSignature");
|
|
4977
5136
|
if (p.functionCall !== undefined) {
|
|
4978
5137
|
if (p.text !== undefined || p.thought !== undefined)
|
|
4979
5138
|
fail("unsupported_content", "Mixed Gemini part kinds", "candidates.content.parts");
|
|
4980
5139
|
const f = record(p.functionCall, "functionCall");
|
|
4981
|
-
|
|
5140
|
+
fields(f, ["id", "name", "args"], "functionCall", "unsupported_tool");
|
|
4982
5141
|
const index = this.serial++, originalId = f.id === undefined ? `call_gemini_${crypto.randomUUID().replaceAll("-", "")}` : string(f.id, "functionCall.id", true);
|
|
4983
5142
|
if (this.ids.has(originalId))
|
|
4984
5143
|
fail("invalid_tool_arguments", "Duplicate Gemini call id", "functionCall.id");
|
|
@@ -5132,7 +5291,7 @@ class CanonicalStreamValidator {
|
|
|
5132
5291
|
this.sequence = n;
|
|
5133
5292
|
}
|
|
5134
5293
|
if (["response.created", "response.in_progress", "response.completed", "response.incomplete", "response.failed"].includes(type)) {
|
|
5135
|
-
|
|
5294
|
+
fields(e, [...common, "response"], "", "unsupported_response");
|
|
5136
5295
|
const r = record(e.response, "response");
|
|
5137
5296
|
const id = string(r.id, "response.id", true);
|
|
5138
5297
|
if (this.responseId !== undefined && this.responseId !== id)
|
|
@@ -5189,7 +5348,7 @@ class CanonicalStreamValidator {
|
|
|
5189
5348
|
];
|
|
5190
5349
|
if (!known.includes(type))
|
|
5191
5350
|
fail("unsupported_response", "Unknown Responses stream event", "type");
|
|
5192
|
-
|
|
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");
|
|
5193
5352
|
if (e.response_id !== undefined && e.response_id !== this.responseId)
|
|
5194
5353
|
fail("invalid_stream", "Event response id changed", "response_id");
|
|
5195
5354
|
const index = integer(e.output_index, "output_index");
|
|
@@ -5283,7 +5442,7 @@ class CanonicalStreamValidator {
|
|
|
5283
5442
|
fail("unsupported_content", "Unknown content part type", "part.type");
|
|
5284
5443
|
if (summary ? p.type !== "summary_text" : p.type === "summary_text")
|
|
5285
5444
|
fail("invalid_stream", "Part kind differs from its output item", "part.type");
|
|
5286
|
-
|
|
5445
|
+
fields(p, p.type === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
|
|
5287
5446
|
if (p.annotations !== undefined && Array.isArray(p.annotations) && p.annotations.length)
|
|
5288
5447
|
fail("unsupported_content", "Annotations cannot cross protocols", "part.annotations");
|
|
5289
5448
|
const initial = string(p[p.type === "refusal" ? "refusal" : "text"], "part text");
|
|
@@ -5308,7 +5467,7 @@ class CanonicalStreamValidator {
|
|
|
5308
5467
|
if (!p.textDone)
|
|
5309
5468
|
fail("invalid_stream", "Part done before text done");
|
|
5310
5469
|
const v = record(e.part, "part");
|
|
5311
|
-
|
|
5470
|
+
fields(v, p.kind === "refusal" ? ["type", "refusal"] : ["type", "text", "annotations"], "part", "unsupported_content");
|
|
5312
5471
|
if (v.annotations !== undefined && (!Array.isArray(v.annotations) || v.annotations.length))
|
|
5313
5472
|
fail("unsupported_content", "Annotations cannot cross protocols", "part.annotations");
|
|
5314
5473
|
if (v.type !== p.kind || v[p.kind === "refusal" ? "refusal" : "text"] !== p.text)
|
|
@@ -5462,7 +5621,7 @@ class CanonicalStreamRenderer {
|
|
|
5462
5621
|
var LLM_PROTOCOLS = ["responses", "chat_completions", "anthropic_messages", "gemini_generate_content"];
|
|
5463
5622
|
|
|
5464
5623
|
// src/protocol-session/index.ts
|
|
5465
|
-
var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.
|
|
5624
|
+
var PROTOCOL_CONVERSION_RULES_VERSION = "1.0.6";
|
|
5466
5625
|
function describeProtocolConversion() {
|
|
5467
5626
|
return {
|
|
5468
5627
|
rulesVersion: PROTOCOL_CONVERSION_RULES_VERSION,
|
|
@@ -5671,9 +5830,9 @@ function validateStreamEnvelope(raw, protocol) {
|
|
|
5671
5830
|
if (Array.isArray(d.tool_calls))
|
|
5672
5831
|
for (const rawCall of d.tool_calls) {
|
|
5673
5832
|
const t = record(rawCall, "tool call");
|
|
5674
|
-
|
|
5833
|
+
fields(t, ["index", "id", "type", "function"], "tool_calls", "unsupported_tool");
|
|
5675
5834
|
if (t.function !== undefined)
|
|
5676
|
-
|
|
5835
|
+
fields(record(t.function, "function"), ["name", "arguments"], "tool_calls.function", "unsupported_tool");
|
|
5677
5836
|
}
|
|
5678
5837
|
}
|
|
5679
5838
|
validateUsage(e.usage, protocol);
|
|
@@ -5682,12 +5841,12 @@ function validateStreamEnvelope(raw, protocol) {
|
|
|
5682
5841
|
validateAnthropicBlock(record(e.content_block, "block"), "content_block");
|
|
5683
5842
|
if (e.type === "content_block_delta") {
|
|
5684
5843
|
const d = record(e.delta, "delta");
|
|
5685
|
-
|
|
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");
|
|
5686
5845
|
if (d.type === "signature_delta" || d.signature !== undefined)
|
|
5687
5846
|
fail("unsupported_reasoning", "Signed provider reasoning cannot cross protocols", "delta.signature");
|
|
5688
5847
|
}
|
|
5689
5848
|
if (e.type === "message_delta")
|
|
5690
|
-
|
|
5849
|
+
fields(record(e.delta, "delta"), ["stop_reason", "stop_sequence"], "delta", "unsupported_response");
|
|
5691
5850
|
if (e.type === "message_start") {
|
|
5692
5851
|
const m = record(e.message, "message");
|
|
5693
5852
|
validateUsage(m.usage, protocol);
|