@kaitranntt/ccs 8.6.1-dev.1 → 8.6.1-dev.10
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/dist/cliproxy/config/provider-route.d.ts +3 -0
- package/dist/cliproxy/config/provider-route.d.ts.map +1 -1
- package/dist/cliproxy/config/provider-route.js +35 -1
- package/dist/cliproxy/config/provider-route.js.map +1 -1
- package/dist/cliproxy/executor/claude-launcher.d.ts.map +1 -1
- package/dist/cliproxy/executor/claude-launcher.js +38 -15
- package/dist/cliproxy/executor/claude-launcher.js.map +1 -1
- package/dist/cliproxy/executor/launch-settings.d.ts +48 -0
- package/dist/cliproxy/executor/launch-settings.d.ts.map +1 -0
- package/dist/cliproxy/executor/launch-settings.js +154 -0
- package/dist/cliproxy/executor/launch-settings.js.map +1 -0
- package/dist/config/loader/config-getters.d.ts +5 -0
- package/dist/config/loader/config-getters.d.ts.map +1 -1
- package/dist/config/loader/config-getters.js +7 -0
- package/dist/config/loader/config-getters.js.map +1 -1
- package/dist/config/loader/defaults-merger.d.ts.map +1 -1
- package/dist/config/loader/defaults-merger.js +5 -0
- package/dist/config/loader/defaults-merger.js.map +1 -1
- package/dist/config/loader/yaml-serializer.d.ts.map +1 -1
- package/dist/config/loader/yaml-serializer.js +3 -2
- package/dist/config/loader/yaml-serializer.js.map +1 -1
- package/dist/config/schemas/index.d.ts +1 -1
- package/dist/config/schemas/index.d.ts.map +1 -1
- package/dist/config/schemas/index.js.map +1 -1
- package/dist/config/schemas/unified-config.d.ts.map +1 -1
- package/dist/config/schemas/unified-config.js +5 -0
- package/dist/config/schemas/unified-config.js.map +1 -1
- package/dist/config/schemas/websearch.d.ts +20 -2
- package/dist/config/schemas/websearch.d.ts.map +1 -1
- package/dist/config/schemas/websearch.js +1 -1
- package/dist/glmt/pipeline/response-builder.d.ts +5 -0
- package/dist/glmt/pipeline/response-builder.d.ts.map +1 -1
- package/dist/glmt/pipeline/response-builder.js +6 -7
- package/dist/glmt/pipeline/response-builder.js.map +1 -1
- package/dist/glmt/pipeline/types.d.ts +2 -7
- package/dist/glmt/pipeline/types.d.ts.map +1 -1
- package/dist/shared/provider-preset-catalog.d.ts +1 -1
- package/dist/shared/provider-preset-catalog.d.ts.map +1 -1
- package/dist/shared/provider-preset-catalog.js +14 -0
- package/dist/shared/provider-preset-catalog.js.map +1 -1
- package/dist/targets/codex-adapter.d.ts.map +1 -1
- package/dist/targets/codex-adapter.js +8 -7
- package/dist/targets/codex-adapter.js.map +1 -1
- package/dist/targets/codex-cliproxy-provider-config.d.ts.map +1 -1
- package/dist/targets/codex-cliproxy-provider-config.js +12 -1
- package/dist/targets/codex-cliproxy-provider-config.js.map +1 -1
- package/dist/ui/assets/{Trans-BpNkQ7ek.js → Trans-By7poS8F.js} +1 -1
- package/dist/ui/assets/{accounts-BjBpKHAo.js → accounts-CT4cNpXE.js} +1 -1
- package/dist/ui/assets/{alert-dialog-pDQKbmfk.js → alert-dialog-D-4eNWT-.js} +1 -1
- package/dist/ui/assets/{api-Bz4gk1bk.js → api-BOsmB6JC.js} +1 -1
- package/dist/ui/assets/{auth-section-DPJ_tnXs.js → auth-section-BNu9bqxZ.js} +1 -1
- package/dist/ui/assets/{backups-section-DGeCRWP2.js → backups-section-QEZ5MeIb.js} +1 -1
- package/dist/ui/assets/{channels-BZHQSZ2O.js → channels-C8lOwrre.js} +1 -1
- package/dist/ui/assets/{checkbox-H7Yhg_4C.js → checkbox-DxCvOyao.js} +1 -1
- package/dist/ui/assets/{claude-extension-BFpic0ox.js → claude-extension-CvbfmbdL.js} +1 -1
- package/dist/ui/assets/{cliproxy-ai-providers-E8zkuN9-.js → cliproxy-ai-providers-jeMd_Enz.js} +1 -1
- package/dist/ui/assets/{cliproxy-control-panel-CXij15eo.js → cliproxy-control-panel-Ylrw7Vt0.js} +1 -1
- package/dist/ui/assets/{cliproxy-DQizRbbC.js → cliproxy-daECx_cg.js} +1 -1
- package/dist/ui/assets/{codex-Clsf_Ll9.js → codex-7d3v_F3-.js} +1 -1
- package/dist/ui/assets/{confirm-dialog-D-AtmCDF.js → confirm-dialog-BGbC3827.js} +1 -1
- package/dist/ui/assets/{copilot-D0Z8CZJb.js → copilot-DGVMqIvj.js} +1 -1
- package/dist/ui/assets/{cursor-BXf4OXxE.js → cursor-D94mZoOn.js} +1 -1
- package/dist/ui/assets/{droid-DUaaFFGf.js → droid-CijT6OtA.js} +1 -1
- package/dist/ui/assets/{globalenv-section-Bi6g0RHv.js → globalenv-section-Cro0fjBM.js} +1 -1
- package/dist/ui/assets/{health-qWLTnC0s.js → health-DFG40_kD.js} +1 -1
- package/dist/ui/assets/{index-BTfHfkkh.js → index-BTJNmedC.js} +1 -1
- package/dist/ui/assets/{index-2aTPFpCV.js → index-Bf0--BiU.js} +1 -1
- package/dist/ui/assets/{index-B8BRpC7W.js → index-Bf5DDwJP.js} +1 -1
- package/dist/ui/assets/{index-BBdOx52b.js → index-BfbJlKvM.js} +1 -1
- package/dist/ui/assets/{index-D4nxVNz2.js → index-D77S3tlM.js} +1 -1
- package/dist/ui/assets/{index-bTno3t7S.js → index-DLRoa85N.js} +1 -1
- package/dist/ui/assets/{index-Dx2jv0Ov.js → index-K_KarWwQ.js} +3 -3
- package/dist/ui/assets/{logs-dRi0gOyI.js → logs-Bc1-UurC.js} +1 -1
- package/dist/ui/assets/{masked-input-DtbQSbOn.js → masked-input-uuW_Ngh8.js} +1 -1
- package/dist/ui/assets/{proxy-status-widget-DxwDomuX.js → proxy-status-widget-BFrQZqYz.js} +1 -1
- package/dist/ui/assets/{raw-json-settings-editor-panel-CDlRVxaa.js → raw-json-settings-editor-panel-DEHwL2oY.js} +1 -1
- package/dist/ui/assets/{searchable-select-DNOKIELZ.js → searchable-select-pEfkrlZT.js} +1 -1
- package/dist/ui/assets/{separator-DlmzFyxp.js → separator-BTcnUF3t.js} +1 -1
- package/dist/ui/assets/{shared-D1fHDQQG.js → shared-DWBCHrPI.js} +1 -1
- package/dist/ui/assets/{table-B0nIYCuj.js → table-DdMU9lLS.js} +1 -1
- package/dist/ui/assets/{updates-BqVdDTJj.js → updates-DfYyQw34.js} +1 -1
- package/dist/ui/assets/{use-accounts-BkjSf38E.js → use-accounts-DnMcRpOC.js} +1 -1
- package/dist/ui/index.html +1 -1
- package/dist/utils/openai-compat-launch-settings.d.ts.map +1 -1
- package/dist/utils/openai-compat-launch-settings.js +6 -0
- package/dist/utils/openai-compat-launch-settings.js.map +1 -1
- package/dist/utils/shell-executor.d.ts +2 -0
- package/dist/utils/shell-executor.d.ts.map +1 -1
- package/dist/utils/shell-executor.js +11 -7
- package/dist/utils/shell-executor.js.map +1 -1
- package/dist/utils/websearch/agy.d.ts +28 -0
- package/dist/utils/websearch/agy.d.ts.map +1 -0
- package/dist/utils/websearch/agy.js +83 -0
- package/dist/utils/websearch/agy.js.map +1 -0
- package/dist/utils/websearch/hook-config.d.ts.map +1 -1
- package/dist/utils/websearch/hook-config.js +3 -0
- package/dist/utils/websearch/hook-config.js.map +1 -1
- package/dist/utils/websearch/hook-env.d.ts.map +1 -1
- package/dist/utils/websearch/hook-env.js +13 -1
- package/dist/utils/websearch/hook-env.js.map +1 -1
- package/dist/utils/websearch/index.d.ts +2 -1
- package/dist/utils/websearch/index.d.ts.map +1 -1
- package/dist/utils/websearch/index.js +7 -2
- package/dist/utils/websearch/index.js.map +1 -1
- package/dist/utils/websearch/status.d.ts.map +1 -1
- package/dist/utils/websearch/status.js +25 -5
- package/dist/utils/websearch/status.js.map +1 -1
- package/dist/utils/websearch/types.d.ts +7 -1
- package/dist/utils/websearch/types.d.ts.map +1 -1
- package/dist/utils/websearch/types.js.map +1 -1
- package/dist/utils/websearch-manager.d.ts +2 -1
- package/dist/utils/websearch-manager.d.ts.map +1 -1
- package/dist/utils/websearch-manager.js +6 -1
- package/dist/utils/websearch-manager.js.map +1 -1
- package/dist/web-server/routes/bar-routes.d.ts +16 -0
- package/dist/web-server/routes/bar-routes.d.ts.map +1 -1
- package/dist/web-server/routes/bar-routes.js.map +1 -1
- package/dist/web-server/routes/websearch-routes.d.ts.map +1 -1
- package/dist/web-server/routes/websearch-routes.js +7 -0
- package/dist/web-server/routes/websearch-routes.js.map +1 -1
- package/dist/web-server/usage/native-quota-collector.d.ts +50 -8
- package/dist/web-server/usage/native-quota-collector.d.ts.map +1 -1
- package/dist/web-server/usage/native-quota-collector.js +849 -71
- package/dist/web-server/usage/native-quota-collector.js.map +1 -1
- package/lib/hooks/websearch-transformer.cjs +81 -4
- package/package.json +1 -1
|
@@ -15,11 +15,48 @@
|
|
|
15
15
|
* - circuit breaker stops calling after repeated 429s for a cooldown
|
|
16
16
|
* - serve-stale-on-failure; only omit a row when there is genuinely no data
|
|
17
17
|
*
|
|
18
|
-
* Claude path: reads
|
|
18
|
+
* Claude path: reads per-profile .credentials.json (file-only, NO keychain)
|
|
19
|
+
* and polls api.anthropic.com/api/oauth/usage. If the file is absent the
|
|
20
|
+
* profile is emitted as a parked row (paused:true) — never a keychain call.
|
|
21
|
+
*
|
|
19
22
|
* Codex path: PRIMARY = live network (chatgpt.com/backend-api/wham/usage, via
|
|
20
23
|
* fetchCodexQuota), FALLBACK = local session logs (getCodexLocalQuota), mirroring
|
|
21
24
|
* the same safety pattern as the Claude path.
|
|
25
|
+
*
|
|
26
|
+
* Multi-profile: each Claude or Codex profile gets its own ProviderState so a
|
|
27
|
+
* 429 on one profile never trips the breaker of another. The active/default
|
|
28
|
+
* profile for each surface is live-polled (paused:false); all other profiles are
|
|
29
|
+
* cache-only (paused:true, force=false hardcoded) so the 2.5s /summary deadline
|
|
30
|
+
* is maintained — at most 2 live upstream calls per /summary regardless of
|
|
31
|
+
* profile count.
|
|
32
|
+
*
|
|
33
|
+
* NO macOS Keychain access anywhere in this module. The old global-default
|
|
34
|
+
* Claude reader (readClaudeCredentials) is kept for back-compat but is no longer
|
|
35
|
+
* used by the multi-profile path.
|
|
22
36
|
*/
|
|
37
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
38
|
+
if (k2 === undefined) k2 = k;
|
|
39
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
40
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
41
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
42
|
+
}
|
|
43
|
+
Object.defineProperty(o, k2, desc);
|
|
44
|
+
}) : (function(o, m, k, k2) {
|
|
45
|
+
if (k2 === undefined) k2 = k;
|
|
46
|
+
o[k2] = m[k];
|
|
47
|
+
}));
|
|
48
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
49
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
50
|
+
}) : function(o, v) {
|
|
51
|
+
o["default"] = v;
|
|
52
|
+
});
|
|
53
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
54
|
+
if (mod && mod.__esModule) return mod;
|
|
55
|
+
var result = {};
|
|
56
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
57
|
+
__setModuleDefault(result, mod);
|
|
58
|
+
return result;
|
|
59
|
+
};
|
|
23
60
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
61
|
exports.getCachedNativeAccountRows = exports.getNativeAccountRows = exports.resetNativeQuotaState = void 0;
|
|
25
62
|
const claude_native_credentials_1 = require("./claude-native-credentials");
|
|
@@ -27,12 +64,25 @@ const quota_fetcher_claude_1 = require("../../cliproxy/quota/quota-fetcher-claud
|
|
|
27
64
|
const quota_fetcher_codex_1 = require("../../cliproxy/quota/quota-fetcher-codex");
|
|
28
65
|
const query_1 = require("../../cliproxy/accounts/query");
|
|
29
66
|
const codex_local_quota_collector_1 = require("./codex-local-quota-collector");
|
|
67
|
+
const fs = __importStar(require("node:fs"));
|
|
68
|
+
const path = __importStar(require("node:path"));
|
|
69
|
+
const os = __importStar(require("node:os"));
|
|
70
|
+
const config_manager_1 = require("../../utils/config-manager");
|
|
30
71
|
// ============================================================================
|
|
31
72
|
// Safety constants (concrete, named, module-level)
|
|
32
73
|
// ============================================================================
|
|
33
74
|
/** On-demand cache TTL. Floor is 5 min; we use 10 min because the bar polls
|
|
34
75
|
* /summary far more often than a hook fires. */
|
|
35
76
|
const NATIVE_QUOTA_TTL_MS = 600000; // 10 minutes
|
|
77
|
+
// After a 401/expired result, cache the reauth row and cool the profile down so
|
|
78
|
+
// an expired account is shown dimmed and re-checked at most this often instead
|
|
79
|
+
// of being re-polled (and re-401'd) on every /summary refresh.
|
|
80
|
+
const REAUTH_COOLDOWN_MS = NATIVE_QUOTA_TTL_MS; // 10 minutes
|
|
81
|
+
// Parked rows (no on-disk creds, quotaStatus 'unsupported') re-check on a short
|
|
82
|
+
// TTL — re-statting credentials is cheap, and this lets a profile that the user
|
|
83
|
+
// just logged into appear within seconds instead of staying dimmed for the full
|
|
84
|
+
// quota TTL. (Reauth/error rows keep the full TTL + cooldown to avoid re-401s.)
|
|
85
|
+
const PARKED_TTL_MS = 30000; // 30 seconds
|
|
36
86
|
/** Exponential backoff base; delay = min(base * 2^n, MAX) + jitter. */
|
|
37
87
|
const RETRY_BASE_MS = 1000;
|
|
38
88
|
/** Ceiling for any single backoff / Retry-After cooldown derived from one call. */
|
|
@@ -43,8 +93,19 @@ const JITTER_MAX_MS = 500;
|
|
|
43
93
|
const CB_TRIP_THRESHOLD = 3;
|
|
44
94
|
/** How long the breaker stays open (zero network) once tripped. */
|
|
45
95
|
const CB_COOLDOWN_MS = 900000; // 15 minutes
|
|
46
|
-
|
|
47
|
-
const
|
|
96
|
+
// Surface identifiers
|
|
97
|
+
const SURFACE_CLAUDE = 'ccs';
|
|
98
|
+
const SURFACE_CODEX = 'ccsx';
|
|
99
|
+
// The "default way of running" a surface — the bare login (e.g. ~/.codex for
|
|
100
|
+
// ccsx), as opposed to a named `ccsx <profile>` profile. Rendered in the Bar as
|
|
101
|
+
// the base command ("ccsx") with a "default" badge, not as a named profile.
|
|
102
|
+
const DEFAULT_PROFILE = 'default';
|
|
103
|
+
// Provider values on the wire (unchanged from before)
|
|
104
|
+
const CLAUDE_NATIVE_PROVIDER = 'claude-code';
|
|
105
|
+
const CODEX_NATIVE_PROVIDER = 'codex';
|
|
106
|
+
// Keep old names as aliases to avoid breaking the existing global collector path
|
|
107
|
+
const CLAUDE_PROVIDER = CLAUDE_NATIVE_PROVIDER;
|
|
108
|
+
const CODEX_PROVIDER = CODEX_NATIVE_PROVIDER;
|
|
48
109
|
function freshProviderState() {
|
|
49
110
|
return {
|
|
50
111
|
cachedRow: null,
|
|
@@ -56,12 +117,21 @@ function freshProviderState() {
|
|
|
56
117
|
backoffAttempt: 0,
|
|
57
118
|
};
|
|
58
119
|
}
|
|
59
|
-
|
|
60
|
-
const
|
|
120
|
+
// Per-profile state maps (key = profile name)
|
|
121
|
+
const claudeProfileStates = new Map();
|
|
122
|
+
const codexProfileStates = new Map();
|
|
123
|
+
function getState(map, key) {
|
|
124
|
+
let s = map.get(key);
|
|
125
|
+
if (!s) {
|
|
126
|
+
s = freshProviderState();
|
|
127
|
+
map.set(key, s);
|
|
128
|
+
}
|
|
129
|
+
return s;
|
|
130
|
+
}
|
|
61
131
|
/** Reset all module state. Tests call this to avoid cross-test pollution. */
|
|
62
132
|
function resetNativeQuotaState() {
|
|
63
|
-
|
|
64
|
-
|
|
133
|
+
claudeProfileStates.clear();
|
|
134
|
+
codexProfileStates.clear();
|
|
65
135
|
}
|
|
66
136
|
exports.resetNativeQuotaState = resetNativeQuotaState;
|
|
67
137
|
// ============================================================================
|
|
@@ -174,12 +244,15 @@ function buildClaudeQuotaWindows(quota) {
|
|
|
174
244
|
}
|
|
175
245
|
return windows;
|
|
176
246
|
}
|
|
177
|
-
function buildClaudeRow(quota, tier, now) {
|
|
247
|
+
function buildClaudeRow(quota, tier, now, surface, profile) {
|
|
178
248
|
const quotaWindows = buildClaudeQuotaWindows(quota);
|
|
179
249
|
return {
|
|
180
|
-
account_id:
|
|
181
|
-
provider:
|
|
182
|
-
|
|
250
|
+
account_id: `${surface}:${profile}`,
|
|
251
|
+
provider: CLAUDE_NATIVE_PROVIDER,
|
|
252
|
+
surface,
|
|
253
|
+
profile,
|
|
254
|
+
is_subscription: true,
|
|
255
|
+
displayName: profile,
|
|
183
256
|
tier,
|
|
184
257
|
paused: false,
|
|
185
258
|
quota_percentage: deriveClaudeQuotaPercentage(quota),
|
|
@@ -208,12 +281,15 @@ function buildCodexQuotaWindows(quota) {
|
|
|
208
281
|
windowMinutes: w.windowMinutes,
|
|
209
282
|
}));
|
|
210
283
|
}
|
|
211
|
-
function buildCodexRow(quota, now) {
|
|
284
|
+
function buildCodexRow(quota, now, surface, profile) {
|
|
212
285
|
const quotaWindows = buildCodexQuotaWindows(quota);
|
|
213
286
|
return {
|
|
214
|
-
account_id:
|
|
215
|
-
provider:
|
|
216
|
-
|
|
287
|
+
account_id: `${surface}:${profile}`,
|
|
288
|
+
provider: CODEX_NATIVE_PROVIDER,
|
|
289
|
+
surface,
|
|
290
|
+
profile,
|
|
291
|
+
is_subscription: true,
|
|
292
|
+
displayName: profile,
|
|
217
293
|
tier: quota.tier,
|
|
218
294
|
paused: false,
|
|
219
295
|
quota_percentage: quota.quotaPercentage,
|
|
@@ -240,7 +316,7 @@ function buildCodexRow(quota, now) {
|
|
|
240
316
|
* stable keys as the Claude path. quota_percentage = min remaining across present
|
|
241
317
|
* core windows. next_reset = soonest core resetAt. No staleAsOf on a live result.
|
|
242
318
|
*/
|
|
243
|
-
function buildCodexNetworkRow(quota, now) {
|
|
319
|
+
function buildCodexNetworkRow(quota, now, surface, profile) {
|
|
244
320
|
const windows = [];
|
|
245
321
|
const fiveHour = quota.coreUsage?.fiveHour;
|
|
246
322
|
if (fiveHour) {
|
|
@@ -276,9 +352,12 @@ function buildCodexNetworkRow(quota, now) {
|
|
|
276
352
|
.sort((a, b) => a.ms - b.ms);
|
|
277
353
|
const nextReset = resets.length > 0 ? resets[0].iso : null;
|
|
278
354
|
return {
|
|
279
|
-
account_id:
|
|
280
|
-
provider:
|
|
281
|
-
|
|
355
|
+
account_id: `${surface}:${profile}`,
|
|
356
|
+
provider: CODEX_NATIVE_PROVIDER,
|
|
357
|
+
surface,
|
|
358
|
+
profile,
|
|
359
|
+
is_subscription: true,
|
|
360
|
+
displayName: profile,
|
|
282
361
|
tier: quota.planType ?? null,
|
|
283
362
|
paused: false,
|
|
284
363
|
quota_percentage: quotaPercentage,
|
|
@@ -302,17 +381,548 @@ function serveCached(state) {
|
|
|
302
381
|
return { ...state.cachedRow, cached: true };
|
|
303
382
|
}
|
|
304
383
|
// ============================================================================
|
|
305
|
-
// Claude
|
|
384
|
+
// File-only Claude credentials reader for per-profile paths (NO keychain)
|
|
385
|
+
// ============================================================================
|
|
386
|
+
/**
|
|
387
|
+
* Read credentials for a specific Claude Code profile (file-only, no keychain).
|
|
388
|
+
*
|
|
389
|
+
* Looks for .credentials.json in the profile's instance directory. If the file
|
|
390
|
+
* is absent or unparseable, returns null — the caller emits a parked row.
|
|
391
|
+
* Never calls security/Keychain — zero new keychain access from this feature.
|
|
392
|
+
*/
|
|
393
|
+
function readClaudeCredentialsForProfileFromDisk(profile) {
|
|
394
|
+
// The bare `ccs` default login uses the standard global credential lookup:
|
|
395
|
+
// ~/.claude/.credentials.json, falling back to the single global
|
|
396
|
+
// "Claude Code-credentials" Keychain item that Claude Code itself maintains.
|
|
397
|
+
// This is the ONE pre-existing global read the shipped Bar already performs --
|
|
398
|
+
// NOT a per-profile Keychain scan. Isolated `ccs auth` profiles below stay
|
|
399
|
+
// file-only and never touch the Keychain.
|
|
400
|
+
if (profile === DEFAULT_PROFILE) {
|
|
401
|
+
return (0, claude_native_credentials_1.readClaudeCredentials)();
|
|
402
|
+
}
|
|
403
|
+
try {
|
|
404
|
+
const instanceDir = path.join((0, config_manager_1.getCcsDir)(), 'instances', profile);
|
|
405
|
+
const credFile = path.join(instanceDir, '.credentials.json');
|
|
406
|
+
if (!fs.existsSync(credFile))
|
|
407
|
+
return null;
|
|
408
|
+
const raw = fs.readFileSync(credFile, 'utf8');
|
|
409
|
+
const parsed = JSON.parse(raw);
|
|
410
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
411
|
+
return parsed;
|
|
412
|
+
}
|
|
413
|
+
return null;
|
|
414
|
+
}
|
|
415
|
+
catch {
|
|
416
|
+
return null;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
// ============================================================================
|
|
420
|
+
// Profile enumeration helpers (production implementations, DI-overridable)
|
|
306
421
|
// ============================================================================
|
|
422
|
+
/**
|
|
423
|
+
* Read Codex native auth from the profile's on-disk auth.json.
|
|
424
|
+
* 'personal' reads ~/.codex/auth.json; other names read codex-instances/<name>/auth.json.
|
|
425
|
+
* Returns null when absent or unparseable.
|
|
426
|
+
*/
|
|
427
|
+
function readCodexNativeAuthFromDisk(profile) {
|
|
428
|
+
try {
|
|
429
|
+
let authPath;
|
|
430
|
+
if (profile === DEFAULT_PROFILE) {
|
|
431
|
+
authPath = path.join(os.homedir(), '.codex', 'auth.json');
|
|
432
|
+
}
|
|
433
|
+
else {
|
|
434
|
+
// resolveCodexProfileDir would validate, but we do it inline to avoid the
|
|
435
|
+
// import coupling and to handle invalid names gracefully (return null).
|
|
436
|
+
const instancesDir = path.join((0, config_manager_1.getCcsDir)(), 'codex-instances');
|
|
437
|
+
authPath = path.join(instancesDir, profile, 'auth.json');
|
|
438
|
+
}
|
|
439
|
+
if (!fs.existsSync(authPath))
|
|
440
|
+
return null;
|
|
441
|
+
const raw = fs.readFileSync(authPath, 'utf8');
|
|
442
|
+
const parsed = JSON.parse(raw);
|
|
443
|
+
const tokens = parsed.tokens;
|
|
444
|
+
if (!tokens)
|
|
445
|
+
return null;
|
|
446
|
+
const accessToken = tokens.access_token;
|
|
447
|
+
const accountId = tokens.account_id;
|
|
448
|
+
if (typeof accessToken !== 'string' || !accessToken)
|
|
449
|
+
return null;
|
|
450
|
+
return {
|
|
451
|
+
accessToken,
|
|
452
|
+
accountId: typeof accountId === 'string' ? accountId : '',
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
catch {
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* List all Claude profiles from the profile registry (merged legacy + unified).
|
|
461
|
+
* Returns [] on any read error so the collector degrades gracefully.
|
|
462
|
+
*/
|
|
463
|
+
function listClaudeProfilesFromDisk() {
|
|
464
|
+
try {
|
|
465
|
+
// Import lazily inside function to avoid circular dep and DI override in tests
|
|
466
|
+
const { ProfileRegistry } = require('../../auth/profile-registry');
|
|
467
|
+
const registry = new ProfileRegistry();
|
|
468
|
+
const profiles = Object.keys(registry.getAllProfilesMerged());
|
|
469
|
+
// Add the bare `ccs` default login (DEFAULT_PROFILE) when ~/.claude exists --
|
|
470
|
+
// the default way of running `ccs`, distinct from named `ccs <profile>`
|
|
471
|
+
// profiles. unshift so it leads before alphabetical sorting downstream.
|
|
472
|
+
if (fs.existsSync(path.join(os.homedir(), '.claude'))) {
|
|
473
|
+
if (!profiles.includes(DEFAULT_PROFILE))
|
|
474
|
+
profiles.unshift(DEFAULT_PROFILE);
|
|
475
|
+
}
|
|
476
|
+
return profiles;
|
|
477
|
+
}
|
|
478
|
+
catch {
|
|
479
|
+
return [];
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Resolve the default Claude profile. A registry-designated default wins;
|
|
484
|
+
* otherwise the bare ~/.claude login (DEFAULT_PROFILE) is the default `ccs`.
|
|
485
|
+
*/
|
|
486
|
+
function getDefaultClaudeProfileFromDisk() {
|
|
487
|
+
try {
|
|
488
|
+
const { ProfileRegistry } = require('../../auth/profile-registry');
|
|
489
|
+
const registry = new ProfileRegistry();
|
|
490
|
+
const reg = registry.getDefaultResolved();
|
|
491
|
+
if (reg)
|
|
492
|
+
return reg;
|
|
493
|
+
}
|
|
494
|
+
catch {
|
|
495
|
+
// fall through to the bare default below
|
|
496
|
+
}
|
|
497
|
+
if (fs.existsSync(path.join(os.homedir(), '.claude')))
|
|
498
|
+
return DEFAULT_PROFILE;
|
|
499
|
+
return null;
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* List all Codex profiles from the registry, plus DEFAULT_PROFILE when the bare
|
|
503
|
+
* ~/.codex/auth.json exists. Returns [] on any read error.
|
|
504
|
+
*/
|
|
505
|
+
function listCodexProfilesFromDisk() {
|
|
506
|
+
try {
|
|
507
|
+
const { CodexProfileRegistry } = require('../../codex-auth/codex-profile-registry');
|
|
508
|
+
const registry = new CodexProfileRegistry();
|
|
509
|
+
const profiles = registry.listProfiles();
|
|
510
|
+
// Add the bare ~/.codex/auth.json (the default `ccsx` invocation) as the
|
|
511
|
+
// DEFAULT_PROFILE account when it exists. It is the "default way of running",
|
|
512
|
+
// distinct from named `ccsx <profile>` profiles.
|
|
513
|
+
if (fs.existsSync(path.join(os.homedir(), '.codex', 'auth.json'))) {
|
|
514
|
+
if (!profiles.includes(DEFAULT_PROFILE))
|
|
515
|
+
profiles.push(DEFAULT_PROFILE);
|
|
516
|
+
}
|
|
517
|
+
return profiles;
|
|
518
|
+
}
|
|
519
|
+
catch {
|
|
520
|
+
return [];
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Resolve the default Codex profile. Falls back to DEFAULT_PROFILE when the bare
|
|
525
|
+
* ~/.codex/auth.json exists and no registry default is set.
|
|
526
|
+
*/
|
|
527
|
+
function getDefaultCodexProfileFromDisk() {
|
|
528
|
+
try {
|
|
529
|
+
const { CodexProfileRegistry } = require('../../codex-auth/codex-profile-registry');
|
|
530
|
+
const registry = new CodexProfileRegistry();
|
|
531
|
+
const def = registry.getDefault();
|
|
532
|
+
if (def)
|
|
533
|
+
return def;
|
|
534
|
+
// Fall back to the bare ~/.codex account (DEFAULT_PROFILE) when no registry
|
|
535
|
+
// default is set — it is the default `ccsx` invocation.
|
|
536
|
+
if (fs.existsSync(path.join(os.homedir(), '.codex', 'auth.json')))
|
|
537
|
+
return DEFAULT_PROFILE;
|
|
538
|
+
return null;
|
|
539
|
+
}
|
|
540
|
+
catch {
|
|
541
|
+
return null;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
// ============================================================================
|
|
545
|
+
// Per-profile collectors with full safety controls
|
|
546
|
+
// ============================================================================
|
|
547
|
+
/**
|
|
548
|
+
* Tag a row with whether it is the surface's default profile (drives the
|
|
549
|
+
* "active" badge only). The row's own `paused` flag is authoritative for
|
|
550
|
+
* dimming: it is already set by the collector to reflect LIVENESS — parked
|
|
551
|
+
* (no on-disk creds / unsupported) rows arrive with paused:true; profiles with
|
|
552
|
+
* a usable token arrive with paused:false regardless of default status. We must
|
|
553
|
+
* NOT override `paused` from `isDefault`, or a valid non-default subscription
|
|
554
|
+
* (e.g. an isolated `ccsx` profile) would render dimmed despite live quota.
|
|
555
|
+
*/
|
|
556
|
+
function markDefault(row, isDefault) {
|
|
557
|
+
return { ...row, is_default: isDefault };
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Tag the row with is_default AND write the flag back onto the cached copy. The
|
|
561
|
+
* collector caches a row before the default profile is known (the default is
|
|
562
|
+
* resolved in the enumerator), so without this the cache-fallback path
|
|
563
|
+
* (getCachedNativeAccountRows) would serve the default account with
|
|
564
|
+
* is_default:false and the UI would stop ordering/tagging it as the default.
|
|
565
|
+
*/
|
|
566
|
+
function markDefaultAndSyncCache(map, profile, row, isDefault) {
|
|
567
|
+
const state = map.get(profile);
|
|
568
|
+
if (state?.cachedRow) {
|
|
569
|
+
state.cachedRow = { ...state.cachedRow, is_default: isDefault };
|
|
570
|
+
}
|
|
571
|
+
return markDefault(row, isDefault);
|
|
572
|
+
}
|
|
573
|
+
async function collectClaudeRowForProfile(profile, deps, force = false) {
|
|
574
|
+
const now = (deps.now ?? Date.now)();
|
|
575
|
+
const state = getState(claudeProfileStates, profile);
|
|
576
|
+
// Serve from cache while within TTL — force bypasses the short-circuit. Parked
|
|
577
|
+
// rows (no creds -> quotaStatus 'unsupported') use a short TTL so a fresh login
|
|
578
|
+
// is picked up within seconds instead of staying dimmed for the full quota TTL.
|
|
579
|
+
if (!force && state.cachedRow) {
|
|
580
|
+
const ttl = state.cachedRow.quotaStatus === 'unsupported' ? PARKED_TTL_MS : NATIVE_QUOTA_TTL_MS;
|
|
581
|
+
if (now - state.cachedAt < ttl)
|
|
582
|
+
return serveCached(state);
|
|
583
|
+
}
|
|
584
|
+
// Breaker open or cooldown active -> zero network, serve stale (may be null).
|
|
585
|
+
// Force does NOT bypass the breaker — it protects the account.
|
|
586
|
+
if (now < state.breakerOpenUntil || now < state.cooldownUntil) {
|
|
587
|
+
return serveCached(state);
|
|
588
|
+
}
|
|
589
|
+
// Coalesce: concurrent callers past TTL share one in-flight fetch.
|
|
590
|
+
if (state.pending) {
|
|
591
|
+
return state.pending;
|
|
592
|
+
}
|
|
593
|
+
// For per-profile reads: use the injected seam (file-only, no keychain).
|
|
594
|
+
const readCreds = deps.readClaudeCredentialsForProfile ??
|
|
595
|
+
((p) => readClaudeCredentialsForProfileFromDisk(p));
|
|
596
|
+
const fetchQuota = deps.fetchClaudeQuota ?? quota_fetcher_claude_1.fetchClaudeQuotaWithToken;
|
|
597
|
+
const sleep = deps.sleep ?? defaultSleep;
|
|
598
|
+
state.pending = (async () => {
|
|
599
|
+
try {
|
|
600
|
+
// Yield once so the `state.pending = (...)()` assignment above completes
|
|
601
|
+
// before any synchronous return below runs the finally that nulls it.
|
|
602
|
+
// Without this, a sync return (e.g. the no-creds parked path) clears
|
|
603
|
+
// pending DURING assignment, leaving a stale resolved promise that the
|
|
604
|
+
// next call's coalescing check would return instead of re-evaluating.
|
|
605
|
+
await Promise.resolve();
|
|
606
|
+
const creds = readCreds(profile);
|
|
607
|
+
// No credentials file found -> emit parked row (needs auth, file absent).
|
|
608
|
+
// This is the expected case when the profile exists in the registry but the
|
|
609
|
+
// user has not logged in via 'ccs auth' for this machine or the credentials
|
|
610
|
+
// are stored only in keychain (which we deliberately do not access here).
|
|
611
|
+
if (!creds) {
|
|
612
|
+
const parkedRow = {
|
|
613
|
+
account_id: `${SURFACE_CLAUDE}:${profile}`,
|
|
614
|
+
provider: CLAUDE_NATIVE_PROVIDER,
|
|
615
|
+
surface: SURFACE_CLAUDE,
|
|
616
|
+
profile,
|
|
617
|
+
is_subscription: true,
|
|
618
|
+
displayName: profile,
|
|
619
|
+
tier: null,
|
|
620
|
+
paused: true,
|
|
621
|
+
quota_percentage: null,
|
|
622
|
+
quotaStatus: 'unsupported',
|
|
623
|
+
next_reset: null,
|
|
624
|
+
is_default: false,
|
|
625
|
+
last_activity_at: null,
|
|
626
|
+
today_cost: null,
|
|
627
|
+
health: 'ok',
|
|
628
|
+
cached: false,
|
|
629
|
+
fetchedAt: new Date(now).toISOString(),
|
|
630
|
+
needsReauth: true,
|
|
631
|
+
};
|
|
632
|
+
// Cache the parked row so repeated calls don't re-stat the fs.
|
|
633
|
+
state.cachedRow = parkedRow;
|
|
634
|
+
state.cachedAt = now;
|
|
635
|
+
return parkedRow;
|
|
636
|
+
}
|
|
637
|
+
// No token / unsupported subscription -> never spend a call, omit the row.
|
|
638
|
+
if (!(0, claude_native_credentials_1.hasSupportedSubscription)(creds)) {
|
|
639
|
+
return serveCached(state);
|
|
640
|
+
}
|
|
641
|
+
const token = (0, claude_native_credentials_1.getAccessToken)(creds);
|
|
642
|
+
if (!token) {
|
|
643
|
+
return serveCached(state);
|
|
644
|
+
}
|
|
645
|
+
const tier = (0, claude_native_credentials_1.getSubscriptionTier)(creds);
|
|
646
|
+
const quota = await fetchQuota(token, `${SURFACE_CLAUDE}:${profile}`);
|
|
647
|
+
if (quota.success) {
|
|
648
|
+
// Success closes the breaker and clears backoff.
|
|
649
|
+
state.consecutive429 = 0;
|
|
650
|
+
state.breakerOpenUntil = 0;
|
|
651
|
+
state.cooldownUntil = 0;
|
|
652
|
+
state.backoffAttempt = 0;
|
|
653
|
+
const row = buildClaudeRow(quota, tier, now, SURFACE_CLAUDE, profile);
|
|
654
|
+
state.cachedRow = row;
|
|
655
|
+
state.cachedAt = now;
|
|
656
|
+
return { ...row, cached: false };
|
|
657
|
+
}
|
|
658
|
+
// 401 -> token expired. Emit a dimmed reauth row so the bar can prompt.
|
|
659
|
+
// Cache it and open a cooldown so the expired account is NOT re-polled
|
|
660
|
+
// (and re-401'd) on every refresh; it re-checks after REAUTH_COOLDOWN_MS,
|
|
661
|
+
// picking up a successful re-auth.
|
|
662
|
+
if (quota.needsReauth) {
|
|
663
|
+
const row = {
|
|
664
|
+
account_id: `${SURFACE_CLAUDE}:${profile}`,
|
|
665
|
+
provider: CLAUDE_NATIVE_PROVIDER,
|
|
666
|
+
surface: SURFACE_CLAUDE,
|
|
667
|
+
profile,
|
|
668
|
+
is_subscription: true,
|
|
669
|
+
displayName: profile,
|
|
670
|
+
tier,
|
|
671
|
+
paused: true,
|
|
672
|
+
quota_percentage: null,
|
|
673
|
+
quotaStatus: 'error',
|
|
674
|
+
next_reset: null,
|
|
675
|
+
is_default: false,
|
|
676
|
+
last_activity_at: null,
|
|
677
|
+
today_cost: null,
|
|
678
|
+
health: 'error',
|
|
679
|
+
cached: false,
|
|
680
|
+
fetchedAt: new Date(now).toISOString(),
|
|
681
|
+
needsReauth: true,
|
|
682
|
+
};
|
|
683
|
+
state.cachedRow = row;
|
|
684
|
+
state.cachedAt = now;
|
|
685
|
+
state.cooldownUntil = now + REAUTH_COOLDOWN_MS;
|
|
686
|
+
return { ...row, cached: false };
|
|
687
|
+
}
|
|
688
|
+
// 429 / 5xx / transient. Apply backoff + breaker, then serve stale.
|
|
689
|
+
const is429 = quota.httpStatus === 429;
|
|
690
|
+
if (is429) {
|
|
691
|
+
state.consecutive429 += 1;
|
|
692
|
+
if (state.consecutive429 >= CB_TRIP_THRESHOLD) {
|
|
693
|
+
state.breakerOpenUntil = now + CB_COOLDOWN_MS;
|
|
694
|
+
}
|
|
695
|
+
const retryAfter = parseRetryAfterMs(quota.errorDetail, now);
|
|
696
|
+
const backoff = retryAfter ?? computeBackoffMs(state.backoffAttempt);
|
|
697
|
+
state.cooldownUntil = now + backoff;
|
|
698
|
+
state.backoffAttempt += 1;
|
|
699
|
+
// We do NOT sleep-then-retry inside the request path (that would burn
|
|
700
|
+
// the request budget). The cooldown gates the NEXT call instead.
|
|
701
|
+
void sleep; // retained as an injectable seam for future inline retry
|
|
702
|
+
}
|
|
703
|
+
else if (quota.retryable) {
|
|
704
|
+
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
705
|
+
state.cooldownUntil = now + backoff;
|
|
706
|
+
state.backoffAttempt += 1;
|
|
707
|
+
}
|
|
708
|
+
// Serve last good row on failure; omit if we never succeeded.
|
|
709
|
+
return serveCached(state);
|
|
710
|
+
}
|
|
711
|
+
catch {
|
|
712
|
+
// Network/parse rejection -> treat as transient, serve stale.
|
|
713
|
+
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
714
|
+
state.cooldownUntil = now + backoff;
|
|
715
|
+
state.backoffAttempt += 1;
|
|
716
|
+
return serveCached(state);
|
|
717
|
+
}
|
|
718
|
+
finally {
|
|
719
|
+
state.pending = null;
|
|
720
|
+
}
|
|
721
|
+
})();
|
|
722
|
+
return state.pending;
|
|
723
|
+
}
|
|
724
|
+
async function collectCodexRowForProfile(profile, deps, force = false) {
|
|
725
|
+
const now = (deps.now ?? Date.now)();
|
|
726
|
+
const state = getState(codexProfileStates, profile);
|
|
727
|
+
// Serve from cache while within TTL — force bypasses the short-circuit. Parked
|
|
728
|
+
// rows (no auth -> quotaStatus 'unsupported') use a short TTL so a fresh login
|
|
729
|
+
// is picked up within seconds instead of staying dimmed for the full quota TTL.
|
|
730
|
+
if (!force && state.cachedRow) {
|
|
731
|
+
const ttl = state.cachedRow.quotaStatus === 'unsupported' ? PARKED_TTL_MS : NATIVE_QUOTA_TTL_MS;
|
|
732
|
+
if (now - state.cachedAt < ttl)
|
|
733
|
+
return serveCached(state);
|
|
734
|
+
}
|
|
735
|
+
// Breaker open or cooldown active -> skip network, go to LOCAL fallback.
|
|
736
|
+
// Force does NOT bypass the breaker — it protects the account.
|
|
737
|
+
const breakerOrCooldownActive = now < state.breakerOpenUntil || now < state.cooldownUntil;
|
|
738
|
+
// Coalesce: concurrent callers past TTL share one in-flight resolution.
|
|
739
|
+
if (state.pending) {
|
|
740
|
+
return state.pending;
|
|
741
|
+
}
|
|
742
|
+
// Resolve the native auth for this profile to get a network accountId.
|
|
743
|
+
const readNativeAuth = deps.readCodexNativeAuth ?? ((p) => readCodexNativeAuthFromDisk(p));
|
|
744
|
+
// For the network fallback: the legacy getDefaultCodexAccountId is the
|
|
745
|
+
// CLIProxy-registry path; for native profiles we use the on-disk auth directly.
|
|
746
|
+
const fetchNetwork = deps.fetchCodexNetworkQuota ?? ((accountId) => (0, quota_fetcher_codex_1.fetchCodexQuota)(accountId));
|
|
747
|
+
const getCodex = deps.getCodexQuota ?? codex_local_quota_collector_1.getCodexLocalQuota;
|
|
748
|
+
const sleep = deps.sleep ?? defaultSleep;
|
|
749
|
+
state.pending = (async () => {
|
|
750
|
+
try {
|
|
751
|
+
// Yield once so the `state.pending = (...)()` assignment completes before
|
|
752
|
+
// any synchronous return below runs the finally that nulls it (otherwise a
|
|
753
|
+
// sync return leaves a stale resolved promise the next call would reuse).
|
|
754
|
+
await Promise.resolve();
|
|
755
|
+
// ----------------------------------------------------------------
|
|
756
|
+
// PRIMARY: live network fetch (skipped when breaker/cooldown active)
|
|
757
|
+
// ----------------------------------------------------------------
|
|
758
|
+
if (!breakerOrCooldownActive) {
|
|
759
|
+
const nativeAuth = readNativeAuth(profile);
|
|
760
|
+
// Use the on-disk accountId for the network call; fall through to local
|
|
761
|
+
// when the auth file is absent (parked profile).
|
|
762
|
+
if (nativeAuth) {
|
|
763
|
+
const quota = await fetchNetwork(nativeAuth.accountId || profile);
|
|
764
|
+
if (quota.success) {
|
|
765
|
+
// A healthy response closes the breaker and clears backoff,
|
|
766
|
+
// regardless of content.
|
|
767
|
+
state.consecutive429 = 0;
|
|
768
|
+
state.breakerOpenUntil = 0;
|
|
769
|
+
state.cooldownUntil = 0;
|
|
770
|
+
state.backoffAttempt = 0;
|
|
771
|
+
// At least one core window (5h/weekly) resolved -> full quota row.
|
|
772
|
+
if (quota.coreUsage?.fiveHour || quota.coreUsage?.weekly) {
|
|
773
|
+
const row = buildCodexNetworkRow(quota, now, SURFACE_CODEX, profile);
|
|
774
|
+
state.cachedRow = row;
|
|
775
|
+
state.cachedAt = now;
|
|
776
|
+
return { ...row, cached: false };
|
|
777
|
+
}
|
|
778
|
+
// Success but no core window. The token authenticated, so this is a
|
|
779
|
+
// VALID active subscription with a sparse payload — emit an active
|
|
780
|
+
// (quota-less) row instead of parking it. Only the bare default keeps
|
|
781
|
+
// falling through to the global local session data below.
|
|
782
|
+
if (profile !== DEFAULT_PROFILE) {
|
|
783
|
+
const row = buildCodexNetworkRow(quota, now, SURFACE_CODEX, profile);
|
|
784
|
+
state.cachedRow = row;
|
|
785
|
+
state.cachedAt = now;
|
|
786
|
+
return { ...row, cached: false };
|
|
787
|
+
}
|
|
788
|
+
// else (default): fall through to LOCAL fallback below.
|
|
789
|
+
}
|
|
790
|
+
else if (quota.needsReauth) {
|
|
791
|
+
// Token expired -> dimmed reauth row. Cache it and cool down so the
|
|
792
|
+
// expired account is NOT re-polled (and re-401'd) every refresh; it
|
|
793
|
+
// re-checks after REAUTH_COOLDOWN_MS to pick up a re-auth.
|
|
794
|
+
const reauthRow = {
|
|
795
|
+
account_id: `${SURFACE_CODEX}:${profile}`,
|
|
796
|
+
provider: CODEX_NATIVE_PROVIDER,
|
|
797
|
+
surface: SURFACE_CODEX,
|
|
798
|
+
profile,
|
|
799
|
+
is_subscription: true,
|
|
800
|
+
displayName: profile,
|
|
801
|
+
tier: null,
|
|
802
|
+
paused: true,
|
|
803
|
+
quota_percentage: null,
|
|
804
|
+
quotaStatus: 'error',
|
|
805
|
+
next_reset: null,
|
|
806
|
+
is_default: false,
|
|
807
|
+
last_activity_at: null,
|
|
808
|
+
today_cost: null,
|
|
809
|
+
health: 'error',
|
|
810
|
+
cached: false,
|
|
811
|
+
fetchedAt: new Date(now).toISOString(),
|
|
812
|
+
needsReauth: true,
|
|
813
|
+
};
|
|
814
|
+
state.cachedRow = reauthRow;
|
|
815
|
+
state.cachedAt = now;
|
|
816
|
+
state.cooldownUntil = now + REAUTH_COOLDOWN_MS;
|
|
817
|
+
return { ...reauthRow, cached: false };
|
|
818
|
+
}
|
|
819
|
+
else if (quota.httpStatus === 429) {
|
|
820
|
+
// 429: apply breaker + backoff, then fall through to local.
|
|
821
|
+
state.consecutive429 += 1;
|
|
822
|
+
if (state.consecutive429 >= CB_TRIP_THRESHOLD) {
|
|
823
|
+
state.breakerOpenUntil = now + CB_COOLDOWN_MS;
|
|
824
|
+
}
|
|
825
|
+
const retryAfter = parseRetryAfterMs(quota.errorDetail, now);
|
|
826
|
+
const backoff = retryAfter ?? computeBackoffMs(state.backoffAttempt);
|
|
827
|
+
state.cooldownUntil = now + backoff;
|
|
828
|
+
state.backoffAttempt += 1;
|
|
829
|
+
void sleep; // retained as an injectable seam for future inline retry
|
|
830
|
+
}
|
|
831
|
+
else if (quota.retryable) {
|
|
832
|
+
// Other transient failure: set cooldown, fall through to local.
|
|
833
|
+
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
834
|
+
state.cooldownUntil = now + backoff;
|
|
835
|
+
state.backoffAttempt += 1;
|
|
836
|
+
}
|
|
837
|
+
else {
|
|
838
|
+
// Terminal non-retryable failure (e.g. 403/404): back off so we
|
|
839
|
+
// don't re-hit a dead endpoint every poll when no local data caches
|
|
840
|
+
// a row to engage the TTL short-circuit. Then fall through to local.
|
|
841
|
+
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
842
|
+
state.cooldownUntil = now + backoff;
|
|
843
|
+
state.backoffAttempt += 1;
|
|
844
|
+
}
|
|
845
|
+
// Fall through to LOCAL fallback below.
|
|
846
|
+
}
|
|
847
|
+
// No on-disk auth for this profile -> fall through to the fallback below.
|
|
848
|
+
}
|
|
849
|
+
// ----------------------------------------------------------------
|
|
850
|
+
// LOCAL FALLBACK: session-log read (zero network). The session logs live
|
|
851
|
+
// in the GLOBAL ~/.codex, so they represent ONLY the bare default account,
|
|
852
|
+
// never a named profile. Using them for a named profile would misattribute
|
|
853
|
+
// the default's usage to the profile, so only the default falls back to
|
|
854
|
+
// local; named profiles park instead.
|
|
855
|
+
// ----------------------------------------------------------------
|
|
856
|
+
if (profile === DEFAULT_PROFILE) {
|
|
857
|
+
const localQuota = await getCodex();
|
|
858
|
+
if (localQuota) {
|
|
859
|
+
const row = buildCodexRow(localQuota, now, SURFACE_CODEX, profile);
|
|
860
|
+
state.cachedRow = row;
|
|
861
|
+
state.cachedAt = now;
|
|
862
|
+
return { ...row, cached: false };
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
// Named profile (or default with no local data): serve the last-known row
|
|
866
|
+
// if any, else a dimmed parked row -- never global local data for a named
|
|
867
|
+
// profile.
|
|
868
|
+
const stale = serveCached(state);
|
|
869
|
+
if (stale)
|
|
870
|
+
return stale;
|
|
871
|
+
const parkedRow = {
|
|
872
|
+
account_id: `${SURFACE_CODEX}:${profile}`,
|
|
873
|
+
provider: CODEX_NATIVE_PROVIDER,
|
|
874
|
+
surface: SURFACE_CODEX,
|
|
875
|
+
profile,
|
|
876
|
+
is_subscription: true,
|
|
877
|
+
displayName: profile,
|
|
878
|
+
tier: null,
|
|
879
|
+
paused: true,
|
|
880
|
+
quota_percentage: null,
|
|
881
|
+
quotaStatus: 'unsupported',
|
|
882
|
+
next_reset: null,
|
|
883
|
+
is_default: false,
|
|
884
|
+
last_activity_at: null,
|
|
885
|
+
today_cost: null,
|
|
886
|
+
health: 'ok',
|
|
887
|
+
cached: false,
|
|
888
|
+
fetchedAt: new Date(now).toISOString(),
|
|
889
|
+
needsReauth: true,
|
|
890
|
+
};
|
|
891
|
+
state.cachedRow = parkedRow;
|
|
892
|
+
state.cachedAt = now;
|
|
893
|
+
return parkedRow;
|
|
894
|
+
}
|
|
895
|
+
catch {
|
|
896
|
+
// Network/parse rejection -> treat as transient, serve stale.
|
|
897
|
+
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
898
|
+
state.cooldownUntil = now + backoff;
|
|
899
|
+
state.backoffAttempt += 1;
|
|
900
|
+
return serveCached(state);
|
|
901
|
+
}
|
|
902
|
+
finally {
|
|
903
|
+
state.pending = null;
|
|
904
|
+
}
|
|
905
|
+
})();
|
|
906
|
+
return state.pending;
|
|
907
|
+
}
|
|
908
|
+
// ============================================================================
|
|
909
|
+
// Legacy single-profile collectors (unchanged; used by old tests + back-compat)
|
|
910
|
+
// ============================================================================
|
|
911
|
+
/**
|
|
912
|
+
* @deprecated Use collectClaudeRowForProfile with the 'default' or appropriate
|
|
913
|
+
* profile name. Kept for backward compatibility with existing tests that stub
|
|
914
|
+
* readCredentials/getDefaultCodexAccountId directly.
|
|
915
|
+
*/
|
|
307
916
|
async function collectClaudeRow(deps, force = false) {
|
|
308
917
|
const now = (deps.now ?? Date.now)();
|
|
309
|
-
|
|
918
|
+
// Use the legacy single-state approach via profile key '__legacy__' to avoid
|
|
919
|
+
// breaking state isolation with the per-profile maps.
|
|
920
|
+
const state = getState(claudeProfileStates, '__legacy__');
|
|
310
921
|
// Serve from cache while within TTL — force bypasses TTL short-circuit.
|
|
311
922
|
if (!force && state.cachedRow && now - state.cachedAt < NATIVE_QUOTA_TTL_MS) {
|
|
312
923
|
return serveCached(state);
|
|
313
924
|
}
|
|
314
925
|
// Breaker open or cooldown active -> zero network, serve stale (may be null).
|
|
315
|
-
// Force does NOT bypass the breaker — it protects the account.
|
|
316
926
|
if (now < state.breakerOpenUntil || now < state.cooldownUntil) {
|
|
317
927
|
return serveCached(state);
|
|
318
928
|
}
|
|
@@ -320,12 +930,12 @@ async function collectClaudeRow(deps, force = false) {
|
|
|
320
930
|
if (state.pending) {
|
|
321
931
|
return state.pending;
|
|
322
932
|
}
|
|
323
|
-
const
|
|
933
|
+
const readCredentialsFn = deps.readCredentials ?? claude_native_credentials_1.readClaudeCredentials;
|
|
324
934
|
const fetchQuota = deps.fetchClaudeQuota ?? quota_fetcher_claude_1.fetchClaudeQuotaWithToken;
|
|
325
935
|
const sleep = deps.sleep ?? defaultSleep;
|
|
326
936
|
state.pending = (async () => {
|
|
327
937
|
try {
|
|
328
|
-
const creds =
|
|
938
|
+
const creds = readCredentialsFn();
|
|
329
939
|
// No token / unsupported subscription -> never spend a call, omit the row.
|
|
330
940
|
if (!creds || !(0, claude_native_credentials_1.hasSupportedSubscription)(creds)) {
|
|
331
941
|
return serveCached(state);
|
|
@@ -342,13 +952,12 @@ async function collectClaudeRow(deps, force = false) {
|
|
|
342
952
|
state.breakerOpenUntil = 0;
|
|
343
953
|
state.cooldownUntil = 0;
|
|
344
954
|
state.backoffAttempt = 0;
|
|
345
|
-
const row =
|
|
955
|
+
const row = buildClaudeRowLegacy(quota, tier, now);
|
|
346
956
|
state.cachedRow = row;
|
|
347
957
|
state.cachedAt = now;
|
|
348
958
|
return { ...row, cached: false };
|
|
349
959
|
}
|
|
350
|
-
// 401 -> token expired.
|
|
351
|
-
// a real, actionable state distinct from a transient failure.
|
|
960
|
+
// 401 -> token expired.
|
|
352
961
|
if (quota.needsReauth) {
|
|
353
962
|
const row = {
|
|
354
963
|
account_id: CLAUDE_PROVIDER,
|
|
@@ -367,11 +976,9 @@ async function collectClaudeRow(deps, force = false) {
|
|
|
367
976
|
fetchedAt: new Date(now).toISOString(),
|
|
368
977
|
needsReauth: true,
|
|
369
978
|
};
|
|
370
|
-
// Do not cache the reauth row as a good value; it should re-evaluate
|
|
371
|
-
// once the user re-auths. But return it now.
|
|
372
979
|
return row;
|
|
373
980
|
}
|
|
374
|
-
// 429 / 5xx / transient.
|
|
981
|
+
// 429 / 5xx / transient.
|
|
375
982
|
const is429 = quota.httpStatus === 429;
|
|
376
983
|
if (is429) {
|
|
377
984
|
state.consecutive429 += 1;
|
|
@@ -382,20 +989,16 @@ async function collectClaudeRow(deps, force = false) {
|
|
|
382
989
|
const backoff = retryAfter ?? computeBackoffMs(state.backoffAttempt);
|
|
383
990
|
state.cooldownUntil = now + backoff;
|
|
384
991
|
state.backoffAttempt += 1;
|
|
385
|
-
|
|
386
|
-
// the request budget). The cooldown gates the NEXT call instead.
|
|
387
|
-
void sleep; // retained as an injectable seam for future inline retry
|
|
992
|
+
void sleep;
|
|
388
993
|
}
|
|
389
994
|
else if (quota.retryable) {
|
|
390
995
|
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
391
996
|
state.cooldownUntil = now + backoff;
|
|
392
997
|
state.backoffAttempt += 1;
|
|
393
998
|
}
|
|
394
|
-
// Serve last good row on failure; omit if we never succeeded.
|
|
395
999
|
return serveCached(state);
|
|
396
1000
|
}
|
|
397
1001
|
catch {
|
|
398
|
-
// Network/parse rejection -> treat as transient, serve stale.
|
|
399
1002
|
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
400
1003
|
state.cooldownUntil = now + backoff;
|
|
401
1004
|
state.backoffAttempt += 1;
|
|
@@ -407,18 +1010,40 @@ async function collectClaudeRow(deps, force = false) {
|
|
|
407
1010
|
})();
|
|
408
1011
|
return state.pending;
|
|
409
1012
|
}
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
1013
|
+
/** Legacy row builder — no surface/profile/is_subscription fields. */
|
|
1014
|
+
function buildClaudeRowLegacy(quota, tier, now) {
|
|
1015
|
+
const quotaWindows = buildClaudeQuotaWindows(quota);
|
|
1016
|
+
return {
|
|
1017
|
+
account_id: CLAUDE_PROVIDER,
|
|
1018
|
+
provider: CLAUDE_PROVIDER,
|
|
1019
|
+
displayName: 'Claude Code',
|
|
1020
|
+
tier,
|
|
1021
|
+
paused: false,
|
|
1022
|
+
quota_percentage: deriveClaudeQuotaPercentage(quota),
|
|
1023
|
+
quotaStatus: 'ok',
|
|
1024
|
+
next_reset: deriveClaudeNextReset(quota),
|
|
1025
|
+
is_default: false,
|
|
1026
|
+
last_activity_at: null,
|
|
1027
|
+
today_cost: null,
|
|
1028
|
+
health: 'ok',
|
|
1029
|
+
cached: false,
|
|
1030
|
+
fetchedAt: new Date(now).toISOString(),
|
|
1031
|
+
needsReauth: false,
|
|
1032
|
+
...(quotaWindows.length > 0 ? { quotaWindows } : {}),
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
/**
|
|
1036
|
+
* Legacy Codex collector — uses the old getDefaultCodexAccountId dep.
|
|
1037
|
+
* Kept for backward compatibility with existing tests.
|
|
1038
|
+
*/
|
|
413
1039
|
async function collectCodexRow(deps, force = false) {
|
|
414
1040
|
const now = (deps.now ?? Date.now)();
|
|
415
|
-
const state =
|
|
1041
|
+
const state = getState(codexProfileStates, '__legacy__');
|
|
416
1042
|
// Serve from cache while within TTL — force bypasses TTL short-circuit.
|
|
417
1043
|
if (!force && state.cachedRow && now - state.cachedAt < NATIVE_QUOTA_TTL_MS) {
|
|
418
1044
|
return serveCached(state);
|
|
419
1045
|
}
|
|
420
1046
|
// Breaker open or cooldown active -> skip network, go to LOCAL fallback.
|
|
421
|
-
// Force does NOT bypass the breaker — it protects the account.
|
|
422
1047
|
const breakerOrCooldownActive = now < state.breakerOpenUntil || now < state.cooldownUntil;
|
|
423
1048
|
// Coalesce: concurrent callers past TTL share one in-flight resolution.
|
|
424
1049
|
if (state.pending) {
|
|
@@ -430,6 +1055,10 @@ async function collectCodexRow(deps, force = false) {
|
|
|
430
1055
|
const sleep = deps.sleep ?? defaultSleep;
|
|
431
1056
|
state.pending = (async () => {
|
|
432
1057
|
try {
|
|
1058
|
+
// Yield once so the `state.pending = (...)()` assignment completes before
|
|
1059
|
+
// any synchronous return below runs the finally that nulls it (otherwise a
|
|
1060
|
+
// sync return leaves a stale resolved promise the next call would reuse).
|
|
1061
|
+
await Promise.resolve();
|
|
433
1062
|
// ----------------------------------------------------------------
|
|
434
1063
|
// PRIMARY: live network fetch (skipped when breaker/cooldown active)
|
|
435
1064
|
// ----------------------------------------------------------------
|
|
@@ -438,19 +1067,12 @@ async function collectCodexRow(deps, force = false) {
|
|
|
438
1067
|
if (accountId) {
|
|
439
1068
|
const quota = await fetchNetwork(accountId);
|
|
440
1069
|
if (quota.success) {
|
|
441
|
-
// A healthy response closes the breaker and clears backoff,
|
|
442
|
-
// regardless of content.
|
|
443
1070
|
state.consecutive429 = 0;
|
|
444
1071
|
state.breakerOpenUntil = 0;
|
|
445
1072
|
state.cooldownUntil = 0;
|
|
446
1073
|
state.backoffAttempt = 0;
|
|
447
|
-
// Only usable when at least one core window (5h/weekly) resolved. A
|
|
448
|
-
// success with empty coreUsage (only code-review/additional windows,
|
|
449
|
-
// or a changed payload) carries no glanceable signal — do NOT cache
|
|
450
|
-
// a contentless "ok" row or clobber a good cache; fall through to
|
|
451
|
-
// the local fallback so the bar shows real data instead.
|
|
452
1074
|
if (quota.coreUsage?.fiveHour || quota.coreUsage?.weekly) {
|
|
453
|
-
const row =
|
|
1075
|
+
const row = buildCodexNetworkRowLegacy(quota, now);
|
|
454
1076
|
state.cachedRow = row;
|
|
455
1077
|
state.cachedAt = now;
|
|
456
1078
|
return { ...row, cached: false };
|
|
@@ -458,7 +1080,6 @@ async function collectCodexRow(deps, force = false) {
|
|
|
458
1080
|
// else: fall through to LOCAL fallback below.
|
|
459
1081
|
}
|
|
460
1082
|
else if (quota.needsReauth) {
|
|
461
|
-
// Token expired -> reauth row; do NOT cache as a good value.
|
|
462
1083
|
return {
|
|
463
1084
|
account_id: CODEX_PROVIDER,
|
|
464
1085
|
provider: CODEX_PROVIDER,
|
|
@@ -478,7 +1099,6 @@ async function collectCodexRow(deps, force = false) {
|
|
|
478
1099
|
};
|
|
479
1100
|
}
|
|
480
1101
|
else if (quota.httpStatus === 429) {
|
|
481
|
-
// 429: apply breaker + backoff, then fall through to local.
|
|
482
1102
|
state.consecutive429 += 1;
|
|
483
1103
|
if (state.consecutive429 >= CB_TRIP_THRESHOLD) {
|
|
484
1104
|
state.breakerOpenUntil = now + CB_COOLDOWN_MS;
|
|
@@ -487,42 +1107,34 @@ async function collectCodexRow(deps, force = false) {
|
|
|
487
1107
|
const backoff = retryAfter ?? computeBackoffMs(state.backoffAttempt);
|
|
488
1108
|
state.cooldownUntil = now + backoff;
|
|
489
1109
|
state.backoffAttempt += 1;
|
|
490
|
-
void sleep;
|
|
1110
|
+
void sleep;
|
|
491
1111
|
}
|
|
492
1112
|
else if (quota.retryable) {
|
|
493
|
-
// Other transient failure: set cooldown, fall through to local.
|
|
494
1113
|
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
495
1114
|
state.cooldownUntil = now + backoff;
|
|
496
1115
|
state.backoffAttempt += 1;
|
|
497
1116
|
}
|
|
498
1117
|
else {
|
|
499
|
-
// Terminal non-retryable failure (e.g. 403/404): back off so we
|
|
500
|
-
// don't re-hit a dead endpoint every poll when no local data caches
|
|
501
|
-
// a row to engage the TTL short-circuit. Then fall through to local.
|
|
502
1118
|
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
503
1119
|
state.cooldownUntil = now + backoff;
|
|
504
1120
|
state.backoffAttempt += 1;
|
|
505
1121
|
}
|
|
506
1122
|
// Fall through to LOCAL fallback below.
|
|
507
1123
|
}
|
|
508
|
-
// No configured accountId -> fall through to local fallback.
|
|
509
1124
|
}
|
|
510
1125
|
// ----------------------------------------------------------------
|
|
511
|
-
// LOCAL FALLBACK
|
|
512
|
-
// when network is unavailable / no accountId / breaker active)
|
|
1126
|
+
// LOCAL FALLBACK
|
|
513
1127
|
// ----------------------------------------------------------------
|
|
514
1128
|
const localQuota = await getCodex();
|
|
515
1129
|
if (localQuota) {
|
|
516
|
-
const row =
|
|
1130
|
+
const row = buildCodexRowLegacy(localQuota, now);
|
|
517
1131
|
state.cachedRow = row;
|
|
518
1132
|
state.cachedAt = now;
|
|
519
1133
|
return { ...row, cached: false };
|
|
520
1134
|
}
|
|
521
|
-
// No local data either: serve stale (may be null).
|
|
522
1135
|
return serveCached(state);
|
|
523
1136
|
}
|
|
524
1137
|
catch {
|
|
525
|
-
// Network/parse rejection -> treat as transient, serve stale.
|
|
526
1138
|
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
527
1139
|
state.cooldownUntil = now + backoff;
|
|
528
1140
|
state.backoffAttempt += 1;
|
|
@@ -534,21 +1146,120 @@ async function collectCodexRow(deps, force = false) {
|
|
|
534
1146
|
})();
|
|
535
1147
|
return state.pending;
|
|
536
1148
|
}
|
|
1149
|
+
/** Legacy Codex row builder (local quota). */
|
|
1150
|
+
function buildCodexRowLegacy(quota, now) {
|
|
1151
|
+
const quotaWindows = buildCodexQuotaWindows(quota);
|
|
1152
|
+
return {
|
|
1153
|
+
account_id: CODEX_PROVIDER,
|
|
1154
|
+
provider: CODEX_PROVIDER,
|
|
1155
|
+
displayName: 'Codex',
|
|
1156
|
+
tier: quota.tier,
|
|
1157
|
+
paused: false,
|
|
1158
|
+
quota_percentage: quota.quotaPercentage,
|
|
1159
|
+
quotaStatus: 'ok',
|
|
1160
|
+
next_reset: quota.nextReset,
|
|
1161
|
+
is_default: false,
|
|
1162
|
+
last_activity_at: null,
|
|
1163
|
+
today_cost: null,
|
|
1164
|
+
health: quota.stale ? 'warning' : 'ok',
|
|
1165
|
+
cached: false,
|
|
1166
|
+
fetchedAt: new Date(now).toISOString(),
|
|
1167
|
+
needsReauth: false,
|
|
1168
|
+
...(quotaWindows.length > 0 ? { quotaWindows } : {}),
|
|
1169
|
+
...(quota.staleAsOf ? { staleAsOf: quota.staleAsOf } : {}),
|
|
1170
|
+
};
|
|
1171
|
+
}
|
|
1172
|
+
/** Legacy Codex network row builder. */
|
|
1173
|
+
function buildCodexNetworkRowLegacy(quota, now) {
|
|
1174
|
+
const windows = [];
|
|
1175
|
+
const fiveHour = quota.coreUsage?.fiveHour;
|
|
1176
|
+
if (fiveHour) {
|
|
1177
|
+
windows.push({
|
|
1178
|
+
key: 'five_hour',
|
|
1179
|
+
label: '5h',
|
|
1180
|
+
usedPercent: 100 - fiveHour.remainingPercent,
|
|
1181
|
+
remainingPercent: fiveHour.remainingPercent,
|
|
1182
|
+
resetAt: fiveHour.resetAt,
|
|
1183
|
+
windowMinutes: FIVE_HOUR_MINUTES,
|
|
1184
|
+
});
|
|
1185
|
+
}
|
|
1186
|
+
const weekly = quota.coreUsage?.weekly;
|
|
1187
|
+
if (weekly) {
|
|
1188
|
+
windows.push({
|
|
1189
|
+
key: 'seven_day',
|
|
1190
|
+
label: 'week',
|
|
1191
|
+
usedPercent: 100 - weekly.remainingPercent,
|
|
1192
|
+
remainingPercent: weekly.remainingPercent,
|
|
1193
|
+
resetAt: weekly.resetAt,
|
|
1194
|
+
windowMinutes: SEVEN_DAY_MINUTES,
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
const coreWindows = [fiveHour, weekly].filter((w) => !!w);
|
|
1198
|
+
const quotaPercentage = coreWindows.length > 0 ? Math.min(...coreWindows.map((w) => w.remainingPercent)) : null;
|
|
1199
|
+
const resets = coreWindows
|
|
1200
|
+
.map((w) => w.resetAt)
|
|
1201
|
+
.filter((r) => typeof r === 'string')
|
|
1202
|
+
.map((r) => ({ iso: r, ms: new Date(r).getTime() }))
|
|
1203
|
+
.filter((r) => Number.isFinite(r.ms))
|
|
1204
|
+
.sort((a, b) => a.ms - b.ms);
|
|
1205
|
+
const nextReset = resets.length > 0 ? resets[0].iso : null;
|
|
1206
|
+
return {
|
|
1207
|
+
account_id: CODEX_PROVIDER,
|
|
1208
|
+
provider: CODEX_PROVIDER,
|
|
1209
|
+
displayName: 'Codex',
|
|
1210
|
+
tier: quota.planType ?? null,
|
|
1211
|
+
paused: false,
|
|
1212
|
+
quota_percentage: quotaPercentage,
|
|
1213
|
+
quotaStatus: 'ok',
|
|
1214
|
+
next_reset: nextReset,
|
|
1215
|
+
is_default: false,
|
|
1216
|
+
last_activity_at: null,
|
|
1217
|
+
today_cost: null,
|
|
1218
|
+
health: 'ok',
|
|
1219
|
+
cached: false,
|
|
1220
|
+
fetchedAt: new Date(now).toISOString(),
|
|
1221
|
+
needsReauth: false,
|
|
1222
|
+
...(windows.length > 0 ? { quotaWindows: windows } : {}),
|
|
1223
|
+
};
|
|
1224
|
+
}
|
|
537
1225
|
// ============================================================================
|
|
538
1226
|
// Public entry point
|
|
539
1227
|
// ============================================================================
|
|
540
1228
|
/**
|
|
541
|
-
* Build the native subscription rows
|
|
1229
|
+
* Build the native subscription rows for /summary.
|
|
1230
|
+
*
|
|
1231
|
+
* When profile-enumeration deps are injected (listClaudeProfiles / listCodexProfiles
|
|
1232
|
+
* etc.), all profiles are enumerated and the active/default profile is live-polled
|
|
1233
|
+
* while non-default profiles are cache-only (parked). This keeps the 2.5s deadline:
|
|
1234
|
+
* at most 2 live upstream calls per /summary regardless of profile count.
|
|
542
1235
|
*
|
|
543
|
-
*
|
|
544
|
-
*
|
|
1236
|
+
* When no enumeration deps are injected (legacy mode / old tests that stub only
|
|
1237
|
+
* readCredentials + getDefaultCodexAccountId), the old single-profile collectors
|
|
1238
|
+
* are used for backward compatibility.
|
|
545
1239
|
*
|
|
546
|
-
* `opts.force` bypasses the TTL short-circuit on
|
|
547
|
-
*
|
|
548
|
-
* respected regardless of force (account protection).
|
|
1240
|
+
* `opts.force` bypasses the TTL short-circuit on the ACTIVE profile. The circuit
|
|
1241
|
+
* breaker is always respected regardless of force (account protection).
|
|
549
1242
|
*/
|
|
550
1243
|
async function getNativeAccountRows(deps = {}, opts) {
|
|
551
1244
|
const force = opts?.force ?? false;
|
|
1245
|
+
// Multi-profile enumeration is the DEFAULT (production) behavior. The legacy
|
|
1246
|
+
// single-profile path is retained ONLY for backward-compat with old tests that
|
|
1247
|
+
// inject readCredentials / getDefaultCodexAccountId and assert the original
|
|
1248
|
+
// single-row output. Those harnesses never inject the enumeration seams; the
|
|
1249
|
+
// new multi-profile tests pair both seams, and production injects neither — so
|
|
1250
|
+
// everything except the legacy harness takes the multi-profile path below.
|
|
1251
|
+
const hasProfileEnumeration = deps.listClaudeProfiles !== undefined ||
|
|
1252
|
+
deps.listCodexProfiles !== undefined ||
|
|
1253
|
+
deps.defaultClaudeProfile !== undefined ||
|
|
1254
|
+
deps.defaultCodexProfile !== undefined;
|
|
1255
|
+
const isLegacyTestHarness = !hasProfileEnumeration &&
|
|
1256
|
+
(deps.readCredentials !== undefined || deps.getDefaultCodexAccountId !== undefined);
|
|
1257
|
+
if (!isLegacyTestHarness) {
|
|
1258
|
+
return getNativeAccountRowsMultiProfile(deps, force);
|
|
1259
|
+
}
|
|
1260
|
+
// Legacy path: backward-compatible with old tests that only inject
|
|
1261
|
+
// readCredentials / getDefaultCodexAccountId. Produces the old single-row
|
|
1262
|
+
// output (account_id='claude-code'/'codex', no surface/profile).
|
|
552
1263
|
const [claude, codex] = await Promise.all([
|
|
553
1264
|
collectClaudeRow(deps, force).catch(() => null),
|
|
554
1265
|
collectCodexRow(deps, force).catch(() => null),
|
|
@@ -561,6 +1272,69 @@ async function getNativeAccountRows(deps = {}, opts) {
|
|
|
561
1272
|
return rows;
|
|
562
1273
|
}
|
|
563
1274
|
exports.getNativeAccountRows = getNativeAccountRows;
|
|
1275
|
+
async function getNativeAccountRowsMultiProfile(deps, force) {
|
|
1276
|
+
const listClaude = deps.listClaudeProfiles ?? listClaudeProfilesFromDisk;
|
|
1277
|
+
const listCodex = deps.listCodexProfiles ?? listCodexProfilesFromDisk;
|
|
1278
|
+
const defaultClaude = deps.defaultClaudeProfile ?? getDefaultClaudeProfileFromDisk;
|
|
1279
|
+
const defaultCodex = deps.defaultCodexProfile ?? getDefaultCodexProfileFromDisk;
|
|
1280
|
+
const claudeProfiles = (() => {
|
|
1281
|
+
try {
|
|
1282
|
+
return listClaude();
|
|
1283
|
+
}
|
|
1284
|
+
catch {
|
|
1285
|
+
return [];
|
|
1286
|
+
}
|
|
1287
|
+
})();
|
|
1288
|
+
const codexProfiles = (() => {
|
|
1289
|
+
try {
|
|
1290
|
+
return listCodex();
|
|
1291
|
+
}
|
|
1292
|
+
catch {
|
|
1293
|
+
return [];
|
|
1294
|
+
}
|
|
1295
|
+
})();
|
|
1296
|
+
const claudeDefault = (() => {
|
|
1297
|
+
try {
|
|
1298
|
+
return defaultClaude();
|
|
1299
|
+
}
|
|
1300
|
+
catch {
|
|
1301
|
+
return null;
|
|
1302
|
+
}
|
|
1303
|
+
})();
|
|
1304
|
+
const codexDefault = (() => {
|
|
1305
|
+
try {
|
|
1306
|
+
return defaultCodex();
|
|
1307
|
+
}
|
|
1308
|
+
catch {
|
|
1309
|
+
return null;
|
|
1310
|
+
}
|
|
1311
|
+
})();
|
|
1312
|
+
const tasks = [];
|
|
1313
|
+
// Forced refresh applies to every profile: parked profiles (no creds) short-
|
|
1314
|
+
// circuit to a parked row with zero network, so forcing them is free, while
|
|
1315
|
+
// every profile that has a usable token gets live quota — not just the
|
|
1316
|
+
// default. Per-profile TTL + breaker still protect each account.
|
|
1317
|
+
for (const p of claudeProfiles) {
|
|
1318
|
+
const isDefault = p === claudeDefault;
|
|
1319
|
+
tasks.push(collectClaudeRowForProfile(p, deps, force)
|
|
1320
|
+
.then((r) => (r ? markDefaultAndSyncCache(claudeProfileStates, p, r, isDefault) : null))
|
|
1321
|
+
.catch(() => null));
|
|
1322
|
+
}
|
|
1323
|
+
for (const p of codexProfiles) {
|
|
1324
|
+
const isDefault = p === codexDefault;
|
|
1325
|
+
tasks.push(collectCodexRowForProfile(p, deps, force)
|
|
1326
|
+
.then((r) => (r ? markDefaultAndSyncCache(codexProfileStates, p, r, isDefault) : null))
|
|
1327
|
+
.catch(() => null));
|
|
1328
|
+
}
|
|
1329
|
+
const results = await Promise.all(tasks);
|
|
1330
|
+
const rows = results.filter((r) => r !== null);
|
|
1331
|
+
// Sort by (surface, profile) for stable ordering.
|
|
1332
|
+
return rows.sort((a, b) => {
|
|
1333
|
+
const sa = (a.surface ?? '') + ':' + (a.profile ?? '');
|
|
1334
|
+
const sb = (b.surface ?? '') + ':' + (b.profile ?? '');
|
|
1335
|
+
return sa.localeCompare(sb);
|
|
1336
|
+
});
|
|
1337
|
+
}
|
|
564
1338
|
/**
|
|
565
1339
|
* Last-known native rows from cache, WITHOUT any fetch (instant, no network).
|
|
566
1340
|
*
|
|
@@ -571,10 +1345,14 @@ exports.getNativeAccountRows = getNativeAccountRows;
|
|
|
571
1345
|
*/
|
|
572
1346
|
function getCachedNativeAccountRows() {
|
|
573
1347
|
const rows = [];
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
1348
|
+
for (const state of claudeProfileStates.values()) {
|
|
1349
|
+
if (state.cachedRow)
|
|
1350
|
+
rows.push({ ...state.cachedRow, cached: true });
|
|
1351
|
+
}
|
|
1352
|
+
for (const state of codexProfileStates.values()) {
|
|
1353
|
+
if (state.cachedRow)
|
|
1354
|
+
rows.push({ ...state.cachedRow, cached: true });
|
|
1355
|
+
}
|
|
578
1356
|
return rows;
|
|
579
1357
|
}
|
|
580
1358
|
exports.getCachedNativeAccountRows = getCachedNativeAccountRows;
|