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
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
// Codex service-tier attribution.
|
|
2
|
-
//
|
|
3
|
-
// The request tier is NOT on the token_count rows. Codex emits it as its own
|
|
4
|
-
// rollout record — `type: "event_msg"`, `payload.type:
|
|
5
|
-
// "thread_settings_applied"`, `payload.thread_settings.service_tier` — written
|
|
6
|
-
// immediately before the `turn_context` of the turn it applies to. A session's
|
|
7
|
-
// first turn has no such record, and CLI-originated sessions
|
|
8
|
-
// (originator codex_cli_rs / codex-tui) often have none at all: on a 1213-file
|
|
9
|
-
// local corpus only 167 files carried the event, covering 25% of token_count
|
|
10
|
-
// events.
|
|
11
|
-
//
|
|
12
|
-
// Attribution rule, and the only one the log shape permits: a token_count row
|
|
13
|
-
// belongs to the most recent preceding thread_settings_applied. With no
|
|
14
|
-
// preceding record the tier is unknown, and unknown is never guessed — it is
|
|
15
|
-
// billed at Standard, exactly as before this file existed.
|
|
16
|
-
|
|
17
|
-
"use strict";
|
|
18
|
-
|
|
19
|
-
// Cheap line prefilter for parsers that avoid JSON.parse on most records.
|
|
20
|
-
const CODEX_SERVICE_TIER_MARKER = '"thread_settings_applied"';
|
|
21
|
-
|
|
22
|
-
// Observed values on the local corpus are "default" (814) and "priority" (58).
|
|
23
|
-
// "priority" is what the CLI writes for what OpenAI's price table and the Codex
|
|
24
|
-
// UI both call Fast; accept the product-facing spelling too so a future rename
|
|
25
|
-
// does not silently fall back to Standard.
|
|
26
|
-
const PRIORITY_SERVICE_TIERS = new Set(["priority", "fast"]);
|
|
27
|
-
|
|
28
|
-
function readCodexServiceTier(obj) {
|
|
29
|
-
if (!obj || obj.type !== "event_msg") return null;
|
|
30
|
-
const payload = obj.payload;
|
|
31
|
-
if (!payload || typeof payload !== "object") return null;
|
|
32
|
-
if (payload.type !== "thread_settings_applied") return null;
|
|
33
|
-
const settings = payload.thread_settings;
|
|
34
|
-
if (!settings || typeof settings !== "object") return null;
|
|
35
|
-
const tier = settings.service_tier;
|
|
36
|
-
if (typeof tier !== "string" || !tier.trim()) return null;
|
|
37
|
-
return tier.trim().toLowerCase();
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function isPriorityServiceTier(tier) {
|
|
41
|
-
return typeof tier === "string" && PRIORITY_SERVICE_TIERS.has(tier);
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
module.exports = {
|
|
45
|
-
CODEX_SERVICE_TIER_MARKER,
|
|
46
|
-
PRIORITY_SERVICE_TIERS,
|
|
47
|
-
readCodexServiceTier,
|
|
48
|
-
isPriorityServiceTier,
|
|
49
|
-
};
|
|
1
|
+
// Codex service-tier attribution.
|
|
2
|
+
//
|
|
3
|
+
// The request tier is NOT on the token_count rows. Codex emits it as its own
|
|
4
|
+
// rollout record — `type: "event_msg"`, `payload.type:
|
|
5
|
+
// "thread_settings_applied"`, `payload.thread_settings.service_tier` — written
|
|
6
|
+
// immediately before the `turn_context` of the turn it applies to. A session's
|
|
7
|
+
// first turn has no such record, and CLI-originated sessions
|
|
8
|
+
// (originator codex_cli_rs / codex-tui) often have none at all: on a 1213-file
|
|
9
|
+
// local corpus only 167 files carried the event, covering 25% of token_count
|
|
10
|
+
// events.
|
|
11
|
+
//
|
|
12
|
+
// Attribution rule, and the only one the log shape permits: a token_count row
|
|
13
|
+
// belongs to the most recent preceding thread_settings_applied. With no
|
|
14
|
+
// preceding record the tier is unknown, and unknown is never guessed — it is
|
|
15
|
+
// billed at Standard, exactly as before this file existed.
|
|
16
|
+
|
|
17
|
+
"use strict";
|
|
18
|
+
|
|
19
|
+
// Cheap line prefilter for parsers that avoid JSON.parse on most records.
|
|
20
|
+
const CODEX_SERVICE_TIER_MARKER = '"thread_settings_applied"';
|
|
21
|
+
|
|
22
|
+
// Observed values on the local corpus are "default" (814) and "priority" (58).
|
|
23
|
+
// "priority" is what the CLI writes for what OpenAI's price table and the Codex
|
|
24
|
+
// UI both call Fast; accept the product-facing spelling too so a future rename
|
|
25
|
+
// does not silently fall back to Standard.
|
|
26
|
+
const PRIORITY_SERVICE_TIERS = new Set(["priority", "fast"]);
|
|
27
|
+
|
|
28
|
+
function readCodexServiceTier(obj) {
|
|
29
|
+
if (!obj || obj.type !== "event_msg") return null;
|
|
30
|
+
const payload = obj.payload;
|
|
31
|
+
if (!payload || typeof payload !== "object") return null;
|
|
32
|
+
if (payload.type !== "thread_settings_applied") return null;
|
|
33
|
+
const settings = payload.thread_settings;
|
|
34
|
+
if (!settings || typeof settings !== "object") return null;
|
|
35
|
+
const tier = settings.service_tier;
|
|
36
|
+
if (typeof tier !== "string" || !tier.trim()) return null;
|
|
37
|
+
return tier.trim().toLowerCase();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function isPriorityServiceTier(tier) {
|
|
41
|
+
return typeof tier === "string" && PRIORITY_SERVICE_TIERS.has(tier);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
module.exports = {
|
|
45
|
+
CODEX_SERVICE_TIER_MARKER,
|
|
46
|
+
PRIORITY_SERVICE_TIERS,
|
|
47
|
+
readCodexServiceTier,
|
|
48
|
+
isPriorityServiceTier,
|
|
49
|
+
};
|
|
@@ -1,140 +1,140 @@
|
|
|
1
|
-
const fs = require("node:fs");
|
|
2
|
-
const path = require("node:path");
|
|
3
|
-
|
|
4
|
-
// Public Codex OAuth client. Same id used by the official `codex` CLI. Aligned with
|
|
5
|
-
// steipete/CodexBar's CodexTokenRefresher.swift — neither is sensitive (it's a public client).
|
|
6
|
-
const REFRESH_ENDPOINT = "https://auth.openai.com/oauth/token";
|
|
7
|
-
const CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
|
|
8
|
-
|
|
9
|
-
// Match the official Codex CLI: when the access token exposes a JWT expiry, refresh only
|
|
10
|
-
// shortly before it expires. Fall back to last_refresh > 8 days for opaque/legacy tokens.
|
|
11
|
-
const REFRESH_THRESHOLD_MS = 8 * 24 * 60 * 60 * 1000;
|
|
12
|
-
const ACCESS_TOKEN_REFRESH_WINDOW_MS = 5 * 60 * 1000;
|
|
13
|
-
|
|
14
|
-
function parseJwtExpirationMs(token) {
|
|
15
|
-
if (typeof token !== "string" || token.length === 0) return null;
|
|
16
|
-
const parts = token.split(".");
|
|
17
|
-
if (parts.length < 2 || !parts[1]) return null;
|
|
18
|
-
try {
|
|
19
|
-
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
20
|
-
const exp = Number(payload?.exp);
|
|
21
|
-
return Number.isFinite(exp) ? exp * 1000 : null;
|
|
22
|
-
} catch (_e) {
|
|
23
|
-
return null;
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function isTokenStale(lastRefreshIso, nowMs = Date.now(), accessToken = null) {
|
|
28
|
-
const expiresAtMs = parseJwtExpirationMs(accessToken);
|
|
29
|
-
if (expiresAtMs !== null) {
|
|
30
|
-
return expiresAtMs <= nowMs + ACCESS_TOKEN_REFRESH_WINDOW_MS;
|
|
31
|
-
}
|
|
32
|
-
if (!lastRefreshIso) return true;
|
|
33
|
-
const ts = Date.parse(lastRefreshIso);
|
|
34
|
-
if (!Number.isFinite(ts)) return true;
|
|
35
|
-
return nowMs - ts > REFRESH_THRESHOLD_MS;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
async function refreshCodexTokens({ refreshToken, fetchImpl = fetch }) {
|
|
39
|
-
if (typeof refreshToken !== "string" || refreshToken.length === 0) {
|
|
40
|
-
const err = new Error("Codex refresh skipped: no refresh_token in auth.json");
|
|
41
|
-
err.code = "NO_REFRESH_TOKEN";
|
|
42
|
-
throw err;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
const res = await fetchImpl(REFRESH_ENDPOINT, {
|
|
46
|
-
method: "POST",
|
|
47
|
-
headers: {
|
|
48
|
-
"Content-Type": "application/json",
|
|
49
|
-
Accept: "application/json",
|
|
50
|
-
},
|
|
51
|
-
body: JSON.stringify({
|
|
52
|
-
client_id: CODEX_CLIENT_ID,
|
|
53
|
-
grant_type: "refresh_token",
|
|
54
|
-
refresh_token: refreshToken,
|
|
55
|
-
}),
|
|
56
|
-
});
|
|
57
|
-
|
|
58
|
-
if (res.status === 401) {
|
|
59
|
-
let openaiErrorCode = null;
|
|
60
|
-
try {
|
|
61
|
-
const body = await res.json();
|
|
62
|
-
openaiErrorCode =
|
|
63
|
-
(body && typeof body.error === "object" && body.error.code) ||
|
|
64
|
-
(typeof body?.error === "string" ? body.error : null) ||
|
|
65
|
-
body?.code ||
|
|
66
|
-
null;
|
|
67
|
-
} catch (_e) {
|
|
68
|
-
// Ignore parse failure — surface the generic reason.
|
|
69
|
-
}
|
|
70
|
-
const reason = String(openaiErrorCode || "").toLowerCase();
|
|
71
|
-
let message = "Codex refresh token was rejected. Run `codex login` to re-authenticate.";
|
|
72
|
-
if (reason === "refresh_token_expired") {
|
|
73
|
-
message = "Codex refresh token expired. Run `codex login` to re-authenticate.";
|
|
74
|
-
} else if (reason === "refresh_token_reused") {
|
|
75
|
-
message =
|
|
76
|
-
"Codex refresh token was already used, likely by another Codex process. " +
|
|
77
|
-
"Run `codex login` to re-authenticate.";
|
|
78
|
-
} else if (reason === "refresh_token_invalidated") {
|
|
79
|
-
message = "Codex refresh token was revoked. Run `codex login` to re-authenticate.";
|
|
80
|
-
}
|
|
81
|
-
const err = new Error(message);
|
|
82
|
-
err.code = "REFRESH_TOKEN_EXPIRED";
|
|
83
|
-
err.openaiErrorCode = openaiErrorCode;
|
|
84
|
-
throw err;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
if (!res.ok) {
|
|
88
|
-
const err = new Error(`Codex token refresh failed: ${res.status}`);
|
|
89
|
-
err.code = "REFRESH_HTTP_ERROR";
|
|
90
|
-
err.status = res.status;
|
|
91
|
-
throw err;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
const body = await res.json();
|
|
95
|
-
if (!body || typeof body.access_token !== "string" || body.access_token.length === 0) {
|
|
96
|
-
const err = new Error("Codex token refresh response missing access_token");
|
|
97
|
-
err.code = "REFRESH_INVALID_RESPONSE";
|
|
98
|
-
throw err;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
return {
|
|
102
|
-
access_token: body.access_token,
|
|
103
|
-
refresh_token:
|
|
104
|
-
typeof body.refresh_token === "string" && body.refresh_token.length > 0
|
|
105
|
-
? body.refresh_token
|
|
106
|
-
: refreshToken,
|
|
107
|
-
id_token: typeof body.id_token === "string" ? body.id_token : null,
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
// Atomic write so a process kill mid-write doesn't corrupt auth.json (which would force the
|
|
112
|
-
// user to re-run `codex` login).
|
|
113
|
-
async function persistRefreshedAuth(authPath, currentAuth, newTokens) {
|
|
114
|
-
const merged = {
|
|
115
|
-
...currentAuth,
|
|
116
|
-
tokens: {
|
|
117
|
-
...(currentAuth.tokens || {}),
|
|
118
|
-
access_token: newTokens.access_token,
|
|
119
|
-
refresh_token: newTokens.refresh_token,
|
|
120
|
-
id_token: newTokens.id_token || currentAuth?.tokens?.id_token || null,
|
|
121
|
-
},
|
|
122
|
-
last_refresh: new Date().toISOString(),
|
|
123
|
-
};
|
|
124
|
-
|
|
125
|
-
const tmp = `${authPath}.tmp.${process.pid}.${Date.now()}`;
|
|
126
|
-
await fs.promises.writeFile(tmp, JSON.stringify(merged, null, 2), { mode: 0o600 });
|
|
127
|
-
await fs.promises.rename(tmp, authPath);
|
|
128
|
-
return merged;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
module.exports = {
|
|
132
|
-
REFRESH_ENDPOINT,
|
|
133
|
-
CODEX_CLIENT_ID,
|
|
134
|
-
REFRESH_THRESHOLD_MS,
|
|
135
|
-
ACCESS_TOKEN_REFRESH_WINDOW_MS,
|
|
136
|
-
parseJwtExpirationMs,
|
|
137
|
-
isTokenStale,
|
|
138
|
-
refreshCodexTokens,
|
|
139
|
-
persistRefreshedAuth,
|
|
140
|
-
};
|
|
1
|
+
const fs = require("node:fs");
|
|
2
|
+
const path = require("node:path");
|
|
3
|
+
|
|
4
|
+
// Public Codex OAuth client. Same id used by the official `codex` CLI. Aligned with
|
|
5
|
+
// steipete/CodexBar's CodexTokenRefresher.swift — neither is sensitive (it's a public client).
|
|
6
|
+
const REFRESH_ENDPOINT = "https://auth.openai.com/oauth/token";
|
|
7
|
+
const CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
|
|
8
|
+
|
|
9
|
+
// Match the official Codex CLI: when the access token exposes a JWT expiry, refresh only
|
|
10
|
+
// shortly before it expires. Fall back to last_refresh > 8 days for opaque/legacy tokens.
|
|
11
|
+
const REFRESH_THRESHOLD_MS = 8 * 24 * 60 * 60 * 1000;
|
|
12
|
+
const ACCESS_TOKEN_REFRESH_WINDOW_MS = 5 * 60 * 1000;
|
|
13
|
+
|
|
14
|
+
function parseJwtExpirationMs(token) {
|
|
15
|
+
if (typeof token !== "string" || token.length === 0) return null;
|
|
16
|
+
const parts = token.split(".");
|
|
17
|
+
if (parts.length < 2 || !parts[1]) return null;
|
|
18
|
+
try {
|
|
19
|
+
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
20
|
+
const exp = Number(payload?.exp);
|
|
21
|
+
return Number.isFinite(exp) ? exp * 1000 : null;
|
|
22
|
+
} catch (_e) {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function isTokenStale(lastRefreshIso, nowMs = Date.now(), accessToken = null) {
|
|
28
|
+
const expiresAtMs = parseJwtExpirationMs(accessToken);
|
|
29
|
+
if (expiresAtMs !== null) {
|
|
30
|
+
return expiresAtMs <= nowMs + ACCESS_TOKEN_REFRESH_WINDOW_MS;
|
|
31
|
+
}
|
|
32
|
+
if (!lastRefreshIso) return true;
|
|
33
|
+
const ts = Date.parse(lastRefreshIso);
|
|
34
|
+
if (!Number.isFinite(ts)) return true;
|
|
35
|
+
return nowMs - ts > REFRESH_THRESHOLD_MS;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function refreshCodexTokens({ refreshToken, fetchImpl = fetch }) {
|
|
39
|
+
if (typeof refreshToken !== "string" || refreshToken.length === 0) {
|
|
40
|
+
const err = new Error("Codex refresh skipped: no refresh_token in auth.json");
|
|
41
|
+
err.code = "NO_REFRESH_TOKEN";
|
|
42
|
+
throw err;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const res = await fetchImpl(REFRESH_ENDPOINT, {
|
|
46
|
+
method: "POST",
|
|
47
|
+
headers: {
|
|
48
|
+
"Content-Type": "application/json",
|
|
49
|
+
Accept: "application/json",
|
|
50
|
+
},
|
|
51
|
+
body: JSON.stringify({
|
|
52
|
+
client_id: CODEX_CLIENT_ID,
|
|
53
|
+
grant_type: "refresh_token",
|
|
54
|
+
refresh_token: refreshToken,
|
|
55
|
+
}),
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
if (res.status === 401) {
|
|
59
|
+
let openaiErrorCode = null;
|
|
60
|
+
try {
|
|
61
|
+
const body = await res.json();
|
|
62
|
+
openaiErrorCode =
|
|
63
|
+
(body && typeof body.error === "object" && body.error.code) ||
|
|
64
|
+
(typeof body?.error === "string" ? body.error : null) ||
|
|
65
|
+
body?.code ||
|
|
66
|
+
null;
|
|
67
|
+
} catch (_e) {
|
|
68
|
+
// Ignore parse failure — surface the generic reason.
|
|
69
|
+
}
|
|
70
|
+
const reason = String(openaiErrorCode || "").toLowerCase();
|
|
71
|
+
let message = "Codex refresh token was rejected. Run `codex login` to re-authenticate.";
|
|
72
|
+
if (reason === "refresh_token_expired") {
|
|
73
|
+
message = "Codex refresh token expired. Run `codex login` to re-authenticate.";
|
|
74
|
+
} else if (reason === "refresh_token_reused") {
|
|
75
|
+
message =
|
|
76
|
+
"Codex refresh token was already used, likely by another Codex process. " +
|
|
77
|
+
"Run `codex login` to re-authenticate.";
|
|
78
|
+
} else if (reason === "refresh_token_invalidated") {
|
|
79
|
+
message = "Codex refresh token was revoked. Run `codex login` to re-authenticate.";
|
|
80
|
+
}
|
|
81
|
+
const err = new Error(message);
|
|
82
|
+
err.code = "REFRESH_TOKEN_EXPIRED";
|
|
83
|
+
err.openaiErrorCode = openaiErrorCode;
|
|
84
|
+
throw err;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (!res.ok) {
|
|
88
|
+
const err = new Error(`Codex token refresh failed: ${res.status}`);
|
|
89
|
+
err.code = "REFRESH_HTTP_ERROR";
|
|
90
|
+
err.status = res.status;
|
|
91
|
+
throw err;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const body = await res.json();
|
|
95
|
+
if (!body || typeof body.access_token !== "string" || body.access_token.length === 0) {
|
|
96
|
+
const err = new Error("Codex token refresh response missing access_token");
|
|
97
|
+
err.code = "REFRESH_INVALID_RESPONSE";
|
|
98
|
+
throw err;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
access_token: body.access_token,
|
|
103
|
+
refresh_token:
|
|
104
|
+
typeof body.refresh_token === "string" && body.refresh_token.length > 0
|
|
105
|
+
? body.refresh_token
|
|
106
|
+
: refreshToken,
|
|
107
|
+
id_token: typeof body.id_token === "string" ? body.id_token : null,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Atomic write so a process kill mid-write doesn't corrupt auth.json (which would force the
|
|
112
|
+
// user to re-run `codex` login).
|
|
113
|
+
async function persistRefreshedAuth(authPath, currentAuth, newTokens) {
|
|
114
|
+
const merged = {
|
|
115
|
+
...currentAuth,
|
|
116
|
+
tokens: {
|
|
117
|
+
...(currentAuth.tokens || {}),
|
|
118
|
+
access_token: newTokens.access_token,
|
|
119
|
+
refresh_token: newTokens.refresh_token,
|
|
120
|
+
id_token: newTokens.id_token || currentAuth?.tokens?.id_token || null,
|
|
121
|
+
},
|
|
122
|
+
last_refresh: new Date().toISOString(),
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
const tmp = `${authPath}.tmp.${process.pid}.${Date.now()}`;
|
|
126
|
+
await fs.promises.writeFile(tmp, JSON.stringify(merged, null, 2), { mode: 0o600 });
|
|
127
|
+
await fs.promises.rename(tmp, authPath);
|
|
128
|
+
return merged;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
module.exports = {
|
|
132
|
+
REFRESH_ENDPOINT,
|
|
133
|
+
CODEX_CLIENT_ID,
|
|
134
|
+
REFRESH_THRESHOLD_MS,
|
|
135
|
+
ACCESS_TOKEN_REFRESH_WINDOW_MS,
|
|
136
|
+
parseJwtExpirationMs,
|
|
137
|
+
isTokenStale,
|
|
138
|
+
refreshCodexTokens,
|
|
139
|
+
persistRefreshedAuth,
|
|
140
|
+
};
|