Files
9router/open-sse/executors/freebuff.js
T
MUH. IQRAM BAHRING 8343d54bf2 feat: add Freebuff provider and fix dompurify security vulnerabilities
- Add Freebuff provider integration (executor, registry, OAuth, usage tracking)
- Upgrade monaco-editor to ^0.56.0
- Add dompurify ^3.4.13 with override to fix security vulnerabilities
- Add Freebuff provider icon and test files
2026-08-06 00:30:06 +08:00

460 lines
19 KiB
JavaScript

import crypto from "node:crypto";
import { BaseExecutor } from "./base.js";
import { PROVIDERS } from "../config/providers.js";
import { proxyAwareFetch } from "../utils/proxyFetch.js";
import { dbg } from "../utils/debugLog.js";
import {
FETCH_CONNECT_TIMEOUT_MS,
DEFAULT_RETRY_CONFIG,
resolveRetryEntry,
} from "../config/runtimeConfig.js";
/**
* Freebuff Executor — OpenAI-compatible chat completions on
* https://www.codebuff.com/api/v1/chat/completions (the Codebuff/Freebuff backend).
*
* Wire shape mirrors the official CLI exactly. The CLI (Vercel AI SDK with the
* codebuff openai-compatible provider) builds `providerOptions.codebuff` =
* { codebuff_metadata, provider } and the provider spreads those entries at
* the TOP LEVEL of the request body — i.e. the body is:
* { model, messages, codebuff_metadata: { run_id, client_id, cost_mode,
* freebuff_instance_id? }, provider: { allow_fallbacks } }
* NOT nested under a `codebuff` object (the backend rejects the nested shape
* with 400 "No runId found in request body").
*
* The run_id is not a free-form uuid: the backend resolves it against its
* agent-run store and rejects unknown ids with 400 "runId Not Found". So every
* chat request first registers a run via POST /api/v1/agent-runs
* ({ action:"START", agentId, ancestorRunIds:[] }) → { runId }, and that id is
* what goes in codebuff_metadata.run_id. The free tier additionally gates on a
* session: POST /api/v1/freebuff/session with an `x-freebuff-model` header
* claims a row (bound to one model, ~1h); its instance id must ride along as
* codebuff_metadata.freebuff_instance_id.
*/
const SESSION_PATH = "/api/v1/freebuff/session";
const RUN_PATH = "/api/v1/agent-runs";
const SESSION_DEFAULT_TTL_MS = 60 * 60 * 1000; // active sessions live ~1h
// Chat statuses that mean our claimed session is stale and must be re-claimed
// before retrying (mirrors the CLI's FreebuffGateErrorKind statuses).
const SESSION_STALE_CODES = new Set([428, 409, 410]);
// The free tier rejects requests whose first system message doesn't open with
// the canonical Freebuff CLI root prompt (server gate
// requestHasFreebuffSystemMarker → 403 free_mode_cli_required). The check is a
// byte-exact prefix test on position 0, so we prepend the canonical opening.
// Same anti-abuse pattern as mimo-free's MIMO_SYSTEM_MARKER injection.
const FREEBUFF_SYSTEM_MARKER = "You are Buffy, the strategic coding assistant.";
// Canonical openings accepted by the server gate (mirrors the CLI's
// FREEBUFF_ROOT_SYSTEM_PROMPT_OPENINGS). The check is a byte-exact prefix on
// the first message, so our injected marker must be one of these verbatim.
const FREEBUFF_ROOT_SYSTEM_OPENINGS = [
"You are Buffy, the strategic coding assistant.",
"You are Buffy, the Freebuff Cloud project planner.",
"You are Buffy, a strategic assistant that orchestrates complex coding tasks through specialized sub-agents.",
];
// Ensure messages[0] opens with a canonical Freebuff root prompt (idempotent).
function injectFreebuffMarker(body) {
const messages = body?.messages;
if (!Array.isArray(messages) || messages.length === 0) return body;
const first = messages[0];
if (first?.role === "system" && typeof first.content === "string") {
const trimmed = first.content.trimStart();
if (FREEBUFF_ROOT_SYSTEM_OPENINGS.some((opening) => trimmed.startsWith(opening))) return body; // already marked
// Prepend the canonical opening to the existing system prompt so it stays
// the first thing the model reads (keep the rest of the messages intact).
return {
...body,
messages: [{ ...first, content: `${FREEBUFF_SYSTEM_MARKER}\n\n${first.content}` }, ...messages.slice(1)],
};
}
// No leading system message — insert one with the canonical opening.
return { ...body, messages: [{ role: "system", content: FREEBUFF_SYSTEM_MARKER }, ...messages] };
}
// Freebuff root agent id per model (mirrors the CLI's FREEBUFF_ROOT_AGENT_ID_BY_MODEL).
const FREE_ROOT_AGENT_BY_MODEL = {
"deepseek/deepseek-v4-flash": "base2-free-deepseek-flash",
"deepseek/deepseek-v4-pro": "base2-free-deepseek",
"mimo/mimo-v2.5": "base2-free-mimo",
"minimax/minimax-m3": "base2-free-minimax-m3",
"openai/gpt-5.6-luna": "base2-free-luna",
};
// Per-token+model session cache (in-memory; keyed so multi-account setups
// don't share one session row). Re-claims are driven by the cache expiring or
// by a 428 from chat — no early re-claim, so we never POST /session while our
// own row is still active (which could come back as a spurious model_locked).
const sessionCache = new Map(); // `${token}::${model}` -> { instanceId, expiresAt }
const inflight = new Map(); // dedupe concurrent claims for the same key
function sessionOrigin() {
return new URL(PROVIDERS.freebuff.baseUrl).origin; // https://www.codebuff.com
}
function sessionCacheKey(token, model) {
return `${token}::${model}`;
}
function rootAgentIdForModel(model) {
return FREE_ROOT_AGENT_BY_MODEL[model] || "base2-free";
}
// Retry transient network errors (ECONNRESET, TLS reset, …) on the session/
// run API calls — mirrors the CLI's fetchWithRetry. Only fetch-level throws
// are retried; HTTP error responses are returned as-is.
//
// The timeout signal is built per attempt: a single shared
// AbortSignal.timeout() would stay aborted forever after it fires, silently
// turning attempts 2..n into instant no-op rejections.
async function fetchWithNetworkRetry(url, options, proxyOptions, attempts = 3, timeoutMs = FETCH_CONNECT_TIMEOUT_MS) {
let lastError;
for (let attempt = 0; attempt < attempts; attempt++) {
try {
const opts = { ...options, signal: AbortSignal.timeout(timeoutMs) };
return await proxyAwareFetch(url, opts, proxyOptions);
} catch (error) {
lastError = error;
if (attempt + 1 < attempts) {
await new Promise((resolve) => setTimeout(resolve, 750));
}
}
}
throw lastError;
}
async function requestSession(token, model, proxyOptions) {
const response = await fetchWithNetworkRetry(`${sessionOrigin()}${SESSION_PATH}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
"User-Agent": "codebuff-cli/0.0.138",
"x-freebuff-model": model,
},
}, proxyOptions);
let data = {};
try { data = await response.json(); } catch { data = {}; }
if (response.status === 401) {
const err = new Error("Freebuff session auth failed (401) — re-login in the dashboard");
err.status = 401;
throw err;
}
if (!response.ok) {
const err = new Error(`Freebuff session request failed: ${response.status} ${JSON.stringify(data).slice(0, 200)}`);
err.status = response.status;
throw err;
}
const status = data?.status;
if (status === "active") {
const parsedExp = Date.parse(data.expiresAt || "");
const entry = {
instanceId: data.instanceId,
expiresAt: Number.isFinite(parsedExp) ? parsedExp : Date.now() + SESSION_DEFAULT_TTL_MS,
};
sessionCache.set(sessionCacheKey(token, model), entry);
return { instanceId: data.instanceId, status: "active" };
}
if (status === "none") {
// Not session-gated right now — proceed without an instance id; a 428 on
// chat tells us the admission gate actually requires a session.
return { instanceId: null, status: "none" };
}
const GATE_MESSAGES = {
country_blocked: "Freebuff is not available in your region (country blocked).",
banned: "Your Freebuff account has been banned.",
ip_capped: "Freebuff IP cap reached — try again later.",
rate_limited: "Freebuff session limit reached for this model — try again later.",
spend_limited: "Freebuff spend limit reached — add credits or wait for the window to reset.",
model_locked: "Freebuff session is locked to another model — end it in the CLI or wait for it to expire.",
model_unavailable: "This model is not available on Freebuff right now.",
premium_slot_taken: "Freebuff premium slot is taken — try another model.",
};
if (GATE_MESSAGES[status]) {
const message = data?.message ? `${GATE_MESSAGES[status]} ${data.message}` : GATE_MESSAGES[status];
throw new Error(message);
}
throw new Error(`Freebuff session rejected (${status || response.status}): ${JSON.stringify(data).slice(0, 200)}`);
}
async function ensureSession(token, model, proxyOptions, force = false) {
const key = sessionCacheKey(token, model);
const cached = sessionCache.get(key);
if (!force && cached && cached.expiresAt > Date.now()) {
return { instanceId: cached.instanceId, status: "active" };
}
if (force) {
// Drop both the cached row and any in-flight claim so the fresh POST can't
// race a stale one back into the cache.
sessionCache.delete(key);
inflight.delete(key);
return requestSession(token, model, proxyOptions);
}
if (!inflight.has(key)) {
inflight.set(key, requestSession(token, model, proxyOptions).finally(() => inflight.delete(key)));
}
return inflight.get(key);
}
// Register an agent run so the chat backend can resolve the run_id we send.
async function startRun(token, model, proxyOptions) {
const response = await fetchWithNetworkRetry(`${sessionOrigin()}${RUN_PATH}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
"User-Agent": "codebuff-cli/0.0.138",
},
body: JSON.stringify({
action: "START",
agentId: rootAgentIdForModel(model),
ancestorRunIds: [],
}),
}, proxyOptions);
const text = await response.text().catch(() => "");
let data = {};
try { data = JSON.parse(text); } catch { data = {}; }
if (response.status === 401) {
const err = new Error("Freebuff run auth failed (401) — re-login in the dashboard");
err.status = 401;
throw err;
}
if (!response.ok) {
const err = new Error(`Freebuff run start failed: ${response.status} ${text.slice(0, 200)}`);
err.status = response.status;
throw err;
}
if (!data?.runId) {
throw new Error(`Freebuff run start returned no runId: ${text.slice(0, 200)}`);
}
return data.runId;
}
// Best-effort run completion — mirrors the CLI's finishAgentRun. Never throws.
async function finishRun(token, runId, status, proxyOptions) {
if (!runId) return;
try {
await proxyAwareFetch(`${sessionOrigin()}${RUN_PATH}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
"User-Agent": "codebuff-cli/0.0.138",
},
body: JSON.stringify({ action: "FINISH", runId, status }),
signal: AbortSignal.timeout(10_000),
}, proxyOptions);
} catch {
// Best-effort only — the server sweeps stale runs.
}
}
export function resetSessionCache() {
sessionCache.clear();
inflight.clear();
}
export class FreebuffExecutor extends BaseExecutor {
constructor() {
super("freebuff", PROVIDERS.freebuff);
}
buildUrl() {
return this.config.baseUrl;
}
transformRequest(model, body, stream, credentials) {
// Top-level wire shape — see header comment. `run_id` and
// `freebuff_instance_id` are attached by execute() (they need the async
// run/session registration), so this only sets the static parts.
body.codebuff_metadata = {
client_id:
credentials?.providerSpecificData?.fingerprintId ||
`9router-${crypto.randomUUID()}`,
cost_mode: "free",
};
body.provider = { allow_fallbacks: false };
// Free-tier gate: first system message must open with the CLI marker.
return injectFreebuffMarker(body);
}
async execute({ model, body, stream, credentials, signal, log, proxyOptions = null }) {
const token = credentials?.accessToken;
if (!token) {
throw new Error("Freebuff requires a connected Freebuff login (no access token found)");
}
let session;
try {
session = await ensureSession(token, model, proxyOptions);
} catch (error) {
log?.error?.("AUTH", `Freebuff session failed: ${error.message}`);
throw error;
}
const url = this.buildUrl();
const headers = this.buildHeaders(credentials, stream);
const retryConfig = { ...DEFAULT_RETRY_CONFIG, ...this.config.retry };
// Registered run whose id the backend resolves on chat. Per-request, like
// the CLI's one-run-per-prompt granularity; closure-local so concurrent
// requests never share a runId. trace_session_id mirrors the CLI's
// extraCodebuffMetadata — one per run, stable across retries.
let runId = null;
const traceSessionId = crypto.randomUUID();
const buildBody = () => {
const transformed = this.transformRequest(model, body, stream, credentials);
transformed.codebuff_metadata.run_id = runId;
transformed.codebuff_metadata.trace_session_id = traceSessionId;
if (session?.instanceId) {
transformed.codebuff_metadata.freebuff_instance_id = session.instanceId;
}
return transformed;
};
// Chat POST with connect timeout + registry 429/502/503 retry + up to 2
// retries on fetch-level network errors (per attempt the body is rebuilt
// so each retry reuses the same registered run_id).
const doChat = async () => {
let networkAttempts = 0;
const MAX_NETWORK_ATTEMPTS = 2;
for (let attempt = 0; ; attempt++) {
const transformedBody = buildBody();
const bodyStr = JSON.stringify(transformedBody);
dbg("FETCH", `FREEBUFF → ${url} | body=${bodyStr.length}B`);
const connectCtrl = new AbortController();
const timeoutMs = this.config?.timeoutMs || FETCH_CONNECT_TIMEOUT_MS;
const connectTimer = setTimeout(() => connectCtrl.abort(new Error("fetch connect timeout")), timeoutMs);
const mergedSignal = signal ? AbortSignal.any([signal, connectCtrl.signal]) : connectCtrl.signal;
const fetchT0 = Date.now();
let response;
try {
response = await proxyAwareFetch(url, { method: "POST", headers, body: bodyStr, signal: mergedSignal }, proxyOptions);
const ct = response.headers?.get?.("content-type") || "";
const cl = response.headers?.get?.("content-length") || "?";
dbg("FETCH", `FREEBUFF ← ${response.status} | ttft=${Date.now() - fetchT0}ms | ct=${ct} | cl=${cl}`);
} catch (error) {
// A caller/stream abort (AbortError) is genuine — never retry it. A
// transient socket/TLS reset (same class as the run-registration
// failure in the field) gets a couple of quick retries so a network
// blip doesn't fail the request and lock the model for 30s.
const aborted = error?.name === "AbortError";
if (aborted || networkAttempts >= MAX_NETWORK_ATTEMPTS) throw error;
networkAttempts += 1;
log?.debug?.("RETRY", `network error on ${url} (${error.message}), retry ${networkAttempts}/${MAX_NETWORK_ATTEMPTS}`);
await new Promise((resolve) => setTimeout(resolve, 750));
continue;
} finally {
clearTimeout(connectTimer);
}
const entry = resolveRetryEntry(retryConfig[response.status]);
if (entry && attempt < entry.attempts) {
log?.debug?.("RETRY", `${response.status} on ${url}, retry ${attempt + 1}/${entry.attempts} after ${entry.delayMs / 1000}s`);
await new Promise((resolve) => setTimeout(resolve, entry.delayMs));
continue;
}
return { response, transformedBody };
}
};
// The run currently in flight. Only this one is FINISH-able: after a stale
// session (428/409/410) the old run is FINISH'd "cancelled" and cleared, so
// a later failure can never double-FINISH it (the server rejects duplicate
// FINISHes for the same runId).
let activeRunId = null;
const markFinished = (status) => {
if (!activeRunId) return;
const id = activeRunId;
activeRunId = null;
finishRun(token, id, status, proxyOptions);
};
try {
try {
runId = await startRun(token, model, proxyOptions);
activeRunId = runId;
} catch (error) {
log?.error?.("AUTH", `Freebuff run start failed: ${error.message}`);
throw error;
}
let { response, transformedBody } = await doChat();
// Session gates that mean our claimed session is stale/absent:
// 428 waiting_room_required — no session row / instance id missing
// 409 session_superseded — another instance took over the session
// 409 session_model_mismatch — session bound to a different model
// 410 session_expired — the active session's expires_at passed
// In every case: abandon the run, force a fresh session claim + a fresh
// run, then retry exactly once.
if (SESSION_STALE_CODES.has(response.status)) {
log?.debug?.("AUTH", `Freebuff ${response.status} session gate — re-claiming session`);
markFinished("cancelled");
try {
session = await ensureSession(token, model, proxyOptions, true);
runId = await startRun(token, model, proxyOptions);
activeRunId = runId;
} catch (error) {
log?.error?.("AUTH", `Freebuff session re-claim failed: ${error.message}`);
throw error;
}
({ response, transformedBody } = await doChat());
if (SESSION_STALE_CODES.has(response.status)) {
const text = await response.text().catch(() => "");
const err = new Error(
`Freebuff session gate refused (${response.status}) — another freebuff instance may be holding the session. ${text.slice(0, 160)}`,
);
err.status = response.status;
throw err;
}
}
// The authToken has no refresh path — when it dies, the user re-logs in.
// Drop the cached session for this token so a re-login starts clean.
if (response.status === 401) {
sessionCache.delete(sessionCacheKey(token, model));
const text = await response.text().catch(() => "");
const err = new Error(`Freebuff auth failed (401) — re-login in the dashboard. ${text.slice(0, 120)}`);
err.status = 401;
throw err;
}
// Best-effort run accounting, mirroring the CLI.
markFinished(response.ok ? "completed" : "failed");
return { response, url, headers, transformedBody };
} finally {
// Never leave the current run dangling on thrown paths (network/abort/gate).
if (activeRunId) {
finishRun(token, activeRunId, "failed", proxyOptions);
}
}
}
}
export const __test__ = {
ensureSession,
requestSession,
startRun,
resetSessionCache,
rootAgentIdForModel,
injectFreebuffMarker,
fetchWithNetworkRetry,
FREEBUFF_SYSTEM_MARKER,
SESSION_STALE_CODES,
};
export default FreebuffExecutor;