@kaitranntt/ccs 8.6.1 → 8.7.0-dev.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/dist/auth/profile-detector.d.ts.map +1 -1
- package/dist/auth/profile-detector.js +7 -0
- package/dist/auth/profile-detector.js.map +1 -1
- 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/index.js +1 -1
- package/dist/cliproxy/executor/index.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/commands/bar/bar-paths.d.ts +1 -1
- package/dist/commands/bar/bar-paths.d.ts.map +1 -1
- package/dist/commands/bar/bar-server-probe.d.ts +4 -6
- package/dist/commands/bar/bar-server-probe.d.ts.map +1 -1
- package/dist/commands/bar/bar-server-probe.js +21 -15
- package/dist/commands/bar/bar-server-probe.js.map +1 -1
- package/dist/commands/bar/install-subcommand.d.ts.map +1 -1
- package/dist/commands/bar/install-subcommand.js +2 -7
- package/dist/commands/bar/install-subcommand.js.map +1 -1
- package/dist/commands/bar/launch-descriptor.d.ts +20 -0
- package/dist/commands/bar/launch-descriptor.d.ts.map +1 -0
- package/dist/commands/bar/launch-descriptor.js +82 -0
- package/dist/commands/bar/launch-descriptor.js.map +1 -0
- package/dist/commands/bar/launch-subcommand.d.ts +3 -0
- package/dist/commands/bar/launch-subcommand.d.ts.map +1 -1
- package/dist/commands/bar/launch-subcommand.js +27 -15
- package/dist/commands/bar/launch-subcommand.js.map +1 -1
- package/dist/commands/cliproxy/help-subcommand.js +1 -1
- package/dist/commands/cliproxy/help-subcommand.js.map +1 -1
- package/dist/commands/cliproxy/proxy-lifecycle-subcommand.d.ts +5 -4
- package/dist/commands/cliproxy/proxy-lifecycle-subcommand.d.ts.map +1 -1
- package/dist/commands/cliproxy/proxy-lifecycle-subcommand.js +7 -5
- package/dist/commands/cliproxy/proxy-lifecycle-subcommand.js.map +1 -1
- package/dist/commands/cursor-command.d.ts.map +1 -1
- package/dist/commands/cursor-command.js +2 -0
- package/dist/commands/cursor-command.js.map +1 -1
- 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/cursor/cursor-daemon-entry.d.ts.map +1 -1
- package/dist/cursor/cursor-daemon-entry.js +32 -13
- package/dist/cursor/cursor-daemon-entry.js.map +1 -1
- package/dist/cursor/cursor-daemon.d.ts +4 -1
- package/dist/cursor/cursor-daemon.d.ts.map +1 -1
- package/dist/cursor/cursor-daemon.js +14 -8
- package/dist/cursor/cursor-daemon.js.map +1 -1
- package/dist/cursor/cursor-runtime-probe.d.ts.map +1 -1
- package/dist/cursor/cursor-runtime-probe.js +2 -1
- package/dist/cursor/cursor-runtime-probe.js.map +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/services/logging/log-redaction.d.ts.map +1 -1
- package/dist/services/logging/log-redaction.js +12 -2
- package/dist/services/logging/log-redaction.js.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/bar-auth-token.d.ts +5 -0
- package/dist/utils/bar-auth-token.d.ts.map +1 -1
- package/dist/utils/bar-auth-token.js +23 -1
- package/dist/utils/bar-auth-token.js.map +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/mcp-installer.d.ts +5 -4
- package/dist/utils/websearch/mcp-installer.d.ts.map +1 -1
- package/dist/utils/websearch/mcp-installer.js +7 -13
- package/dist/utils/websearch/mcp-installer.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/cursor-routes.d.ts.map +1 -1
- package/dist/web-server/routes/cursor-routes.js +2 -0
- package/dist/web-server/routes/cursor-routes.js.map +1 -1
- package/dist/web-server/routes/index.d.ts.map +1 -1
- package/dist/web-server/routes/index.js +7 -5
- package/dist/web-server/routes/index.js.map +1 -1
- package/dist/web-server/routes/route-helpers.d.ts.map +1 -1
- package/dist/web-server/routes/route-helpers.js +8 -5
- package/dist/web-server/routes/route-helpers.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 +883 -71
- package/dist/web-server/usage/native-quota-collector.js.map +1 -1
- package/lib/hooks/websearch-transformer.cjs +73 -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,582 @@ 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)
|
|
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 pausedIdentities = getPausedCodexAccountIdentities();
|
|
510
|
+
const profiles = registry
|
|
511
|
+
.listProfiles()
|
|
512
|
+
.filter((name) => !codexProfileMatchesPausedAccount(name, registry.getProfile(name), pausedIdentities));
|
|
513
|
+
// Add the bare ~/.codex/auth.json (the default `ccsx` invocation) as the
|
|
514
|
+
// DEFAULT_PROFILE account when it exists. It is the "default way of running",
|
|
515
|
+
// distinct from named `ccsx <profile>` profiles.
|
|
516
|
+
if (fs.existsSync(path.join(os.homedir(), '.codex', 'auth.json'))) {
|
|
517
|
+
if (!profiles.includes(DEFAULT_PROFILE))
|
|
518
|
+
profiles.push(DEFAULT_PROFILE);
|
|
519
|
+
}
|
|
520
|
+
return profiles;
|
|
521
|
+
}
|
|
522
|
+
catch {
|
|
523
|
+
return [];
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* Resolve the default Codex profile. Falls back to DEFAULT_PROFILE when the bare
|
|
528
|
+
* ~/.codex/auth.json exists and no registry default is set.
|
|
529
|
+
*/
|
|
530
|
+
function getDefaultCodexProfileFromDisk() {
|
|
531
|
+
try {
|
|
532
|
+
const { CodexProfileRegistry } = require('../../codex-auth/codex-profile-registry');
|
|
533
|
+
const registry = new CodexProfileRegistry();
|
|
534
|
+
const pausedIdentities = getPausedCodexAccountIdentities();
|
|
535
|
+
const def = registry.getDefault();
|
|
536
|
+
if (def && !codexProfileMatchesPausedAccount(def, registry.getProfile(def), pausedIdentities)) {
|
|
537
|
+
return def;
|
|
538
|
+
}
|
|
539
|
+
const fallback = registry
|
|
540
|
+
.listProfiles()
|
|
541
|
+
.find((name) => !codexProfileMatchesPausedAccount(name, registry.getProfile(name), pausedIdentities));
|
|
542
|
+
if (fallback)
|
|
543
|
+
return fallback;
|
|
544
|
+
// Fall back to the bare ~/.codex account (DEFAULT_PROFILE) when no registry
|
|
545
|
+
// default is set — it is the default `ccsx` invocation.
|
|
546
|
+
if (fs.existsSync(path.join(os.homedir(), '.codex', 'auth.json')))
|
|
547
|
+
return DEFAULT_PROFILE;
|
|
548
|
+
return null;
|
|
549
|
+
}
|
|
550
|
+
catch {
|
|
551
|
+
return null;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
function getPausedCodexAccountIdentities() {
|
|
555
|
+
try {
|
|
556
|
+
const accounts = (0, query_1.getProviderAccounts)('codex');
|
|
557
|
+
if (accounts.length === 0)
|
|
558
|
+
return null;
|
|
559
|
+
const identities = new Set();
|
|
560
|
+
for (const account of accounts) {
|
|
561
|
+
if (!account.paused)
|
|
562
|
+
continue;
|
|
563
|
+
identities.add(account.id);
|
|
564
|
+
if (account.email)
|
|
565
|
+
identities.add(account.email);
|
|
566
|
+
}
|
|
567
|
+
return identities;
|
|
568
|
+
}
|
|
569
|
+
catch {
|
|
570
|
+
return null;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
function codexProfileMatchesPausedAccount(profileName, profile, pausedIdentities) {
|
|
574
|
+
if (!pausedIdentities || pausedIdentities.size === 0)
|
|
575
|
+
return false;
|
|
576
|
+
return [profileName, profile.email, profile.account_id].some((identity) => typeof identity === 'string' && pausedIdentities.has(identity));
|
|
577
|
+
}
|
|
578
|
+
// ============================================================================
|
|
579
|
+
// Per-profile collectors with full safety controls
|
|
580
|
+
// ============================================================================
|
|
581
|
+
/**
|
|
582
|
+
* Tag a row with whether it is the surface's default profile (drives the
|
|
583
|
+
* "active" badge only). The row's own `paused` flag is authoritative for
|
|
584
|
+
* dimming: it is already set by the collector to reflect LIVENESS — parked
|
|
585
|
+
* (no on-disk creds / unsupported) rows arrive with paused:true; profiles with
|
|
586
|
+
* a usable token arrive with paused:false regardless of default status. We must
|
|
587
|
+
* NOT override `paused` from `isDefault`, or a valid non-default subscription
|
|
588
|
+
* (e.g. an isolated `ccsx` profile) would render dimmed despite live quota.
|
|
589
|
+
*/
|
|
590
|
+
function markDefault(row, isDefault) {
|
|
591
|
+
return { ...row, is_default: isDefault };
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* Tag the row with is_default AND write the flag back onto the cached copy. The
|
|
595
|
+
* collector caches a row before the default profile is known (the default is
|
|
596
|
+
* resolved in the enumerator), so without this the cache-fallback path
|
|
597
|
+
* (getCachedNativeAccountRows) would serve the default account with
|
|
598
|
+
* is_default:false and the UI would stop ordering/tagging it as the default.
|
|
599
|
+
*/
|
|
600
|
+
function markDefaultAndSyncCache(map, profile, row, isDefault) {
|
|
601
|
+
const state = map.get(profile);
|
|
602
|
+
if (state?.cachedRow) {
|
|
603
|
+
state.cachedRow = { ...state.cachedRow, is_default: isDefault };
|
|
604
|
+
}
|
|
605
|
+
return markDefault(row, isDefault);
|
|
606
|
+
}
|
|
607
|
+
async function collectClaudeRowForProfile(profile, deps, force = false) {
|
|
608
|
+
const now = (deps.now ?? Date.now)();
|
|
609
|
+
const state = getState(claudeProfileStates, profile);
|
|
610
|
+
// Serve from cache while within TTL — force bypasses the short-circuit. Parked
|
|
611
|
+
// rows (no creds -> quotaStatus 'unsupported') use a short TTL so a fresh login
|
|
612
|
+
// is picked up within seconds instead of staying dimmed for the full quota TTL.
|
|
613
|
+
if (!force && state.cachedRow) {
|
|
614
|
+
const ttl = state.cachedRow.quotaStatus === 'unsupported' ? PARKED_TTL_MS : NATIVE_QUOTA_TTL_MS;
|
|
615
|
+
if (now - state.cachedAt < ttl)
|
|
616
|
+
return serveCached(state);
|
|
617
|
+
}
|
|
618
|
+
// Breaker open or cooldown active -> zero network, serve stale (may be null).
|
|
619
|
+
// Force does NOT bypass the breaker — it protects the account.
|
|
620
|
+
if (now < state.breakerOpenUntil || now < state.cooldownUntil) {
|
|
621
|
+
return serveCached(state);
|
|
622
|
+
}
|
|
623
|
+
// Coalesce: concurrent callers past TTL share one in-flight fetch.
|
|
624
|
+
if (state.pending) {
|
|
625
|
+
return state.pending;
|
|
626
|
+
}
|
|
627
|
+
// For per-profile reads: use the injected seam (file-only, no keychain).
|
|
628
|
+
const readCreds = deps.readClaudeCredentialsForProfile ??
|
|
629
|
+
((p) => readClaudeCredentialsForProfileFromDisk(p));
|
|
630
|
+
const fetchQuota = deps.fetchClaudeQuota ?? quota_fetcher_claude_1.fetchClaudeQuotaWithToken;
|
|
631
|
+
const sleep = deps.sleep ?? defaultSleep;
|
|
632
|
+
state.pending = (async () => {
|
|
633
|
+
try {
|
|
634
|
+
// Yield once so the `state.pending = (...)()` assignment above completes
|
|
635
|
+
// before any synchronous return below runs the finally that nulls it.
|
|
636
|
+
// Without this, a sync return (e.g. the no-creds parked path) clears
|
|
637
|
+
// pending DURING assignment, leaving a stale resolved promise that the
|
|
638
|
+
// next call's coalescing check would return instead of re-evaluating.
|
|
639
|
+
await Promise.resolve();
|
|
640
|
+
const creds = readCreds(profile);
|
|
641
|
+
// No credentials file found -> emit parked row (needs auth, file absent).
|
|
642
|
+
// This is the expected case when the profile exists in the registry but the
|
|
643
|
+
// user has not logged in via 'ccs auth' for this machine or the credentials
|
|
644
|
+
// are stored only in keychain (which we deliberately do not access here).
|
|
645
|
+
if (!creds) {
|
|
646
|
+
const parkedRow = {
|
|
647
|
+
account_id: `${SURFACE_CLAUDE}:${profile}`,
|
|
648
|
+
provider: CLAUDE_NATIVE_PROVIDER,
|
|
649
|
+
surface: SURFACE_CLAUDE,
|
|
650
|
+
profile,
|
|
651
|
+
is_subscription: true,
|
|
652
|
+
displayName: profile,
|
|
653
|
+
tier: null,
|
|
654
|
+
paused: true,
|
|
655
|
+
quota_percentage: null,
|
|
656
|
+
quotaStatus: 'unsupported',
|
|
657
|
+
next_reset: null,
|
|
658
|
+
is_default: false,
|
|
659
|
+
last_activity_at: null,
|
|
660
|
+
today_cost: null,
|
|
661
|
+
health: 'ok',
|
|
662
|
+
cached: false,
|
|
663
|
+
fetchedAt: new Date(now).toISOString(),
|
|
664
|
+
needsReauth: true,
|
|
665
|
+
};
|
|
666
|
+
// Cache the parked row so repeated calls don't re-stat the fs.
|
|
667
|
+
state.cachedRow = parkedRow;
|
|
668
|
+
state.cachedAt = now;
|
|
669
|
+
return parkedRow;
|
|
670
|
+
}
|
|
671
|
+
// No token / unsupported subscription -> never spend a call, omit the row.
|
|
672
|
+
if (!(0, claude_native_credentials_1.hasSupportedSubscription)(creds)) {
|
|
673
|
+
return serveCached(state);
|
|
674
|
+
}
|
|
675
|
+
const token = (0, claude_native_credentials_1.getAccessToken)(creds);
|
|
676
|
+
if (!token) {
|
|
677
|
+
return serveCached(state);
|
|
678
|
+
}
|
|
679
|
+
const tier = (0, claude_native_credentials_1.getSubscriptionTier)(creds);
|
|
680
|
+
const quota = await fetchQuota(token, `${SURFACE_CLAUDE}:${profile}`);
|
|
681
|
+
if (quota.success) {
|
|
682
|
+
// Success closes the breaker and clears backoff.
|
|
683
|
+
state.consecutive429 = 0;
|
|
684
|
+
state.breakerOpenUntil = 0;
|
|
685
|
+
state.cooldownUntil = 0;
|
|
686
|
+
state.backoffAttempt = 0;
|
|
687
|
+
const row = buildClaudeRow(quota, tier, now, SURFACE_CLAUDE, profile);
|
|
688
|
+
state.cachedRow = row;
|
|
689
|
+
state.cachedAt = now;
|
|
690
|
+
return { ...row, cached: false };
|
|
691
|
+
}
|
|
692
|
+
// 401 -> token expired. Emit a dimmed reauth row so the bar can prompt.
|
|
693
|
+
// Cache it and open a cooldown so the expired account is NOT re-polled
|
|
694
|
+
// (and re-401'd) on every refresh; it re-checks after REAUTH_COOLDOWN_MS,
|
|
695
|
+
// picking up a successful re-auth.
|
|
696
|
+
if (quota.needsReauth) {
|
|
697
|
+
const row = {
|
|
698
|
+
account_id: `${SURFACE_CLAUDE}:${profile}`,
|
|
699
|
+
provider: CLAUDE_NATIVE_PROVIDER,
|
|
700
|
+
surface: SURFACE_CLAUDE,
|
|
701
|
+
profile,
|
|
702
|
+
is_subscription: true,
|
|
703
|
+
displayName: profile,
|
|
704
|
+
tier,
|
|
705
|
+
paused: true,
|
|
706
|
+
quota_percentage: null,
|
|
707
|
+
quotaStatus: 'error',
|
|
708
|
+
next_reset: null,
|
|
709
|
+
is_default: false,
|
|
710
|
+
last_activity_at: null,
|
|
711
|
+
today_cost: null,
|
|
712
|
+
health: 'error',
|
|
713
|
+
cached: false,
|
|
714
|
+
fetchedAt: new Date(now).toISOString(),
|
|
715
|
+
needsReauth: true,
|
|
716
|
+
};
|
|
717
|
+
state.cachedRow = row;
|
|
718
|
+
state.cachedAt = now;
|
|
719
|
+
state.cooldownUntil = now + REAUTH_COOLDOWN_MS;
|
|
720
|
+
return { ...row, cached: false };
|
|
721
|
+
}
|
|
722
|
+
// 429 / 5xx / transient. Apply backoff + breaker, then serve stale.
|
|
723
|
+
const is429 = quota.httpStatus === 429;
|
|
724
|
+
if (is429) {
|
|
725
|
+
state.consecutive429 += 1;
|
|
726
|
+
if (state.consecutive429 >= CB_TRIP_THRESHOLD) {
|
|
727
|
+
state.breakerOpenUntil = now + CB_COOLDOWN_MS;
|
|
728
|
+
}
|
|
729
|
+
const retryAfter = parseRetryAfterMs(quota.errorDetail, now);
|
|
730
|
+
const backoff = retryAfter ?? computeBackoffMs(state.backoffAttempt);
|
|
731
|
+
state.cooldownUntil = now + backoff;
|
|
732
|
+
state.backoffAttempt += 1;
|
|
733
|
+
// We do NOT sleep-then-retry inside the request path (that would burn
|
|
734
|
+
// the request budget). The cooldown gates the NEXT call instead.
|
|
735
|
+
void sleep; // retained as an injectable seam for future inline retry
|
|
736
|
+
}
|
|
737
|
+
else if (quota.retryable) {
|
|
738
|
+
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
739
|
+
state.cooldownUntil = now + backoff;
|
|
740
|
+
state.backoffAttempt += 1;
|
|
741
|
+
}
|
|
742
|
+
// Serve last good row on failure; omit if we never succeeded.
|
|
743
|
+
return serveCached(state);
|
|
744
|
+
}
|
|
745
|
+
catch {
|
|
746
|
+
// Network/parse rejection -> treat as transient, serve stale.
|
|
747
|
+
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
748
|
+
state.cooldownUntil = now + backoff;
|
|
749
|
+
state.backoffAttempt += 1;
|
|
750
|
+
return serveCached(state);
|
|
751
|
+
}
|
|
752
|
+
finally {
|
|
753
|
+
state.pending = null;
|
|
754
|
+
}
|
|
755
|
+
})();
|
|
756
|
+
return state.pending;
|
|
757
|
+
}
|
|
758
|
+
async function collectCodexRowForProfile(profile, deps, force = false) {
|
|
759
|
+
const now = (deps.now ?? Date.now)();
|
|
760
|
+
const state = getState(codexProfileStates, profile);
|
|
761
|
+
// Serve from cache while within TTL — force bypasses the short-circuit. Parked
|
|
762
|
+
// rows (no auth -> quotaStatus 'unsupported') use a short TTL so a fresh login
|
|
763
|
+
// is picked up within seconds instead of staying dimmed for the full quota TTL.
|
|
764
|
+
if (!force && state.cachedRow) {
|
|
765
|
+
const ttl = state.cachedRow.quotaStatus === 'unsupported' ? PARKED_TTL_MS : NATIVE_QUOTA_TTL_MS;
|
|
766
|
+
if (now - state.cachedAt < ttl)
|
|
767
|
+
return serveCached(state);
|
|
768
|
+
}
|
|
769
|
+
// Breaker open or cooldown active -> skip network, go to LOCAL fallback.
|
|
770
|
+
// Force does NOT bypass the breaker — it protects the account.
|
|
771
|
+
const breakerOrCooldownActive = now < state.breakerOpenUntil || now < state.cooldownUntil;
|
|
772
|
+
// Coalesce: concurrent callers past TTL share one in-flight resolution.
|
|
773
|
+
if (state.pending) {
|
|
774
|
+
return state.pending;
|
|
775
|
+
}
|
|
776
|
+
// Resolve the native auth for this profile to get a network accountId.
|
|
777
|
+
const readNativeAuth = deps.readCodexNativeAuth ?? ((p) => readCodexNativeAuthFromDisk(p));
|
|
778
|
+
// For the network fallback: the legacy getDefaultCodexAccountId is the
|
|
779
|
+
// CLIProxy-registry path; for native profiles we use the on-disk auth directly.
|
|
780
|
+
const fetchNetwork = deps.fetchCodexNetworkQuota ?? ((accountId) => (0, quota_fetcher_codex_1.fetchCodexQuota)(accountId));
|
|
781
|
+
const getCodex = deps.getCodexQuota ?? codex_local_quota_collector_1.getCodexLocalQuota;
|
|
782
|
+
const sleep = deps.sleep ?? defaultSleep;
|
|
783
|
+
state.pending = (async () => {
|
|
784
|
+
try {
|
|
785
|
+
// Yield once so the `state.pending = (...)()` assignment completes before
|
|
786
|
+
// any synchronous return below runs the finally that nulls it (otherwise a
|
|
787
|
+
// sync return leaves a stale resolved promise the next call would reuse).
|
|
788
|
+
await Promise.resolve();
|
|
789
|
+
// ----------------------------------------------------------------
|
|
790
|
+
// PRIMARY: live network fetch (skipped when breaker/cooldown active)
|
|
791
|
+
// ----------------------------------------------------------------
|
|
792
|
+
if (!breakerOrCooldownActive) {
|
|
793
|
+
const nativeAuth = readNativeAuth(profile);
|
|
794
|
+
// Use the on-disk accountId for the network call; fall through to local
|
|
795
|
+
// when the auth file is absent (parked profile).
|
|
796
|
+
if (nativeAuth) {
|
|
797
|
+
const quota = await fetchNetwork(nativeAuth.accountId || profile);
|
|
798
|
+
if (quota.success) {
|
|
799
|
+
// A healthy response closes the breaker and clears backoff,
|
|
800
|
+
// regardless of content.
|
|
801
|
+
state.consecutive429 = 0;
|
|
802
|
+
state.breakerOpenUntil = 0;
|
|
803
|
+
state.cooldownUntil = 0;
|
|
804
|
+
state.backoffAttempt = 0;
|
|
805
|
+
// At least one core window (5h/weekly) resolved -> full quota row.
|
|
806
|
+
if (quota.coreUsage?.fiveHour || quota.coreUsage?.weekly) {
|
|
807
|
+
const row = buildCodexNetworkRow(quota, now, SURFACE_CODEX, profile);
|
|
808
|
+
state.cachedRow = row;
|
|
809
|
+
state.cachedAt = now;
|
|
810
|
+
return { ...row, cached: false };
|
|
811
|
+
}
|
|
812
|
+
// Success but no core window. The token authenticated, so this is a
|
|
813
|
+
// VALID active subscription with a sparse payload — emit an active
|
|
814
|
+
// (quota-less) row instead of parking it. Only the bare default keeps
|
|
815
|
+
// falling through to the global local session data below.
|
|
816
|
+
if (profile !== DEFAULT_PROFILE) {
|
|
817
|
+
const row = buildCodexNetworkRow(quota, now, SURFACE_CODEX, profile);
|
|
818
|
+
state.cachedRow = row;
|
|
819
|
+
state.cachedAt = now;
|
|
820
|
+
return { ...row, cached: false };
|
|
821
|
+
}
|
|
822
|
+
// else (default): fall through to LOCAL fallback below.
|
|
823
|
+
}
|
|
824
|
+
else if (quota.needsReauth) {
|
|
825
|
+
// Token expired -> dimmed reauth row. Cache it and cool down so the
|
|
826
|
+
// expired account is NOT re-polled (and re-401'd) every refresh; it
|
|
827
|
+
// re-checks after REAUTH_COOLDOWN_MS to pick up a re-auth.
|
|
828
|
+
const reauthRow = {
|
|
829
|
+
account_id: `${SURFACE_CODEX}:${profile}`,
|
|
830
|
+
provider: CODEX_NATIVE_PROVIDER,
|
|
831
|
+
surface: SURFACE_CODEX,
|
|
832
|
+
profile,
|
|
833
|
+
is_subscription: true,
|
|
834
|
+
displayName: profile,
|
|
835
|
+
tier: null,
|
|
836
|
+
paused: true,
|
|
837
|
+
quota_percentage: null,
|
|
838
|
+
quotaStatus: 'error',
|
|
839
|
+
next_reset: null,
|
|
840
|
+
is_default: false,
|
|
841
|
+
last_activity_at: null,
|
|
842
|
+
today_cost: null,
|
|
843
|
+
health: 'error',
|
|
844
|
+
cached: false,
|
|
845
|
+
fetchedAt: new Date(now).toISOString(),
|
|
846
|
+
needsReauth: true,
|
|
847
|
+
};
|
|
848
|
+
state.cachedRow = reauthRow;
|
|
849
|
+
state.cachedAt = now;
|
|
850
|
+
state.cooldownUntil = now + REAUTH_COOLDOWN_MS;
|
|
851
|
+
return { ...reauthRow, cached: false };
|
|
852
|
+
}
|
|
853
|
+
else if (quota.httpStatus === 429) {
|
|
854
|
+
// 429: apply breaker + backoff, then fall through to local.
|
|
855
|
+
state.consecutive429 += 1;
|
|
856
|
+
if (state.consecutive429 >= CB_TRIP_THRESHOLD) {
|
|
857
|
+
state.breakerOpenUntil = now + CB_COOLDOWN_MS;
|
|
858
|
+
}
|
|
859
|
+
const retryAfter = parseRetryAfterMs(quota.errorDetail, now);
|
|
860
|
+
const backoff = retryAfter ?? computeBackoffMs(state.backoffAttempt);
|
|
861
|
+
state.cooldownUntil = now + backoff;
|
|
862
|
+
state.backoffAttempt += 1;
|
|
863
|
+
void sleep; // retained as an injectable seam for future inline retry
|
|
864
|
+
}
|
|
865
|
+
else if (quota.retryable) {
|
|
866
|
+
// Other transient failure: set cooldown, fall through to local.
|
|
867
|
+
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
868
|
+
state.cooldownUntil = now + backoff;
|
|
869
|
+
state.backoffAttempt += 1;
|
|
870
|
+
}
|
|
871
|
+
else {
|
|
872
|
+
// Terminal non-retryable failure (e.g. 403/404): back off so we
|
|
873
|
+
// don't re-hit a dead endpoint every poll when no local data caches
|
|
874
|
+
// a row to engage the TTL short-circuit. Then fall through to local.
|
|
875
|
+
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
876
|
+
state.cooldownUntil = now + backoff;
|
|
877
|
+
state.backoffAttempt += 1;
|
|
878
|
+
}
|
|
879
|
+
// Fall through to LOCAL fallback below.
|
|
880
|
+
}
|
|
881
|
+
// No on-disk auth for this profile -> fall through to the fallback below.
|
|
882
|
+
}
|
|
883
|
+
// ----------------------------------------------------------------
|
|
884
|
+
// LOCAL FALLBACK: session-log read (zero network). The session logs live
|
|
885
|
+
// in the GLOBAL ~/.codex, so they represent ONLY the bare default account,
|
|
886
|
+
// never a named profile. Using them for a named profile would misattribute
|
|
887
|
+
// the default's usage to the profile, so only the default falls back to
|
|
888
|
+
// local; named profiles park instead.
|
|
889
|
+
// ----------------------------------------------------------------
|
|
890
|
+
if (profile === DEFAULT_PROFILE) {
|
|
891
|
+
const localQuota = await getCodex();
|
|
892
|
+
if (localQuota) {
|
|
893
|
+
const row = buildCodexRow(localQuota, now, SURFACE_CODEX, profile);
|
|
894
|
+
state.cachedRow = row;
|
|
895
|
+
state.cachedAt = now;
|
|
896
|
+
return { ...row, cached: false };
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
// Named profile (or default with no local data): serve the last-known row
|
|
900
|
+
// if any, else a dimmed parked row -- never global local data for a named
|
|
901
|
+
// profile.
|
|
902
|
+
const stale = serveCached(state);
|
|
903
|
+
if (stale)
|
|
904
|
+
return stale;
|
|
905
|
+
const parkedRow = {
|
|
906
|
+
account_id: `${SURFACE_CODEX}:${profile}`,
|
|
907
|
+
provider: CODEX_NATIVE_PROVIDER,
|
|
908
|
+
surface: SURFACE_CODEX,
|
|
909
|
+
profile,
|
|
910
|
+
is_subscription: true,
|
|
911
|
+
displayName: profile,
|
|
912
|
+
tier: null,
|
|
913
|
+
paused: true,
|
|
914
|
+
quota_percentage: null,
|
|
915
|
+
quotaStatus: 'unsupported',
|
|
916
|
+
next_reset: null,
|
|
917
|
+
is_default: false,
|
|
918
|
+
last_activity_at: null,
|
|
919
|
+
today_cost: null,
|
|
920
|
+
health: 'ok',
|
|
921
|
+
cached: false,
|
|
922
|
+
fetchedAt: new Date(now).toISOString(),
|
|
923
|
+
needsReauth: true,
|
|
924
|
+
};
|
|
925
|
+
state.cachedRow = parkedRow;
|
|
926
|
+
state.cachedAt = now;
|
|
927
|
+
return parkedRow;
|
|
928
|
+
}
|
|
929
|
+
catch {
|
|
930
|
+
// Network/parse rejection -> treat as transient, serve stale.
|
|
931
|
+
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
932
|
+
state.cooldownUntil = now + backoff;
|
|
933
|
+
state.backoffAttempt += 1;
|
|
934
|
+
return serveCached(state);
|
|
935
|
+
}
|
|
936
|
+
finally {
|
|
937
|
+
state.pending = null;
|
|
938
|
+
}
|
|
939
|
+
})();
|
|
940
|
+
return state.pending;
|
|
941
|
+
}
|
|
942
|
+
// ============================================================================
|
|
943
|
+
// Legacy single-profile collectors (unchanged; used by old tests + back-compat)
|
|
306
944
|
// ============================================================================
|
|
945
|
+
/**
|
|
946
|
+
* @deprecated Use collectClaudeRowForProfile with the 'default' or appropriate
|
|
947
|
+
* profile name. Kept for backward compatibility with existing tests that stub
|
|
948
|
+
* readCredentials/getDefaultCodexAccountId directly.
|
|
949
|
+
*/
|
|
307
950
|
async function collectClaudeRow(deps, force = false) {
|
|
308
951
|
const now = (deps.now ?? Date.now)();
|
|
309
|
-
|
|
952
|
+
// Use the legacy single-state approach via profile key '__legacy__' to avoid
|
|
953
|
+
// breaking state isolation with the per-profile maps.
|
|
954
|
+
const state = getState(claudeProfileStates, '__legacy__');
|
|
310
955
|
// Serve from cache while within TTL — force bypasses TTL short-circuit.
|
|
311
956
|
if (!force && state.cachedRow && now - state.cachedAt < NATIVE_QUOTA_TTL_MS) {
|
|
312
957
|
return serveCached(state);
|
|
313
958
|
}
|
|
314
959
|
// Breaker open or cooldown active -> zero network, serve stale (may be null).
|
|
315
|
-
// Force does NOT bypass the breaker — it protects the account.
|
|
316
960
|
if (now < state.breakerOpenUntil || now < state.cooldownUntil) {
|
|
317
961
|
return serveCached(state);
|
|
318
962
|
}
|
|
@@ -320,12 +964,12 @@ async function collectClaudeRow(deps, force = false) {
|
|
|
320
964
|
if (state.pending) {
|
|
321
965
|
return state.pending;
|
|
322
966
|
}
|
|
323
|
-
const
|
|
967
|
+
const readCredentialsFn = deps.readCredentials ?? claude_native_credentials_1.readClaudeCredentials;
|
|
324
968
|
const fetchQuota = deps.fetchClaudeQuota ?? quota_fetcher_claude_1.fetchClaudeQuotaWithToken;
|
|
325
969
|
const sleep = deps.sleep ?? defaultSleep;
|
|
326
970
|
state.pending = (async () => {
|
|
327
971
|
try {
|
|
328
|
-
const creds =
|
|
972
|
+
const creds = readCredentialsFn();
|
|
329
973
|
// No token / unsupported subscription -> never spend a call, omit the row.
|
|
330
974
|
if (!creds || !(0, claude_native_credentials_1.hasSupportedSubscription)(creds)) {
|
|
331
975
|
return serveCached(state);
|
|
@@ -342,13 +986,12 @@ async function collectClaudeRow(deps, force = false) {
|
|
|
342
986
|
state.breakerOpenUntil = 0;
|
|
343
987
|
state.cooldownUntil = 0;
|
|
344
988
|
state.backoffAttempt = 0;
|
|
345
|
-
const row =
|
|
989
|
+
const row = buildClaudeRowLegacy(quota, tier, now);
|
|
346
990
|
state.cachedRow = row;
|
|
347
991
|
state.cachedAt = now;
|
|
348
992
|
return { ...row, cached: false };
|
|
349
993
|
}
|
|
350
|
-
// 401 -> token expired.
|
|
351
|
-
// a real, actionable state distinct from a transient failure.
|
|
994
|
+
// 401 -> token expired.
|
|
352
995
|
if (quota.needsReauth) {
|
|
353
996
|
const row = {
|
|
354
997
|
account_id: CLAUDE_PROVIDER,
|
|
@@ -367,11 +1010,9 @@ async function collectClaudeRow(deps, force = false) {
|
|
|
367
1010
|
fetchedAt: new Date(now).toISOString(),
|
|
368
1011
|
needsReauth: true,
|
|
369
1012
|
};
|
|
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
1013
|
return row;
|
|
373
1014
|
}
|
|
374
|
-
// 429 / 5xx / transient.
|
|
1015
|
+
// 429 / 5xx / transient.
|
|
375
1016
|
const is429 = quota.httpStatus === 429;
|
|
376
1017
|
if (is429) {
|
|
377
1018
|
state.consecutive429 += 1;
|
|
@@ -382,20 +1023,16 @@ async function collectClaudeRow(deps, force = false) {
|
|
|
382
1023
|
const backoff = retryAfter ?? computeBackoffMs(state.backoffAttempt);
|
|
383
1024
|
state.cooldownUntil = now + backoff;
|
|
384
1025
|
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
|
|
1026
|
+
void sleep;
|
|
388
1027
|
}
|
|
389
1028
|
else if (quota.retryable) {
|
|
390
1029
|
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
391
1030
|
state.cooldownUntil = now + backoff;
|
|
392
1031
|
state.backoffAttempt += 1;
|
|
393
1032
|
}
|
|
394
|
-
// Serve last good row on failure; omit if we never succeeded.
|
|
395
1033
|
return serveCached(state);
|
|
396
1034
|
}
|
|
397
1035
|
catch {
|
|
398
|
-
// Network/parse rejection -> treat as transient, serve stale.
|
|
399
1036
|
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
400
1037
|
state.cooldownUntil = now + backoff;
|
|
401
1038
|
state.backoffAttempt += 1;
|
|
@@ -407,18 +1044,40 @@ async function collectClaudeRow(deps, force = false) {
|
|
|
407
1044
|
})();
|
|
408
1045
|
return state.pending;
|
|
409
1046
|
}
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
1047
|
+
/** Legacy row builder — no surface/profile/is_subscription fields. */
|
|
1048
|
+
function buildClaudeRowLegacy(quota, tier, now) {
|
|
1049
|
+
const quotaWindows = buildClaudeQuotaWindows(quota);
|
|
1050
|
+
return {
|
|
1051
|
+
account_id: CLAUDE_PROVIDER,
|
|
1052
|
+
provider: CLAUDE_PROVIDER,
|
|
1053
|
+
displayName: 'Claude Code',
|
|
1054
|
+
tier,
|
|
1055
|
+
paused: false,
|
|
1056
|
+
quota_percentage: deriveClaudeQuotaPercentage(quota),
|
|
1057
|
+
quotaStatus: 'ok',
|
|
1058
|
+
next_reset: deriveClaudeNextReset(quota),
|
|
1059
|
+
is_default: false,
|
|
1060
|
+
last_activity_at: null,
|
|
1061
|
+
today_cost: null,
|
|
1062
|
+
health: 'ok',
|
|
1063
|
+
cached: false,
|
|
1064
|
+
fetchedAt: new Date(now).toISOString(),
|
|
1065
|
+
needsReauth: false,
|
|
1066
|
+
...(quotaWindows.length > 0 ? { quotaWindows } : {}),
|
|
1067
|
+
};
|
|
1068
|
+
}
|
|
1069
|
+
/**
|
|
1070
|
+
* Legacy Codex collector — uses the old getDefaultCodexAccountId dep.
|
|
1071
|
+
* Kept for backward compatibility with existing tests.
|
|
1072
|
+
*/
|
|
413
1073
|
async function collectCodexRow(deps, force = false) {
|
|
414
1074
|
const now = (deps.now ?? Date.now)();
|
|
415
|
-
const state =
|
|
1075
|
+
const state = getState(codexProfileStates, '__legacy__');
|
|
416
1076
|
// Serve from cache while within TTL — force bypasses TTL short-circuit.
|
|
417
1077
|
if (!force && state.cachedRow && now - state.cachedAt < NATIVE_QUOTA_TTL_MS) {
|
|
418
1078
|
return serveCached(state);
|
|
419
1079
|
}
|
|
420
1080
|
// Breaker open or cooldown active -> skip network, go to LOCAL fallback.
|
|
421
|
-
// Force does NOT bypass the breaker — it protects the account.
|
|
422
1081
|
const breakerOrCooldownActive = now < state.breakerOpenUntil || now < state.cooldownUntil;
|
|
423
1082
|
// Coalesce: concurrent callers past TTL share one in-flight resolution.
|
|
424
1083
|
if (state.pending) {
|
|
@@ -430,6 +1089,10 @@ async function collectCodexRow(deps, force = false) {
|
|
|
430
1089
|
const sleep = deps.sleep ?? defaultSleep;
|
|
431
1090
|
state.pending = (async () => {
|
|
432
1091
|
try {
|
|
1092
|
+
// Yield once so the `state.pending = (...)()` assignment completes before
|
|
1093
|
+
// any synchronous return below runs the finally that nulls it (otherwise a
|
|
1094
|
+
// sync return leaves a stale resolved promise the next call would reuse).
|
|
1095
|
+
await Promise.resolve();
|
|
433
1096
|
// ----------------------------------------------------------------
|
|
434
1097
|
// PRIMARY: live network fetch (skipped when breaker/cooldown active)
|
|
435
1098
|
// ----------------------------------------------------------------
|
|
@@ -438,19 +1101,12 @@ async function collectCodexRow(deps, force = false) {
|
|
|
438
1101
|
if (accountId) {
|
|
439
1102
|
const quota = await fetchNetwork(accountId);
|
|
440
1103
|
if (quota.success) {
|
|
441
|
-
// A healthy response closes the breaker and clears backoff,
|
|
442
|
-
// regardless of content.
|
|
443
1104
|
state.consecutive429 = 0;
|
|
444
1105
|
state.breakerOpenUntil = 0;
|
|
445
1106
|
state.cooldownUntil = 0;
|
|
446
1107
|
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
1108
|
if (quota.coreUsage?.fiveHour || quota.coreUsage?.weekly) {
|
|
453
|
-
const row =
|
|
1109
|
+
const row = buildCodexNetworkRowLegacy(quota, now);
|
|
454
1110
|
state.cachedRow = row;
|
|
455
1111
|
state.cachedAt = now;
|
|
456
1112
|
return { ...row, cached: false };
|
|
@@ -458,7 +1114,6 @@ async function collectCodexRow(deps, force = false) {
|
|
|
458
1114
|
// else: fall through to LOCAL fallback below.
|
|
459
1115
|
}
|
|
460
1116
|
else if (quota.needsReauth) {
|
|
461
|
-
// Token expired -> reauth row; do NOT cache as a good value.
|
|
462
1117
|
return {
|
|
463
1118
|
account_id: CODEX_PROVIDER,
|
|
464
1119
|
provider: CODEX_PROVIDER,
|
|
@@ -478,7 +1133,6 @@ async function collectCodexRow(deps, force = false) {
|
|
|
478
1133
|
};
|
|
479
1134
|
}
|
|
480
1135
|
else if (quota.httpStatus === 429) {
|
|
481
|
-
// 429: apply breaker + backoff, then fall through to local.
|
|
482
1136
|
state.consecutive429 += 1;
|
|
483
1137
|
if (state.consecutive429 >= CB_TRIP_THRESHOLD) {
|
|
484
1138
|
state.breakerOpenUntil = now + CB_COOLDOWN_MS;
|
|
@@ -487,42 +1141,34 @@ async function collectCodexRow(deps, force = false) {
|
|
|
487
1141
|
const backoff = retryAfter ?? computeBackoffMs(state.backoffAttempt);
|
|
488
1142
|
state.cooldownUntil = now + backoff;
|
|
489
1143
|
state.backoffAttempt += 1;
|
|
490
|
-
void sleep;
|
|
1144
|
+
void sleep;
|
|
491
1145
|
}
|
|
492
1146
|
else if (quota.retryable) {
|
|
493
|
-
// Other transient failure: set cooldown, fall through to local.
|
|
494
1147
|
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
495
1148
|
state.cooldownUntil = now + backoff;
|
|
496
1149
|
state.backoffAttempt += 1;
|
|
497
1150
|
}
|
|
498
1151
|
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
1152
|
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
503
1153
|
state.cooldownUntil = now + backoff;
|
|
504
1154
|
state.backoffAttempt += 1;
|
|
505
1155
|
}
|
|
506
1156
|
// Fall through to LOCAL fallback below.
|
|
507
1157
|
}
|
|
508
|
-
// No configured accountId -> fall through to local fallback.
|
|
509
1158
|
}
|
|
510
1159
|
// ----------------------------------------------------------------
|
|
511
|
-
// LOCAL FALLBACK
|
|
512
|
-
// when network is unavailable / no accountId / breaker active)
|
|
1160
|
+
// LOCAL FALLBACK
|
|
513
1161
|
// ----------------------------------------------------------------
|
|
514
1162
|
const localQuota = await getCodex();
|
|
515
1163
|
if (localQuota) {
|
|
516
|
-
const row =
|
|
1164
|
+
const row = buildCodexRowLegacy(localQuota, now);
|
|
517
1165
|
state.cachedRow = row;
|
|
518
1166
|
state.cachedAt = now;
|
|
519
1167
|
return { ...row, cached: false };
|
|
520
1168
|
}
|
|
521
|
-
// No local data either: serve stale (may be null).
|
|
522
1169
|
return serveCached(state);
|
|
523
1170
|
}
|
|
524
1171
|
catch {
|
|
525
|
-
// Network/parse rejection -> treat as transient, serve stale.
|
|
526
1172
|
const backoff = computeBackoffMs(state.backoffAttempt);
|
|
527
1173
|
state.cooldownUntil = now + backoff;
|
|
528
1174
|
state.backoffAttempt += 1;
|
|
@@ -534,21 +1180,120 @@ async function collectCodexRow(deps, force = false) {
|
|
|
534
1180
|
})();
|
|
535
1181
|
return state.pending;
|
|
536
1182
|
}
|
|
1183
|
+
/** Legacy Codex row builder (local quota). */
|
|
1184
|
+
function buildCodexRowLegacy(quota, now) {
|
|
1185
|
+
const quotaWindows = buildCodexQuotaWindows(quota);
|
|
1186
|
+
return {
|
|
1187
|
+
account_id: CODEX_PROVIDER,
|
|
1188
|
+
provider: CODEX_PROVIDER,
|
|
1189
|
+
displayName: 'Codex',
|
|
1190
|
+
tier: quota.tier,
|
|
1191
|
+
paused: false,
|
|
1192
|
+
quota_percentage: quota.quotaPercentage,
|
|
1193
|
+
quotaStatus: 'ok',
|
|
1194
|
+
next_reset: quota.nextReset,
|
|
1195
|
+
is_default: false,
|
|
1196
|
+
last_activity_at: null,
|
|
1197
|
+
today_cost: null,
|
|
1198
|
+
health: quota.stale ? 'warning' : 'ok',
|
|
1199
|
+
cached: false,
|
|
1200
|
+
fetchedAt: new Date(now).toISOString(),
|
|
1201
|
+
needsReauth: false,
|
|
1202
|
+
...(quotaWindows.length > 0 ? { quotaWindows } : {}),
|
|
1203
|
+
...(quota.staleAsOf ? { staleAsOf: quota.staleAsOf } : {}),
|
|
1204
|
+
};
|
|
1205
|
+
}
|
|
1206
|
+
/** Legacy Codex network row builder. */
|
|
1207
|
+
function buildCodexNetworkRowLegacy(quota, now) {
|
|
1208
|
+
const windows = [];
|
|
1209
|
+
const fiveHour = quota.coreUsage?.fiveHour;
|
|
1210
|
+
if (fiveHour) {
|
|
1211
|
+
windows.push({
|
|
1212
|
+
key: 'five_hour',
|
|
1213
|
+
label: '5h',
|
|
1214
|
+
usedPercent: 100 - fiveHour.remainingPercent,
|
|
1215
|
+
remainingPercent: fiveHour.remainingPercent,
|
|
1216
|
+
resetAt: fiveHour.resetAt,
|
|
1217
|
+
windowMinutes: FIVE_HOUR_MINUTES,
|
|
1218
|
+
});
|
|
1219
|
+
}
|
|
1220
|
+
const weekly = quota.coreUsage?.weekly;
|
|
1221
|
+
if (weekly) {
|
|
1222
|
+
windows.push({
|
|
1223
|
+
key: 'seven_day',
|
|
1224
|
+
label: 'week',
|
|
1225
|
+
usedPercent: 100 - weekly.remainingPercent,
|
|
1226
|
+
remainingPercent: weekly.remainingPercent,
|
|
1227
|
+
resetAt: weekly.resetAt,
|
|
1228
|
+
windowMinutes: SEVEN_DAY_MINUTES,
|
|
1229
|
+
});
|
|
1230
|
+
}
|
|
1231
|
+
const coreWindows = [fiveHour, weekly].filter((w) => !!w);
|
|
1232
|
+
const quotaPercentage = coreWindows.length > 0 ? Math.min(...coreWindows.map((w) => w.remainingPercent)) : null;
|
|
1233
|
+
const resets = coreWindows
|
|
1234
|
+
.map((w) => w.resetAt)
|
|
1235
|
+
.filter((r) => typeof r === 'string')
|
|
1236
|
+
.map((r) => ({ iso: r, ms: new Date(r).getTime() }))
|
|
1237
|
+
.filter((r) => Number.isFinite(r.ms))
|
|
1238
|
+
.sort((a, b) => a.ms - b.ms);
|
|
1239
|
+
const nextReset = resets.length > 0 ? resets[0].iso : null;
|
|
1240
|
+
return {
|
|
1241
|
+
account_id: CODEX_PROVIDER,
|
|
1242
|
+
provider: CODEX_PROVIDER,
|
|
1243
|
+
displayName: 'Codex',
|
|
1244
|
+
tier: quota.planType ?? null,
|
|
1245
|
+
paused: false,
|
|
1246
|
+
quota_percentage: quotaPercentage,
|
|
1247
|
+
quotaStatus: 'ok',
|
|
1248
|
+
next_reset: nextReset,
|
|
1249
|
+
is_default: false,
|
|
1250
|
+
last_activity_at: null,
|
|
1251
|
+
today_cost: null,
|
|
1252
|
+
health: 'ok',
|
|
1253
|
+
cached: false,
|
|
1254
|
+
fetchedAt: new Date(now).toISOString(),
|
|
1255
|
+
needsReauth: false,
|
|
1256
|
+
...(windows.length > 0 ? { quotaWindows: windows } : {}),
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
537
1259
|
// ============================================================================
|
|
538
1260
|
// Public entry point
|
|
539
1261
|
// ============================================================================
|
|
540
1262
|
/**
|
|
541
|
-
* Build the native subscription rows
|
|
1263
|
+
* Build the native subscription rows for /summary.
|
|
1264
|
+
*
|
|
1265
|
+
* When profile-enumeration deps are injected (listClaudeProfiles / listCodexProfiles
|
|
1266
|
+
* etc.), all profiles are enumerated and the active/default profile is live-polled
|
|
1267
|
+
* while non-default profiles are cache-only (parked). This keeps the 2.5s deadline:
|
|
1268
|
+
* at most 2 live upstream calls per /summary regardless of profile count.
|
|
542
1269
|
*
|
|
543
|
-
*
|
|
544
|
-
*
|
|
1270
|
+
* When no enumeration deps are injected (legacy mode / old tests that stub only
|
|
1271
|
+
* readCredentials + getDefaultCodexAccountId), the old single-profile collectors
|
|
1272
|
+
* are used for backward compatibility.
|
|
545
1273
|
*
|
|
546
|
-
* `opts.force` bypasses the TTL short-circuit on
|
|
547
|
-
*
|
|
548
|
-
* respected regardless of force (account protection).
|
|
1274
|
+
* `opts.force` bypasses the TTL short-circuit on the ACTIVE profile. The circuit
|
|
1275
|
+
* breaker is always respected regardless of force (account protection).
|
|
549
1276
|
*/
|
|
550
1277
|
async function getNativeAccountRows(deps = {}, opts) {
|
|
551
1278
|
const force = opts?.force ?? false;
|
|
1279
|
+
// Multi-profile enumeration is the DEFAULT (production) behavior. The legacy
|
|
1280
|
+
// single-profile path is retained ONLY for backward-compat with old tests that
|
|
1281
|
+
// inject readCredentials / getDefaultCodexAccountId and assert the original
|
|
1282
|
+
// single-row output. Those harnesses never inject the enumeration seams; the
|
|
1283
|
+
// new multi-profile tests pair both seams, and production injects neither — so
|
|
1284
|
+
// everything except the legacy harness takes the multi-profile path below.
|
|
1285
|
+
const hasProfileEnumeration = deps.listClaudeProfiles !== undefined ||
|
|
1286
|
+
deps.listCodexProfiles !== undefined ||
|
|
1287
|
+
deps.defaultClaudeProfile !== undefined ||
|
|
1288
|
+
deps.defaultCodexProfile !== undefined;
|
|
1289
|
+
const isLegacyTestHarness = !hasProfileEnumeration &&
|
|
1290
|
+
(deps.readCredentials !== undefined || deps.getDefaultCodexAccountId !== undefined);
|
|
1291
|
+
if (!isLegacyTestHarness) {
|
|
1292
|
+
return getNativeAccountRowsMultiProfile(deps, force);
|
|
1293
|
+
}
|
|
1294
|
+
// Legacy path: backward-compatible with old tests that only inject
|
|
1295
|
+
// readCredentials / getDefaultCodexAccountId. Produces the old single-row
|
|
1296
|
+
// output (account_id='claude-code'/'codex', no surface/profile).
|
|
552
1297
|
const [claude, codex] = await Promise.all([
|
|
553
1298
|
collectClaudeRow(deps, force).catch(() => null),
|
|
554
1299
|
collectCodexRow(deps, force).catch(() => null),
|
|
@@ -561,6 +1306,69 @@ async function getNativeAccountRows(deps = {}, opts) {
|
|
|
561
1306
|
return rows;
|
|
562
1307
|
}
|
|
563
1308
|
exports.getNativeAccountRows = getNativeAccountRows;
|
|
1309
|
+
async function getNativeAccountRowsMultiProfile(deps, force) {
|
|
1310
|
+
const listClaude = deps.listClaudeProfiles ?? listClaudeProfilesFromDisk;
|
|
1311
|
+
const listCodex = deps.listCodexProfiles ?? listCodexProfilesFromDisk;
|
|
1312
|
+
const defaultClaude = deps.defaultClaudeProfile ?? getDefaultClaudeProfileFromDisk;
|
|
1313
|
+
const defaultCodex = deps.defaultCodexProfile ?? getDefaultCodexProfileFromDisk;
|
|
1314
|
+
const claudeProfiles = (() => {
|
|
1315
|
+
try {
|
|
1316
|
+
return listClaude();
|
|
1317
|
+
}
|
|
1318
|
+
catch {
|
|
1319
|
+
return [];
|
|
1320
|
+
}
|
|
1321
|
+
})();
|
|
1322
|
+
const codexProfiles = (() => {
|
|
1323
|
+
try {
|
|
1324
|
+
return listCodex();
|
|
1325
|
+
}
|
|
1326
|
+
catch {
|
|
1327
|
+
return [];
|
|
1328
|
+
}
|
|
1329
|
+
})();
|
|
1330
|
+
const claudeDefault = (() => {
|
|
1331
|
+
try {
|
|
1332
|
+
return defaultClaude();
|
|
1333
|
+
}
|
|
1334
|
+
catch {
|
|
1335
|
+
return null;
|
|
1336
|
+
}
|
|
1337
|
+
})();
|
|
1338
|
+
const codexDefault = (() => {
|
|
1339
|
+
try {
|
|
1340
|
+
return defaultCodex();
|
|
1341
|
+
}
|
|
1342
|
+
catch {
|
|
1343
|
+
return null;
|
|
1344
|
+
}
|
|
1345
|
+
})();
|
|
1346
|
+
const tasks = [];
|
|
1347
|
+
// Forced refresh applies to every profile: parked profiles (no creds) short-
|
|
1348
|
+
// circuit to a parked row with zero network, so forcing them is free, while
|
|
1349
|
+
// every profile that has a usable token gets live quota — not just the
|
|
1350
|
+
// default. Per-profile TTL + breaker still protect each account.
|
|
1351
|
+
for (const p of claudeProfiles) {
|
|
1352
|
+
const isDefault = p === claudeDefault;
|
|
1353
|
+
tasks.push(collectClaudeRowForProfile(p, deps, force)
|
|
1354
|
+
.then((r) => (r ? markDefaultAndSyncCache(claudeProfileStates, p, r, isDefault) : null))
|
|
1355
|
+
.catch(() => null));
|
|
1356
|
+
}
|
|
1357
|
+
for (const p of codexProfiles) {
|
|
1358
|
+
const isDefault = p === codexDefault;
|
|
1359
|
+
tasks.push(collectCodexRowForProfile(p, deps, force)
|
|
1360
|
+
.then((r) => (r ? markDefaultAndSyncCache(codexProfileStates, p, r, isDefault) : null))
|
|
1361
|
+
.catch(() => null));
|
|
1362
|
+
}
|
|
1363
|
+
const results = await Promise.all(tasks);
|
|
1364
|
+
const rows = results.filter((r) => r !== null);
|
|
1365
|
+
// Sort by (surface, profile) for stable ordering.
|
|
1366
|
+
return rows.sort((a, b) => {
|
|
1367
|
+
const sa = (a.surface ?? '') + ':' + (a.profile ?? '');
|
|
1368
|
+
const sb = (b.surface ?? '') + ':' + (b.profile ?? '');
|
|
1369
|
+
return sa.localeCompare(sb);
|
|
1370
|
+
});
|
|
1371
|
+
}
|
|
564
1372
|
/**
|
|
565
1373
|
* Last-known native rows from cache, WITHOUT any fetch (instant, no network).
|
|
566
1374
|
*
|
|
@@ -571,10 +1379,14 @@ exports.getNativeAccountRows = getNativeAccountRows;
|
|
|
571
1379
|
*/
|
|
572
1380
|
function getCachedNativeAccountRows() {
|
|
573
1381
|
const rows = [];
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
1382
|
+
for (const state of claudeProfileStates.values()) {
|
|
1383
|
+
if (state.cachedRow)
|
|
1384
|
+
rows.push({ ...state.cachedRow, cached: true });
|
|
1385
|
+
}
|
|
1386
|
+
for (const state of codexProfileStates.values()) {
|
|
1387
|
+
if (state.cachedRow)
|
|
1388
|
+
rows.push({ ...state.cachedRow, cached: true });
|
|
1389
|
+
}
|
|
578
1390
|
return rows;
|
|
579
1391
|
}
|
|
580
1392
|
exports.getCachedNativeAccountRows = getCachedNativeAccountRows;
|