File size: 24,032 Bytes
928fda2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575d5bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
928fda2
 
 
 
 
575d5bd
928fda2
 
 
 
 
 
8a2cc31
4f29dcb
 
 
 
928fda2
 
575d5bd
 
 
 
 
928fda2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3ce3c5
928fda2
367e31c
928fda2
 
 
 
 
575d5bd
 
 
 
 
928fda2
 
 
 
 
 
 
ce7f455
928fda2
 
 
 
 
 
 
 
 
575d5bd
 
928fda2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebeef74
928fda2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10cdd7b
928fda2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575d5bd
 
 
 
 
 
 
 
 
 
99d4eee
 
 
 
 
 
 
 
 
 
 
 
 
575d5bd
99d4eee
 
575d5bd
 
 
99d4eee
 
 
 
 
 
 
928fda2
575d5bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
928fda2
 
 
ce7f455
 
 
 
 
 
 
928fda2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d148812
928fda2
 
 
 
 
4f29dcb
 
 
 
 
928fda2
d148812
928fda2
 
 
4f29dcb
928fda2
 
 
d148812
928fda2
 
 
4f29dcb
928fda2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367e31c
 
 
 
 
 
 
 
 
 
 
 
 
928fda2
367e31c
928fda2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575d5bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
928fda2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575d5bd
 
 
 
 
 
 
 
 
 
 
 
 
 
928fda2
 
 
 
 
 
 
 
 
 
 
 
c3ce3c5
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
// 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 {
    // String(e) leaks "TypeError: Failed to fetch" into user-facing alerts;
    // the cause is always the same for the operator β€” the gateway is unreachable.
    throw new ApiError(0, "Cannot reach the gateway. Check your connection and try again.");
  }
  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,
  ClineAutoConnectResponse,
  ClineConnectResponse,
  ClineDisconnectResponse,
  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; secret?: string },
) =>
  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; enabled?: 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 }>("/auth/signup", {
    method: "POST",
    body: JSON.stringify(body),
    credentials: "include",
  });

// Login 401s are about the credential being submitted, not an expired admin
// session β€” keep the server's wording ("invalid credentials", "invalid
// master key") instead of the generic bearer message. UpstreamAuthError is
// the existing no-session-redirect escape hatch; nothing here is upstream,
// but the semantics (401 without the global sign-out bounce) are identical.
export const loginUser = (body: { username: string; password: string }) =>
  api<{ user: User }>("/auth/login", {
    method: "POST",
    body: JSON.stringify(body),
    credentials: "include",
    upstream401: true,
  });

export const loginMaster = (body: { master_key: string }) =>
  api<{ user: User }>("/auth/login", {
    method: "POST",
    body: JSON.stringify(body),
    credentials: "include",
    upstream401: true,
  });

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 --------------------------------------------------------------
// The connect UIs open the login page through the redirect pipeline:
// POST /admin/cline/oauth/auto-connect mints an auth_url whose callback_url is
// wiwi's own /cline/oauth/callback, guarded by a single-use state token. If
// Cline honours callback_url, the browser returns to `returnPath` with
// ?cline_connected=1 (banner hooks on the accounts and provider-detail pages
// read it). Cline's Google OAuth currently ignores callback_url and lands on
// app.cline.bot/auth/callback?code=… instead β€” the paste-code fallback in the
// same dialogs still completes the connect, which is why it is always shown.
// POST /admin/cline/oauth/login-url (plain link, no pending session) remains
// backend-side but has no SPA caller.
export const clineAutoConnect = (provider: string, returnPath: string) =>
  api<ClineAutoConnectResponse>("/admin/cline/oauth/auto-connect", {
    method: "POST",
    body: JSON.stringify({ provider, return_path: returnPath }),
  });

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}`);