fix(opencode): strip prior reasoning items on Muse Spark Responses models

Strip prior-turn type: reasoning items and encrypted_content fields from body.input on Muse Spark Responses endpoints in OpenCode and OpenCode Go executors to avoid HTTP 400 errors across rotated proxy accounts.
This commit is contained in:
anojndr
2026-09-17 18:17:18 +07:00
parent c49efdf528
commit eafac37dcb
4 changed files with 167 additions and 2 deletions

View File

@@ -94,6 +94,12 @@ function sanitizeResponsesItems(body) {
if (!Array.isArray(body.input)) return;
body.input = body.input.filter((item) => {
if (!item || typeof item !== "object" || Array.isArray(item)) return true;
// Strip prior-turn reasoning items: Muse Spark contributor models route to
// an upstream Console backend where encrypted_content cannot be validated across
// rotated accounts or sessions, causing 400 "reasoning encrypted_content was not issued to this caller".
if (item.type === "reasoning") return false;
delete item.encrypted_content;
delete item.reasoning_encrypted_content;
if (item.type === "function_call") {
if (!item.name || typeof item.name !== "string" || item.name.trim() === "") return false;
item.name = item.name.trim().slice(0, MAX_TOOL_NAME_LEN);

View File

@@ -7,9 +7,16 @@ import { injectReasoningContent } from "../utils/reasoningContentInjector.js";
import { resolveSessionId } from "../utils/sessionManager.js";
import { isMuseSparkModel } from "../providers/models/helpers.js";
import { ANTHROPIC_API_VERSION } from "../providers/shared.js";
import {
normalizeResponsesInput,
clampResponsesCallId,
coerceResponsesArguments,
coerceResponsesOutput,
} from "../translator/formats/responsesApi.js";
const OPENCODE_UA = "opencode/1.18.31";
const MAX_SESSION_LENGTH = 256;
const MAX_TOOL_NAME_LEN = 128;
const SESSION_HEADER = "x-opencode-session";
const SESSION_FIELD = "_opencodeSession";
const REQ_FIELD = "_opencodeRequest";
@@ -24,7 +31,6 @@ function hasValidOpencodeVersion(ua) {
const minor = parseInt(m[2], 10);
return major > 1 || (major === 1 && minor >= 17);
}
// Models served by /zen/v1/responses; every other model stays on /chat/completions.
const RESPONSES_MODELS = new Set([
"muse-spark-1.2-contributor-free",
@@ -300,6 +306,69 @@ function resolveOpencodeRequestId(body, credentials, sessionId) {
return deriveRequestId(sessionId, body);
}
function normalizeResponsesTools(body) {
if (!Array.isArray(body.tools)) return;
const validNames = new Set();
body.tools = body.tools.filter((tool) => {
if (!tool || typeof tool !== "object" || Array.isArray(tool)) return false;
const fn = tool.function && typeof tool.function === "object" && !Array.isArray(tool.function) ? tool.function : null;
const rawName = typeof tool.name === "string" ? tool.name : (typeof fn?.name === "string" ? fn.name : "");
const name = rawName.trim();
if (!name) return false;
const description = typeof tool.description === "string" ? tool.description : (typeof fn?.description === "string" ? fn.description : "");
let parameters = (tool.parameters && typeof tool.parameters === "object" && !Array.isArray(tool.parameters))
? tool.parameters
: (fn?.parameters && typeof fn.parameters === "object" && !Array.isArray(fn.parameters) ? fn.parameters : { type: "object", properties: {} });
if (parameters.type === "object" && !parameters.properties) parameters = { ...parameters, properties: {} };
for (const k of Object.keys(tool)) delete tool[k];
tool.type = "function";
tool.name = name.slice(0, MAX_TOOL_NAME_LEN);
if (description) tool.description = description;
tool.parameters = parameters;
validNames.add(tool.name);
return true;
});
if (body.tool_choice && typeof body.tool_choice === "object" && !Array.isArray(body.tool_choice)) {
if (body.tool_choice.type === "function") {
const n = typeof body.tool_choice.name === "string" ? body.tool_choice.name.trim() : "";
if (!n || !validNames.has(n)) delete body.tool_choice;
}
}
}
function sanitizeResponsesItems(body) {
if (!Array.isArray(body.input)) return;
body.input = body.input.filter((item) => {
if (!item || typeof item !== "object" || Array.isArray(item)) return true;
// Strip prior-turn reasoning items: OpenCode Free uses public/pooled credentials
// (`Bearer public`) routing to an upstream OpenAI/Console account pool.
// OpenAI Responses API strictly enforces that reasoning `encrypted_content`
// can only be decrypted by the exact caller/account that issued it; sending it
// across different accounts or rotating proxy relays triggers:
// [invalid_request_error] reasoning `encrypted_content` was not issued to this caller (400).
// Furthermore, under stateless mode (store=false), omitting encrypted_content
// causes OpenAI to reject the referenced reasoning item as "not found or was deleted".
// Dropping prior reasoning items allows multi-turn conversations and tool-calling
// loops to succeed cleanly.
if (item.type === "reasoning") return false;
delete item.encrypted_content;
delete item.reasoning_encrypted_content;
if (item.type === "function_call") {
if (!item.name || typeof item.name !== "string" || item.name.trim() === "") return false;
item.name = item.name.trim().slice(0, MAX_TOOL_NAME_LEN);
item.call_id = clampResponsesCallId(item.call_id);
item.arguments = coerceResponsesArguments(item.arguments);
return true;
}
if (item.type === "function_call_output") {
item.call_id = clampResponsesCallId(item.call_id);
item.output = coerceResponsesOutput(item.output);
return true;
}
return true;
});
}
function normalizeOpencodeReasoning(model, body) {
const current = body.reasoning;
const currentReasoning = current && typeof current === "object" && !Array.isArray(current)
@@ -341,7 +410,12 @@ export class OpenCodeExecutor extends BaseExecutor {
transformRequest(model, body, stream, credentials) {
if (body && typeof body === "object" && model && !body.model) body.model = model;
if (isResponsesModel(model) && body && typeof body === "object") {
if (isResponsesModel(model || body?.model) && body && typeof body === "object") {
const normalized = normalizeResponsesInput(body.input);
if (normalized) body.input = normalized;
if (!Array.isArray(body.input) || body.input.length === 0) {
body.input = [{ type: "message", role: "user", content: [{ type: "input_text", text: "..." }] }];
}
// Responses API names the output cap max_output_tokens and takes thinking
// as reasoning:{effort,summary} — normalize the Chat fields at this boundary.
if (body.max_output_tokens === undefined) {
@@ -351,6 +425,10 @@ export class OpenCodeExecutor extends BaseExecutor {
delete body.max_tokens;
delete body.max_completion_tokens;
normalizeOpencodeReasoning(model, body);
body.stream = true;
body.store = false;
normalizeResponsesTools(body);
sanitizeResponsesItems(body);
}
return injectReasoningContent({ provider: this.provider, model, body });
}

View File

@@ -136,6 +136,28 @@ describe("OpenCodeGoExecutor routing + sanitization", () => {
expect(out.tools.find((t) => t.name === "bare").parameters).toEqual({ type: "object", properties: {} });
expect(out.tools.find((t) => t.name === "full").parameters).toEqual({ type: "object", properties: { a: { type: "string" } } });
});
it("strips prior-turn reasoning items carrying encrypted_content from input", () => {
const ex = new OpenCodeGoExecutor();
const body = {
model: MODEL,
input: [
{ type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] },
{
type: "reasoning",
id: "rs_123",
encrypted_content: "ENC_BLOB_TURN_1",
summary: [{ type: "summary_text", text: "thinking text" }],
},
{ type: "function_call", call_id: "c1", name: "read", arguments: "{}" },
{ type: "function_call_output", call_id: "c1", output: "ok" },
],
};
const out = ex.transformRequest(MODEL, body, true, {});
expect(out.input.some((i) => i.type === "reasoning")).toBe(false);
expect(JSON.stringify(out.input)).not.toContain("ENC_BLOB_TURN_1");
expect(out.input.map((i) => i.type)).toEqual(["message", "function_call", "function_call_output"]);
});
});
describe("chat/claude clients translate to Responses without breaking tools", () => {

View File

@@ -165,4 +165,63 @@ describe("OpenCode Free Muse Spark thinking", () => {
expect(out.max_tokens).toBeUndefined();
}
});
it("strips prior-turn reasoning items carrying encrypted_content from input", () => {
const executor = new OpenCodeExecutor();
const model = "muse-spark-1.3-contributor-free";
const body = {
model,
input: [
{ type: "message", role: "user", content: [{ type: "input_text", text: "say hi" }] },
{
type: "reasoning",
id: "rs_123",
encrypted_content: "ENC_BLOB_TURN_1",
summary: [{ type: "summary_text", text: "thinking text" }],
},
{
type: "function_call",
id: "fc_1",
call_id: "call_1",
name: "shell",
arguments: JSON.stringify({ command: "echo hi" }),
},
{
type: "function_call_output",
call_id: "call_1",
output: "hi",
},
{ type: "message", role: "user", content: [{ type: "input_text", text: "now say bye" }] },
],
tools: [
{
type: "function",
function: {
name: "shell",
description: "Run shell command",
parameters: { type: "object" },
},
},
],
};
const out = executor.transformRequest(model, body, true, {});
expect(out.stream).toBe(true);
expect(out.store).toBe(false);
// Prior reasoning items stripped to prevent 400 "reasoning encrypted_content was not issued to this caller"
expect(out.input.some((item) => item.type === "reasoning")).toBe(false);
expect(JSON.stringify(out.input)).not.toContain("ENC_BLOB_TURN_1");
// User message, function_call, function_call_output, and next user message survive
const types = out.input.map((item) => item.type);
expect(types).toEqual(["message", "function_call", "function_call_output", "message"]);
// Tools flattened and empty properties added
expect(out.tools).toEqual([
{
type: "function",
name: "shell",
description: "Run shell command",
parameters: { type: "object", properties: {} },
},
]);
});
});