OpenCode upstream validates free-tier requests: User-Agent must be opencode/<version> (>= 1.17.0) and x-opencode-session must match canonical ses_ format. Default OPENCODE_UA to opencode/1.18.31, generate canonical descending session IDs, provide deterministic foreign session translation, and isolate credentials per-request.
232 lines
8.0 KiB
JavaScript
232 lines
8.0 KiB
JavaScript
import crypto from "crypto";
|
|
import { BaseExecutor } from "./base.js";
|
|
import { PROVIDERS } from "../config/providers.js";
|
|
import { getThinkingLevels } from "../providers/thinkingLevels.js";
|
|
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";
|
|
|
|
const OPENCODE_UA = "opencode/1.18.31";
|
|
const MAX_SESSION_LENGTH = 256;
|
|
const SESSION_HEADER = "x-opencode-session";
|
|
const SESSION_FIELD = "_opencodeSession";
|
|
export const OPENCODE_SESSION_RE = /^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/;
|
|
const BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
|
|
function hasValidOpencodeVersion(ua) {
|
|
const m = String(ua || "").match(/opencode\/(\d+)\.(\d+)(?:\.(\d+))?/i);
|
|
if (!m) return false;
|
|
const major = parseInt(m[1], 10);
|
|
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",
|
|
"muse-spark-1.3-contributor-free",
|
|
]);
|
|
const MESSAGES_MODELS = new Set(["union-alpha"]);
|
|
|
|
let lastTimestamp = 0;
|
|
let counter = 0;
|
|
|
|
function unstableRandom() {
|
|
const bytes = crypto.randomBytes(14);
|
|
let randomPart = "";
|
|
for (let i = 0; i < 14; i++) {
|
|
randomPart += BASE62_CHARS[bytes[i] % 62];
|
|
}
|
|
return randomPart;
|
|
}
|
|
|
|
export function generateSessionId(timestamp = Date.now()) {
|
|
if (timestamp !== lastTimestamp) {
|
|
lastTimestamp = timestamp;
|
|
counter = 0;
|
|
}
|
|
counter++;
|
|
|
|
const current = BigInt(timestamp) * 0x1000n + BigInt(counter);
|
|
const value = ~current;
|
|
const time = Array.from({ length: 6 }, (_, index) =>
|
|
Number((value >> BigInt(40 - 8 * index)) & 0xffn)
|
|
.toString(16)
|
|
.padStart(2, "0")
|
|
).join("");
|
|
return `ses_${time}${unstableRandom()}`;
|
|
}
|
|
|
|
export function generateRequestId(timestamp = Date.now()) {
|
|
const current = BigInt(timestamp) * 0x1000n + 1n;
|
|
const value = current;
|
|
const time = Array.from({ length: 6 }, (_, index) =>
|
|
Number((value >> BigInt(40 - 8 * index)) & 0xffn)
|
|
.toString(16)
|
|
.padStart(2, "0")
|
|
).join("");
|
|
return `msg_${time}${unstableRandom()}`;
|
|
}
|
|
|
|
export function translateSessionId(sessionId, clientTool = "") {
|
|
if (typeof sessionId === "string" && OPENCODE_SESSION_RE.test(sessionId.trim())) {
|
|
return sessionId.trim();
|
|
}
|
|
const digest = crypto
|
|
.createHash("sha256")
|
|
.update(`opencode\0${clientTool || "generic"}\0${sessionId || ""}`)
|
|
.digest();
|
|
const timeHex = digest.subarray(0, 6).toString("hex");
|
|
let randomPart = "";
|
|
for (let i = 6; i < 20; i++) {
|
|
randomPart += BASE62_CHARS[digest[i] % 62];
|
|
}
|
|
return `ses_${timeHex}${randomPart}`;
|
|
}
|
|
|
|
function normalizeSession(value) {
|
|
if (typeof value !== "string") return null;
|
|
const normalized = value.trim();
|
|
if (!normalized || normalized.length > MAX_SESSION_LENGTH) return null;
|
|
return normalized;
|
|
}
|
|
|
|
function nativeSession(headers) {
|
|
if (!headers || typeof headers !== "object") return null;
|
|
for (const [key, value] of Object.entries(headers)) {
|
|
if (key.toLowerCase() === SESSION_HEADER) {
|
|
const normalized = normalizeSession(value);
|
|
if (normalized && OPENCODE_SESSION_RE.test(normalized)) return normalized;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// Strip the thinking suffix "model(level)" so registry lookups hit the base id.
|
|
function baseModelId(model) {
|
|
return String(model || "").replace(/\([^()]+\)\s*$/, "").trim();
|
|
}
|
|
|
|
function isResponsesModel(model) {
|
|
const base = baseModelId(model);
|
|
return RESPONSES_MODELS.has(base) || isMuseSparkModel(base);
|
|
}
|
|
|
|
function isMessagesModel(model) {
|
|
return MESSAGES_MODELS.has(baseModelId(model));
|
|
}
|
|
|
|
function resolveOpencodeSession(body, credentials, providerSessionId, clientTool) {
|
|
const headers = credentials?.rawHeaders || {};
|
|
const native = nativeSession(headers);
|
|
if (native) return native;
|
|
|
|
let incoming = null;
|
|
for (const [key, value] of Object.entries(headers)) {
|
|
if (key.toLowerCase() === SESSION_HEADER) {
|
|
incoming = normalizeSession(value);
|
|
break;
|
|
}
|
|
}
|
|
|
|
const resolved = incoming || normalizeSession(providerSessionId) || resolveSessionId({
|
|
headers,
|
|
body,
|
|
connectionId: credentials?.connectionId,
|
|
scope: "opencode",
|
|
});
|
|
|
|
return resolved ? translateSessionId(resolved, clientTool) : generateSessionId();
|
|
}
|
|
|
|
function normalizeOpencodeReasoning(model, body) {
|
|
const current = body.reasoning;
|
|
const currentReasoning = current && typeof current === "object" && !Array.isArray(current)
|
|
? current
|
|
: null;
|
|
const requestedEffort = typeof body.reasoning_effort === "string"
|
|
? body.reasoning_effort
|
|
: currentReasoning?.effort;
|
|
if (typeof requestedEffort !== "string") return;
|
|
|
|
const cleanModel = baseModelId(model || body.model);
|
|
const supportedLevels = getThinkingLevels("opencode", cleanModel);
|
|
let effort = requestedEffort.toLowerCase().trim();
|
|
if ((effort === "max" || effort === "ultra") && supportedLevels?.length && !supportedLevels.includes(effort)) {
|
|
if (effort === "ultra" && supportedLevels.includes("max")) effort = "max";
|
|
else if (supportedLevels.includes("xhigh")) effort = "xhigh";
|
|
}
|
|
|
|
body.reasoning = { ...currentReasoning, effort };
|
|
if (!body.reasoning.summary) body.reasoning.summary = "auto";
|
|
delete body.reasoning_effort;
|
|
}
|
|
|
|
export class OpenCodeExecutor extends BaseExecutor {
|
|
constructor() {
|
|
super("opencode", PROVIDERS.opencode);
|
|
}
|
|
|
|
prepareRequestCredentials({ body, credentials, providerSessionId, clientTool } = {}) {
|
|
const sourceCredentials = credentials || {};
|
|
const resolved = resolveOpencodeSession(body, sourceCredentials, providerSessionId, clientTool);
|
|
|
|
return {
|
|
...sourceCredentials,
|
|
[SESSION_FIELD]: resolved,
|
|
};
|
|
}
|
|
|
|
transformRequest(model, body, stream, credentials) {
|
|
if (body && typeof body === "object" && model && !body.model) body.model = model;
|
|
if (isResponsesModel(model) && body && typeof body === "object") {
|
|
// 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) {
|
|
if (body.max_completion_tokens !== undefined) body.max_output_tokens = body.max_completion_tokens;
|
|
else if (body.max_tokens !== undefined) body.max_output_tokens = body.max_tokens;
|
|
}
|
|
delete body.max_tokens;
|
|
delete body.max_completion_tokens;
|
|
normalizeOpencodeReasoning(model, body);
|
|
}
|
|
return injectReasoningContent({ provider: this.provider, model, body });
|
|
}
|
|
|
|
async execute(args) {
|
|
return super.execute({ ...args, credentials: this.prepareRequestCredentials(args) });
|
|
}
|
|
|
|
buildUrl(model) {
|
|
const base = this.config.baseUrl;
|
|
if (isResponsesModel(model)) return `${base}/zen/v1/responses`;
|
|
if (isMessagesModel(model)) return `${base}/zen/v1/messages`;
|
|
return `${base}/zen/v1/chat/completions`;
|
|
}
|
|
|
|
buildHeaders(credentials, stream = true, url = "") {
|
|
const raw = credentials?.rawHeaders || {};
|
|
const lower = {};
|
|
for (const [k, v] of Object.entries(raw)) lower[k.toLowerCase()] = v;
|
|
|
|
const downstreamUa = lower["user-agent"] || "";
|
|
const isOpencodeDownstream = hasValidOpencodeVersion(downstreamUa);
|
|
|
|
const session = credentials?.[SESSION_FIELD] || this.prepareRequestCredentials({ credentials })[SESSION_FIELD];
|
|
|
|
const headers = {
|
|
"Content-Type": "application/json",
|
|
"Authorization": "Bearer public",
|
|
"User-Agent": isOpencodeDownstream ? downstreamUa : OPENCODE_UA,
|
|
"x-opencode-client": lower["x-opencode-client"] || "desktop",
|
|
"x-opencode-session": session,
|
|
"x-opencode-request": lower["x-opencode-request"] || generateRequestId(),
|
|
"x-opencode-project": lower["x-opencode-project"] || "global",
|
|
"Accept": stream ? "text/event-stream" : "*/*",
|
|
};
|
|
if (url.endsWith("/messages")) headers["anthropic-version"] = ANTHROPIC_API_VERSION;
|
|
return headers;
|
|
}
|
|
}
|