yapapa / web /src /api /client.ts
wiwi deploy
Deploy wiwi b15bc31
c3ce3c5
Raw History Blame Contribute Delete
22.9 kB
// Fetch wrapper: bearer auth from localStorage, JSON errors as ApiError.
export class ApiError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
const TOKEN_KEY = "wiwi.master_key";
// Same-tab token changes don't fire the window "storage" event (cross-tab
// only), so components that hold a long-lived connection keyed to the token
// (AdminStreamProvider's SSE) subscribe here to notice set/clear. Cross-tab
// writes of the same key are bridged in via the storage event so subscribers
// see both.
const tokenListeners = new Set<() => void>();
function onStorageEvent(e: StorageEvent): void {
if (e.key === TOKEN_KEY || e.key === null) notifyTokenChanged();
}
export function subscribeToken(listener: () => void): () => void {
if (tokenListeners.size === 0 && typeof window !== "undefined") {
window.addEventListener("storage", onStorageEvent);
}
tokenListeners.add(listener);
return () => {
tokenListeners.delete(listener);
if (tokenListeners.size === 0 && typeof window !== "undefined") {
window.removeEventListener("storage", onStorageEvent);
}
};
}
function notifyTokenChanged(): void {
for (const listener of tokenListeners) listener();
}
export function getToken(): string {
return localStorage.getItem(TOKEN_KEY) ?? "";
}
export function setToken(token: string): void {
localStorage.setItem(TOKEN_KEY, token);
notifyTokenChanged();
}
export function clearToken(): void {
localStorage.removeItem(TOKEN_KEY);
notifyTokenChanged();
}
/** A 401 that is *not* an admin-session failure: an endpoint whose 401 is
* about the upstream credential rather than the caller's key. Hermes answers
* `/admin/hermes/oauth/{refresh,poll}` with 401 "Nous refresh token rejected —
* re-login required" when one *account's* grant is dead, which is exactly the
* case the per-account Refresh button exists to recover from. The global
* mutation/query error handler (redirectOnAuthError in main.tsx) treats every
* `ApiError` with status 401 as an expired admin session — it clears the token
* and hard-navigates to /login — so an operator clicking Refresh to fix one
* dead account would be signed out of the console instead. Endpoints with an
* upstream 401 pass `{ upstream401: true }` and get this type instead: same
* status and message plumbing, no session redirect. */
export class UpstreamAuthError extends Error {
readonly status = 401;
constructor(message: string) {
super(message);
this.name = "UpstreamAuthError";
}
}
/** Pull the human message out of a wire error body, falling back to the raw
* text for a non-JSON body. */
async function readErrorMessage(resp: Response): Promise<string> {
const text = await resp.text();
if (!text) return `HTTP ${resp.status}`;
try {
const body = JSON.parse(text) as { error?: { message?: string } };
return body.error?.message ?? text;
} catch {
// plain-text error body
return text;
}
}
export async function api<T>(
path: string,
init?: RequestInit & { upstream401?: boolean },
): Promise<T> {
const headers = new Headers(init?.headers);
headers.set("Authorization", `Bearer ${getToken()}`);
if (init?.body != null && !headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
const upstream401 = init?.upstream401 === true;
let resp: Response;
try {
// credentials:"include" carries the HttpOnly session cookie alongside the
// bearer header (kept for master-key admin back-compat). For username/
// password users the token is empty → "Bearer " header is harmless and the
// server falls back to the cookie.
resp = await fetch(path, { ...init, headers, credentials: "include" });
} catch (e) {
throw new ApiError(0, `network error: ${String(e)}`);
}
if (resp.status === 401) {
if (upstream401) {
// Keep the server's message — it names the failing account ("re-login
// required", the Nous error code) instead of blaming the admin key.
throw new UpstreamAuthError(await readErrorMessage(resp));
}
throw new ApiError(401, "master key required or invalid");
}
const text = await resp.text();
if (!resp.ok) {
let msg = text;
try {
const body = JSON.parse(text) as { error?: { message?: string } };
msg = body.error?.message ?? text;
} catch {
// plain-text error body
}
throw new ApiError(resp.status, msg || `HTTP ${resp.status}`);
}
return (text ? JSON.parse(text) : null) as T;
}
// -- typed endpoint helpers --------------------------------------------------
import type {
AlertRule,
AuditLogEntry,
BuiltinProvider,
ClineConnectResponse,
ClineDisconnectResponse,
ClineLoginUrlResponse,
ClineRefreshResponse,
ClineStatusResponse,
DeploymentInfo,
HermesDeviceCodeResponse,
HermesDisconnectResponse,
HermesPollResponse,
HermesRefreshResponse,
HermesStatusResponse,
ModelAliasEntry,
ModelPrice,
ModelsResponse,
OverviewStats,
PoolKey,
Provider,
ProxyLogEntry,
PlaygroundMetrics,
PublicModelGroup,
RequestLogEntry,
TimeseriesMetric,
TimeseriesResponse,
UpstreamModel,
WorkBuddyAccountsResponse,
WorkBuddyAuthFile,
WorkBuddyExportResponse,
WorkBuddyImportResponse,
WorkBuddyLoginPollResponse,
WorkBuddyLoginStartResponse,
WorkBuddyRefreshResponse,
ProviderBackup,
ProviderExportResponse,
ProviderImportResponse,
User,
VirtualKey,
} from "./types";
export interface ProvidersResponse {
providers: Provider[];
alias_to_provider: Record<string, string>;
}
export const getProviders = () =>
api<ProvidersResponse>("/admin/providers");
export const getBuiltinProviders = () =>
api<BuiltinProvider[]>("/admin/provider-catalog");
export const patchProviderKey = (
provider: string,
label: string,
patch: { enabled?: boolean; weight?: number },
) =>
api<{ key: PoolKey }>(`/admin/providers/${encodeURIComponent(provider)}/keys/${encodeURIComponent(label)}`, {
method: "PATCH",
body: JSON.stringify(patch),
});
export const addProviderKey = (
provider: string,
body: { label: string; key: string; weight?: number },
) =>
api<{ key: PoolKey }>(`/admin/providers/${encodeURIComponent(provider)}/keys`, {
method: "POST",
body: JSON.stringify(body),
});
export const revealProviderKey = (provider: string, label: string) =>
api<{ label: string; secret: string }>(
`/admin/providers/${encodeURIComponent(provider)}/keys/${encodeURIComponent(label)}/secret`,
{ method: "GET" },
);
export const addProvider = (body: {
name: string;
provider_type: string;
base_url?: string;
label?: string;
key: string;
}) => api<{ name: string }>("/admin/providers", { method: "POST", body: JSON.stringify(body) });
export const deleteProvider = (name: string) =>
api<{ deleted: boolean; name: string }>(
`/admin/providers/${encodeURIComponent(name)}`,
{ method: "DELETE" },
);
export const patchProvider = (
name: string,
patch: { name?: string; base_url?: string; provider_type?: string;
round_robin?: boolean; alias_id?: string | null },
) =>
api<Provider>(`/admin/providers/${encodeURIComponent(name)}`, {
method: "PATCH",
body: JSON.stringify(patch),
});
export const deleteProviderKey = (provider: string, label: string) =>
api<{ deleted: boolean; label: string }>(
`/admin/providers/${encodeURIComponent(provider)}/keys/${encodeURIComponent(label)}`,
{ method: "DELETE" },
);
export const getModels = () => api<ModelsResponse>("/admin/models");
export const updateAliases = (body: {
set: Record<string, string | ModelAliasEntry>;
unset: string[];
}) =>
api<{ aliases: Record<string, string | ModelAliasEntry> }>("/admin/aliases", {
method: "POST",
body: JSON.stringify(body),
});
export const patchModelGroup = (
group: string,
patch: { weights?: Record<string, number>; strategy?: string },
) =>
api<{ group: string }>(`/admin/model-groups/${encodeURIComponent(group)}`, {
method: "PATCH",
body: JSON.stringify(patch),
});
export const fetchProviderModels = (provider: string) =>
api<{ models: UpstreamModel[] }>(
`/admin/providers/${encodeURIComponent(provider)}/models`,
);
export const fetchClineModels = () =>
api<{ models: UpstreamModel[] }>("/admin/cline/models");
// Global Cline default-model settings — a list of model ids that should
// be auto-deployed to every Cline account. Persists across restarts and
// auto-applies to providers added at runtime. See backend
// ``/admin/cline/settings`` and tests/test_cline_global_model.py.
export interface ClineSettingsResponse {
default_models: string[];
}
export const getClineSettings = () =>
api<ClineSettingsResponse>("/admin/cline/settings");
export const putClineSettings = (default_models: string[]) =>
api<ClineSettingsResponse>("/admin/cline/settings", {
method: "PUT",
body: JSON.stringify({ default_models }),
});
export const deleteClineDefaultModel = (modelId: string) =>
api<{ default_models: string[] }>(
`/admin/cline/settings/default-models/${encodeURIComponent(modelId)}`,
{ method: "DELETE" },
);
export const addDeployment = (
group: string,
body: { provider: string; model_id: string; weight?: number },
) =>
api<{ deployment: DeploymentInfo }>(
`/admin/model-groups/${encodeURIComponent(group)}/deployments`,
{ method: "POST", body: JSON.stringify(body) },
);
// provider/model_id travel as query params, not path segments: model ids
// contain slashes (e.g. z-ai/glm-5.2) that a path param would mangle.
export const deleteDeployment = (group: string, provider: string, modelId: string) =>
api<{ deleted: boolean; group: string; provider: string; model_id: string;
group_emptied: boolean }>(
`/admin/model-groups/${encodeURIComponent(group)}/deployments`
+ `?provider=${encodeURIComponent(provider)}`
+ `&model_id=${encodeURIComponent(modelId)}`,
{ method: "DELETE" },
);
export const listKeys = () => api<{ keys: VirtualKey[] }>("/admin/keys");
export const generateKey = (body: {
name: string;
custom_key?: string;
models?: string[];
max_budget?: number | null;
rpm?: number | null;
tpm?: number | null;
ttl_seconds?: number | null;
}) =>
api<{ key: string; id: string; note: string }>("/admin/keys/generate", {
method: "POST",
body: JSON.stringify(body),
});
export const patchKey = (
id: string,
patch: {
max_budget?: number | null;
rpm?: number | null;
tpm?: number | null;
models?: string[];
expires_at?: number | null;
},
) =>
api<{ key: VirtualKey }>(`/admin/keys/${encodeURIComponent(id)}`, {
method: "PATCH",
body: JSON.stringify(patch),
});
export const disableKey = (id: string, disabled: boolean) =>
api<{ key_id: string; disabled: boolean }>(`/admin/keys/${encodeURIComponent(id)}/disable`, {
method: "POST",
body: JSON.stringify({ disabled }),
});
export const deleteKey = (id: string) =>
api<{ deleted: boolean }>(`/admin/keys/${encodeURIComponent(id)}`, { method: "DELETE" });
export const getOverview = (minutes: number) =>
api<OverviewStats>(`/admin/stats/overview?minutes=${minutes}`);
export const getTimeseries = (metric: TimeseriesMetric, minutes: number) =>
api<TimeseriesResponse>(
`/admin/stats/timeseries?bucket=minute&metric=${metric}&minutes=${minutes}`,
);
/** Rows per request the console asks for, and the page size the export walk
* below advances by. The endpoint's own ceiling is 50 000 (a runaway-caller
* guard), so this leaves room to page rather than sitting on the limit. */
const LOG_PAGE_LIMIT = 10_000;
/** Rows the export walk will load before it stops and says so. A gateway with
* more history than this still exports — it just reports the file as partial
* rather than fetching unboundedly in one click. */
const LOG_EXPORT_CEILING = 200_000;
/** Request-log rows, newest-first.
*
* The zero-argument call keeps its exact historical request
* (`/admin/logs/requests?limit=10000`) so existing callers are unchanged.
* Pass `minutes` to push the lookback window server-side (0 = all-time) and
* `offset` to page; both are only appended when actually provided.
*
* `signal` is react-query's `QueryFunctionContext.signal`, forwarded so a
* superseded query (a fast range switch) aborts its in-flight fetch instead of
* racing the newer one to populate the cache. */
export const getRequestLogs = (opts?: {
minutes?: number;
offset?: number;
limit?: number;
signal?: AbortSignal;
}) => {
const params = new URLSearchParams({
limit: String(opts?.limit ?? LOG_PAGE_LIMIT),
});
if (opts?.minutes !== undefined) params.set("minutes", String(opts.minutes));
if (opts?.offset !== undefined) params.set("offset", String(opts.offset));
return api<{ logs: RequestLogEntry[] }>(
`/admin/logs/requests?${params.toString()}`,
{ signal: opts?.signal },
);
};
/** Every log row the gateway will hand out, paging until the server runs dry.
*
* `getRequestLogs` fetches one page — enough for the pages the console
* *renders*, which is why they pass a limit and stop. An export is the one
* caller that has to agree with the database instead of with the viewport: a
* CSV built from the rendered page covers only the newest rows and, before
* this existed, said nothing about the rest. So the walk advances `offset`
* until a short page ends it.
*
* Returns `truncated: true` when `LOG_EXPORT_CEILING` stopped the walk, so the
* caller can label the file partial — an export that cannot finish must not
* look like one that did. */
export async function getAllRequestLogs(opts?: {
minutes?: number;
signal?: AbortSignal;
}): Promise<{ logs: RequestLogEntry[]; truncated: boolean }> {
const logs: RequestLogEntry[] = [];
for (let offset = 0; ; offset += LOG_PAGE_LIMIT) {
const page = (await getRequestLogs({
minutes: opts?.minutes,
offset,
// Stated rather than inherited from the default: the walk's step and the
// size it asks for have to be the same number, and a silent change to one
// would turn every page short and end the walk early.
limit: LOG_PAGE_LIMIT,
signal: opts?.signal,
})).logs;
logs.push(...page);
if (page.length < LOG_PAGE_LIMIT) return { logs, truncated: false };
if (logs.length >= LOG_EXPORT_CEILING) return { logs, truncated: true };
}
}
export const getPricing = () =>
api<{ models: ModelPrice[] }>("/admin/pricing");
/** Exact server-recorded metrics for one completed request. */
export const getPlaygroundMetrics = (requestId: string, signal?: AbortSignal) =>
api<PlaygroundMetrics>(
`/admin/logs/requests/${encodeURIComponent(requestId)}/metrics`,
{ signal },
);
/** `provider` scopes the price to one provider (an account name or a provider
* type). Omit it to write the base rate that covers every provider. */
export const upsertPricing = (
modelId: string,
body: {
input_per_1m: number;
output_per_1m: number;
cache_read_per_1m?: number;
cache_creation_per_1m?: number;
max_input_tokens?: number;
max_output_tokens?: number;
mode?: string;
},
provider?: string,
) =>
api<ModelPrice & { retroactive?: { applied: boolean; keys: number; total_delta: number } }>(
`/admin/pricing/${encodeURIComponent(modelId)}${providerQuery(provider)}`,
{
method: "PUT",
body: JSON.stringify(body),
},
);
export const deletePricing = (modelId: string, provider?: string) =>
api<{ deleted: boolean; model_id: string }>(
`/admin/pricing/${encodeURIComponent(modelId)}${providerQuery(provider)}`,
{ method: "DELETE" },
);
/** Scope travels as a query param, not a path segment: model ids contain
* slashes and the route is already `{model_id:path}`. */
function providerQuery(provider?: string): string {
return provider ? `?provider=${encodeURIComponent(provider)}` : "";
}
export const getProxyLogs = () =>
api<{ logs: ProxyLogEntry[] }>("/admin/logs/proxy");
export const getAlertRules = () => api<{ rules: AlertRule[] }>("/admin/alert-rules");
export const putAlertRules = (rules: AlertRule[]) =>
api<{ rules: AlertRule[] }>("/admin/alert-rules", {
method: "PUT",
body: JSON.stringify({ rules }),
});
// -- session auth + user + public catalog helpers ----------------------------
export const getMe = () => api<{ user: User | null }>("/auth/me");
export const signupUser = (body: { username: string; password: string }) =>
api<{ user: User; playground_key?: string }>("/auth/signup", {
method: "POST",
body: JSON.stringify(body),
credentials: "include",
});
export const loginUser = (body: { username: string; password: string }) =>
api<{ user: User; playground_key?: string }>("/auth/login", {
method: "POST",
body: JSON.stringify(body),
credentials: "include",
});
export const loginMaster = (body: { master_key: string }) =>
api<{ user: User; playground_key?: string }>("/auth/login", {
method: "POST",
body: JSON.stringify(body),
credentials: "include",
});
export const logoutSession = () =>
api<{ ok: true }>("/auth/logout", { method: "POST", credentials: "include" });
export const getUsers = () =>
api<{ users: (User & { disabled: boolean; created_at: number })[] }>(
"/admin/users",
);
export const patchUser = (
id: string,
body: { role?: string; disabled?: boolean },
) =>
api<User>(`/admin/users/${encodeURIComponent(id)}`, {
method: "PATCH",
body: JSON.stringify(body),
credentials: "include",
});
export const getPublicModels = () =>
api<{ groups: PublicModelGroup[]; aliases: Record<string, string> }>(
"/public/models",
);
// -- Cline OAuth (paste-code flow) -------------------------------------------
// The backend also exposes POST /admin/cline/oauth/auto-connect, but Cline's
// Google OAuth ignores callback_url (see pages/OAuthProviders.tsx), so every
// UI drives the paste-code flow below and that route has no SPA caller.
export const clineLoginUrl = (callbackUrl: string) =>
api<ClineLoginUrlResponse>("/admin/cline/oauth/login-url", {
method: "POST",
body: JSON.stringify({ callback_url: callbackUrl }),
});
export const clineConnect = (provider: string, code: string) =>
api<ClineConnectResponse>("/admin/cline/oauth/connect", {
method: "POST",
body: JSON.stringify({ provider, code }),
});
export const clineStatus = (provider: string) =>
api<ClineStatusResponse>(
`/admin/cline/oauth/status?provider=${encodeURIComponent(provider)}`,
);
export const clineRefresh = (provider: string) =>
api<ClineRefreshResponse>("/admin/cline/oauth/refresh", {
method: "POST",
body: JSON.stringify({ provider }),
});
export const clineDisconnect = (provider: string) =>
api<ClineDisconnectResponse>("/admin/cline/oauth/disconnect", {
method: "DELETE",
body: JSON.stringify({ provider }),
});
// -- Hermes (Nous Portal) OAuth (device-code flow) ---------------------------
export const hermesDeviceCode = (provider: string) =>
api<HermesDeviceCodeResponse>(
`/admin/hermes/oauth/device-code?provider=${encodeURIComponent(provider)}`,
{ method: "POST" },
);
export const hermesPoll = (state: string) =>
api<HermesPollResponse>("/admin/hermes/oauth/poll", {
method: "POST",
body: JSON.stringify({ state }),
// A rejected device code is a 401 about the Nous grant, not the admin key.
upstream401: true,
});
export const hermesStatus = (provider: string) =>
api<HermesStatusResponse>(
`/admin/hermes/oauth/status?provider=${encodeURIComponent(provider)}`,
);
// ``key_label`` targets one account in the pool; omitting it makes the server
// pick the first managed account (refresh) or remove every managed account
// (disconnect) — see wiwi/server/app.py's /admin/hermes/oauth/{refresh,disconnect}.
export const hermesRefresh = (provider: string, keyLabel?: string) =>
api<HermesRefreshResponse>("/admin/hermes/oauth/refresh", {
method: "POST",
body: JSON.stringify({ provider, ...(keyLabel ? { key_label: keyLabel } : {}) }),
// A terminal grant answers 401 "re-login required" — that is the state the
// operator is trying to escape from, so it must not read as "your admin key
// is invalid" (see UpstreamAuthError).
upstream401: true,
});
export const hermesDisconnect = (provider: string, keyLabel?: string) =>
api<HermesDisconnectResponse>("/admin/hermes/oauth/disconnect", {
method: "DELETE",
body: JSON.stringify({ provider, ...(keyLabel ? { key_label: keyLabel } : {}) }),
});
// -- WorkBuddy accounts (auths/ JSON import/export) ---------------------------
export const workbuddyAccounts = () =>
api<WorkBuddyAccountsResponse>("/admin/workbuddy/accounts");
export const workbuddyImport = (
provider: string,
accounts: WorkBuddyAuthFile[] | WorkBuddyAuthFile,
) =>
api<WorkBuddyImportResponse>("/admin/workbuddy/import", {
method: "POST",
body: JSON.stringify({ provider, accounts }),
});
export const workbuddyExport = (provider?: string) => {
const q = provider ? `?provider=${encodeURIComponent(provider)}` : "";
return api<WorkBuddyExportResponse>(`/admin/workbuddy/export${q}`);
};
export const workbuddyRefresh = (provider: string, label: string) =>
api<WorkBuddyRefreshResponse>("/admin/workbuddy/refresh", {
method: "POST",
body: JSON.stringify({ provider, label }),
});
/** Open a browser-login session. Returns the upstream login URL to hand the user. */
export const workbuddyLoginStart = (provider: string, realm: "cn" | "global") =>
api<WorkBuddyLoginStartResponse>("/admin/workbuddy/login/start", {
method: "POST",
body: JSON.stringify({ provider, realm }),
});
/** Poll an open login session; ``{pending:true}`` until the user approves. */
export const workbuddyLoginPoll = (state: string) =>
api<WorkBuddyLoginPollResponse>("/admin/workbuddy/login/poll", {
method: "POST",
body: JSON.stringify({ state }),
});
// -- Provider backup (full export/import with secrets + deployments) -----------
export const exportProviders = (provider?: string) => {
const q = provider ? `?provider=${encodeURIComponent(provider)}` : "";
return api<ProviderExportResponse>(`/admin/providers/export${q}`);
};
export const importProviders = (providers: ProviderBackup[]) =>
api<ProviderImportResponse>("/admin/providers/import", {
method: "POST",
body: JSON.stringify({ providers }),
});
// -- Audit log (admin only) ----------------------------------------------------
/** Newest-first admin mutation trail. The endpoint caps `limit` at 5000. */
export const getAuditLogs = (limit = 200) =>
api<{ logs: AuditLogEntry[] }>(`/admin/logs/audit?limit=${limit}`);