dsh-cliproxyapi-pro 1.8.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.
- package/CHANGELOG.md +23 -0
- package/README.en.md +38 -409
- package/README.md +38 -409
- package/lib/client.js +131 -28
- package/lib/host/accounts.js +176 -0
- package/lib/host/apply/agent-tool.js +406 -0
- package/lib/host/apply/commands.js +122 -0
- package/lib/host/apply/controller.js +105 -0
- package/lib/host/apply/http-routes.js +273 -0
- package/lib/host/apply/image-jobs.js +171 -0
- package/lib/host/apply/index.js +41 -0
- package/lib/host/apply/interpret.js +72 -0
- package/lib/host/apply/lifecycle.js +34 -0
- package/lib/host/apply/media-failures.js +68 -0
- package/lib/host/apply/media-service.js +202 -0
- package/lib/host/apply/quota-service.js +42 -0
- package/lib/host/apply/references.js +43 -0
- package/lib/host/apply/session-status.js +104 -0
- package/lib/host/apply/state.js +78 -0
- package/lib/host/apply/updates.js +55 -0
- package/lib/host/apply/video-command.js +152 -0
- package/lib/host/apply/video-edit.js +253 -0
- package/lib/host/apply/video-jobs.js +206 -0
- package/lib/host/apply-utils.js +39 -0
- package/lib/host/config.js +205 -0
- package/lib/host/controller.js +435 -0
- package/lib/host/discovery.js +295 -0
- package/lib/host/http-gate.js +144 -0
- package/lib/host/models.js +102 -0
- package/lib/host/mount-guard.js +56 -0
- package/lib/host/routes.js +165 -0
- package/lib/host/runtime.js +445 -0
- package/lib/host/state-store.js +39 -0
- package/lib/host/status-text.js +93 -0
- package/lib/index.js +17 -4330
- package/lib/media/agent-tool.js +255 -0
- package/lib/media/choice.js +83 -0
- package/lib/media/classify.js +65 -0
- package/lib/media/codec/fit.js +76 -0
- package/lib/media/codec/jpeg.js +158 -0
- package/lib/media/codec/png.js +102 -0
- package/lib/media/commands/parsing.js +269 -0
- package/lib/media/constants.js +46 -0
- package/lib/media/diagnose.js +134 -0
- package/lib/media/images.js +165 -0
- package/lib/media/index.js +29 -0
- package/lib/media/interpret.js +126 -0
- package/lib/media/job-store.js +99 -0
- package/lib/media/mp4.js +44 -0
- package/lib/media/output-files.js +59 -0
- package/lib/media/session-store.js +293 -0
- package/lib/media/settings.js +255 -0
- package/lib/media/util.js +45 -0
- package/lib/media/video.js +326 -0
- package/lib/quota/auth-state.js +33 -0
- package/lib/quota/constants.js +86 -0
- package/lib/quota/controller.js +467 -0
- package/lib/quota/helpers.js +325 -0
- package/lib/quota/index.js +19 -0
- package/lib/quota/management.js +216 -0
- package/lib/quota/matching.js +143 -0
- package/lib/quota/parsers.js +352 -0
- package/lib/quota/probes/billing.js +80 -0
- package/lib/quota/probes/google.js +120 -0
- package/lib/quota/probes/oauth.js +27 -0
- package/lib/quota/probes/plugin.js +18 -0
- package/lib/updater/constants.js +23 -0
- package/lib/updater/errors.js +8 -0
- package/lib/updater/index.js +11 -0
- package/lib/updater/registry.js +83 -0
- package/lib/updater/settings.js +45 -0
- package/lib/updater/store.js +23 -0
- package/lib/updater/updater.js +148 -0
- package/lib/updater/verify.js +110 -0
- package/lib/updater/version.js +31 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +6 -9
- package/lib/media.js +0 -2528
- package/lib/quota.js +0 -1646
- package/lib/updater.js +0 -443
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// Maps account model ids to credentials and builds snapshot lookup indexes.
|
|
2
|
+
import { isObj, text, normalizeProvider, prefixOf } from "./helpers.js";
|
|
3
|
+
|
|
4
|
+
//#region Model Matching
|
|
5
|
+
|
|
6
|
+
function modelFamily(modelId) {
|
|
7
|
+
const s = text(modelId).toLowerCase();
|
|
8
|
+
if (s === "") return "";
|
|
9
|
+
if (/grok|xai/.test(s)) return "xai";
|
|
10
|
+
if (/kimi|moonshot/.test(s)) return "kimi";
|
|
11
|
+
if (/qwen|qwq/.test(s)) return "qwen";
|
|
12
|
+
if (/iflow/.test(s)) return "iflow";
|
|
13
|
+
if (/glm|chatglm|zhipu/.test(s)) return "glm";
|
|
14
|
+
if (/deepseek/.test(s)) return "deepseek";
|
|
15
|
+
if (/gemini|gemma/.test(s)) return "gemini";
|
|
16
|
+
if (/claude|sonnet|opus|haiku/.test(s)) return "claude";
|
|
17
|
+
if (/gpt|openai|codex/.test(s) || /(?:^|[-_:/.])o[1-9](?:$|[-_:/.])/.test(s)) return "gpt";
|
|
18
|
+
return "";
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** CPA `owned_by` → family (or a provider type for families without a model-name pattern). */
|
|
22
|
+
function ownedByFamily(ownedBy) {
|
|
23
|
+
const o = text(ownedBy).toLowerCase();
|
|
24
|
+
if (o === "") return "";
|
|
25
|
+
if (/anthropic|claude/.test(o)) return "claude";
|
|
26
|
+
if (/openai|codex/.test(o)) return "gpt";
|
|
27
|
+
if (/google|gemini|antigravity/.test(o)) return "gemini";
|
|
28
|
+
if (/xai|grok/.test(o)) return "xai";
|
|
29
|
+
if (/moonshot|kimi/.test(o)) return "kimi";
|
|
30
|
+
return `provider:${normalizeProvider(o)}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function windowsMention(credential, word) {
|
|
34
|
+
const rows = Array.isArray(credential.windows) ? credential.windows : [];
|
|
35
|
+
return rows.some((w) =>
|
|
36
|
+
(Array.isArray(w.modelPrefixes) && w.modelPrefixes.some((p) => text(p).toLowerCase().startsWith(word)))
|
|
37
|
+
|| (Array.isArray(w.modelIds) && w.modelIds.some((id) => text(id).toLowerCase().includes(word)))
|
|
38
|
+
|| text(w.group).toLowerCase().includes(word));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function servesFamily(credential, family) {
|
|
42
|
+
if (family === "") return false;
|
|
43
|
+
const provider = text(credential.provider).toLowerCase();
|
|
44
|
+
if (family.startsWith("provider:")) return provider === family.slice("provider:".length);
|
|
45
|
+
switch (provider) {
|
|
46
|
+
case "claude": return family === "claude";
|
|
47
|
+
case "codex":
|
|
48
|
+
case "openai": return family === "gpt";
|
|
49
|
+
case "gemini":
|
|
50
|
+
case "gemini-cli":
|
|
51
|
+
case "gemini-api":
|
|
52
|
+
case "aistudio": return family === "gemini";
|
|
53
|
+
case "vertex": return family === "gemini" || family === "claude";
|
|
54
|
+
// Antigravity serves Gemini, and Claude/GPT only when its quota groups say so.
|
|
55
|
+
case "antigravity": return family === "gemini" || ((family === "claude" || family === "gpt") && windowsMention(credential, family));
|
|
56
|
+
case "kimi":
|
|
57
|
+
case "xai":
|
|
58
|
+
case "qwen":
|
|
59
|
+
case "iflow":
|
|
60
|
+
case "glm":
|
|
61
|
+
case "deepseek": return family === provider;
|
|
62
|
+
default: return false;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const listHas = (credential, idLower) => Array.isArray(credential.models) && credential.models.some((m) => text(m).toLowerCase() === idLower);
|
|
67
|
+
|
|
68
|
+
function finishMatch(list, matchedBy) {
|
|
69
|
+
const seen = new Set();
|
|
70
|
+
const unique = list.filter((c) => (seen.has(c.id) ? false : (seen.add(c.id), true)));
|
|
71
|
+
const rank = (c) => (c.status === "active" ? 0 : 1);
|
|
72
|
+
const credentialIds = unique
|
|
73
|
+
.map((c, index) => ({ c, index }))
|
|
74
|
+
.sort((a, b) => rank(a.c) - rank(b.c) || a.index - b.index)
|
|
75
|
+
.map(({ c }) => c.id);
|
|
76
|
+
return { credentialIds, matchedBy: credentialIds.length === 0 ? "none" : matchedBy };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Credentials of one snapshot account entry that serve `modelId`. */
|
|
80
|
+
export function matchCredentials(accountEntry, modelId) {
|
|
81
|
+
const credentials = (Array.isArray(accountEntry?.credentials) ? accountEntry.credentials : [])
|
|
82
|
+
.filter((c) => isObj(c) && typeof c.id === "string" && c.id !== "");
|
|
83
|
+
const id = text(modelId).toLowerCase();
|
|
84
|
+
if (id === "" || credentials.length === 0) return { credentialIds: [], matchedBy: "none" };
|
|
85
|
+
|
|
86
|
+
// Rule 1: "p/rest" routes only to credentials with prefix p.
|
|
87
|
+
const slash = id.indexOf("/");
|
|
88
|
+
if (slash > 0) {
|
|
89
|
+
const prefix = id.slice(0, slash);
|
|
90
|
+
const prefixed = credentials.filter((c) => prefixOf(c) === prefix);
|
|
91
|
+
if (prefixed.length > 0) {
|
|
92
|
+
const confirmed = prefixed.filter((c) => listHas(c, id));
|
|
93
|
+
const unknown = prefixed.filter((c) => !Array.isArray(c.models));
|
|
94
|
+
if (confirmed.length > 0) return finishMatch([...confirmed, ...unknown], "model-list");
|
|
95
|
+
return finishMatch(unknown.length > 0 ? unknown : prefixed, "prefix");
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Rule 2: exact model-list hits, un-prefixed credentials first.
|
|
100
|
+
const unprefixed = credentials.filter((c) => prefixOf(c) === "");
|
|
101
|
+
const prefixed = credentials.filter((c) => prefixOf(c) !== "");
|
|
102
|
+
const plainHits = unprefixed.filter((c) => listHas(c, id));
|
|
103
|
+
const prefixedHits = plainHits.length > 0 ? [] : prefixed.filter((c) => listHas(c, `${prefixOf(c)}/${id}`) || listHas(c, id));
|
|
104
|
+
|
|
105
|
+
// Rule 3: family heuristics for un-prefixed credentials whose model list is unknown.
|
|
106
|
+
let family = modelFamily(id);
|
|
107
|
+
if (family === "") {
|
|
108
|
+
const picker = Array.isArray(accountEntry?.pickerModels) ? accountEntry.pickerModels : [];
|
|
109
|
+
const hint = picker.find((m) => isObj(m) && text(m.id).toLowerCase() === id && text(m.ownedBy) !== "");
|
|
110
|
+
if (hint !== undefined) family = ownedByFamily(hint.ownedBy);
|
|
111
|
+
}
|
|
112
|
+
const familyHits = family === "" ? [] : unprefixed.filter((c) => !Array.isArray(c.models) && servesFamily(c, family));
|
|
113
|
+
|
|
114
|
+
const listHits = [...plainHits, ...prefixedHits];
|
|
115
|
+
if (listHits.length > 0) return finishMatch([...listHits, ...familyHits], "model-list");
|
|
116
|
+
if (familyHits.length > 0) return finishMatch(familyHits, "family");
|
|
117
|
+
return { credentialIds: [], matchedBy: "none" };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function buildModelIndex(entry) {
|
|
121
|
+
const ids = new Set();
|
|
122
|
+
for (const c of entry.credentials) {
|
|
123
|
+
if (!Array.isArray(c.models)) continue;
|
|
124
|
+
const prefix = prefixOf(c);
|
|
125
|
+
for (const m of c.models) {
|
|
126
|
+
ids.add(m);
|
|
127
|
+
if (prefix !== "" && m.toLowerCase().startsWith(`${prefix}/`)) ids.add(m.slice(prefix.length + 1));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
for (const m of entry.pickerModels ?? []) if (text(m?.id) !== "") ids.add(text(m.id));
|
|
131
|
+
const modelIndex = {};
|
|
132
|
+
const modelMatch = {};
|
|
133
|
+
for (const id of ids) {
|
|
134
|
+
const match = matchCredentials(entry, id);
|
|
135
|
+
modelIndex[id] = match.credentialIds;
|
|
136
|
+
modelMatch[id] = match.matchedBy;
|
|
137
|
+
}
|
|
138
|
+
return { modelIndex, modelMatch };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
//#endregion
|
|
142
|
+
|
|
143
|
+
export { buildModelIndex };
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
// Converts provider quota payloads into safe windows and plan labels.
|
|
2
|
+
import { GROUP_CLAUDE_GPT, GROUP_GEMINI, GROUP_OTHER, PLAN_LABELS } from "./constants.js";
|
|
3
|
+
import { QuotaError, isObj, text, firstText, numberOrNull, flagOf, clampPct, roundPct, getPath, fractionPercent, kindFromText, kindFromSeconds, durationSeconds, kindFromReset, isoFromUnix, isoFromString, isoFromRelative, makeWindow, dedupeWindows, extractPlan } from "./helpers.js";
|
|
4
|
+
|
|
5
|
+
//#region Upstream Parsers
|
|
6
|
+
|
|
7
|
+
function parseCodexWindows(body, nowMs) {
|
|
8
|
+
const windows = [];
|
|
9
|
+
const addLimit = (info, idPrefix, group) => {
|
|
10
|
+
if (!isObj(info)) return;
|
|
11
|
+
const exhausted = flagOf(info.limit_reached ?? info.limitReached) === true || info.allowed === false;
|
|
12
|
+
const slots = [
|
|
13
|
+
["primary", info.primary_window ?? info.primaryWindow, "5h"],
|
|
14
|
+
["secondary", info.secondary_window ?? info.secondaryWindow, "7d"],
|
|
15
|
+
];
|
|
16
|
+
for (const [slot, raw, fallbackKind] of slots) {
|
|
17
|
+
if (!isObj(raw)) continue;
|
|
18
|
+
const seconds = raw.limit_window_seconds ?? raw.limitWindowSeconds;
|
|
19
|
+
const kind = kindFromSeconds(seconds) || (numberOrNull(seconds) === null ? fallbackKind : "other");
|
|
20
|
+
const used = numberOrNull(raw.used_percent ?? raw.usedPercent);
|
|
21
|
+
const resetAt = isoFromUnix(raw.reset_at ?? raw.resetAt) ?? isoFromRelative(raw.reset_after_seconds ?? raw.resetAfterSeconds, nowMs);
|
|
22
|
+
if (used === null && resetAt === null) continue;
|
|
23
|
+
windows.push(makeWindow({
|
|
24
|
+
id: `${idPrefix}:${slot}`,
|
|
25
|
+
kind,
|
|
26
|
+
label: "",
|
|
27
|
+
group,
|
|
28
|
+
remainingPercent: used !== null ? 100 - clampPct(used) : exhausted ? 0 : null,
|
|
29
|
+
resetAt,
|
|
30
|
+
}));
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
addLimit(body.rate_limit ?? body.rateLimit, "codex", undefined);
|
|
34
|
+
addLimit(body.code_review_rate_limit ?? body.codeReviewRateLimit, "codex-review", "code_review");
|
|
35
|
+
const extras = body.additional_rate_limits ?? body.additionalRateLimits;
|
|
36
|
+
if (Array.isArray(extras)) {
|
|
37
|
+
extras.forEach((item, index) => {
|
|
38
|
+
if (!isObj(item)) return;
|
|
39
|
+
const name = firstText(item.limit_name, item.limitName, item.metered_feature, item.meteredFeature, `extra-${index + 1}`);
|
|
40
|
+
addLimit(item.rate_limit ?? item.rateLimit, `codex-extra:${name}`, name);
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
return windows;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const CLAUDE_WINDOWS = [
|
|
47
|
+
["five_hour", "5h", undefined, undefined],
|
|
48
|
+
["seven_day", "7d", undefined, undefined],
|
|
49
|
+
["seven_day_oauth_apps", "7d", "oauth_apps", undefined],
|
|
50
|
+
["seven_day_opus", "7d", "opus", ["claude-opus"]],
|
|
51
|
+
["seven_day_sonnet", "7d", "sonnet", ["claude-sonnet"]],
|
|
52
|
+
["seven_day_cowork", "7d", "cowork", undefined],
|
|
53
|
+
["iguana_necktie", "7d", "fable", undefined],
|
|
54
|
+
];
|
|
55
|
+
|
|
56
|
+
function parseClaudeWindows(body) {
|
|
57
|
+
const rows = [];
|
|
58
|
+
for (const [key, kind, group, prefixes] of CLAUDE_WINDOWS) {
|
|
59
|
+
const raw = body[key];
|
|
60
|
+
if (!isObj(raw)) continue;
|
|
61
|
+
// Anthropic reports utilization in percent (0..100).
|
|
62
|
+
const used = numberOrNull(raw.utilization);
|
|
63
|
+
const resetAt = isoFromString(firstText(raw.resets_at, raw.resetsAt, raw.reset_at, raw.resetAt));
|
|
64
|
+
if (used === null && resetAt === null) continue;
|
|
65
|
+
rows.push(makeWindow({ id: `claude:${key}`, kind, label: key, group, remainingPercent: used === null ? null : 100 - clampPct(used), resetAt, modelPrefixes: prefixes }));
|
|
66
|
+
}
|
|
67
|
+
if (Array.isArray(body.limits)) {
|
|
68
|
+
for (const limit of body.limits) {
|
|
69
|
+
if (!isObj(limit) || text(limit.kind).toLowerCase() !== "weekly_scoped") continue;
|
|
70
|
+
const model = text(getPath(limit, ["scope", "model", "display_name"]));
|
|
71
|
+
if (model === "") continue;
|
|
72
|
+
const used = numberOrNull(limit.percent);
|
|
73
|
+
const resetAt = isoFromString(firstText(limit.resets_at, limit.resetAt));
|
|
74
|
+
if (used === null && resetAt === null) continue;
|
|
75
|
+
const group = model.toLowerCase().replace(/\s+\d+(?:\.\d+)*$/, "").replace(/\s+/g, "_");
|
|
76
|
+
rows.push(makeWindow({ id: `claude:scoped:${group}`, kind: "7d", label: model, group, remainingPercent: used === null ? null : 100 - clampPct(used), resetAt }));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const extra = body.extra_usage;
|
|
80
|
+
if (isObj(extra)) {
|
|
81
|
+
const limit = numberOrNull(extra.monthly_limit);
|
|
82
|
+
const used = numberOrNull(extra.used_credits);
|
|
83
|
+
if (limit !== null && limit > 0 && used !== null) {
|
|
84
|
+
rows.push(makeWindow({ id: "claude:extra_usage", kind: "30d", label: "extra_usage", group: "extra_usage", remainingPercent: ((limit - used) / limit) * 100, resetAt: null }));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
// The same scoped weekly limit can arrive as a named key and as limits[].
|
|
88
|
+
return dedupeWindows(rows, (row) => `${row.kind}:${row.group ?? ""}`);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function claudeProfilePlan(profile) {
|
|
92
|
+
const hasMax = flagOf(getPath(profile, ["account", "has_claude_max"]));
|
|
93
|
+
const hasPro = flagOf(getPath(profile, ["account", "has_claude_pro"]));
|
|
94
|
+
const orgType = text(getPath(profile, ["organization", "organization_type"])).toLowerCase();
|
|
95
|
+
const subStatus = text(getPath(profile, ["organization", "subscription_status"])).toLowerCase();
|
|
96
|
+
if (hasMax === true) return "Max";
|
|
97
|
+
if (hasPro === true) return "Pro";
|
|
98
|
+
if (orgType === "claude_team" && subStatus === "active") return "Team";
|
|
99
|
+
if (orgType === "claude_enterprise" && subStatus === "active") return "Enterprise";
|
|
100
|
+
if (hasMax === false && hasPro === false) return "Free";
|
|
101
|
+
return extractPlan(profile);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function groupPrefixes(groupText) {
|
|
105
|
+
const s = groupText.toLowerCase();
|
|
106
|
+
if (s.includes("claude") || s.includes("gpt")) return ["claude", "gpt"];
|
|
107
|
+
if (s.includes("gemini")) return ["gemini", "gemma"];
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function groupForModel(modelId, label) {
|
|
112
|
+
const s = `${text(modelId)} ${text(label)}`.toLowerCase();
|
|
113
|
+
if (s.includes("claude") || s.includes("gpt")) return GROUP_CLAUDE_GPT;
|
|
114
|
+
if (s.includes("gemini") || s.includes("gemma")) return GROUP_GEMINI;
|
|
115
|
+
return GROUP_OTHER;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function antigravitySummaryWindows(body) {
|
|
119
|
+
return groupedQuotaWindows(body, "ag");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* groups[].buckets[] with remainingFraction / resetTime: the Antigravity
|
|
124
|
+
* summary shape, which CPA also uses for its normalized plugin quota
|
|
125
|
+
* (pluginapi.QuotaFetchResponse).
|
|
126
|
+
*/
|
|
127
|
+
function groupedQuotaWindows(body, idPrefix) {
|
|
128
|
+
const groups = Array.isArray(body.groups) ? body.groups
|
|
129
|
+
: Array.isArray(body.quota?.groups) ? body.quota.groups
|
|
130
|
+
: Array.isArray(body.data?.groups) ? body.data.groups : [];
|
|
131
|
+
const rows = [];
|
|
132
|
+
groups.forEach((group, groupIndex) => {
|
|
133
|
+
if (!isObj(group)) return;
|
|
134
|
+
const groupLabel = firstText(group.displayName, group.display_name, group.name, `Quota Group ${groupIndex + 1}`);
|
|
135
|
+
const groupId = text(group.id) || groupLabel.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || `group-${groupIndex + 1}`;
|
|
136
|
+
const prefixes = groupPrefixes(`${groupLabel} ${text(group.description)}`);
|
|
137
|
+
const buckets = Array.isArray(group.buckets) ? group.buckets : [];
|
|
138
|
+
buckets.forEach((bucket, bucketIndex) => {
|
|
139
|
+
if (!isObj(bucket)) return;
|
|
140
|
+
const remaining = fractionPercent(bucket.remainingFraction ?? bucket.remaining_fraction);
|
|
141
|
+
const resetAt = isoFromString(firstText(bucket.resetTime, bucket.reset_time));
|
|
142
|
+
if (remaining === null && resetAt === null) return;
|
|
143
|
+
const label = firstText(bucket.displayName, bucket.display_name, bucket.label, bucket.description, bucket.window);
|
|
144
|
+
const kind = kindFromText(bucket.window, bucket.windowType, bucket.window_type, label)
|
|
145
|
+
|| kindFromSeconds(bucket.windowSeconds ?? bucket.window_seconds ?? bucket.limitWindowSeconds ?? bucket.limit_window_seconds)
|
|
146
|
+
|| "other";
|
|
147
|
+
rows.push(makeWindow({
|
|
148
|
+
id: `${idPrefix}:${groupId}:${firstText(bucket.bucketId, bucket.bucket_id, `${kind}-${bucketIndex + 1}`)}`,
|
|
149
|
+
kind,
|
|
150
|
+
label,
|
|
151
|
+
group: groupLabel,
|
|
152
|
+
remainingPercent: remaining,
|
|
153
|
+
resetAt,
|
|
154
|
+
modelPrefixes: prefixes,
|
|
155
|
+
}));
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
return rows;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function antigravityModelWindows(body, nowMs) {
|
|
162
|
+
const models = body.models;
|
|
163
|
+
if (models === null || typeof models !== "object") return [];
|
|
164
|
+
const entries = Array.isArray(models) ? models.map((raw, i) => [String(i), raw]) : Object.entries(models);
|
|
165
|
+
const rows = [];
|
|
166
|
+
for (const [key, raw] of entries) {
|
|
167
|
+
if (!isObj(raw)) continue;
|
|
168
|
+
const modelId = firstText(raw.modelId, raw.model_id, raw.id, raw.model, Array.isArray(models) ? "" : key, raw.name);
|
|
169
|
+
if (modelId === "") continue;
|
|
170
|
+
const quota = isObj(raw.quotaInfo) ? raw.quotaInfo : isObj(raw.quota_info) ? raw.quota_info : raw;
|
|
171
|
+
let remaining = fractionPercent(quota.remainingFraction ?? quota.remaining_fraction ?? quota.remaining);
|
|
172
|
+
const amount = numberOrNull(quota.remainingAmount ?? quota.remaining_amount);
|
|
173
|
+
const resetAt = isoFromString(firstText(quota.resetTime, quota.reset_time, raw.resetTime, raw.reset_time));
|
|
174
|
+
if (remaining === null && amount !== null && amount <= 0) remaining = 0;
|
|
175
|
+
if (remaining === null && resetAt === null) continue;
|
|
176
|
+
const label = firstText(raw.displayName, raw.display_name, raw.name);
|
|
177
|
+
rows.push(makeWindow({
|
|
178
|
+
id: `ag-model:${modelId}`,
|
|
179
|
+
kind: kindFromReset(resetAt, nowMs),
|
|
180
|
+
label,
|
|
181
|
+
group: groupForModel(modelId, label),
|
|
182
|
+
remainingPercent: remaining,
|
|
183
|
+
resetAt,
|
|
184
|
+
modelIds: [modelId],
|
|
185
|
+
}));
|
|
186
|
+
}
|
|
187
|
+
return rows;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Google per-model quota buckets; identical buckets are merged into one window with all their model ids. */
|
|
191
|
+
function googleBucketWindows(body, nowMs, idPrefix) {
|
|
192
|
+
const buckets = Array.isArray(body.buckets) ? body.buckets : [];
|
|
193
|
+
const merged = new Map();
|
|
194
|
+
for (const bucket of buckets) {
|
|
195
|
+
if (!isObj(bucket)) continue;
|
|
196
|
+
const modelId = firstText(bucket.modelId, bucket.model_id).replace(/_vertex$/, "");
|
|
197
|
+
if (!/^(?:gemini|gemma)/i.test(modelId)) continue;
|
|
198
|
+
const remaining = fractionPercent(bucket.remainingFraction ?? bucket.remaining_fraction ?? bucket.remaining);
|
|
199
|
+
const resetAt = isoFromString(firstText(bucket.resetTime, bucket.reset_time));
|
|
200
|
+
if (remaining === null && resetAt === null) continue;
|
|
201
|
+
const label = firstText(bucket.displayName, bucket.display_name, bucket.label);
|
|
202
|
+
const kind = kindFromText(bucket.window, bucket.windowType, label) || kindFromReset(resetAt, nowMs);
|
|
203
|
+
const pct = roundPct(remaining);
|
|
204
|
+
const key = `${kind}|${pct}|${resetAt ?? ""}|${label}`;
|
|
205
|
+
const prev = merged.get(key);
|
|
206
|
+
if (prev !== undefined) {
|
|
207
|
+
if (!prev.modelIds.includes(modelId)) prev.modelIds.push(modelId);
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
merged.set(key, { kind, pct, resetAt, label, modelIds: [modelId] });
|
|
211
|
+
}
|
|
212
|
+
return [...merged.values()].map((w, i) => makeWindow({
|
|
213
|
+
id: `${idPrefix}:${w.kind}:${i + 1}`,
|
|
214
|
+
kind: w.kind,
|
|
215
|
+
label: w.label,
|
|
216
|
+
group: GROUP_GEMINI,
|
|
217
|
+
remainingPercent: w.pct,
|
|
218
|
+
resetAt: w.resetAt,
|
|
219
|
+
modelIds: w.modelIds,
|
|
220
|
+
}));
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Hints in the auth-file listing that the credential is a kimi.ai account. */
|
|
224
|
+
function kimiPrefersAi(entry) {
|
|
225
|
+
const hint = (v) => {
|
|
226
|
+
const s = text(v).toLowerCase();
|
|
227
|
+
if (s === "") return null;
|
|
228
|
+
if (["ai", "kimi-ai", "kimi_ai", "kimi.ai"].includes(s) || /(?:^|[./])kimi\.ai(?:[/:]|$)/.test(s)) return true;
|
|
229
|
+
if (["com", "kimi", "kimi.com"].includes(s) || /(?:^|[./])kimi\.com(?:[/:]|$)/.test(s)) return false;
|
|
230
|
+
return null;
|
|
231
|
+
};
|
|
232
|
+
for (const v of [
|
|
233
|
+
entry.domain, getPath(entry, ["metadata", "domain"]), getPath(entry, ["attributes", "domain"]),
|
|
234
|
+
entry.base_url, getPath(entry, ["metadata", "base_url"]), getPath(entry, ["attributes", "base_url"]),
|
|
235
|
+
entry.provider, entry.type,
|
|
236
|
+
]) {
|
|
237
|
+
const h = hint(v);
|
|
238
|
+
if (h !== null) return h;
|
|
239
|
+
}
|
|
240
|
+
return /kimi[-_.]ai/i.test(`${text(entry.id)} ${text(entry.name)}`);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function parseKimiWindows(body, nowMs) {
|
|
244
|
+
const rows = [];
|
|
245
|
+
const add = (data, index, duration, unit) => {
|
|
246
|
+
if (!isObj(data)) return;
|
|
247
|
+
const limit = numberOrNull(data.limit);
|
|
248
|
+
const used = numberOrNull(data.used);
|
|
249
|
+
const remainingAmount = numberOrNull(data.remaining);
|
|
250
|
+
let remaining = null;
|
|
251
|
+
if (limit !== null && limit > 0) {
|
|
252
|
+
if (remainingAmount !== null) remaining = (remainingAmount / limit) * 100;
|
|
253
|
+
else if (used !== null) remaining = 100 - (used / limit) * 100;
|
|
254
|
+
}
|
|
255
|
+
const resetAt = isoFromString(firstText(data.reset_at, data.resetAt, data.reset_time, data.resetTime))
|
|
256
|
+
?? isoFromRelative(data.reset_in ?? data.resetIn ?? data.ttl, nowMs);
|
|
257
|
+
if (remaining === null && resetAt === null) return;
|
|
258
|
+
const label = firstText(data.name, data.title, data.scope);
|
|
259
|
+
const kind = kindFromText(label) || kindFromSeconds(durationSeconds(duration, unit)) || (index === "usage" ? "7d" : "other");
|
|
260
|
+
rows.push(makeWindow({ id: `kimi:${index}`, kind, label, remainingPercent: remaining, resetAt }));
|
|
261
|
+
};
|
|
262
|
+
(Array.isArray(body.limits) ? body.limits : []).forEach((item, index) => {
|
|
263
|
+
if (!isObj(item)) return;
|
|
264
|
+
const detail = isObj(item.detail) ? item.detail : item;
|
|
265
|
+
const window = isObj(item.window) ? item.window : {};
|
|
266
|
+
add(detail, String(index), window.duration ?? item.duration ?? detail.duration, window.timeUnit ?? item.timeUnit ?? detail.timeUnit);
|
|
267
|
+
});
|
|
268
|
+
if (isObj(body.usage)) add(body.usage, "usage", null, null);
|
|
269
|
+
return rows;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function parseXaiWindows(body, period) {
|
|
273
|
+
const config = isObj(body.config) ? body.config : body;
|
|
274
|
+
const rows = [];
|
|
275
|
+
const current = isObj(config.currentPeriod) ? config.currentPeriod : isObj(config.current_period) ? config.current_period : {};
|
|
276
|
+
const periodEnd = isoFromString(firstText(current.end, config.billingPeriodEnd, config.billing_period_end));
|
|
277
|
+
const creditUsage = numberOrNull(config.creditUsagePercent ?? config.credit_usage_percent);
|
|
278
|
+
if (creditUsage !== null && period !== "monthly") {
|
|
279
|
+
rows.push(makeWindow({ id: "xai:weekly", kind: "7d", label: "credits", remainingPercent: 100 - clampPct(creditUsage), resetAt: periodEnd }));
|
|
280
|
+
}
|
|
281
|
+
const valueOf = (v) => (isObj(v) ? numberOrNull(v.val) : numberOrNull(v));
|
|
282
|
+
const monthlyLimit = valueOf(config.monthlyLimit ?? config.monthly_limit);
|
|
283
|
+
const used = valueOf(config.used);
|
|
284
|
+
if (monthlyLimit !== null && monthlyLimit > 0 && used !== null) {
|
|
285
|
+
rows.push(makeWindow({ id: "xai:monthly", kind: "30d", label: "monthly credits", remainingPercent: ((monthlyLimit - used) / monthlyLimit) * 100, resetAt: period === "monthly" ? periodEnd : null }));
|
|
286
|
+
}
|
|
287
|
+
const products = config.productUsage ?? config.product_usage;
|
|
288
|
+
if (Array.isArray(products)) {
|
|
289
|
+
products.forEach((item, index) => {
|
|
290
|
+
if (!isObj(item)) return;
|
|
291
|
+
const usage = numberOrNull(item.usagePercent ?? item.usage_percent);
|
|
292
|
+
if (usage === null) return;
|
|
293
|
+
rows.push(makeWindow({ id: `xai:product:${index}`, kind: "7d", label: firstText(item.product), group: firstText(item.product), remainingPercent: 100 - clampPct(usage), resetAt: periodEnd }));
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
return rows;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Devin GetUserStatus: one account-wide daily and weekly quota shared by
|
|
301
|
+
* every Devin model (windows carry no model filter). Percentages are
|
|
302
|
+
* remaining 0–100; resets are Unix seconds. Mirrors CPA's management center.
|
|
303
|
+
*/
|
|
304
|
+
function parseDevinStatus(body) {
|
|
305
|
+
const status = isObj(body.userStatus) && isObj(body.userStatus.planStatus) ? body.userStatus.planStatus : {};
|
|
306
|
+
const planInfo = isObj(status.planInfo) ? status.planInfo : isObj(body.planInfo) ? body.planInfo : {};
|
|
307
|
+
const percent = (v) => {
|
|
308
|
+
const n = numberOrNull(v);
|
|
309
|
+
return n !== null && n >= 0 && n <= 100 ? n : null;
|
|
310
|
+
};
|
|
311
|
+
const windows = [];
|
|
312
|
+
for (const [id, kind] of [["daily", "1d"], ["weekly", "7d"]]) {
|
|
313
|
+
const remainingPercent = percent(status[`${id}QuotaRemainingPercent`]);
|
|
314
|
+
const resetAt = isoFromUnix(status[`${id}QuotaResetAtUnix`]);
|
|
315
|
+
if (remainingPercent === null && resetAt === null) continue;
|
|
316
|
+
windows.push(makeWindow({ id: `devin:${id}`, kind, label: id, remainingPercent, resetAt }));
|
|
317
|
+
}
|
|
318
|
+
if (windows.length === 0) throw new QuotaError("invalid-response");
|
|
319
|
+
const name = text(planInfo.planName);
|
|
320
|
+
return { windows, plan: name === "" ? "" : PLAN_LABELS[name.toLowerCase()] ?? name };
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Meta Muse Code `subs_usage`: a rolling window (window_duration_mins) and a
|
|
325
|
+
* weekly window, each with used_percent and resets_at (Unix seconds). Only
|
|
326
|
+
* these fields are read: the endpoint can echo api_key and PII. A valid body
|
|
327
|
+
* without subs_usage is a reachable account with no quota observed yet.
|
|
328
|
+
*/
|
|
329
|
+
function parseMetaUsage(body) {
|
|
330
|
+
const usage = isObj(body.subs_usage) ? body.subs_usage : {};
|
|
331
|
+
const windows = [];
|
|
332
|
+
for (const [id, raw] of [["window", usage.window], ["weekly", usage.weekly]]) {
|
|
333
|
+
if (!isObj(raw)) continue;
|
|
334
|
+
const used = numberOrNull(raw.used_percent);
|
|
335
|
+
const resetAt = isoFromUnix(raw.resets_at);
|
|
336
|
+
if (used === null && resetAt === null) continue;
|
|
337
|
+
const minutes = numberOrNull(raw.window_duration_mins);
|
|
338
|
+
const kind = id === "weekly" ? "7d" : (minutes !== null && minutes > 0 ? kindFromSeconds(minutes * 60) : "") || "other";
|
|
339
|
+
windows.push(makeWindow({ id: `meta:${id}`, kind, label: id, remainingPercent: used === null ? null : 100 - clampPct(used), resetAt }));
|
|
340
|
+
}
|
|
341
|
+
return { windows, plan: firstText(body.subs_tier_name, usage.tier) };
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** CPA's normalized plugin quota (`/v0/management/quota/fetch`). */
|
|
345
|
+
function parsePluginQuota(body) {
|
|
346
|
+
const sub = isObj(body.subscription) ? body.subscription : {};
|
|
347
|
+
return { windows: groupedQuotaWindows(body, "plugin"), plan: firstText(sub.tierName, sub.plan, sub.tierId) };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
//#endregion
|
|
351
|
+
|
|
352
|
+
export { parseCodexWindows, parseClaudeWindows, claudeProfilePlan, antigravitySummaryWindows, antigravityModelWindows, googleBucketWindows, kimiPrefersAi, parseKimiWindows, parseXaiWindows, parseDevinStatus, parseMetaUsage, parsePluginQuota };
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Kimi, Meta, xAI, and Devin provider-specific account usage requests.
|
|
2
|
+
import { UPSTREAM, DEVIN_METADATA } from "../constants.js";
|
|
3
|
+
import { QuotaError, isObj, text, firstText, flagOf, getPath, extractPlan } from "../helpers.js";
|
|
4
|
+
import { kimiPrefersAi, parseKimiWindows, parseMetaUsage, parseXaiWindows, parseDevinStatus } from "../parsers.js";
|
|
5
|
+
|
|
6
|
+
export function createBillingProbes({ apiCall, management, now }) {
|
|
7
|
+
return {
|
|
8
|
+
async kimi(ctx, entry, authIndex) {
|
|
9
|
+
// kimi.com and Kimi International (kimi.ai) share the API on two hosts.
|
|
10
|
+
// Prefer the host the credential hints at; on a rejected token try the
|
|
11
|
+
// other one (both are Moonshot's own endpoints, never arbitrary hosts).
|
|
12
|
+
const hosts = kimiPrefersAi(entry) ? [UPSTREAM.kimiAiUsage, UPSTREAM.kimiUsage] : [UPSTREAM.kimiUsage, UPSTREAM.kimiAiUsage];
|
|
13
|
+
let lastError = null;
|
|
14
|
+
for (const url of hosts) {
|
|
15
|
+
try {
|
|
16
|
+
const body = await apiCall(ctx, { auth_index: authIndex, method: "GET", url, header: { Authorization: "Bearer $TOKEN$" } });
|
|
17
|
+
return { windows: parseKimiWindows(body, now()), plan: extractPlan(body) };
|
|
18
|
+
} catch (error) {
|
|
19
|
+
if (error?.code === "aborted") throw error;
|
|
20
|
+
lastError = error;
|
|
21
|
+
if (error?.code !== "upstream-unauthorized" && error?.code !== "upstream-forbidden") break;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
throw lastError;
|
|
25
|
+
},
|
|
26
|
+
|
|
27
|
+
async meta(ctx, entry, authIndex) {
|
|
28
|
+
// Meta's usage endpoint takes the credential's dca_token, not the LLM key
|
|
29
|
+
// CPA would substitute for $TOKEN$. Read only that field from the auth
|
|
30
|
+
// file for this one request; it is never stored, logged or returned.
|
|
31
|
+
const name = firstText(entry.name, entry.id);
|
|
32
|
+
if (name === "" || flagOf(entry.runtime_only ?? entry.runtimeOnly) === true) throw new QuotaError("missing-token");
|
|
33
|
+
const file = await management(ctx, `/v0/management/auth-files/download?name=${encodeURIComponent(name)}`);
|
|
34
|
+
const token = isObj(file) ? text(file.dca_token) : "";
|
|
35
|
+
if (!/^dca:\S+$/.test(token)) throw new QuotaError("missing-token");
|
|
36
|
+
const body = await apiCall(ctx, {
|
|
37
|
+
auth_index: authIndex,
|
|
38
|
+
method: "POST",
|
|
39
|
+
url: UPSTREAM.metaUsage,
|
|
40
|
+
header: { Accept: "application/json", "Content-Type": "application/json", Authorization: `Bearer ${token}`, "x-api-version": "1.0.0" },
|
|
41
|
+
data: "{}",
|
|
42
|
+
});
|
|
43
|
+
return parseMetaUsage(body);
|
|
44
|
+
},
|
|
45
|
+
|
|
46
|
+
async xai(ctx, entry, authIndex) {
|
|
47
|
+
const header = {
|
|
48
|
+
Authorization: "Bearer $TOKEN$",
|
|
49
|
+
"x-xai-token-auth": "xai-grok-cli",
|
|
50
|
+
"x-grok-client-version": "0.2.91",
|
|
51
|
+
accept: "*/*",
|
|
52
|
+
"user-agent": "grok-pager/0.2.91 grok-shell/0.2.91 (windows; amd64)",
|
|
53
|
+
};
|
|
54
|
+
const userId = firstText(entry.sub, entry.subject, entry.user_id, entry.userId, getPath(entry, ["metadata", "sub"]), getPath(entry, ["metadata", "user_id"]), getPath(entry, ["attributes", "sub"]));
|
|
55
|
+
if (userId !== "") header["x-userid"] = userId;
|
|
56
|
+
const results = await Promise.allSettled([
|
|
57
|
+
apiCall(ctx, { auth_index: authIndex, method: "GET", url: UPSTREAM.xaiBillingWeekly, header }),
|
|
58
|
+
apiCall(ctx, { auth_index: authIndex, method: "GET", url: UPSTREAM.xaiBillingMonthly, header }),
|
|
59
|
+
]);
|
|
60
|
+
if (results.every((r) => r.status === "rejected")) throw results[0].reason;
|
|
61
|
+
const rows = new Map();
|
|
62
|
+
if (results[0].status === "fulfilled") for (const row of parseXaiWindows(results[0].value, "weekly")) rows.set(row.id, row);
|
|
63
|
+
if (results[1].status === "fulfilled") for (const row of parseXaiWindows(results[1].value, "monthly")) rows.set(row.id, row);
|
|
64
|
+
// Paid accounts expose no billing counters: reachable but window-less.
|
|
65
|
+
return { windows: [...rows.values()], plan: rows.size === 0 ? "Paid" : "" };
|
|
66
|
+
},
|
|
67
|
+
|
|
68
|
+
async devin(ctx, entry, authIndex) {
|
|
69
|
+
const body = await apiCall(ctx, {
|
|
70
|
+
auth_index: authIndex,
|
|
71
|
+
method: "POST",
|
|
72
|
+
url: UPSTREAM.devinStatus,
|
|
73
|
+
header: { "Content-Type": "application/json", "Connect-Protocol-Version": "1" },
|
|
74
|
+
data: JSON.stringify({ metadata: DEVIN_METADATA }),
|
|
75
|
+
});
|
|
76
|
+
return parseDevinStatus(body);
|
|
77
|
+
},
|
|
78
|
+
|
|
79
|
+
};
|
|
80
|
+
}
|