Files
OmniRoute/open-sse/services/conolUsage.ts
Praveen K Palaniswamy 65e81158ab fix(ollama): route models by advertised capability (#11088)
Landed with the design call resolved per the owner's pick — **option 1**: the synced store is now endpoint-agnostic (persistDiscoveredModels and managedModelImport no longer drop non-chat models at write time), and chat selectability moved to read time (auto-pool expansion in autoStrategy applies filterChatSelectableModels; the models-route projection already had its chatOnly filter). Your discovery test now passes end-to-end (3/3): /api/show capabilities persist per connection and image/embedding requests route through the advertising host.

Reconciliation notes: conflicted areas merged onto the current tip (adobe discovery import, requestedModel preflight signature, resolvedProvider fast-path coexists with the synced-route override — explicit resolution wins); carried base-red drains (#10055 memoization, #11071 test variants) dropped as already-landed; the managed-model-import exclusion test was propagated to the new contract (image/video models persist; the read filter still hides them from chat pickers — pinned by a new assertion). Full battery: 205/206 focused (the one red is a confirmed periodic-timer timing flake on the loaded devbox — 20/20 isolated), autoCombo vitest 30/30, combo suites 46/46, gates + typecheck clean.

Thank you @yourspraveen — the capability probe + routing design was right; it just needed the store contract opened up. Fixes #11087.
2026-08-23 11:45:01 -03:00

112 lines
3.3 KiB
TypeScript

import { normalizeConolCookie } from "./conolAuth.ts";
interface UsageQuota {
used: number;
total: number;
remaining: number;
remainingPercentage: number;
resetAt: null;
unlimited: boolean;
}
interface ConolBalance {
dailyCredits?: unknown;
subscriptionCredits?: unknown;
subscriptionAmount?: unknown;
extraCredits?: unknown;
total?: unknown;
}
interface ConolUsageResult {
plan: string;
quotas: Record<"credits" | "daily" | "subscription" | "extra", UsageQuota>;
message: string | null;
}
function numberValue(value: unknown): number {
const parsed = typeof value === "number" ? value : Number(value);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
}
function remainingQuota(remaining: number, total = remaining): UsageQuota {
const boundedTotal = Math.max(total, remaining);
const used = Math.max(0, boundedTotal - remaining);
return {
used,
total: boundedTotal,
remaining,
remainingPercentage:
boundedTotal > 0 ? Math.round((remaining / boundedTotal) * 1000) / 10 : 0,
resetAt: null,
unlimited: false,
};
}
export function buildConolUsageResult(balance: ConolBalance): ConolUsageResult {
const daily = numberValue(balance.dailyCredits);
const subscription = numberValue(balance.subscriptionCredits);
const subscriptionAmount = numberValue(balance.subscriptionAmount);
const extra = numberValue(balance.extraCredits);
const aggregate = numberValue(balance.total) || daily + subscription + extra;
return {
plan: subscriptionAmount > 0 ? "Subscription" : "Free",
quotas: {
credits: remainingQuota(aggregate),
daily: remainingQuota(daily),
subscription: remainingQuota(subscription, subscriptionAmount || subscription),
extra: remainingQuota(extra),
},
message: null,
};
}
function readString(value: unknown): string {
return typeof value === "string" ? value.trim() : "";
}
function readProviderValue(data: unknown, keys: readonly string[]): string {
if (!data || typeof data !== "object" || Array.isArray(data)) return "";
const record = data as Record<string, unknown>;
for (const key of keys) {
const value = readString(record[key]);
if (value) return value;
}
return "";
}
export async function getConolUsage(
apiKey: unknown,
providerSpecificData?: unknown
): Promise<ConolUsageResult | { message: string }> {
const raw =
readProviderValue(providerSpecificData, [
"cookie",
"__Secure-better-auth.session_token",
"sessionToken",
]) || readString(apiKey);
const cookie = normalizeConolCookie(raw);
if (!cookie) return { message: "Missing Conol session cookie" };
try {
const response = await fetch("https://conol.ai/api/billing/balance", {
method: "GET",
headers: {
accept: "application/json",
cookie,
referer: "https://conol.ai/home",
},
signal: AbortSignal.timeout(15_000),
});
if (response.status === 401 || response.status === 403) {
return { message: "Conol session expired or is invalid" };
}
if (!response.ok) {
return { message: `Conol balance request failed (HTTP ${response.status})` };
}
return buildConolUsageResult((await response.json()) as ConolBalance);
} catch {
return { message: "Conol balance request failed" };
}
}