merge: pull mhiqrambg/9router-mibp-version into master
Merge the MIBP fork (v1.0.14, synced to decolua v0.5.81) into our master
(0.5.86) at merge-base a8c9d380. Keep HEAD's infra policy (untracked
lockfile, mirror-configurable Dockerfile, decolua GHCR/DockerHub, README)
while absorbing the fork's engine features:
- feat(providers): freebuff provider + executor + OAuth + usage tracking
- feat(providers): cline free-tier models, Freebuff catalog sync
- feat(proxy-pools): pool egress geo probe, proxy-pool fitness + retry
- fix(usage): hide noAuth providers (devin-cli, mimo-free) from usage list
- test(harness): DATA_DIR isolation so tests never write the real DB
- fix(codebuddy-intl): probe token in connection test, OAuth by identity
- chore(guards): durable markers so fixes aren't silently dropped
Resolutions:
- registry/index.js regenerated deterministically (122 providers, alpha
order). trae/windsurf/devin-cli stay hidden per HEAD security posture
(no tool-calling / local-agent shell access) — not re-enabled.
- nonStreamingHandler: drop the generic unconditional unwrapDataEnvelope
call; envelope unwrap stays scoped to clineEnvelope-quirk providers
(unwrapClineEnvelope), fixing a latent mibp bug where non-opted-in
providers ({success,data} bodies) were stripped.
- Drop fork-local Docker lockfile policy (package-lock.json, AGENTS.md,
.npmrc verify scripts): this repo keeps package-lock untracked (nix
build deploy). .npmrc (audit=false/fund=false) kept.
- Keep gitbook-pages workflow enabled (ours); mibp disabled it.
- Restore 13 upstream tests mibp deleted (they cover features we keep).
Verified: 2841 tests, 2687 pass, fail set byte-identical to HEAD (zero
new regressions); providers/alias/oauth baselines regenerated to merged
code and all green.
This commit is contained in:
@@ -5,17 +5,11 @@ const FETCH_TIMEOUT_MS = 5000;
|
||||
|
||||
/**
|
||||
* Build request headers for the ClinePass /models endpoint (Cline's upstream API).
|
||||
* - API keys are sent as plain Bearer tokens.
|
||||
* - OAuth access tokens must carry the WorkOS `workos:` prefix (handled by buildClineHeaders).
|
||||
* Auth shape lives in shared/clineAuth: API keys ride plain Bearer, OAuth
|
||||
* access tokens carry the WorkOS `workos:` prefix.
|
||||
*/
|
||||
function buildModelListHeaders(token, isApiKey) {
|
||||
if (isApiKey) {
|
||||
return {
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
};
|
||||
}
|
||||
return buildClineHeaders(token, { Accept: "application/json" });
|
||||
return buildClineHeaders(token, { Accept: "application/json" }, { isApiKey });
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
// Pool egress geo — engine layer, shared by the dashboard UI (Proxy Fitness /
|
||||
// Proxy Pools egress column) and any provider region policy that wants to
|
||||
// pre-mark pools unfit by egress region.
|
||||
//
|
||||
// The probe transport is provider-agnostic: it fetches a geo service THROUGH
|
||||
// the pool itself (relay headers for vercel/cloudflare/deno, proxy URL for
|
||||
// socks/http), so it works for every pool type and every provider.
|
||||
//
|
||||
// A chain of free endpoints is tried in order so a rate-limited or broken
|
||||
// provider drops to the next; ipinfo (the most quota-bound) is last.
|
||||
//
|
||||
// State lives on globalThis (same reason as proxyPoolFitness): the background
|
||||
// probe and the /api/proxy-pools reader must share ONE cache across Next dev
|
||||
// bundles.
|
||||
|
||||
const GEO_STATE_KEY = "__9routerPoolGeo__";
|
||||
const geoCache = (globalThis[GEO_STATE_KEY] ??= new Map()); // poolId -> { ip, country, ..., ts, ipHistory }
|
||||
|
||||
export const POOL_GEO_TTL_MS = 60 * 60 * 1000;
|
||||
// How many past egress IPs to remember for flapping detection.
|
||||
export const POOL_GEO_IP_HISTORY_MAX = 8;
|
||||
|
||||
// Test helper: drop all cached geo (module state is globalThis-backed).
|
||||
export function resetPoolGeo() {
|
||||
geoCache.clear();
|
||||
}
|
||||
|
||||
// Attach stability classification: >=2 distinct egress IPs observed = flapping
|
||||
// (typical for serverless relays — Vercel/Cloudflare egress varies per colo).
|
||||
function withStability(entry) {
|
||||
const ips = new Set([entry?.ip, ...(entry?.ipHistory || []).map((h) => h.ip)]);
|
||||
ips.delete("");
|
||||
const ipCount = ips.size;
|
||||
return { ...entry, ipCount, isUnstable: ipCount >= 2 };
|
||||
}
|
||||
|
||||
export function getPoolGeo(poolId) {
|
||||
const entry = geoCache.get(poolId);
|
||||
if (!entry) return null;
|
||||
if (entry.ts + POOL_GEO_TTL_MS < Date.now()) {
|
||||
geoCache.delete(poolId);
|
||||
return null;
|
||||
}
|
||||
return withStability(entry);
|
||||
}
|
||||
|
||||
export function setPoolGeo(poolId, geo) {
|
||||
if (!poolId || !geo?.ip) return;
|
||||
const prev = geoCache.get(poolId);
|
||||
const ipHistory = prev?.ipHistory ? [...prev.ipHistory] : [];
|
||||
if (prev?.ip && prev.ip !== geo.ip) {
|
||||
// Record the IP we are leaving — the history tracks past egress IPs.
|
||||
ipHistory.push({ ip: prev.ip, ts: Date.now() });
|
||||
if (ipHistory.length > POOL_GEO_IP_HISTORY_MAX) ipHistory.shift();
|
||||
}
|
||||
geoCache.set(poolId, { ...geo, ts: Date.now(), ipHistory });
|
||||
}
|
||||
|
||||
export function poolGeoSnapshot(now = Date.now()) {
|
||||
const out = {};
|
||||
for (const [poolId, entry] of geoCache) {
|
||||
if (entry.ts + POOL_GEO_TTL_MS <= now) {
|
||||
geoCache.delete(poolId);
|
||||
continue;
|
||||
}
|
||||
out[poolId] = withStability(entry);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Sweep geo entries past their TTL (ipHistory rides along with the entry).
|
||||
// Returns how many entries were removed.
|
||||
export function pruneStaleGeo(now = Date.now()) {
|
||||
let removed = 0;
|
||||
for (const [poolId, entry] of geoCache) {
|
||||
if (entry.ts + POOL_GEO_TTL_MS <= now) {
|
||||
geoCache.delete(poolId);
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
// Normalize a single provider's geo payload to { ip, country, region, city, org }.
|
||||
const GEO_PARSE = {
|
||||
"ipwho.is": (d) => ({ ip: d?.ip, country: d?.country, region: d?.region, city: d?.city, org: d?.org || d?.connection?.org }),
|
||||
"ip-api": (d) => ({ ip: d?.query, country: d?.country, region: d?.regionName, city: d?.city, org: d?.org }),
|
||||
"ipapi.co": (d) => ({ ip: d?.ip, country: d?.country_name, region: d?.region, city: d?.city, org: d?.org }),
|
||||
ipinfo: (d) => ({ ip: d?.ip, country: d?.country, region: d?.region, city: d?.city, org: d?.org }),
|
||||
};
|
||||
|
||||
// Tried in order — rate-friendly first, quota-bound ipinfo last.
|
||||
const GEO_PROBES = [
|
||||
{ name: "ipwho.is", url: "https://ipwho.is/" },
|
||||
{ name: "ip-api", url: "https://ip-api.com/json/?fields=status,message,query,country,regionName,city,org" },
|
||||
{ name: "ipapi.co", url: "https://ipapi.co/json/" },
|
||||
{ name: "ipinfo", url: "https://ipinfo.io/json" },
|
||||
];
|
||||
|
||||
// Custom single endpoint via env (replaces the chain). Keys mapped generically.
|
||||
function customGeoParse(d) {
|
||||
if (!d || typeof d !== "object") return null;
|
||||
const pick = (...keys) => keys.map((k) => d[k]).find((v) => v != null && v !== "");
|
||||
return {
|
||||
ip: pick("query", "ip"),
|
||||
country: pick("country", "country_name", "countryName"),
|
||||
region: pick("regionName", "region", "state", "regionCode"),
|
||||
city: pick("city"),
|
||||
org: pick("org", "organization", "isp", "orgName", "connection", "asn"),
|
||||
};
|
||||
}
|
||||
|
||||
function probeSource({ proxyAwareFetch, url, proxyOptions, timeoutMs, name }) {
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(new Error("geo probe timeout")), timeoutMs);
|
||||
return (async () => {
|
||||
try {
|
||||
const res = await proxyAwareFetch(url, { signal: ctrl.signal }, proxyOptions);
|
||||
if (!res.ok) {
|
||||
const txt = await res.text().catch(() => "");
|
||||
const error = res.status === 429 || res.status === 403 ? "rate-limit"
|
||||
: res.status >= 500 ? "server"
|
||||
: "network";
|
||||
return { ok: false, error, detail: `${res.status} ${txt.slice(0, 80)}` };
|
||||
}
|
||||
const data = await res.json().catch(() => null);
|
||||
const parsed = name ? GEO_PARSE[name]?.(data) : customGeoParse(data);
|
||||
if (!parsed?.ip) return { ok: false, error: "no-ip", detail: `${name || "custom"}` };
|
||||
return {
|
||||
ok: true,
|
||||
geo: {
|
||||
ip: String(parsed.ip || "").trim(),
|
||||
country: String(parsed.country || "").trim(),
|
||||
region: String(parsed.region || "").trim(),
|
||||
city: String(parsed.city || "").trim(),
|
||||
org: String(parsed.org || "").trim(),
|
||||
isDatacenter: /(cloudflare|vercel|amazon|aws|google|microsoft|azure|digitalocean|hetzner|ovh|contabo|leaseweb)/i.test(
|
||||
String(parsed.org || ""),
|
||||
),
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
const timedOut = ctrl.signal?.aborted && error?.name === "AbortError";
|
||||
return { ok: false, error: timedOut ? "timeout" : "network", detail: `${error?.name}: ${error?.message}` };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
// Probe the egress geo of one pool through a chain of geo providers. Fail-open:
|
||||
// returns { ok:true, geo } on success, { ok:false, error } otherwise with
|
||||
// `error` one of "rate-limit" | "server" | "no-ip" | "network" | "timeout".
|
||||
// `pool` shape: { proxyUrl, type }. 15s timeout per endpoint by default.
|
||||
export async function probePoolGeo(pool, timeoutMs = 15000) {
|
||||
const proxyUrl = pool?.proxyUrl;
|
||||
if (!proxyUrl) return { ok: false, error: "network", detail: "no proxy url" };
|
||||
const { proxyAwareFetch } = await import("../utils/proxyFetch.js");
|
||||
const isRelay = ["vercel", "cloudflare", "deno"].includes(pool?.type);
|
||||
const proxyOptions = isRelay
|
||||
? { vercelRelayUrl: proxyUrl }
|
||||
: { connectionProxyEnabled: true, connectionProxyUrl: proxyUrl };
|
||||
|
||||
const custom = process.env.GEO_PROBE_URL ? [{ name: null, url: process.env.GEO_PROBE_URL }] : [];
|
||||
const probes = custom.length ? custom : GEO_PROBES;
|
||||
|
||||
let last = { ok: false, error: "network", detail: "no provider responded" };
|
||||
for (const p of probes) {
|
||||
const res = await probeSource({ proxyAwareFetch, url: p.url, proxyOptions, timeoutMs, name: p.name });
|
||||
if (res.ok) return res;
|
||||
// Prefer the most specific failure: rate-limit/server over generic network.
|
||||
if (res.error === "rate-limit" || res.error === "server") last = res;
|
||||
else if (last.error === "network") last = res;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// Pool fitness registry — shared, in-memory, engine layer.
|
||||
//
|
||||
// Rotation strategies can opt into region/provider-aware pool selection: an
|
||||
// executor that learns a pool's egress is unfit for a provider/model (e.g.
|
||||
// Freebuff limited-mode IP) marks it here, and the pool picker skips it for
|
||||
// that scope until the cooldown expires.
|
||||
//
|
||||
// Scope format: `provider::model` (e.g. "freebuff::openai/gpt-5.6-luna").
|
||||
// All functions are fail-open: unknown pool/scope ⇒ fit.
|
||||
|
||||
// Scope format: `provider::model` (e.g. "freebuff::openai/gpt-5.6-luna").
|
||||
// All functions are fail-open: unknown pool/scope ⇒ fit.
|
||||
//
|
||||
// State lives on globalThis so Next dev (Turbopack) never splits one Map into
|
||||
// several per-bundle copies — the executor/chatCore marks and the
|
||||
// /api/proxy-pools/fitness reader must share the SAME registry.
|
||||
|
||||
const FITNESS_STATE_KEY = "__9routerPoolFitness__";
|
||||
const fitness = (globalThis[FITNESS_STATE_KEY] ??= new Map()); // poolId -> Map<scope, { until, reason }>
|
||||
let persistTimer = null;
|
||||
let hydratePromise = null;
|
||||
|
||||
export const POOL_UNFIT_MS = 5 * 60 * 1000;
|
||||
|
||||
function schedulePersist() {
|
||||
if (persistTimer) return;
|
||||
persistTimer = setTimeout(async () => {
|
||||
persistTimer = null;
|
||||
try {
|
||||
const { updateSettings } = await import("@/lib/db/repos/settingsRepo.js");
|
||||
await updateSettings({ proxyPoolFitness: poolFitnessSnapshot() });
|
||||
} catch {
|
||||
// Fitness is advisory; persistence failures must not block requests.
|
||||
}
|
||||
}, 25);
|
||||
if (persistTimer.unref) persistTimer.unref();
|
||||
}
|
||||
|
||||
export function hydratePoolFitness(snapshot = {}) {
|
||||
for (const [poolId, byScope] of Object.entries(snapshot || {})) {
|
||||
const entries = Object.entries(byScope || {}).filter(([, entry]) => Number(entry?.until) > Date.now());
|
||||
if (entries.length) fitness.set(poolId, new Map(entries));
|
||||
}
|
||||
}
|
||||
|
||||
export async function ensurePoolFitnessHydrated() {
|
||||
if (!hydratePromise) {
|
||||
hydratePromise = import("@/lib/db/repos/settingsRepo.js")
|
||||
.then(({ getSettings }) => getSettings())
|
||||
.then((settings) => hydratePoolFitness(settings.proxyPoolFitness || {}))
|
||||
.catch(() => {})
|
||||
.then(() => undefined);
|
||||
}
|
||||
return hydratePromise;
|
||||
}
|
||||
|
||||
export function markPoolUnfit(poolId, scope, until = Date.now() + POOL_UNFIT_MS, reason = "") {
|
||||
if (!poolId || !scope) return;
|
||||
const byScope = fitness.get(poolId) || new Map();
|
||||
byScope.set(scope, { until, reason });
|
||||
fitness.set(poolId, byScope);
|
||||
schedulePersist();
|
||||
}
|
||||
|
||||
export function clearPoolUnfit(poolId, scope) {
|
||||
const byScope = fitness.get(poolId);
|
||||
if (!byScope) return;
|
||||
byScope.delete(scope);
|
||||
if (byScope.size === 0) fitness.delete(poolId);
|
||||
schedulePersist();
|
||||
}
|
||||
|
||||
// "provider::model" -> "provider::*" (null when the scope has no provider part)
|
||||
function providerWildcardScope(scope) {
|
||||
const sep = String(scope || "").indexOf("::");
|
||||
if (sep < 0) return null;
|
||||
return `${scope.slice(0, sep)}::*`;
|
||||
}
|
||||
|
||||
export function isPoolFit(poolId, scope, now = Date.now()) {
|
||||
if (!poolId) return true;
|
||||
const byScope = fitness.get(poolId);
|
||||
if (!byScope) return true;
|
||||
// A provider-wide mark ("provider::*", e.g. manual blocks) also covers any
|
||||
// model lookup for that provider.
|
||||
const candidates = [scope, providerWildcardScope(scope)];
|
||||
for (const key of candidates) {
|
||||
if (!key) continue;
|
||||
const entry = byScope.get(key);
|
||||
if (!entry) continue;
|
||||
if (entry.until <= now) {
|
||||
byScope.delete(key);
|
||||
if (byScope.size === 0) fitness.delete(poolId);
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Keep only pool ids that are not in cooldown for the scope.
|
||||
export function fitPoolIds(poolIds, scope, now = Date.now()) {
|
||||
return (poolIds || []).filter((id) => isPoolFit(id, scope, now));
|
||||
}
|
||||
|
||||
// Clear every mark — or only scopes belonging to one provider (`provider::*`).
|
||||
export function clearAllPoolUnfit(provider = null) {
|
||||
if (provider) {
|
||||
const prefix = `${provider}::`;
|
||||
for (const [poolId, byScope] of fitness) {
|
||||
for (const scope of [...byScope.keys()]) {
|
||||
if (scope.startsWith(prefix)) byScope.delete(scope);
|
||||
}
|
||||
if (byScope.size === 0) fitness.delete(poolId);
|
||||
}
|
||||
schedulePersist();
|
||||
return;
|
||||
}
|
||||
fitness.clear();
|
||||
schedulePersist();
|
||||
}
|
||||
|
||||
// Snapshot of live (non-expired) marks — expired entries are pruned here so
|
||||
// consumers never see stale data and memory stays bounded.
|
||||
// Test helper: drop all marks (module state is globalThis-backed).
|
||||
export function resetPoolFitness() {
|
||||
fitness.clear();
|
||||
hydratePromise = Promise.resolve();
|
||||
schedulePersist();
|
||||
}
|
||||
|
||||
// Sweep all expired marks. Returns how many scope entries were removed.
|
||||
export function pruneExpired(now = Date.now()) {
|
||||
let removed = 0;
|
||||
for (const [poolId, byScope] of fitness) {
|
||||
for (const [scope, entry] of byScope) {
|
||||
if (entry.until <= now) {
|
||||
byScope.delete(scope);
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
if (byScope.size === 0) fitness.delete(poolId);
|
||||
}
|
||||
if (removed) schedulePersist();
|
||||
return removed;
|
||||
}
|
||||
|
||||
export function poolFitnessSnapshot(now = Date.now()) {
|
||||
const out = {};
|
||||
for (const [poolId, byScope] of fitness) {
|
||||
let pruned = false;
|
||||
for (const [scope, entry] of byScope) {
|
||||
if (entry.until <= now) {
|
||||
byScope.delete(scope);
|
||||
pruned = true;
|
||||
}
|
||||
}
|
||||
if (byScope.size === 0) {
|
||||
fitness.delete(poolId);
|
||||
continue;
|
||||
}
|
||||
if (pruned || byScope.size > 0) {
|
||||
out[poolId] = Object.fromEntries(byScope);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { getCodeBuddyCnUsage, getCodeBuddyIntlUsage } from "./usage/codebuddy-cn
|
||||
import { getGrokCliUsage } from "./usage/grok-cli.js";
|
||||
import { getKimiUsage } from "./usage/kimi.js";
|
||||
import { getDeepseekUsage } from "./usage/deepseek.js";
|
||||
import { getFreebuffUsage } from "./usage/freebuff.js";
|
||||
import { getOpenCodeGoUsage } from "./usage/opencode-go.js";
|
||||
import { getOpenCodeZenUsage } from "./usage/opencode-zen.js";
|
||||
import { getGroqUsage } from "./usage/groq.js";
|
||||
@@ -58,6 +59,7 @@ const USAGE_HANDLERS = {
|
||||
"opencode-go": (c) => getOpenCodeGoUsage(c.apiKey, c.proxyOptions),
|
||||
"opencode-zen": (c) => getOpenCodeZenUsage(c.apiKey, c.proxyOptions),
|
||||
deepseek: (c) => getDeepseekUsage(c.apiKey, c.proxyOptions),
|
||||
freebuff: (c) => getFreebuffUsage(c.accessToken, c.providerSpecificData, c.proxyOptions),
|
||||
groq: (c) => getGroqUsage(c.apiKey, c.proxyOptions),
|
||||
zed: (c) => getZedUsage(c.accessToken, c.providerSpecificData, c.proxyOptions),
|
||||
"xiaomi-mimo": (c) => getXiaomiMimoUsage(c.accessToken, c.providerSpecificData, c.proxyOptions),
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
/**
|
||||
* 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).
|
||||
*
|
||||
* Freebucks-metered accounts (2026-09-02+) get NO pool rows: the server sends
|
||||
* a `freebucks` block instead — { balance, daily:{limit,spent,remaining,resetAt},
|
||||
* wallet:{balance,...}, monthly?:{limitUsd,spentUsd,remainingUsd,resetAt},
|
||||
* planId, prices:{model→Freebucks/hr}, priceNotices?, priceChanges? }. The
|
||||
* daily pool replaces rateLimitsByModel, so the tracker folds it in by
|
||||
* replicating the pool snapshot under every priced model id, exactly as the
|
||||
* official picker does.
|
||||
*
|
||||
* Pricing is SERVER-AUTHORITATIVE and nothing here hardcodes a number: each
|
||||
* row carries the live `prices[model]` (plus its `priceNotices` tagline), and
|
||||
* `applyFreebucksPriceChanges` folds the server's announced `priceChanges`
|
||||
* schedule into the map — a promo (e.g. Solar Pro 4's Labor Day 0-Freebucks
|
||||
* offer) expires and reverts on the server's timeline with no client release,
|
||||
* mirroring upstream common/src/util/freebuff-price-changes.ts. A compact
|
||||
* account summary (`freebucks`) rides the response for the card header.
|
||||
*/
|
||||
|
||||
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]),
|
||||
);
|
||||
|
||||
// Fold the server's announced price schedule into the live price map —
|
||||
// mirrors upstream applyFreebucksPriceChanges: due changes override the price
|
||||
// AND its picker tagline, and drop off the pending list.
|
||||
function applyFreebucksPriceChanges(info) {
|
||||
const now = Date.now();
|
||||
const due = (info?.priceChanges || []).filter((c) => Date.parse(c.at) <= now);
|
||||
if (due.length === 0) return info;
|
||||
const prices = { ...(info.prices || {}) };
|
||||
const priceNotices = { ...(info.priceNotices || {}) };
|
||||
for (const change of due.sort((a, b) => Date.parse(a.at) - Date.parse(b.at))) {
|
||||
if (prices[change.modelId] === undefined) continue;
|
||||
prices[change.modelId] = change.price;
|
||||
priceNotices[change.modelId] = change.tagline;
|
||||
}
|
||||
return {
|
||||
...info,
|
||||
prices,
|
||||
priceNotices,
|
||||
priceChanges: (info.priceChanges || []).filter((c) => Date.parse(c.at) > now),
|
||||
};
|
||||
}
|
||||
|
||||
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] } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
// Freebucks meter: the daily Freebucks pool is the quota for metered
|
||||
// accounts, replicated under each priced model like the picker's rings.
|
||||
// Prices come off the wire (prices + priceChanges folded in); each row
|
||||
// carries its own price/tagline, and a compact summary rides the response
|
||||
// for the account header in the UI.
|
||||
let freebucksSummary = null;
|
||||
const rawFreebucks = data.freebucks;
|
||||
if (rawFreebucks && rawFreebucks.daily && typeof rawFreebucks.daily === "object") {
|
||||
const freebucks = applyFreebucksPriceChanges(rawFreebucks);
|
||||
const spent = Number(freebucks.daily.spent);
|
||||
const limit = Number(freebucks.daily.limit);
|
||||
for (const [model, price] of Object.entries(freebucks.prices || {})) {
|
||||
quotas[model] = {
|
||||
used: Number.isFinite(spent) ? spent : 0,
|
||||
total: Number.isFinite(limit) ? limit : 0,
|
||||
resetAt: freebucks.daily.resetAt || null,
|
||||
unlimited: false,
|
||||
recurring: true,
|
||||
price: Number.isFinite(Number(price)) ? Number(price) : undefined,
|
||||
...(freebucks.priceNotices?.[model] ? { priceNote: freebucks.priceNotices[model] } : {}),
|
||||
...(MODEL_LABELS[model] ? { displayName: MODEL_LABELS[model] } : {}),
|
||||
};
|
||||
}
|
||||
freebucksSummary = {
|
||||
balance: Number.isFinite(Number(freebucks.balance)) ? Number(freebucks.balance) : null,
|
||||
daily: {
|
||||
limit: Number.isFinite(limit) ? limit : 0,
|
||||
spent: Number.isFinite(spent) ? spent : 0,
|
||||
remaining: Number.isFinite(Number(freebucks.daily.remaining)) ? Number(freebucks.daily.remaining) : 0,
|
||||
resetAt: freebucks.daily.resetAt || null,
|
||||
},
|
||||
wallet: {
|
||||
balance: Number.isFinite(Number(freebucks.wallet?.balance)) ? Number(freebucks.wallet.balance) : 0,
|
||||
},
|
||||
...(freebucks.monthly && Number.isFinite(Number(freebucks.monthly.remainingUsd))
|
||||
? {
|
||||
monthly: {
|
||||
remainingUsd: Number(freebucks.monthly.remainingUsd),
|
||||
limitUsd: Number.isFinite(Number(freebucks.monthly.limitUsd)) ? Number(freebucks.monthly.limitUsd) : null,
|
||||
resetAt: freebucks.monthly.resetAt || null,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
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." };
|
||||
}
|
||||
const out = { plan, quotas };
|
||||
if (freebucksSummary) out.freebucks = freebucksSummary;
|
||||
return out;
|
||||
} catch (error) {
|
||||
return { message: `Freebuff usage error: ${error.message}` };
|
||||
}
|
||||
}
|
||||
|
||||
export default getFreebuffUsage;
|
||||
Reference in New Issue
Block a user