dsh-cliproxyapi-pro 1.9.0 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.en.md +23 -407
  3. package/README.md +23 -407
  4. package/lib/client.js +46 -20
  5. package/lib/host/accounts.js +176 -0
  6. package/lib/host/apply/agent-tool.js +406 -0
  7. package/lib/host/apply/commands.js +122 -0
  8. package/lib/host/apply/controller.js +105 -0
  9. package/lib/host/apply/http-routes.js +273 -0
  10. package/lib/host/apply/image-jobs.js +171 -0
  11. package/lib/host/apply/index.js +41 -0
  12. package/lib/host/apply/interpret.js +72 -0
  13. package/lib/host/apply/lifecycle.js +34 -0
  14. package/lib/host/apply/media-failures.js +68 -0
  15. package/lib/host/apply/media-service.js +202 -0
  16. package/lib/host/apply/quota-service.js +42 -0
  17. package/lib/host/apply/references.js +43 -0
  18. package/lib/host/apply/session-status.js +104 -0
  19. package/lib/host/apply/state.js +78 -0
  20. package/lib/host/apply/updates.js +55 -0
  21. package/lib/host/apply/video-command.js +152 -0
  22. package/lib/host/apply/video-edit.js +253 -0
  23. package/lib/host/apply/video-jobs.js +206 -0
  24. package/lib/host/apply-utils.js +39 -0
  25. package/lib/host/config.js +205 -0
  26. package/lib/host/controller.js +435 -0
  27. package/lib/host/discovery.js +295 -0
  28. package/lib/host/http-gate.js +144 -0
  29. package/lib/host/models.js +102 -0
  30. package/lib/host/mount-guard.js +56 -0
  31. package/lib/host/routes.js +165 -0
  32. package/lib/host/runtime.js +445 -0
  33. package/lib/host/state-store.js +39 -0
  34. package/lib/host/status-text.js +93 -0
  35. package/lib/index.js +17 -4417
  36. package/lib/media/agent-tool.js +255 -0
  37. package/lib/media/choice.js +83 -0
  38. package/lib/media/classify.js +65 -0
  39. package/lib/media/codec/fit.js +76 -0
  40. package/lib/media/codec/jpeg.js +158 -0
  41. package/lib/media/codec/png.js +102 -0
  42. package/lib/media/commands/parsing.js +269 -0
  43. package/lib/media/constants.js +46 -0
  44. package/lib/media/diagnose.js +134 -0
  45. package/lib/media/images.js +165 -0
  46. package/lib/media/index.js +29 -0
  47. package/lib/media/interpret.js +126 -0
  48. package/lib/media/job-store.js +99 -0
  49. package/lib/media/mp4.js +44 -0
  50. package/lib/media/output-files.js +59 -0
  51. package/lib/media/session-store.js +293 -0
  52. package/lib/media/settings.js +255 -0
  53. package/lib/media/util.js +45 -0
  54. package/lib/media/video.js +326 -0
  55. package/lib/quota/auth-state.js +33 -0
  56. package/lib/quota/constants.js +86 -0
  57. package/lib/quota/controller.js +467 -0
  58. package/lib/quota/helpers.js +325 -0
  59. package/lib/quota/index.js +19 -0
  60. package/lib/quota/management.js +216 -0
  61. package/lib/quota/matching.js +143 -0
  62. package/lib/quota/parsers.js +352 -0
  63. package/lib/quota/probes/billing.js +80 -0
  64. package/lib/quota/probes/google.js +120 -0
  65. package/lib/quota/probes/oauth.js +27 -0
  66. package/lib/quota/probes/plugin.js +18 -0
  67. package/lib/updater/constants.js +23 -0
  68. package/lib/updater/errors.js +8 -0
  69. package/lib/updater/index.js +11 -0
  70. package/lib/updater/registry.js +83 -0
  71. package/lib/updater/settings.js +45 -0
  72. package/lib/updater/store.js +23 -0
  73. package/lib/updater/updater.js +148 -0
  74. package/lib/updater/verify.js +110 -0
  75. package/lib/updater/version.js +31 -0
  76. package/locale/en.json +1 -1
  77. package/locale/zh.json +1 -1
  78. package/package.json +6 -9
  79. package/lib/media.js +0 -2542
  80. package/lib/quota.js +0 -1748
  81. package/lib/updater.js +0 -443
@@ -0,0 +1,325 @@
1
+ // Shared quota value normalization, window construction, and safe credential metadata.
2
+ import { STATUS_MESSAGE_MAX, W5H, W1D, W7D, KIND_RANK, PLAN_LABELS } from "./constants.js";
3
+
4
+ //#region Helpers
5
+
6
+ class QuotaError extends Error {
7
+ constructor(code, status) {
8
+ super(`quota: ${code}${status === undefined ? "" : ` (${status})`}`);
9
+ this.name = "QuotaError";
10
+ this.code = code;
11
+ if (status !== undefined) this.status = status;
12
+ }
13
+ }
14
+
15
+ const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
16
+ const text = (v) => (typeof v === "string" ? v.trim() : "");
17
+ const firstText = (...values) => {
18
+ for (const v of values) {
19
+ const t = typeof v === "number" && Number.isFinite(v) ? String(v) : text(v);
20
+ if (t !== "") return t;
21
+ }
22
+ return "";
23
+ };
24
+ const numberOrNull = (v) => {
25
+ if (typeof v === "number" && Number.isFinite(v)) return v;
26
+ if (typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v))) return Number(v);
27
+ return null;
28
+ };
29
+ const flagOf = (v) => {
30
+ if (v === true || v === 1) return true;
31
+ if (v === false || v === 0) return false;
32
+ if (typeof v === "string") {
33
+ const s = v.trim().toLowerCase();
34
+ if (["true", "1", "yes", "on"].includes(s)) return true;
35
+ if (["false", "0", "no", "off"].includes(s)) return false;
36
+ }
37
+ return undefined;
38
+ };
39
+ const clampPct = (v) => Math.max(0, Math.min(100, v));
40
+ const roundPct = (v) => (v === null ? null : Math.round(clampPct(v) * 100) / 100);
41
+ const getPath = (obj, path) => {
42
+ let cur = obj;
43
+ for (const key of path) {
44
+ if (cur === null || typeof cur !== "object") return undefined;
45
+ cur = cur[key];
46
+ }
47
+ return cur;
48
+ };
49
+
50
+ function fractionPercent(value) {
51
+ const raw = text(value);
52
+ if (raw.endsWith("%")) {
53
+ const n = Number(raw.slice(0, -1));
54
+ return Number.isFinite(n) ? clampPct(n) : null;
55
+ }
56
+ const n = numberOrNull(value);
57
+ if (n === null) return null;
58
+ return n > 1 && n <= 100 ? clampPct(n) : clampPct(n * 100);
59
+ }
60
+
61
+ function kindFromText(...values) {
62
+ const s = values.map((v) => text(v).toLowerCase()).filter(Boolean).join(" ");
63
+ if (s === "") return "";
64
+ if (/(?:^|[^0-9])5\s*[-_ ]?(?:h|hr|hour|hours)\b|five\s*[-_ ]?hour/.test(s)) return "5h";
65
+ if (/(?:^|[^0-9])7\s*[-_ ]?(?:d|day|days)\b|weekly|week/.test(s)) return "7d";
66
+ if (/(?:28|29|30|31)\s*[-_ ]?(?:d|day|days)\b|monthly|month/.test(s)) return "30d";
67
+ if (/daily|(?:^|[^0-9])1\s*[-_ ]?(?:d|day)\b|\bday\b/.test(s)) return "1d";
68
+ return "";
69
+ }
70
+
71
+ function kindFromSeconds(value) {
72
+ const seconds = numberOrNull(value);
73
+ if (seconds === null || seconds <= 0) return "";
74
+ if (seconds === W5H) return "5h";
75
+ if (seconds === W7D) return "7d";
76
+ if (seconds >= 28 * W1D && seconds <= 31 * W1D) return "30d";
77
+ if (seconds === W1D) return "1d";
78
+ return "";
79
+ }
80
+
81
+ function durationSeconds(value, unit) {
82
+ const n = numberOrNull(value);
83
+ if (n === null || n <= 0) return null;
84
+ const u = text(unit).toLowerCase().replace(/^time_unit_/, "");
85
+ if (u.startsWith("second")) return n;
86
+ if (u.startsWith("hour")) return n * 3600;
87
+ if (u.startsWith("day")) return n * W1D;
88
+ if (u.startsWith("week")) return n * W7D;
89
+ return n * 60;
90
+ }
91
+
92
+ /** Infers a window kind from the reset distance (Google per-model buckets carry no window metadata). */
93
+ function kindFromReset(resetAt, nowMs) {
94
+ if (resetAt === null) return "other";
95
+ const delta = Date.parse(resetAt) - nowMs;
96
+ if (!Number.isFinite(delta)) return "other";
97
+ return delta <= 8 * 3600 * 1000 ? "5h" : delta <= 8 * W1D * 1000 ? "7d" : "other";
98
+ }
99
+
100
+ function isoFromUnix(value) {
101
+ const n = numberOrNull(value);
102
+ if (n === null || n <= 0) return null;
103
+ const ms = n > 1e12 ? n : n * 1000;
104
+ const d = new Date(ms);
105
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
106
+ }
107
+
108
+ function isoFromString(value) {
109
+ const raw = text(value);
110
+ if (raw === "") return null;
111
+ if (/^\d+(?:\.\d+)?$/.test(raw)) return isoFromUnix(raw);
112
+ const ms = Date.parse(raw);
113
+ return Number.isNaN(ms) ? null : new Date(ms).toISOString();
114
+ }
115
+
116
+ function isoFromRelative(seconds, nowMs) {
117
+ const n = numberOrNull(seconds);
118
+ if (n === null || n < 0) return null;
119
+ return new Date(nowMs + n * 1000).toISOString();
120
+ }
121
+
122
+ function makeWindow({ id, kind, label, group, remainingPercent, resetAt, modelIds, modelPrefixes }) {
123
+ const row = {
124
+ id,
125
+ kind: KIND_RANK[kind] === undefined ? "other" : kind,
126
+ label: text(label),
127
+ remainingPercent: roundPct(remainingPercent ?? null),
128
+ resetAt: resetAt ?? null,
129
+ };
130
+ if (text(group) !== "") row.group = text(group);
131
+ if (Array.isArray(modelIds) && modelIds.length > 0) row.modelIds = [...new Set(modelIds)];
132
+ if (Array.isArray(modelPrefixes) && modelPrefixes.length > 0) row.modelPrefixes = [...modelPrefixes];
133
+ return row;
134
+ }
135
+
136
+ function sortWindows(rows) {
137
+ return rows
138
+ .map((row, index) => ({ row, index }))
139
+ .sort((a, b) => KIND_RANK[a.row.kind] - KIND_RANK[b.row.kind] || a.index - b.index)
140
+ .map(({ row }) => row);
141
+ }
142
+
143
+ /** Keeps the most conservative row for duplicate keys. */
144
+ function dedupeWindows(rows, keyOf) {
145
+ const map = new Map();
146
+ for (const row of rows) {
147
+ const key = keyOf(row);
148
+ const prev = map.get(key);
149
+ if (prev === undefined) {
150
+ map.set(key, row);
151
+ } else if (row.remainingPercent !== null && (prev.remainingPercent === null || row.remainingPercent < prev.remainingPercent)) {
152
+ map.set(key, { ...prev, remainingPercent: row.remainingPercent, resetAt: prev.resetAt ?? row.resetAt });
153
+ }
154
+ }
155
+ return [...map.values()];
156
+ }
157
+
158
+ function normalizeProvider(value) {
159
+ const p = text(value).toLowerCase();
160
+ if (p === "anthropic" || p === "claude-code") return "claude";
161
+ if (p === "grok" || p === "x-ai" || p === "x.ai") return "xai";
162
+ if (p === "zai" || p === "zhipu" || p === "chatglm") return "glm";
163
+ if (p === "moonshot" || p === "kimi-ai" || p === "kimi_ai") return "kimi";
164
+ return p;
165
+ }
166
+
167
+ function normalizePlanToken(value) {
168
+ const raw = text(value);
169
+ if (raw === "") return "";
170
+ const key = raw.toLowerCase().replace(/[\s_]+/g, "-");
171
+ if (PLAN_LABELS[key] !== undefined) return key;
172
+ if (/ultra-?lite/.test(key)) return "ultra-lite";
173
+ if (/ultra/.test(key)) return "ultra";
174
+ if (/(^|-)pro($|-)/.test(key)) return "pro";
175
+ if (/(^|-)free($|-)/.test(key)) return "free";
176
+ if (/plus/.test(key)) return "plus";
177
+ if (/(^|-)max($|-)/.test(key)) return "max";
178
+ if (/team/.test(key)) return "team";
179
+ if (/enterprise/.test(key)) return "enterprise";
180
+ return "";
181
+ }
182
+
183
+ const PLAN_FIELD = /plan|tier|subscription|membership/i;
184
+
185
+ function planValue(value, field) {
186
+ if (typeof value === "string") {
187
+ const raw = text(value);
188
+ if (raw === "") return "";
189
+ const token = normalizePlanToken(raw);
190
+ if (token !== "") return PLAN_LABELS[token];
191
+ return PLAN_FIELD.test(field) && raw.length <= 40 && !raw.includes("@") ? raw : "";
192
+ }
193
+ if (!isObj(value)) return "";
194
+ for (const key of ["plan", "plan_type", "planType", "tier_name", "tierName", "tier_id", "tierId"]) {
195
+ const resolved = planValue(value[key], key);
196
+ if (resolved !== "") return resolved;
197
+ }
198
+ if (PLAN_FIELD.test(field)) {
199
+ for (const key of ["name", "id"]) {
200
+ const resolved = planValue(value[key], `${field}.${key}`);
201
+ if (resolved !== "") return resolved;
202
+ }
203
+ }
204
+ return "";
205
+ }
206
+
207
+ const PLAN_PATHS = [
208
+ ["paidTier"], ["paid_tier"], ["subscription"], ["plan"], ["plan_type"], ["planType"],
209
+ ["chatgpt_plan_type"], ["https://api.openai.com/auth", "chatgpt_plan_type"],
210
+ ["tier"], ["tier_name"], ["tierName"], ["tier_id"], ["tierId"], ["currentTier"], ["current_tier"],
211
+ ["account", "subscription"], ["account", "plan"], ["account", "plan_type"], ["account", "tier"],
212
+ ["organization", "subscription"], ["organization", "plan"],
213
+ ["metadata", "subscription"], ["metadata", "plan"], ["metadata", "plan_type"], ["metadata", "tier"],
214
+ ["attributes", "subscription"], ["attributes", "plan"], ["attributes", "plan_type"], ["attributes", "tier"],
215
+ ["account_type"],
216
+ ];
217
+
218
+ /** Plan label from auth-file / upstream payloads; paid tiers are checked before current/default tiers. */
219
+ function extractPlan(...sources) {
220
+ for (const source of sources) {
221
+ if (!isObj(source)) continue;
222
+ for (const path of PLAN_PATHS) {
223
+ const resolved = planValue(getPath(source, path), path.join("."));
224
+ if (resolved !== "") return resolved;
225
+ }
226
+ }
227
+ return "";
228
+ }
229
+
230
+ function claimsOf(value) {
231
+ if (isObj(value)) return value;
232
+ const raw = text(value);
233
+ if (raw === "") return null;
234
+ try {
235
+ if (raw.startsWith("{")) return JSON.parse(raw);
236
+ const parts = raw.split(".");
237
+ if (parts.length < 2) return null;
238
+ const parsed = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
239
+ return isObj(parsed) ? parsed : null;
240
+ } catch {
241
+ return null;
242
+ }
243
+ }
244
+
245
+ function entryClaims(entry) {
246
+ return [entry.id_token, getPath(entry, ["tokens", "id_token"]), getPath(entry, ["metadata", "id_token"]), getPath(entry, ["attributes", "id_token"])]
247
+ .map(claimsOf)
248
+ .filter((c) => c !== null);
249
+ }
250
+
251
+ function codexAccountId(entry) {
252
+ const direct = firstText(
253
+ entry.chatgpt_account_id,
254
+ entry.account_id,
255
+ getPath(entry, ["tokens", "account_id"]),
256
+ getPath(entry, ["tokens", "chatgpt_account_id"]),
257
+ getPath(entry, ["metadata", "account_id"]),
258
+ getPath(entry, ["attributes", "account_id"]),
259
+ );
260
+ if (direct !== "") return direct;
261
+ for (const claims of entryClaims(entry)) {
262
+ const id = firstText(claims.chatgpt_account_id, getPath(claims, ["https://api.openai.com/auth", "chatgpt_account_id"]));
263
+ if (id !== "") return id;
264
+ }
265
+ return "";
266
+ }
267
+
268
+ function projectIdOf(entry) {
269
+ return firstText(
270
+ entry.project_id,
271
+ entry.projectId,
272
+ getPath(entry, ["metadata", "project_id"]),
273
+ getPath(entry, ["metadata", "projectId"]),
274
+ getPath(entry, ["attributes", "project_id"]),
275
+ getPath(entry, ["attributes", "projectId"]),
276
+ getPath(entry, ["attributes", "gemini_virtual_project"]),
277
+ );
278
+ }
279
+
280
+ function shortMessage(value) {
281
+ const raw = typeof value === "string" ? value : "";
282
+ const cleaned = raw
283
+ .replace(/\s+/g, " ")
284
+ .replace(/\b(Bearer|Basic)\s+[^\s"',;]+/gi, "$1 [redacted]")
285
+ .replace(/\b(?:sk|rk|pk|xai|ya29)[-_.][A-Za-z0-9_\-.]{8,}/g, "[redacted]")
286
+ .trim();
287
+ return cleaned.length > STATUS_MESSAGE_MAX ? `${cleaned.slice(0, STATUS_MESSAGE_MAX - 1)}…` : cleaned;
288
+ }
289
+
290
+ function parseRecent(entry) {
291
+ let success = 0;
292
+ let failed = 0;
293
+ let seen = false;
294
+ const add = (item) => {
295
+ if (!isObj(item)) return;
296
+ const s = numberOrNull(item.success ?? item.success_count ?? item.successCount);
297
+ const f = numberOrNull(item.failed ?? item.failure ?? item.failed_count ?? item.failure_count ?? item.failedCount);
298
+ if (s === null && f === null) return;
299
+ seen = true;
300
+ success += Math.max(0, s ?? 0);
301
+ failed += Math.max(0, f ?? 0);
302
+ };
303
+ const raw = entry.recent_requests ?? entry.recentRequests;
304
+ if (Array.isArray(raw)) raw.forEach(add);
305
+ else add(raw);
306
+ if (!seen) add(entry);
307
+ return seen ? { success, failed } : undefined;
308
+ }
309
+
310
+ function credentialStatus(entry) {
311
+ if (flagOf(entry.disabled) === true) return "disabled";
312
+ const status = text(entry.status).toLowerCase();
313
+ if (status === "disabled") return "disabled";
314
+ if (flagOf(entry.unavailable) === true || status === "unavailable") return "unavailable";
315
+ if (status === "error" || status === "invalid" || status === "expired") return "error";
316
+ return "active";
317
+ }
318
+
319
+ function prefixOf(credential) {
320
+ return text(credential?.prefix).toLowerCase();
321
+ }
322
+
323
+ //#endregion
324
+
325
+ export { QuotaError, isObj, text, firstText, numberOrNull, flagOf, clampPct, roundPct, getPath, fractionPercent, kindFromText, kindFromSeconds, durationSeconds, kindFromReset, isoFromUnix, isoFromString, isoFromRelative, makeWindow, sortWindows, dedupeWindows, normalizeProvider, extractPlan, entryClaims, codexAccountId, projectIdOf, shortMessage, parseRecent, credentialStatus, prefixOf };
@@ -0,0 +1,19 @@
1
+ // Host-side quota engine public surface; implementation modules remain internal.
2
+ // Host-side quota engine for dsh-cliproxyapi-pro.
3
+ //
4
+ // Reads a CLIProxyAPI (CPA) server's credentials through its management API
5
+ // (`/v0/management/auth-files`, `/auth-files/models`, `/api-call` with
6
+ // `$TOKEN$` substitution) and queries the upstream quota endpoints that the
7
+ // providers expose (Codex, Claude, Antigravity, Gemini CLI, Kimi, xAI, Devin,
8
+ // Meta), plus CPA's own normalized quota route for plugin providers. It
9
+ // produces a JSON-serializable snapshot without keys, tokens or raw upstream
10
+ // bodies, and maps DSH model ids to the credentials that serve them.
11
+ //
12
+ // Upstream protocol knowledge follows the MIT-licensed "CliProxyAPI quota"
13
+ // browser plugin, re-implemented here for the host.
14
+
15
+ export { QUOTA_TTL_MS, DEFAULT_QUOTA_TIMEOUT_MS, DEFAULT_QUOTA_CONCURRENCY, MAX_QUOTA_RESPONSE_BYTES } from "./constants.js";
16
+ export { managementKeyRef, managementOrigin } from "./management.js";
17
+ export { matchCredentials } from "./matching.js";
18
+ export { AUTH_FAILURE_LIMIT, QUOTA_AUTH_STATE_VERSION, normalizeQuotaAuthState } from "./auth-state.js";
19
+ export { createQuotaController } from "./controller.js";
@@ -0,0 +1,216 @@
1
+ // Owns management origin/key refs, bounded HTTP transport, and management API reads.
2
+ import { MANAGEMENT_KEY_REF, MAX_QUOTA_RESPONSE_BYTES } from "./constants.js";
3
+ import { QuotaError, isObj, text, firstText, numberOrNull } from "./helpers.js";
4
+
5
+ //#region Management Origin & Key Ref
6
+
7
+ /** Credential ref for an account's CPA management key. */
8
+ export function managementKeyRef(accountId) {
9
+ const id = text(accountId);
10
+ if (id === "" || id === "default") return MANAGEMENT_KEY_REF;
11
+ return `${MANAGEMENT_KEY_REF}_${id.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
12
+ }
13
+
14
+ /** Management API base of an account endpoint: trailing slashes and a trailing `/v1` removed. */
15
+ export function managementOrigin(baseURL) {
16
+ let raw = text(baseURL);
17
+ if (raw === "") return undefined;
18
+ raw = raw.replace(/[?#].*$/, "").replace(/\/+$/, "").replace(/\/v1$/i, "").replace(/\/+$/, "");
19
+ let url;
20
+ try {
21
+ url = new URL(raw);
22
+ } catch {
23
+ return undefined;
24
+ }
25
+ if (url.protocol !== "http:" && url.protocol !== "https:") return undefined;
26
+ if (url.username !== "" || url.password !== "") return undefined;
27
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
28
+ }
29
+
30
+ //#endregion
31
+
32
+ //#region HTTP
33
+
34
+ async function readBounded(response, limit) {
35
+ const declared = Number(response.headers?.get?.("content-length"));
36
+ if (Number.isFinite(declared) && declared > limit) throw new QuotaError("invalid-response");
37
+ const body = response.body;
38
+ if (body !== null && body !== undefined && typeof body.getReader === "function") {
39
+ const reader = body.getReader();
40
+ const chunks = [];
41
+ let size = 0;
42
+ for (;;) {
43
+ const { done, value } = await reader.read();
44
+ if (done) break;
45
+ size += value.byteLength;
46
+ if (size > limit) {
47
+ reader.cancel().catch(() => {});
48
+ throw new QuotaError("invalid-response");
49
+ }
50
+ chunks.push(value);
51
+ }
52
+ const all = new Uint8Array(size);
53
+ let offset = 0;
54
+ for (const chunk of chunks) {
55
+ all.set(chunk, offset);
56
+ offset += chunk.byteLength;
57
+ }
58
+ return new TextDecoder().decode(all);
59
+ }
60
+ const raw = typeof response.text === "function" ? await response.text() : "";
61
+ if (Buffer.byteLength(raw, "utf8") > limit) throw new QuotaError("invalid-response");
62
+ return raw;
63
+ }
64
+
65
+ function parseJsonLoose(raw) {
66
+ if (typeof raw !== "string") return raw;
67
+ const s = raw.trim();
68
+ if (s === "") return null;
69
+ try {
70
+ return JSON.parse(s);
71
+ } catch {
72
+ return undefined;
73
+ }
74
+ }
75
+
76
+ /** Unwraps the occasional `{body|data|result}` wrapper or JSON-string nesting around an upstream payload. */
77
+ function unwrapNested(value) {
78
+ let current = value;
79
+ for (let depth = 0; depth < 4; depth += 1) {
80
+ if (typeof current === "string") {
81
+ const parsed = parseJsonLoose(current);
82
+ if (parsed === undefined || parsed === null) return current;
83
+ current = parsed;
84
+ }
85
+ if (!isObj(current)) return current;
86
+ if (["groups", "models", "currentTier", "paidTier", "cloudaicompanionProject", "config", "limits", "usage", "rate_limit", "rateLimit", "five_hour", "seven_day", "buckets", "account", "organization", "plan_type"].some((k) => Object.hasOwn(current, k))) return current;
87
+ const nested = current.body ?? current.data ?? current.result;
88
+ if (nested === undefined || nested === null || nested === current) return current;
89
+ current = nested;
90
+ }
91
+ return current;
92
+ }
93
+
94
+ function upstreamErrorCode(status) {
95
+ if (status === 401) return "upstream-unauthorized";
96
+ if (status === 403) return "upstream-forbidden";
97
+ if (status === 404) return "upstream-not-found";
98
+ if (status === 429) return "upstream-rate-limited";
99
+ return "upstream-http";
100
+ }
101
+
102
+ function createLimiter(limit) {
103
+ let active = 0;
104
+ const queue = [];
105
+ const next = () => {
106
+ while (active < limit && queue.length > 0) {
107
+ const job = queue.shift();
108
+ active += 1;
109
+ Promise.resolve()
110
+ .then(job.fn)
111
+ .then(job.resolve, job.reject)
112
+ .finally(() => {
113
+ active -= 1;
114
+ next();
115
+ });
116
+ }
117
+ };
118
+ return (fn, signal) => new Promise((resolve, reject) => {
119
+ const job = {
120
+ fn: () => {
121
+ if (signal?.aborted) throw new QuotaError("aborted");
122
+ return fn();
123
+ },
124
+ resolve,
125
+ reject,
126
+ };
127
+ queue.push(job);
128
+ next();
129
+ });
130
+ }
131
+
132
+ //#endregion
133
+
134
+ export function createManagement({ fetchImpl, timeoutMs }) {
135
+ // --- HTTP with per-request timeout, linked to the cycle signal ---
136
+ async function request(url, init, signal) {
137
+ const controller = new AbortController();
138
+ let timedOut = false;
139
+ const timer = setTimeout(() => {
140
+ timedOut = true;
141
+ controller.abort();
142
+ }, timeoutMs);
143
+ const onAbort = () => controller.abort();
144
+ if (signal.aborted) controller.abort();
145
+ else signal.addEventListener("abort", onAbort, { once: true });
146
+ // Settles even if the fetch implementation ignores the signal.
147
+ const aborted = new Promise((_, reject) => {
148
+ const fail = () => reject(new QuotaError(timedOut ? "timeout" : "aborted"));
149
+ if (controller.signal.aborted) fail();
150
+ else controller.signal.addEventListener("abort", fail, { once: true });
151
+ });
152
+ aborted.catch(() => {});
153
+ try {
154
+ const response = await Promise.race([fetchImpl(url, { ...init, signal: controller.signal, redirect: "error" }), aborted]);
155
+ const body = await Promise.race([readBounded(response, MAX_QUOTA_RESPONSE_BYTES), aborted]);
156
+ return { status: response.status, ok: response.ok, body };
157
+ } catch (error) {
158
+ if (timedOut) throw new QuotaError("timeout");
159
+ if (signal.aborted) throw new QuotaError("aborted");
160
+ if (error instanceof QuotaError) throw error;
161
+ throw new QuotaError("network");
162
+ } finally {
163
+ clearTimeout(timer);
164
+ signal.removeEventListener("abort", onAbort);
165
+ }
166
+ }
167
+
168
+ async function management(ctx, path, { method = "GET", body } = {}) {
169
+ const headers = { Accept: "application/json", Authorization: `Bearer ${ctx.key}` };
170
+ if (body !== undefined) headers["Content-Type"] = "application/json";
171
+ const response = await request(`${ctx.origin}${path}`, { method, headers, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }, ctx.signal);
172
+ if (response.status === 401) throw new QuotaError("unauthorized", 401);
173
+ if (response.status === 403) throw new QuotaError("forbidden", 403);
174
+ if (!response.ok) throw new QuotaError("http", response.status);
175
+ const json = parseJsonLoose(response.body);
176
+ if (json === undefined) throw new QuotaError("invalid-response");
177
+ return json;
178
+ }
179
+
180
+ /** POST /v0/management/api-call; returns the upstream JSON object or throws an upstream code. */
181
+ async function apiCall(ctx, payload) {
182
+ const response = await management(ctx, "/v0/management/api-call", { method: "POST", body: payload });
183
+ if (!isObj(response)) throw new QuotaError("invalid-response");
184
+ const status = numberOrNull(response.status_code ?? response.statusCode ?? response.status);
185
+ if (status === null) throw new QuotaError("invalid-response");
186
+ if (status < 200 || status >= 300) throw new QuotaError(upstreamErrorCode(status), status);
187
+ const body = unwrapNested(response.body ?? response.data);
188
+ if (!isObj(body)) throw new QuotaError("invalid-response");
189
+ return body;
190
+ }
191
+
192
+ async function loadModels(ctx, name, prefix, status) {
193
+ try {
194
+ const payload = await management(ctx, `/v0/management/auth-files/models?name=${encodeURIComponent(name)}`);
195
+ const rows = Array.isArray(payload) ? payload : Array.isArray(payload?.models) ? payload.models : null;
196
+ if (rows === null) return null;
197
+ const ids = [];
198
+ for (const row of rows) {
199
+ const id = typeof row === "string" ? text(row) : firstText(row?.id, row?.name);
200
+ if (id === "") continue;
201
+ const full = prefix !== "" && !id.toLowerCase().startsWith(`${prefix}/`) ? `${prefix}/${id}` : id;
202
+ if (!ids.includes(full)) ids.push(full);
203
+ }
204
+ // CPA drops inactive credentials from its model registry; an empty list then means "unknown".
205
+ if (ids.length === 0 && status !== "active") return null;
206
+ return ids;
207
+ } catch (error) {
208
+ if (error?.code === "aborted") throw error;
209
+ return null;
210
+ }
211
+ }
212
+
213
+ return { management, apiCall, loadModels };
214
+ }
215
+
216
+ export { createLimiter };