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
This commit is contained in:
@@ -0,0 +1,459 @@
|
||||
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;
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Freebuff — the free, ad-supported coding agent by Codebuff (freebuff.com).
|
||||
*
|
||||
* The Freebuff CLI (github.com/CodebuffAI/freebuff) is an interactive TUI that
|
||||
* talks to the Codebuff/Freebuff backend. Two hosts are involved:
|
||||
* - login flow (freebuff mode) runs on https://freebuff.com
|
||||
* POST /api/auth/cli/code {fingerprintId} → { loginUrl, fingerprintHash, expiresAt }
|
||||
* open loginUrl in browser, then GET /api/auth/cli/status until {user}.
|
||||
* (The server echoes the request host into loginUrl, so calling
|
||||
* freebuff.com yields freebuff.com/login?auth_code=… exactly like the
|
||||
* official CLI — www.codebuff.com would yield the wrong link.)
|
||||
* - LLM traffic goes to the OpenAI-compatible endpoint on
|
||||
* https://www.codebuff.com/api/v1/chat/completions
|
||||
* (freebuff.com does NOT serve /api/v1/* — it 404s with the SPA shell.)
|
||||
*
|
||||
* Both hosts share one backend: the authToken obtained via the freebuff.com
|
||||
* login validates against www.codebuff.com (Bearer auth). The request body
|
||||
* must carry the CLI's `codebuff` provider block
|
||||
* (`codebuff_metadata.run_id/client_id/cost_mode`) — injected by
|
||||
* executors/freebuff.js. cost_mode:"free" is what admits a session on the free
|
||||
* (country-gated, session-limited) tier instead of billing credits.
|
||||
*/
|
||||
export default {
|
||||
id: "freebuff",
|
||||
priority: 45,
|
||||
hasFree: true,
|
||||
alias: "fb",
|
||||
uiAlias: "fb",
|
||||
display: {
|
||||
name: "Freebuff",
|
||||
icon: "bolt",
|
||||
color: "#84CC16",
|
||||
textIcon: "FB",
|
||||
website: "https://freebuff.com",
|
||||
notice: {
|
||||
signupUrl: "https://freebuff.com",
|
||||
text: "Free ad-supported coding agent by Codebuff. Sign in with your Freebuff/Codebuff account via browser login. Free tier is ad-supported and limited in some regions (limited mode: 6 x 1-hour sessions/day); full mode runs in select countries.",
|
||||
},
|
||||
},
|
||||
category: "free",
|
||||
authType: "oauth",
|
||||
authModes: ["oauth"],
|
||||
hasOAuth: true,
|
||||
transport: {
|
||||
baseUrl: "https://www.codebuff.com/api/v1/chat/completions",
|
||||
format: "openai",
|
||||
headers: {
|
||||
"User-Agent": "ai-sdk/openai-compatible/1.0/codebuff",
|
||||
},
|
||||
retry: {
|
||||
429: { attempts: 2, delayMs: 2000 },
|
||||
503: { attempts: 2, delayMs: 1500 },
|
||||
},
|
||||
// Session endpoint doubles as the quota API: GET /api/v1/freebuff/session
|
||||
// returns the shared daily session quota (rateLimitsByModel) without
|
||||
// claiming anything — POST would burn a session, so quota reads are GET
|
||||
// only (see services/usage/freebuff.js).
|
||||
usage: {
|
||||
url: "https://www.codebuff.com/api/v1/freebuff/session",
|
||||
},
|
||||
},
|
||||
features: {
|
||||
usage: true,
|
||||
},
|
||||
// Mirrors the CLI's free picker (FREEBUFF_ROOT_AGENT_ID_BY_MODEL).
|
||||
// mimo/mimo-v2.5-pro is intentionally absent — it is not a free-tier model
|
||||
// and would bill credits or be rejected under the base2-free agent.
|
||||
models: [
|
||||
{ id: "deepseek/deepseek-v4-flash", name: "DeepSeek V4 Flash" },
|
||||
{ id: "deepseek/deepseek-v4-pro", name: "DeepSeek V4 Pro" },
|
||||
{ id: "mimo/mimo-v2.5", name: "MiMo 2.5" },
|
||||
{ id: "minimax/minimax-m3", name: "MiniMax M3" },
|
||||
{ id: "openai/gpt-5.6-luna", name: "GPT-5.6 Luna" },
|
||||
],
|
||||
// Login-flow host — the CLI in freebuff mode logs in via freebuff.com, and
|
||||
// the server builds loginUrl from the host it was called on, so the link the
|
||||
// user opens must come from freebuff.com to match the official CLI.
|
||||
oauth: {
|
||||
baseUrl: "https://freebuff.com",
|
||||
loginCodePath: "/api/auth/cli/code",
|
||||
loginStatusPath: "/api/auth/cli/status",
|
||||
oauthTimeoutMs: 300000,
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* Freebuff usage handler
|
||||
*
|
||||
* Freebuff has no separate billing/quota API — the daily free/premium session
|
||||
* quota lives on the session endpoint itself. Reading it MUST use
|
||||
* GET /api/v1/freebuff/session (the CLI's status poll): POST would CLAIM a
|
||||
* session and burn 1.0 unit of the daily quota, which a quota tracker must
|
||||
* never do.
|
||||
*
|
||||
* The GET response carries the shared session quota as `rateLimitsByModel`,
|
||||
* keyed by model id, on the pre-join (`none`), `active`, and `ended` states:
|
||||
* { limit, recentCount, resetAt, period: 'pacific_day'|'pacific_week',
|
||||
* resetTimeZone, entitlementBreakdown? }
|
||||
* `recentCount` is fractional — a long agent run can consume 1.3 units — and
|
||||
* includes the active session's own 1.0-unit reservation. `limit` can be
|
||||
* raised by referral/streak rewards (entitlementBreakdown.base + referral +
|
||||
* streak).
|
||||
*/
|
||||
|
||||
import REGISTRY from "../../providers/registry/index.js";
|
||||
import { U, fetchWithTimeout } from "./shared.js";
|
||||
|
||||
// Friendly labels from the registry model list (mirrors the CLI picker).
|
||||
const freebuffRegistry = REGISTRY.find((r) => r.id === "freebuff") || {};
|
||||
const MODEL_LABELS = Object.fromEntries(
|
||||
(freebuffRegistry.models || []).map((m) => [m.id, m.name]),
|
||||
);
|
||||
|
||||
function sessionUrl() {
|
||||
return U("freebuff").url;
|
||||
}
|
||||
|
||||
export async function getFreebuffUsage(accessToken, providerSpecificData, proxyOptions = null) {
|
||||
if (!accessToken) {
|
||||
return { message: "Freebuff credential not available — connect a Freebuff login first." };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetchWithTimeout(
|
||||
sessionUrl(),
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
"User-Agent": "codebuff-cli/0.0.138",
|
||||
Accept: "application/json",
|
||||
},
|
||||
},
|
||||
15000,
|
||||
proxyOptions,
|
||||
);
|
||||
|
||||
if (response.status === 401) {
|
||||
return { message: "Freebuff credential invalid or expired — re-login in the dashboard." };
|
||||
}
|
||||
if (response.status === 403) {
|
||||
// A 403 from the session endpoint is usually a server-side gate status
|
||||
// (country_blocked / banned), not a credential problem — telling the
|
||||
// user to re-login would be misleading (mirrors the CLI's
|
||||
// callFreebuffSession 403 branch).
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (body?.status === "country_blocked") {
|
||||
return { message: "Freebuff is not available in your region." };
|
||||
}
|
||||
if (body?.status === "banned") {
|
||||
return { message: "Your Freebuff account has been banned." };
|
||||
}
|
||||
return {
|
||||
message: `Freebuff quota access denied (403)${body?.message ? `: ${body.message}` : ""}.`,
|
||||
};
|
||||
}
|
||||
// 404 = no session row at all → pre-join state, no quota to report.
|
||||
if (response.status === 404) {
|
||||
return { plan: "Freebuff", message: "Freebuff connected. No session quota to report right now." };
|
||||
}
|
||||
if (!response.ok) {
|
||||
return { message: `Freebuff quota API error (${response.status}).` };
|
||||
}
|
||||
|
||||
const data = await response.json().catch(() => ({}));
|
||||
const rateLimits = { ...(data.rateLimitsByModel || {}) };
|
||||
// An active session carries its own `rateLimit` row — fold it in when the
|
||||
// shared map omits the model (older servers).
|
||||
if (data.status === "active" && data.rateLimit && !rateLimits[data.model]) {
|
||||
rateLimits[data.model] = data.rateLimit;
|
||||
}
|
||||
|
||||
const quotas = {};
|
||||
for (const [model, rl] of Object.entries(rateLimits)) {
|
||||
if (!rl || typeof rl !== "object") continue;
|
||||
const used = Number(rl.recentCount);
|
||||
const total = Number(rl.limit);
|
||||
quotas[model] = {
|
||||
used: Number.isFinite(used) ? used : 0,
|
||||
total: Number.isFinite(total) ? total : 0,
|
||||
resetAt: rl.resetAt || null,
|
||||
unlimited: false,
|
||||
// Daily/weekly Pacific session allowance replenishes at resetAt — the
|
||||
// UI must say "Resets in", not "Expires in".
|
||||
recurring: true,
|
||||
...(MODEL_LABELS[model] ? { displayName: MODEL_LABELS[model] } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const plan = data.accessTier === "limited" ? "Freebuff (Limited)" : "Freebuff";
|
||||
if (Object.keys(quotas).length === 0) {
|
||||
return { plan, message: "Freebuff connected. No session quota to report right now." };
|
||||
}
|
||||
return { plan, quotas };
|
||||
} catch (error) {
|
||||
return { message: `Freebuff usage error: ${error.message}` };
|
||||
}
|
||||
}
|
||||
|
||||
export default getFreebuffUsage;
|
||||
Reference in New Issue
Block a user