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