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