tokenusage-cli 0.1.0 → 0.2.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 +46 -19
- package/LICENSE +22 -22
- package/README.md +123 -94
- package/THIRD_PARTY_NOTICES.md +140 -140
- package/bin/tokenusage.js +69 -69
- package/package.json +59 -59
- package/src/cli.js +146 -134
- package/src/commands/device-login.js +205 -205
- package/src/commands/diagnostics.js +38 -38
- package/src/commands/doctor.js +110 -110
- package/src/commands/init.js +2484 -2436
- package/src/commands/pause.js +77 -0
- package/src/commands/sessions.js +29 -29
- package/src/commands/status.js +1758 -1747
- package/src/commands/sync.js +8048 -7934
- package/src/commands/uninstall.js +322 -312
- package/src/lib/account-usage-dedup.js +267 -267
- package/src/lib/antigravity-paths.js +48 -48
- package/src/lib/ark-agent-plan-limits.js +438 -438
- package/src/lib/ark-coding-plan-limits.js +537 -537
- package/src/lib/async-queue-reader.js +138 -138
- package/src/lib/atomic-json.js +27 -27
- package/src/lib/bearer-token.js +11 -11
- package/src/lib/categorizer-utils.js +232 -232
- package/src/lib/claude-categorizer.js +1343 -1343
- package/src/lib/claude-config.js +279 -279
- package/src/lib/claude-user-identity.js +56 -56
- package/src/lib/cli-ui.js +179 -179
- package/src/lib/cloud-account.js +541 -541
- package/src/lib/cloud-device-token.js +141 -141
- package/src/lib/cloud-sync-prefs.js +14 -14
- package/src/lib/cloud-usage-reset.js +115 -115
- package/src/lib/codex-config.js +595 -595
- package/src/lib/codex-context-breakdown.js +806 -806
- package/src/lib/codex-model-attribution.js +128 -128
- package/src/lib/codex-rollout-parser.js +1471 -1471
- package/src/lib/codex-service-tier.js +49 -49
- package/src/lib/codex-token-refresh.js +140 -140
- package/src/lib/codex-token-usage.js +195 -195
- package/src/lib/codex-usage-record.js +195 -195
- package/src/lib/collection-pause.js +77 -0
- package/src/lib/command-runner.js +313 -313
- package/src/lib/commandcode-limits.js +317 -317
- package/src/lib/context-health.js +124 -124
- package/src/lib/cursor-config.js +605 -605
- package/src/lib/cursor-store.js +1918 -1918
- package/src/lib/debug-flags.js +7 -7
- package/src/lib/devin-limits.js +249 -249
- package/src/lib/devin-usage.js +212 -212
- package/src/lib/diagnostics.js +383 -383
- package/src/lib/doctor.js +385 -385
- package/src/lib/dumate.js +95 -95
- package/src/lib/fs.js +455 -455
- package/src/lib/function-url.js +14 -14
- package/src/lib/gemini-config.js +291 -291
- package/src/lib/git-outcomes.js +243 -243
- package/src/lib/grok-context-breakdown.js +890 -890
- package/src/lib/grok-hook.js +360 -360
- package/src/lib/grok-limits.js +865 -865
- package/src/lib/grok-usage.js +98 -98
- package/src/lib/heatmap-compact.js +114 -114
- package/src/lib/ingest-sanitize.js +41 -41
- package/src/lib/init-flow.js +42 -42
- package/src/lib/install-resolver.js +170 -170
- package/src/lib/jsonl-lines.js +134 -134
- package/src/lib/kimi-model-repair.js +173 -173
- package/src/lib/kimi-profile.js +61 -61
- package/src/lib/kimi-session.js +216 -216
- package/src/lib/local-api.js +3588 -3588
- package/src/lib/machine-id.js +238 -238
- package/src/lib/multi-install-parser.js +113 -113
- package/src/lib/notify-command.js +38 -38
- package/src/lib/omp-hook.js +589 -589
- package/src/lib/openclaw-cli.js +104 -104
- package/src/lib/openclaw-hook.js +375 -375
- package/src/lib/openclaw-session-plugin.js +560 -560
- package/src/lib/opencode-config.js +121 -121
- package/src/lib/opencode-go-limits.js +807 -807
- package/src/lib/outcomes-engine.js +253 -253
- package/src/lib/passive-mode.js +219 -219
- package/src/lib/pet-packages.js +722 -722
- package/src/lib/pricing/curated-overrides.json +822 -822
- package/src/lib/pricing/index.js +379 -379
- package/src/lib/pricing/litellm-fetcher.js +172 -172
- package/src/lib/pricing/matcher.js +456 -456
- package/src/lib/pricing/seed-snapshot.json +1 -1
- package/src/lib/progress.js +76 -76
- package/src/lib/project-usage-purge.js +117 -117
- package/src/lib/prompt.js +24 -24
- package/src/lib/provider-status.js +104 -104
- package/src/lib/proxy-env.js +489 -489
- package/src/lib/proxy-settings.js +163 -163
- package/src/lib/qoder-cn-cli-limits.js +119 -119
- package/src/lib/qoder-limits.js +880 -880
- package/src/lib/quiet-warnings.js +26 -26
- package/src/lib/rollout.js +26005 -25966
- package/src/lib/runtime-config.js +9 -4
- package/src/lib/scan-roots.js +277 -277
- package/src/lib/scheduled-task.js +145 -0
- package/src/lib/sentry.js +231 -231
- package/src/lib/session-analytics.js +2972 -2972
- package/src/lib/session-performance.js +237 -237
- package/src/lib/session-upload.js +379 -379
- package/src/lib/skill-usage.js +267 -267
- package/src/lib/skills-manager.js +1591 -1591
- package/src/lib/source-metadata.js +48 -48
- package/src/lib/sqlite-reader.js +215 -215
- package/src/lib/star-cta.js +73 -73
- package/src/lib/subscription-manager.js +293 -293
- package/src/lib/subscriptions.js +508 -508
- package/src/lib/sync-report.js +138 -0
- package/src/lib/telemetry.js +193 -193
- package/src/lib/tracker-paths.js +16 -16
- package/src/lib/trae-cn-config.js +548 -548
- package/src/lib/trae-db.js +127 -127
- package/src/lib/trae-snapshot.js +230 -230
- package/src/lib/trae-sqlite.js +143 -143
- package/src/lib/trae-usage.js +121 -121
- package/src/lib/upload-queue.js +134 -134
- package/src/lib/upload-throttle.js +171 -171
- package/src/lib/usage-limits.js +4552 -4552
- package/src/lib/wrapped-aggregator.js +236 -236
- package/src/lib/wsl-probe.js +281 -281
- package/src/lib/zcode-limits.js +1172 -1172
- package/src/lib/zcode-reset-credits.js +66 -66
- package/test/audit-fixes.test.js +200 -0
- package/test/cli-smoke.test.js +53 -53
- package/test/collection-controls.test.js +210 -0
- package/test/ingest-sanitize.test.js +162 -162
- package/test/quiet-warnings.test.js +53 -53
- package/test/session-upload.test.js +427 -427
package/src/lib/debug-flags.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
function stripDebugFlag(argv, env = process.env) {
|
|
2
|
-
const filtered = Array.isArray(argv) ? argv.filter((arg) => arg !== "--debug") : [];
|
|
3
|
-
const debugEnv = String(env?.TOKENUSAGE_DEBUG || "") === "1";
|
|
4
|
-
return { argv: filtered, debug: filtered.length !== (argv || []).length || debugEnv };
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
module.exports = { stripDebugFlag };
|
|
1
|
+
function stripDebugFlag(argv, env = process.env) {
|
|
2
|
+
const filtered = Array.isArray(argv) ? argv.filter((arg) => arg !== "--debug") : [];
|
|
3
|
+
const debugEnv = String(env?.TOKENUSAGE_DEBUG || "") === "1";
|
|
4
|
+
return { argv: filtered, debug: filtered.length !== (argv || []).length || debugEnv };
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
module.exports = { stripDebugFlag };
|
package/src/lib/devin-limits.js
CHANGED
|
@@ -1,249 +1,249 @@
|
|
|
1
|
-
// Devin subscription usage limits.
|
|
2
|
-
//
|
|
3
|
-
// Source: the official seat-management RPC the Devin web app calls,
|
|
4
|
-
// POST https://server.codeium.com/exa.seat_management_pb.SeatManagementService/GetPlanStatus
|
|
5
|
-
// authenticated by `x-auth-token` — the session token the Devin CLI stores in
|
|
6
|
-
// $XDG_DATA_HOME/devin/credentials.toml (~/.local/share/devin/ fallback).
|
|
7
|
-
//
|
|
8
|
-
// Two non-obvious contract points, both verified against the official
|
|
9
|
-
// generated descriptor (docs/devin-limits.md):
|
|
10
|
-
// - the quota percent/reset fields are proto3 implicit scalars, so the
|
|
11
|
-
// server omits them at 0: absent percent + live reset = exhausted
|
|
12
|
-
// (100% used), both absent = no such window;
|
|
13
|
-
// - a non-default api_server_url is an unsupported configuration, never a
|
|
14
|
-
// different request destination — the token only ever goes to the fixed
|
|
15
|
-
// host above.
|
|
16
|
-
|
|
17
|
-
const fs = require("node:fs");
|
|
18
|
-
const path = require("node:path");
|
|
19
|
-
|
|
20
|
-
const DEVIN_PLAN_STATUS_URL =
|
|
21
|
-
"https://server.codeium.com/exa.seat_management_pb.SeatManagementService/GetPlanStatus";
|
|
22
|
-
const DEVIN_API_ORIGIN = "https://server.codeium.com";
|
|
23
|
-
|
|
24
|
-
const DEVIN_DAILY_WINDOW_SECONDS = 24 * 60 * 60;
|
|
25
|
-
const DEVIN_WEEKLY_WINDOW_SECONDS = 7 * 24 * 60 * 60;
|
|
26
|
-
|
|
27
|
-
function isNonEmptyString(value) {
|
|
28
|
-
return typeof value === "string" && value.trim().length > 0;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
// Minimal root-level TOML reader for the CLI-written credentials file: bare
|
|
32
|
-
// `key = value` lines before the first `[section]`, nothing else.
|
|
33
|
-
function parseDevinCredentialsToml(raw) {
|
|
34
|
-
const fields = {};
|
|
35
|
-
for (const line of String(raw).split(/\r?\n/)) {
|
|
36
|
-
const trimmed = line.trim();
|
|
37
|
-
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
38
|
-
if (trimmed.startsWith("[")) break;
|
|
39
|
-
const match = /^([A-Za-z0-9_]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s#]+))\s*(?:#.*)?$/.exec(
|
|
40
|
-
trimmed,
|
|
41
|
-
);
|
|
42
|
-
if (!match) continue;
|
|
43
|
-
const [, key, doubleQuoted, singleQuoted, bare] = match;
|
|
44
|
-
fields[key] = doubleQuoted ?? singleQuoted ?? bare ?? "";
|
|
45
|
-
}
|
|
46
|
-
return fields;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
// Returns { apiKey } or null when no sign-in exists (no home, or the file is
|
|
50
|
-
// absent — ENOENT only). Any other read failure or a mangled file throws an
|
|
51
|
-
// owned, actionable error with no path or filesystem details, so a broken
|
|
52
|
-
// sign-in can never masquerade as "not configured".
|
|
53
|
-
function readDevinCredentials({ home, env = process.env } = {}) {
|
|
54
|
-
const xdg = env && typeof env === "object" ? env.XDG_DATA_HOME : null;
|
|
55
|
-
const dir = isNonEmptyString(xdg)
|
|
56
|
-
? xdg.trim()
|
|
57
|
-
: isNonEmptyString(home)
|
|
58
|
-
? home.trim()
|
|
59
|
-
: isNonEmptyString(env?.HOME)
|
|
60
|
-
? env.HOME.trim()
|
|
61
|
-
: null;
|
|
62
|
-
if (!dir) return null;
|
|
63
|
-
const base = isNonEmptyString(xdg)
|
|
64
|
-
? path.join(dir, "devin", "credentials.toml")
|
|
65
|
-
: path.join(dir, ".local", "share", "devin", "credentials.toml");
|
|
66
|
-
let raw;
|
|
67
|
-
try {
|
|
68
|
-
raw = fs.readFileSync(base, "utf8");
|
|
69
|
-
} catch (error) {
|
|
70
|
-
if (error && error.code === "ENOENT") return null;
|
|
71
|
-
throw new Error(
|
|
72
|
-
"Could not read the Devin CLI credentials file — check its permissions or run `devin auth login` to sign in again.",
|
|
73
|
-
);
|
|
74
|
-
}
|
|
75
|
-
const fields = parseDevinCredentialsToml(raw);
|
|
76
|
-
const apiKey = isNonEmptyString(fields.windsurf_api_key)
|
|
77
|
-
? fields.windsurf_api_key.trim()
|
|
78
|
-
: null;
|
|
79
|
-
if (!apiKey) {
|
|
80
|
-
throw new Error(
|
|
81
|
-
"Devin credentials file has no sign-in token — run `devin auth login`.",
|
|
82
|
-
);
|
|
83
|
-
}
|
|
84
|
-
const apiServerUrl = isNonEmptyString(fields.api_server_url)
|
|
85
|
-
? fields.api_server_url.trim().replace(/\/+$/, "")
|
|
86
|
-
: null;
|
|
87
|
-
if (apiServerUrl && apiServerUrl !== DEVIN_API_ORIGIN) {
|
|
88
|
-
throw new Error(
|
|
89
|
-
"Devin credentials point at a custom api_server_url, which this quota provider does not support.",
|
|
90
|
-
);
|
|
91
|
-
}
|
|
92
|
-
return { apiKey };
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
function malformed(field) {
|
|
96
|
-
return new Error(`Devin quota response has a malformed ${field}.`);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
// undefined → proto-default semantics handled by the caller; null/non-numeric
|
|
100
|
-
// → malformed. Percentages are clamped defensively to 0..100.
|
|
101
|
-
function normalizeRemainingPercent(value) {
|
|
102
|
-
if (value === undefined) return undefined;
|
|
103
|
-
if (typeof value !== "number" && typeof value !== "string") {
|
|
104
|
-
throw malformed("quota remaining percent");
|
|
105
|
-
}
|
|
106
|
-
if (typeof value === "string" && value.trim() === "") {
|
|
107
|
-
throw malformed("quota remaining percent");
|
|
108
|
-
}
|
|
109
|
-
const n = Number(value);
|
|
110
|
-
if (!Number.isFinite(n)) throw malformed("quota remaining percent");
|
|
111
|
-
if (n <= 0) return 0;
|
|
112
|
-
if (n >= 100) return 100;
|
|
113
|
-
return n;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// int64 unix seconds (JSON string or number). undefined or proto-default 0 →
|
|
117
|
-
// absent; null/non-numeric/non-positive → malformed. Returns epoch ms.
|
|
118
|
-
function normalizeResetMs(value) {
|
|
119
|
-
if (value === undefined || value === 0 || value === "0") return null;
|
|
120
|
-
if (typeof value !== "number" && typeof value !== "string") {
|
|
121
|
-
throw malformed("quota reset timestamp");
|
|
122
|
-
}
|
|
123
|
-
if (typeof value === "string" && value.trim() === "") {
|
|
124
|
-
throw malformed("quota reset timestamp");
|
|
125
|
-
}
|
|
126
|
-
const n = Number(value);
|
|
127
|
-
if (!Number.isFinite(n) || n <= 0) throw malformed("quota reset timestamp");
|
|
128
|
-
const ms = n * 1000;
|
|
129
|
-
if (!Number.isFinite(new Date(ms).getTime())) {
|
|
130
|
-
throw malformed("quota reset timestamp");
|
|
131
|
-
}
|
|
132
|
-
return ms;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
function normalizeWindow({ remainingPercent, resetUnix, hidden, windowSeconds }) {
|
|
136
|
-
if (hidden === true) return null;
|
|
137
|
-
const resetMs = normalizeResetMs(resetUnix);
|
|
138
|
-
const remaining = normalizeRemainingPercent(remainingPercent);
|
|
139
|
-
if (remaining === undefined && resetMs === null) return null;
|
|
140
|
-
return {
|
|
141
|
-
used_percent: remaining === undefined ? 100 : 100 - remaining,
|
|
142
|
-
reset_at: resetMs === null ? null : new Date(resetMs).toISOString(),
|
|
143
|
-
limit_window_seconds: windowSeconds,
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
function normalizePlanStatus(body) {
|
|
148
|
-
const planStatus =
|
|
149
|
-
body && typeof body === "object" ? body.planStatus : undefined;
|
|
150
|
-
if (!planStatus || typeof planStatus !== "object") {
|
|
151
|
-
throw new Error("Devin quota response is missing planStatus.");
|
|
152
|
-
}
|
|
153
|
-
const planInfo =
|
|
154
|
-
planStatus.planInfo && typeof planStatus.planInfo === "object"
|
|
155
|
-
? planStatus.planInfo
|
|
156
|
-
: {};
|
|
157
|
-
const planLabel = isNonEmptyString(planInfo.planName)
|
|
158
|
-
? planInfo.planName.trim()
|
|
159
|
-
: null;
|
|
160
|
-
|
|
161
|
-
// Legacy Windsurf billing fills ACU credit fields instead of the daily /
|
|
162
|
-
// weekly quota; those strategies have nothing renderable here.
|
|
163
|
-
const billingStrategy = planInfo.billingStrategy;
|
|
164
|
-
if (
|
|
165
|
-
billingStrategy !== undefined &&
|
|
166
|
-
billingStrategy !== "BILLING_STRATEGY_QUOTA"
|
|
167
|
-
) {
|
|
168
|
-
return { plan_label: planLabel, primary_window: null, secondary_window: null };
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
return {
|
|
172
|
-
plan_label: planLabel,
|
|
173
|
-
primary_window: normalizeWindow({
|
|
174
|
-
remainingPercent: planStatus.dailyQuotaRemainingPercent,
|
|
175
|
-
resetUnix: planStatus.dailyQuotaResetAtUnix,
|
|
176
|
-
hidden: planInfo.hideDailyQuota === true,
|
|
177
|
-
windowSeconds: DEVIN_DAILY_WINDOW_SECONDS,
|
|
178
|
-
}),
|
|
179
|
-
secondary_window: normalizeWindow({
|
|
180
|
-
remainingPercent: planStatus.weeklyQuotaRemainingPercent,
|
|
181
|
-
resetUnix: planStatus.weeklyQuotaResetAtUnix,
|
|
182
|
-
hidden: planInfo.hideWeeklyQuota === true,
|
|
183
|
-
windowSeconds: DEVIN_WEEKLY_WINDOW_SECONDS,
|
|
184
|
-
}),
|
|
185
|
-
};
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// `{ configured: false }` when the provider is not enabled or no Devin CLI
|
|
189
|
-
// sign-in exists, otherwise the normalized windows. `enabled` is the user's
|
|
190
|
-
// explicit provider selection forwarded from the local API — without it the
|
|
191
|
-
// credentials file is never opened and no request is made. Throws owned
|
|
192
|
-
// errors only — never raw upstream bodies, filesystem paths or token values.
|
|
193
|
-
// `code: "AUTH_EXPIRED"` flags genuine auth failure for the aggregator's
|
|
194
|
-
// auth_action_required path.
|
|
195
|
-
async function fetchDevinLimits({ home, env = process.env, enabled = false, fetchImpl = fetch } = {}) {
|
|
196
|
-
if (enabled !== true) return { configured: false };
|
|
197
|
-
const credentials = readDevinCredentials({ home, env });
|
|
198
|
-
if (!credentials) return { configured: false };
|
|
199
|
-
|
|
200
|
-
let response;
|
|
201
|
-
try {
|
|
202
|
-
response = await fetchImpl(DEVIN_PLAN_STATUS_URL, {
|
|
203
|
-
method: "POST",
|
|
204
|
-
headers: {
|
|
205
|
-
Accept: "application/json",
|
|
206
|
-
"Content-Type": "application/json",
|
|
207
|
-
"Connect-Protocol-Version": "1",
|
|
208
|
-
"x-auth-token": credentials.apiKey,
|
|
209
|
-
},
|
|
210
|
-
body: "{}",
|
|
211
|
-
// The session token must never reach another origin.
|
|
212
|
-
redirect: "error",
|
|
213
|
-
});
|
|
214
|
-
} catch (error) {
|
|
215
|
-
throw new Error(
|
|
216
|
-
error && (error.name === "AbortError" || error.name === "TimeoutError")
|
|
217
|
-
? "Devin quota request timed out."
|
|
218
|
-
: "Devin quota request failed.",
|
|
219
|
-
);
|
|
220
|
-
}
|
|
221
|
-
if (response?.status === 401 || response?.status === 403) {
|
|
222
|
-
const error = new Error(
|
|
223
|
-
"Devin sign-in expired or was rejected — run `devin auth login` to sign in again.",
|
|
224
|
-
);
|
|
225
|
-
error.code = "AUTH_EXPIRED";
|
|
226
|
-
throw error;
|
|
227
|
-
}
|
|
228
|
-
if (!response?.ok) {
|
|
229
|
-
throw new Error(
|
|
230
|
-
`Devin quota request was rejected (HTTP ${response?.status ?? "?"}).`,
|
|
231
|
-
);
|
|
232
|
-
}
|
|
233
|
-
let body;
|
|
234
|
-
try {
|
|
235
|
-
body = await response.json();
|
|
236
|
-
} catch {
|
|
237
|
-
throw new Error("Devin quota response was not JSON.");
|
|
238
|
-
}
|
|
239
|
-
const windows = normalizePlanStatus(body);
|
|
240
|
-
return {
|
|
241
|
-
configured: true,
|
|
242
|
-
error: null,
|
|
243
|
-
plan_label: windows.plan_label,
|
|
244
|
-
primary_window: windows.primary_window,
|
|
245
|
-
secondary_window: windows.secondary_window,
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
module.exports = { fetchDevinLimits };
|
|
1
|
+
// Devin subscription usage limits.
|
|
2
|
+
//
|
|
3
|
+
// Source: the official seat-management RPC the Devin web app calls,
|
|
4
|
+
// POST https://server.codeium.com/exa.seat_management_pb.SeatManagementService/GetPlanStatus
|
|
5
|
+
// authenticated by `x-auth-token` — the session token the Devin CLI stores in
|
|
6
|
+
// $XDG_DATA_HOME/devin/credentials.toml (~/.local/share/devin/ fallback).
|
|
7
|
+
//
|
|
8
|
+
// Two non-obvious contract points, both verified against the official
|
|
9
|
+
// generated descriptor (docs/devin-limits.md):
|
|
10
|
+
// - the quota percent/reset fields are proto3 implicit scalars, so the
|
|
11
|
+
// server omits them at 0: absent percent + live reset = exhausted
|
|
12
|
+
// (100% used), both absent = no such window;
|
|
13
|
+
// - a non-default api_server_url is an unsupported configuration, never a
|
|
14
|
+
// different request destination — the token only ever goes to the fixed
|
|
15
|
+
// host above.
|
|
16
|
+
|
|
17
|
+
const fs = require("node:fs");
|
|
18
|
+
const path = require("node:path");
|
|
19
|
+
|
|
20
|
+
const DEVIN_PLAN_STATUS_URL =
|
|
21
|
+
"https://server.codeium.com/exa.seat_management_pb.SeatManagementService/GetPlanStatus";
|
|
22
|
+
const DEVIN_API_ORIGIN = "https://server.codeium.com";
|
|
23
|
+
|
|
24
|
+
const DEVIN_DAILY_WINDOW_SECONDS = 24 * 60 * 60;
|
|
25
|
+
const DEVIN_WEEKLY_WINDOW_SECONDS = 7 * 24 * 60 * 60;
|
|
26
|
+
|
|
27
|
+
function isNonEmptyString(value) {
|
|
28
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Minimal root-level TOML reader for the CLI-written credentials file: bare
|
|
32
|
+
// `key = value` lines before the first `[section]`, nothing else.
|
|
33
|
+
function parseDevinCredentialsToml(raw) {
|
|
34
|
+
const fields = {};
|
|
35
|
+
for (const line of String(raw).split(/\r?\n/)) {
|
|
36
|
+
const trimmed = line.trim();
|
|
37
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
38
|
+
if (trimmed.startsWith("[")) break;
|
|
39
|
+
const match = /^([A-Za-z0-9_]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s#]+))\s*(?:#.*)?$/.exec(
|
|
40
|
+
trimmed,
|
|
41
|
+
);
|
|
42
|
+
if (!match) continue;
|
|
43
|
+
const [, key, doubleQuoted, singleQuoted, bare] = match;
|
|
44
|
+
fields[key] = doubleQuoted ?? singleQuoted ?? bare ?? "";
|
|
45
|
+
}
|
|
46
|
+
return fields;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Returns { apiKey } or null when no sign-in exists (no home, or the file is
|
|
50
|
+
// absent — ENOENT only). Any other read failure or a mangled file throws an
|
|
51
|
+
// owned, actionable error with no path or filesystem details, so a broken
|
|
52
|
+
// sign-in can never masquerade as "not configured".
|
|
53
|
+
function readDevinCredentials({ home, env = process.env } = {}) {
|
|
54
|
+
const xdg = env && typeof env === "object" ? env.XDG_DATA_HOME : null;
|
|
55
|
+
const dir = isNonEmptyString(xdg)
|
|
56
|
+
? xdg.trim()
|
|
57
|
+
: isNonEmptyString(home)
|
|
58
|
+
? home.trim()
|
|
59
|
+
: isNonEmptyString(env?.HOME)
|
|
60
|
+
? env.HOME.trim()
|
|
61
|
+
: null;
|
|
62
|
+
if (!dir) return null;
|
|
63
|
+
const base = isNonEmptyString(xdg)
|
|
64
|
+
? path.join(dir, "devin", "credentials.toml")
|
|
65
|
+
: path.join(dir, ".local", "share", "devin", "credentials.toml");
|
|
66
|
+
let raw;
|
|
67
|
+
try {
|
|
68
|
+
raw = fs.readFileSync(base, "utf8");
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (error && error.code === "ENOENT") return null;
|
|
71
|
+
throw new Error(
|
|
72
|
+
"Could not read the Devin CLI credentials file — check its permissions or run `devin auth login` to sign in again.",
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
const fields = parseDevinCredentialsToml(raw);
|
|
76
|
+
const apiKey = isNonEmptyString(fields.windsurf_api_key)
|
|
77
|
+
? fields.windsurf_api_key.trim()
|
|
78
|
+
: null;
|
|
79
|
+
if (!apiKey) {
|
|
80
|
+
throw new Error(
|
|
81
|
+
"Devin credentials file has no sign-in token — run `devin auth login`.",
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
const apiServerUrl = isNonEmptyString(fields.api_server_url)
|
|
85
|
+
? fields.api_server_url.trim().replace(/\/+$/, "")
|
|
86
|
+
: null;
|
|
87
|
+
if (apiServerUrl && apiServerUrl !== DEVIN_API_ORIGIN) {
|
|
88
|
+
throw new Error(
|
|
89
|
+
"Devin credentials point at a custom api_server_url, which this quota provider does not support.",
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
return { apiKey };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function malformed(field) {
|
|
96
|
+
return new Error(`Devin quota response has a malformed ${field}.`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// undefined → proto-default semantics handled by the caller; null/non-numeric
|
|
100
|
+
// → malformed. Percentages are clamped defensively to 0..100.
|
|
101
|
+
function normalizeRemainingPercent(value) {
|
|
102
|
+
if (value === undefined) return undefined;
|
|
103
|
+
if (typeof value !== "number" && typeof value !== "string") {
|
|
104
|
+
throw malformed("quota remaining percent");
|
|
105
|
+
}
|
|
106
|
+
if (typeof value === "string" && value.trim() === "") {
|
|
107
|
+
throw malformed("quota remaining percent");
|
|
108
|
+
}
|
|
109
|
+
const n = Number(value);
|
|
110
|
+
if (!Number.isFinite(n)) throw malformed("quota remaining percent");
|
|
111
|
+
if (n <= 0) return 0;
|
|
112
|
+
if (n >= 100) return 100;
|
|
113
|
+
return n;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// int64 unix seconds (JSON string or number). undefined or proto-default 0 →
|
|
117
|
+
// absent; null/non-numeric/non-positive → malformed. Returns epoch ms.
|
|
118
|
+
function normalizeResetMs(value) {
|
|
119
|
+
if (value === undefined || value === 0 || value === "0") return null;
|
|
120
|
+
if (typeof value !== "number" && typeof value !== "string") {
|
|
121
|
+
throw malformed("quota reset timestamp");
|
|
122
|
+
}
|
|
123
|
+
if (typeof value === "string" && value.trim() === "") {
|
|
124
|
+
throw malformed("quota reset timestamp");
|
|
125
|
+
}
|
|
126
|
+
const n = Number(value);
|
|
127
|
+
if (!Number.isFinite(n) || n <= 0) throw malformed("quota reset timestamp");
|
|
128
|
+
const ms = n * 1000;
|
|
129
|
+
if (!Number.isFinite(new Date(ms).getTime())) {
|
|
130
|
+
throw malformed("quota reset timestamp");
|
|
131
|
+
}
|
|
132
|
+
return ms;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function normalizeWindow({ remainingPercent, resetUnix, hidden, windowSeconds }) {
|
|
136
|
+
if (hidden === true) return null;
|
|
137
|
+
const resetMs = normalizeResetMs(resetUnix);
|
|
138
|
+
const remaining = normalizeRemainingPercent(remainingPercent);
|
|
139
|
+
if (remaining === undefined && resetMs === null) return null;
|
|
140
|
+
return {
|
|
141
|
+
used_percent: remaining === undefined ? 100 : 100 - remaining,
|
|
142
|
+
reset_at: resetMs === null ? null : new Date(resetMs).toISOString(),
|
|
143
|
+
limit_window_seconds: windowSeconds,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function normalizePlanStatus(body) {
|
|
148
|
+
const planStatus =
|
|
149
|
+
body && typeof body === "object" ? body.planStatus : undefined;
|
|
150
|
+
if (!planStatus || typeof planStatus !== "object") {
|
|
151
|
+
throw new Error("Devin quota response is missing planStatus.");
|
|
152
|
+
}
|
|
153
|
+
const planInfo =
|
|
154
|
+
planStatus.planInfo && typeof planStatus.planInfo === "object"
|
|
155
|
+
? planStatus.planInfo
|
|
156
|
+
: {};
|
|
157
|
+
const planLabel = isNonEmptyString(planInfo.planName)
|
|
158
|
+
? planInfo.planName.trim()
|
|
159
|
+
: null;
|
|
160
|
+
|
|
161
|
+
// Legacy Windsurf billing fills ACU credit fields instead of the daily /
|
|
162
|
+
// weekly quota; those strategies have nothing renderable here.
|
|
163
|
+
const billingStrategy = planInfo.billingStrategy;
|
|
164
|
+
if (
|
|
165
|
+
billingStrategy !== undefined &&
|
|
166
|
+
billingStrategy !== "BILLING_STRATEGY_QUOTA"
|
|
167
|
+
) {
|
|
168
|
+
return { plan_label: planLabel, primary_window: null, secondary_window: null };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return {
|
|
172
|
+
plan_label: planLabel,
|
|
173
|
+
primary_window: normalizeWindow({
|
|
174
|
+
remainingPercent: planStatus.dailyQuotaRemainingPercent,
|
|
175
|
+
resetUnix: planStatus.dailyQuotaResetAtUnix,
|
|
176
|
+
hidden: planInfo.hideDailyQuota === true,
|
|
177
|
+
windowSeconds: DEVIN_DAILY_WINDOW_SECONDS,
|
|
178
|
+
}),
|
|
179
|
+
secondary_window: normalizeWindow({
|
|
180
|
+
remainingPercent: planStatus.weeklyQuotaRemainingPercent,
|
|
181
|
+
resetUnix: planStatus.weeklyQuotaResetAtUnix,
|
|
182
|
+
hidden: planInfo.hideWeeklyQuota === true,
|
|
183
|
+
windowSeconds: DEVIN_WEEKLY_WINDOW_SECONDS,
|
|
184
|
+
}),
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// `{ configured: false }` when the provider is not enabled or no Devin CLI
|
|
189
|
+
// sign-in exists, otherwise the normalized windows. `enabled` is the user's
|
|
190
|
+
// explicit provider selection forwarded from the local API — without it the
|
|
191
|
+
// credentials file is never opened and no request is made. Throws owned
|
|
192
|
+
// errors only — never raw upstream bodies, filesystem paths or token values.
|
|
193
|
+
// `code: "AUTH_EXPIRED"` flags genuine auth failure for the aggregator's
|
|
194
|
+
// auth_action_required path.
|
|
195
|
+
async function fetchDevinLimits({ home, env = process.env, enabled = false, fetchImpl = fetch } = {}) {
|
|
196
|
+
if (enabled !== true) return { configured: false };
|
|
197
|
+
const credentials = readDevinCredentials({ home, env });
|
|
198
|
+
if (!credentials) return { configured: false };
|
|
199
|
+
|
|
200
|
+
let response;
|
|
201
|
+
try {
|
|
202
|
+
response = await fetchImpl(DEVIN_PLAN_STATUS_URL, {
|
|
203
|
+
method: "POST",
|
|
204
|
+
headers: {
|
|
205
|
+
Accept: "application/json",
|
|
206
|
+
"Content-Type": "application/json",
|
|
207
|
+
"Connect-Protocol-Version": "1",
|
|
208
|
+
"x-auth-token": credentials.apiKey,
|
|
209
|
+
},
|
|
210
|
+
body: "{}",
|
|
211
|
+
// The session token must never reach another origin.
|
|
212
|
+
redirect: "error",
|
|
213
|
+
});
|
|
214
|
+
} catch (error) {
|
|
215
|
+
throw new Error(
|
|
216
|
+
error && (error.name === "AbortError" || error.name === "TimeoutError")
|
|
217
|
+
? "Devin quota request timed out."
|
|
218
|
+
: "Devin quota request failed.",
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
if (response?.status === 401 || response?.status === 403) {
|
|
222
|
+
const error = new Error(
|
|
223
|
+
"Devin sign-in expired or was rejected — run `devin auth login` to sign in again.",
|
|
224
|
+
);
|
|
225
|
+
error.code = "AUTH_EXPIRED";
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
if (!response?.ok) {
|
|
229
|
+
throw new Error(
|
|
230
|
+
`Devin quota request was rejected (HTTP ${response?.status ?? "?"}).`,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
let body;
|
|
234
|
+
try {
|
|
235
|
+
body = await response.json();
|
|
236
|
+
} catch {
|
|
237
|
+
throw new Error("Devin quota response was not JSON.");
|
|
238
|
+
}
|
|
239
|
+
const windows = normalizePlanStatus(body);
|
|
240
|
+
return {
|
|
241
|
+
configured: true,
|
|
242
|
+
error: null,
|
|
243
|
+
plan_label: windows.plan_label,
|
|
244
|
+
primary_window: windows.primary_window,
|
|
245
|
+
secondary_window: windows.secondary_window,
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
module.exports = { fetchDevinLimits };
|