@cortexkit/opencode-openai-auth 0.7.2 → 0.9.0

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.
Files changed (118) hide show
  1. package/README.md +9 -5
  2. package/dist/index-301y4qa1.js +2 -0
  3. package/dist/index-338z7171.js +211 -0
  4. package/dist/index-5y4vzdf8.js +2 -0
  5. package/dist/{index-zxqb5ydj.js → index-9ehhb051.js} +1 -1
  6. package/dist/{index-zg1x8sty.js → index-jwn4r3sw.js} +1 -1
  7. package/dist/{index-9jpc8yct.js → index-sdt2d2ra.js} +1 -1
  8. package/dist/index-w42s0g6m.js +2 -0
  9. package/dist/index.d.ts +213 -36
  10. package/dist/index.js +59 -154
  11. package/dist/internal-Y7QNVDJT.d.ts +908 -0
  12. package/dist/quota-normalize-3qffywcm.js +1 -0
  13. package/dist/rpc/port-file.d.ts +11 -9
  14. package/dist/rpc/port-file.js +1 -1
  15. package/dist/rpc/protocol.d.ts +2 -21
  16. package/dist/rpc/rpc-client.d.ts +7 -4
  17. package/dist/rpc/rpc-client.js +1 -1
  18. package/dist/rpc/rpc-dir.d.ts +7 -5
  19. package/dist/rpc/rpc-dir.js +1 -1
  20. package/dist/sidebar-state-B98sERYt.d.ts +219 -0
  21. package/dist/sidebar-state.d.ts +2 -171
  22. package/dist/sidebar-state.js +1 -1
  23. package/dist/{token-bvp0y166.js → token-9823y0pc.js} +1 -1
  24. package/dist/token-util-ypgz7rge.js +1 -0
  25. package/dist/tui-preferences.d.ts +27 -26
  26. package/dist/tui-preferences.js +1 -1
  27. package/dist/tui.d.ts +42 -19
  28. package/package.json +8 -14
  29. package/src/tui/entry.mjs +2 -2
  30. package/src/tui-compiled/{core/account-paths.ts → raw/core-account-paths.ts} +29 -18
  31. package/src/tui-compiled/raw/core-custody-state.ts +243 -0
  32. package/src/tui-compiled/raw/logger.ts +53 -0
  33. package/src/tui-compiled/{rpc/port-file.ts → raw/rpc-port-file.ts} +1 -1
  34. package/src/tui-compiled/raw/rpc-protocol.ts +12 -0
  35. package/src/{rpc/rpc-client.ts → tui-compiled/raw/rpc-rpc-client.ts} +2 -2
  36. package/src/{sidebar-state.ts → tui-compiled/raw/sidebar-state.ts} +142 -13
  37. package/src/{tui/command-dialogs.tsx → tui-compiled/raw/tui-command-dialogs.tsx} +94 -44
  38. package/src/{tui.tsx → tui-compiled/raw/tui.tsx} +149 -28
  39. package/src/{core/account-paths.ts → tui-compiled/runtime/core-account-paths.ts} +29 -18
  40. package/src/tui-compiled/runtime/core-custody-state.ts +243 -0
  41. package/src/tui-compiled/runtime/logger.ts +53 -0
  42. package/src/{rpc/port-file.ts → tui-compiled/runtime/rpc-port-file.ts} +1 -1
  43. package/src/tui-compiled/runtime/rpc-protocol.ts +12 -0
  44. package/src/tui-compiled/{rpc/rpc-client.ts → runtime/rpc-rpc-client.ts} +2 -2
  45. package/src/tui-compiled/{sidebar-state.ts → runtime/sidebar-state.ts} +142 -13
  46. package/src/tui-compiled/{tui/command-dialogs.tsx → runtime/tui-command-dialogs.tsx} +73 -37
  47. package/src/tui-compiled/{tui.tsx → runtime/tui.tsx} +251 -153
  48. package/src/tui-compiled/shared/internal.ts +6 -0
  49. package/src/{logger.ts → tui-compiled/shared/logger.ts} +91 -23
  50. package/src/tui-compiled/shared/paths.ts +33 -0
  51. package/src/{core → tui-compiled/shared}/refresh-file-lock.ts +7 -4
  52. package/dist/cli.d.ts +0 -2
  53. package/dist/cli.js +0 -15
  54. package/dist/codex-http.d.ts +0 -3
  55. package/dist/commands.d.ts +0 -88
  56. package/dist/config.d.ts +0 -47
  57. package/dist/core/account-paths.d.ts +0 -25
  58. package/dist/core/accounts.d.ts +0 -330
  59. package/dist/core/atomic-write.d.ts +0 -1
  60. package/dist/core/background-quota-refresh.d.ts +0 -46
  61. package/dist/core/backoff.d.ts +0 -53
  62. package/dist/core/cachekeep.d.ts +0 -118
  63. package/dist/core/oauth.d.ts +0 -138
  64. package/dist/core/provider.d.ts +0 -70
  65. package/dist/core/quota-manager.d.ts +0 -192
  66. package/dist/core/refresh-all-quota.d.ts +0 -86
  67. package/dist/core/refresh-file-lock.d.ts +0 -12
  68. package/dist/core/reset-credits.d.ts +0 -116
  69. package/dist/core/sticky-routing.d.ts +0 -43
  70. package/dist/dump.d.ts +0 -20
  71. package/dist/hosted-web-search.d.ts +0 -5
  72. package/dist/index-87145jkw.js +0 -2
  73. package/dist/index-8f1200qx.js +0 -6
  74. package/dist/index-cfjed1st.js +0 -89
  75. package/dist/index-nrvjr97q.js +0 -3
  76. package/dist/index-qaggaze1.js +0 -2
  77. package/dist/index-sdcpzbnk.js +0 -2
  78. package/dist/logger.d.ts +0 -22
  79. package/dist/model-costs.d.ts +0 -29
  80. package/dist/prompt-context.d.ts +0 -19
  81. package/dist/quota-normalize-dvwtmy7f.js +0 -1
  82. package/dist/quota-normalize.d.ts +0 -43
  83. package/dist/raw-ws-bun.d.ts +0 -40
  84. package/dist/raw-ws-node.d.ts +0 -37
  85. package/dist/raw-ws-upgrade.d.ts +0 -2
  86. package/dist/raw-ws.d.ts +0 -3
  87. package/dist/response-stream-error.d.ts +0 -12
  88. package/dist/rpc/notifications.d.ts +0 -5
  89. package/dist/rpc/rpc-server.d.ts +0 -17
  90. package/dist/token-util-jcj7k7pa.js +0 -1
  91. package/dist/tui/command-dialogs.d.ts +0 -21
  92. package/dist/util/error.d.ts +0 -1
  93. package/dist/util/open-url.d.ts +0 -6
  94. package/dist/util/proxy-env.d.ts +0 -4
  95. package/dist/util/record.d.ts +0 -1
  96. package/dist/util/stable-json.d.ts +0 -1
  97. package/dist/util/uuid-v7.d.ts +0 -1
  98. package/dist/version.d.ts +0 -1
  99. package/dist/ws-pool.d.ts +0 -57
  100. package/dist/ws.d.ts +0 -71
  101. package/src/rpc/notifications.ts +0 -54
  102. package/src/rpc/protocol.ts +0 -33
  103. package/src/rpc/rpc-server.ts +0 -172
  104. package/src/tui-compiled/core/refresh-file-lock.ts +0 -381
  105. package/src/tui-compiled/logger.ts +0 -196
  106. package/src/tui-compiled/rpc/protocol.ts +0 -33
  107. package/src/util/error.ts +0 -9
  108. package/src/util/open-url.ts +0 -30
  109. package/src/util/proxy-env.ts +0 -42
  110. package/src/util/record.ts +0 -3
  111. package/src/util/stable-json.ts +0 -15
  112. package/src/util/uuid-v7.ts +0 -18
  113. /package/src/{rpc/rpc-dir.ts → tui-compiled/raw/rpc-rpc-dir.ts} +0 -0
  114. /package/src/tui-compiled/{tui-preferences.ts → raw/tui-preferences.ts} +0 -0
  115. /package/src/tui-compiled/{rpc/rpc-dir.ts → runtime/rpc-rpc-dir.ts} +0 -0
  116. /package/src/{tui-preferences.ts → tui-compiled/runtime/tui-preferences.ts} +0 -0
  117. /package/src/tui-compiled/{util → shared/util}/error.ts +0 -0
  118. /package/src/tui-compiled/{util → shared/util}/open-url.ts +0 -0
@@ -1,70 +0,0 @@
1
- /**
2
- * Provider injection seam — shared types and the 2 Codex provider fns.
3
- *
4
- * Both fns are constructor-injected into FallbackAccountManager and
5
- * QuotaManager so the generic core never imports provider specifics
6
- * directly.
7
- */
8
- import type { OAuthQuotaSnapshot } from './accounts.ts';
9
- declare const log: {
10
- error: (m: string, d?: unknown) => void;
11
- warn: (m: string, d?: unknown) => void;
12
- info: (m: string, d?: unknown) => void;
13
- debug: (m: string, d?: unknown) => void;
14
- trace: (m: string, d?: unknown) => void;
15
- };
16
- type QuotaLogger = Pick<typeof log, 'debug' | 'warn'>;
17
- export type QuotaWindowName = string;
18
- export declare const PRIMARY: QuotaWindowName;
19
- export declare const SECONDARY: QuotaWindowName;
20
- export interface ProviderHttpError extends Error {
21
- status?: number;
22
- retryAfter?: number;
23
- /** True when this error originated from a token-refresh call (not a quota fetch). */
24
- isRefreshError?: boolean;
25
- }
26
- export type ProviderRefreshFn = (input: {
27
- refreshToken: string;
28
- fetchImpl: typeof fetch;
29
- now: () => number;
30
- }) => Promise<{
31
- access: string;
32
- refresh: string;
33
- expires: number;
34
- expiresIn: number;
35
- }>;
36
- export type ProviderQuotaFn = (input: {
37
- accessToken: string;
38
- fetchImpl: typeof fetch;
39
- now: () => number;
40
- }) => Promise<OAuthQuotaSnapshot>;
41
- export declare const CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
42
- export declare const CODEX_ISSUER = "https://auth.openai.com";
43
- /**
44
- * Core Codex OAuth refresh — the single entry point for refreshing an
45
- * OpenAI OAuth token. Used by both the legacy refreshAccessToken in
46
- * index.ts AND the FallbackAccountManager (via constructor injection).
47
- *
48
- * Throws a ProviderHttpError carrying `.status` (from the HTTP response)
49
- * and `.retryAfter` (parsed from Retry-After) so backoff machinery can
50
- * duck-type them without instanceof checks.
51
- */
52
- export declare function codexRefreshFn(input: {
53
- refreshToken: string;
54
- fetchImpl: typeof fetch;
55
- now: () => number;
56
- }): Promise<{
57
- access: string;
58
- refresh: string;
59
- expires: number;
60
- expiresIn: number;
61
- }>;
62
- export declare function whamUsageFn(input: {
63
- accessToken: string;
64
- fetchImpl: typeof fetch;
65
- now: () => number;
66
- accountId?: string;
67
- accountKey?: string;
68
- logger?: QuotaLogger;
69
- }): Promise<OAuthQuotaSnapshot>;
70
- export {};
@@ -1,192 +0,0 @@
1
- /**
2
- * Unified quota cache and API gateway.
3
- *
4
- * Single source of truth for main + fallback quota state. All consumers
5
- * share one QuotaManager instance so they see the same in-memory cache.
6
- * Handles deduplication, rate-limiting (429 backoff), and staleness.
7
- *
8
- * Adapted from anthropic-auth — provider-specific quota fetch injected via
9
- * fetchQuotaFn instead of hard-importing fetchOAuthQuotaSnapshot.
10
- */
11
- import type { AccountOperationError, AccountQuotaWindow, AccountStorage, OAuthAccount, OAuthQuotaSnapshot } from './accounts.ts';
12
- import { type ProviderQuotaFn } from './provider.ts';
13
- export type { ProviderQuotaFn };
14
- export declare function quotaWindowResetIsPast(window: AccountQuotaWindow | undefined, now: number): boolean;
15
- /**
16
- * Resolve when a WS-exhausted account becomes usable. Admission errors can
17
- * carry the provider's authoritative reset; response.failed frames do not, so
18
- * those fall back to the named window in the last-known quota snapshot. Never
19
- * borrow the other window's reset — an unrelated window can blackhole the
20
- * account long past its actual limit. The bounded default self-corrects when a
21
- * later request reports exhaustion again.
22
- */
23
- export declare function resolveMidStreamRateLimitResetAt(quota: OAuthQuotaSnapshot | undefined, window: string, now: number, defaultMs: number, explicitResetAt?: number): number;
24
- /**
25
- * Stable, non-reversible fingerprint of an access token. Used to detect a
26
- * main-account switch so a different account's persisted/cached quota is never
27
- * reused. Not a secret — a truncated SHA-256, safe to persist alongside quota.
28
- */
29
- export declare function tokenFingerprint(token: string): string;
30
- export type QuotaEntry = {
31
- quota: OAuthQuotaSnapshot;
32
- refreshAfter: number;
33
- checkedAt: number;
34
- accountId?: string;
35
- };
36
- export type QuotaManagerOptions = {
37
- storage: AccountStorage | null;
38
- fetchImpl?: typeof fetch;
39
- now?: () => number;
40
- /** Injected quota-fetch function — replaces the hard-imported Anthropic fetchOAuthQuotaSnapshot */
41
- fetchQuotaFn?: ProviderQuotaFn;
42
- onMainQuotaFetched?: (quota: OAuthQuotaSnapshot, checkedAt: number, fingerprint: string, fetchStartedAt: number) => void;
43
- onApiError?: (error: AccountOperationError) => void;
44
- };
45
- export declare class QuotaManager {
46
- private main;
47
- private mainTokenFp;
48
- private mainQuotaAccountId;
49
- private fallbacks;
50
- private fallbackTokenFps;
51
- private inflightMain;
52
- private inflightMainFp;
53
- private inflightFallbacks;
54
- private mainLastApiError;
55
- private fallbackApiErrors;
56
- private fallbackErrorTokenFps;
57
- private rateLimitedUntilMap;
58
- private apiGate;
59
- private lastApiCallAt;
60
- private storage;
61
- private readonly fetchImpl;
62
- private readonly now;
63
- private readonly fetchQuotaFn;
64
- private readonly onMainQuotaFetched;
65
- private readonly onApiError;
66
- constructor(opts: QuotaManagerOptions);
67
- /**
68
- * Cached main quota entry. Pass the live access token to enforce token
69
- * binding: if the cached entry was produced by a different token (main
70
- * account switched), it is dropped and null is returned so the caller
71
- * refetches for the current account. Called without a token (e.g. for
72
- * display) it returns whatever is cached.
73
- */
74
- getMain(accessToken?: string): QuotaEntry | null;
75
- /**
76
- * Cached fallback quota entry. Pass the live access token to enforce token
77
- * binding: if the entry was produced by a different token (account re-login),
78
- * it is dropped and null is returned so the caller refetches.
79
- */
80
- getFallback(accountId: string, accessToken?: string): QuotaEntry | null;
81
- getAllFallbacks(): Map<string, QuotaEntry>;
82
- setMain(accessToken: string, entry: QuotaEntry, accountId?: string, completeSnapshot?: boolean): void;
83
- /**
84
- * Non-invalidating read of the cached main quota for POLICY decisions
85
- * (killswitch). Unlike getMain(token), a token mismatch does NOT drop the
86
- * cache — an access-token refresh is a same-account event and must not turn a
87
- * known-exhausted account into "unknown" (which would fail open and spend).
88
- *
89
- * Pass the live ChatGPT accountId to still drop on a genuine account SWITCH:
90
- * if the cached entry's account identity is known and differs, return null so
91
- * the killswitch treats it as unknown rather than judging account A by account
92
- * B's quota. When identity is unknown on either side, the cached snapshot is
93
- * returned (best-effort) — the same fail-open-on-unknown stance as elsewhere.
94
- */
95
- peekMainForPolicy(accountId?: string): QuotaEntry | null;
96
- /**
97
- * Non-invalidating read of a cached fallback quota for POLICY decisions
98
- * (killswitch, admission). Keyed by the stable internal account id, so a
99
- * token refresh for the same account does not drop it (getFallback(id, token)
100
- * would).
101
- *
102
- * Pass the live ChatGPT identity to still drop on a genuine re-login: if the
103
- * cached entry's identity is known and differs, return null so the previous
104
- * identity's (possibly exhausted) quota is never judged against its
105
- * replacement. Unknown on either side fails open, matching peekMainForPolicy.
106
- */
107
- peekFallbackForPolicy(accountId: string, identity?: string): QuotaEntry | null;
108
- setFallback(accountId: string, entry: QuotaEntry, accessToken?: string, completeSnapshot?: boolean, identity?: string): void;
109
- /**
110
- * Mark accountId ('main' or a fallback id) rate-limited until resetAtMs.
111
- * Keeps the LATER reset: skips only when an existing mark is strictly
112
- * later than resetAtMs, so an equal-reset re-mark still applies (idempotent)
113
- * instead of being silently dropped by a stale `>=` comparison.
114
- */
115
- markRateLimited(accountId: string, resetAtMs: number): void;
116
- /** True iff accountId has a mark whose reset has not yet passed. */
117
- isRateLimited(accountId: string): boolean;
118
- /**
119
- * Raw stored reset for accountId's mark, or undefined if none. Unlike
120
- * isRateLimited, this does NOT apply read-time expiry — callers on the
121
- * block path already know the mark is live (isRateLimited just returned
122
- * true) and want its exact reset estimate for a Retry-After computation.
123
- */
124
- rateLimitedUntil(accountId: string): number | undefined;
125
- /** Explicit early clear — read-time expiry in isRateLimited is primary. */
126
- clearRateLimited(accountId: string): void;
127
- refreshMain(accessToken: string): Promise<OAuthQuotaSnapshot>;
128
- refreshFallback(accountId: string, accessToken: string): Promise<OAuthQuotaSnapshot>;
129
- refreshAllFallbacks(accounts: OAuthAccount[]): Promise<void>;
130
- /**
131
- * Fire-and-forget refresh. Does not await, swallows errors.
132
- */
133
- refreshMainInBackground(accessToken: string): void;
134
- isMainStale(): boolean;
135
- isFallbackStale(accountId: string, accessToken?: string): boolean;
136
- shouldRefreshOnRequestCount(requestCount: number): boolean;
137
- /**
138
- * Combined check: should a refresh happen right now?
139
- * True if main is stale by time OR triggered by request count.
140
- */
141
- needsRefresh(requestCount: number): boolean;
142
- updateStorage(storage: AccountStorage | null): void;
143
- /**
144
- * Seed/update the main quota cache from persisted state. This is deliberately
145
- * callable after every disk load so another plugin process's fresh quota write
146
- * can stop this process from showing "checking…" or making a redundant quota
147
- * API call.
148
- */
149
- seedMainFromStorage(storage: AccountStorage | null, accessToken?: string): void;
150
- private seedMainBackoffFromStorage;
151
- /**
152
- * Seed fallback cache entries from persisted account.quota data.
153
- * Updates older in-memory entries so a fresh quota write from another plugin
154
- * process prevents redundant checks and stale sidebar writes.
155
- */
156
- seedFallbacksFromAccounts(accounts: OAuthAccount[]): void;
157
- /**
158
- * Whether the MAIN quota API is currently in backoff. Scoped to the main
159
- * account — a fallback account's 429 never reports here.
160
- */
161
- isBackedOff(): boolean;
162
- /**
163
- * Whether a specific fallback account's quota API is in backoff.
164
- */
165
- isFallbackBackedOff(accountId: string, accessToken?: string): boolean;
166
- getLastApiError(): AccountOperationError | undefined;
167
- /** Minimum gap between consecutive quota API calls (ms). */
168
- private static readonly API_CALL_GAP_MS;
169
- private static fallbackInflightKey;
170
- private static quotaLockName;
171
- /**
172
- * Serialize API calls through a shared gate so only one
173
- * quota API request runs at a time, with a minimum gap
174
- * between calls. Prevents concurrent and rapid-fire calls
175
- * from triggering rate limits.
176
- */
177
- private _enqueueApiFetch;
178
- private _fetchMain;
179
- private _fetchFallback;
180
- /** Route through injected fetchQuotaFn, or throw if unset. */
181
- private _fetchQuota;
182
- private static isAuthError;
183
- /** Main quota failure: arms main-only backoff and persists via onApiError. */
184
- private _handleMainFetchError;
185
- /**
186
- * Fallback quota failure: arms backoff for THIS account only. Never touches
187
- * main backoff state and never calls onApiError (which persists the main
188
- * quota error) — the per-account error is recorded by the caller via the
189
- * account's lastQuotaRefreshError.
190
- */
191
- private _handleFallbackFetchError;
192
- }
@@ -1,86 +0,0 @@
1
- import { type SidebarState } from '../sidebar-state';
2
- import type { FallbackAccountManager, isOAuthAccount, loadAccounts } from './accounts';
3
- import type { whamUsageFn } from './provider';
4
- import type { QuotaManager } from './quota-manager';
5
- declare const log: {
6
- error: (m: string, d?: unknown) => void;
7
- warn: (m: string, d?: unknown) => void;
8
- info: (m: string, d?: unknown) => void;
9
- debug: (m: string, d?: unknown) => void;
10
- trace: (m: string, d?: unknown) => void;
11
- };
12
- type QuotaLogger = Pick<typeof log, 'debug' | 'warn'>;
13
- export interface RefreshAllQuotaDeps {
14
- getAuth: () => Promise<{
15
- type: string;
16
- access?: string;
17
- refresh?: string;
18
- expires?: number;
19
- }>;
20
- codexRefreshFn: (input: {
21
- refreshToken: string;
22
- fetchImpl: typeof fetch;
23
- now: () => number;
24
- }) => Promise<{
25
- access: string;
26
- refresh: string;
27
- expires: number;
28
- }>;
29
- refreshMainWithLease: () => Promise<{
30
- access: string;
31
- refresh: string;
32
- expires: number;
33
- }>;
34
- fallbackManager: FallbackAccountManager;
35
- quotaManager: QuotaManager;
36
- loadAccounts: typeof loadAccounts;
37
- writeSidebarState: (qm: QuotaManager, store: Awaited<ReturnType<typeof loadAccounts>>) => Promise<void>;
38
- client: {
39
- auth: {
40
- set: (input: {
41
- path: {
42
- id: string;
43
- };
44
- body: {
45
- type: string;
46
- access?: string;
47
- refresh: string;
48
- expires?: number;
49
- };
50
- }) => Promise<unknown>;
51
- };
52
- };
53
- fetchImpl: typeof fetch;
54
- now: () => number;
55
- configPath: string;
56
- storageMainAccountId: string | undefined;
57
- isOAuthAccountFn: typeof isOAuthAccount;
58
- whamFn?: typeof whamUsageFn;
59
- respectBackoff?: boolean;
60
- logger?: QuotaLogger;
61
- skipFresherThanMs?: number;
62
- readSidebarState?: () => Promise<SidebarState>;
63
- }
64
- export interface RefreshAllQuotaOptions {
65
- accountKey?: string;
66
- }
67
- export interface RefreshAllQuotaOptions {
68
- accountKey?: string;
69
- }
70
- export interface RefreshAllQuotaResult {
71
- account: string;
72
- ok: boolean;
73
- error?: string;
74
- /**
75
- * The account cannot recover on its own: the provider has rejected its
76
- * credentials, so no amount of retrying will help until the operator re-adds
77
- * it.
78
- *
79
- * Carried as a flag rather than left for the caller to infer from `error`,
80
- * because sniffing an error string for a user-facing decision breaks the
81
- * moment the wording changes.
82
- */
83
- permanent?: boolean;
84
- }
85
- export declare function refreshAllQuota(deps: RefreshAllQuotaDeps, options?: RefreshAllQuotaOptions): Promise<RefreshAllQuotaResult[]>;
86
- export {};
@@ -1,12 +0,0 @@
1
- export declare function isLostMarkerRaceError(error: unknown): boolean;
2
- export declare function acquireRefreshFileLock(options: {
3
- name: string;
4
- ttlMs: number;
5
- path?: string;
6
- now?: () => number;
7
- renew?: boolean;
8
- renewIntervalMs?: number;
9
- onStep?: (step: 'stale-marker-stat' | 'stale-marker-claimed' | 'stale-lock-confirmed' | 'eviction-marker-acquired' | 'renewal-owner-confirmed' | 'renewal-marker-unavailable' | 'renewal-write-fenced' | 'renewal-write-ready' | 'relinquish-read' | 'renewal-finished' | 'release-owner-confirmed') => void | Promise<void>;
10
- }): Promise<{
11
- release: () => Promise<void>;
12
- } | null>;
@@ -1,116 +0,0 @@
1
- import { type loadAccounts, type mutateAccounts, type OAuthQuotaSnapshot, type ResetAccountState, type ResetInFlight } from './accounts.ts';
2
- export interface ResetCredit {
3
- id: string;
4
- status: string;
5
- grantedAt?: string;
6
- expiresAt: string;
7
- resetType?: string;
8
- isSupportedByPlan: boolean;
9
- }
10
- export interface ResetCreditList {
11
- credits: ResetCredit[];
12
- availableCount?: number;
13
- }
14
- export type ResetConsumeKind = 'reset' | 'already_redeemed' | 'nothing_to_reset' | 'no_credit' | 'http_error' | 'ambiguous';
15
- export interface ResetConsumeOutcome {
16
- kind: ResetConsumeKind;
17
- raw: unknown;
18
- status?: number;
19
- }
20
- export type ResetPrecondition = {
21
- ok: true;
22
- } | {
23
- ok: false;
24
- reason: 'not exhausted';
25
- };
26
- export interface ResetStateDeps {
27
- configPath: string;
28
- mutateAccountsFn: typeof mutateAccounts;
29
- loadAccountsFn: typeof loadAccounts;
30
- now: () => number;
31
- randomUUID: () => string;
32
- }
33
- export interface ResetResolvedTarget {
34
- accountKey: string;
35
- label: string;
36
- accessToken: string;
37
- chatgptAccountId?: string;
38
- }
39
- export interface RunResetCreditDeps extends ResetStateDeps {
40
- fetchImpl: typeof fetch;
41
- resolveTarget(accountKey: string): Promise<ResetResolvedTarget>;
42
- fetchUsage(target: ResetResolvedTarget): Promise<OAuthQuotaSnapshot>;
43
- hasActiveRateLimitMark(accountKey: string): boolean;
44
- }
45
- export interface RunResetCreditInput {
46
- accountKey: string;
47
- expectedChatgptAccountId: string;
48
- retry: boolean;
49
- }
50
- export type ResetRedemptionErrorKind = 'invalid_account_key' | 'identity_mismatch' | 'cooldown_active' | 'expired_unreconciled' | 'retry_without_inflight' | 'not_exhausted' | 'no_eligible_credit';
51
- export declare class ResetRedemptionError extends Error {
52
- readonly kind: ResetRedemptionErrorKind;
53
- readonly cooldownUntil?: number;
54
- constructor(kind: ResetRedemptionErrorKind, message: string, cooldownUntil?: number);
55
- }
56
- export interface ResetLocalAmbiguousOutcome {
57
- kind: 'ambiguous_local';
58
- raw: {
59
- reason: 'corrupt_in_flight';
60
- };
61
- }
62
- export type ResetRedemptionOutcome = ResetConsumeOutcome | ResetLocalAmbiguousOutcome;
63
- export type ResetSelectedCredit = ResetCredit | {
64
- id: string;
65
- };
66
- export interface RunResetCreditResult {
67
- target: ResetResolvedTarget;
68
- selectedCredit: ResetSelectedCredit | undefined;
69
- beforeState: ResetAccountState | undefined;
70
- outcome: ResetRedemptionOutcome;
71
- retrySafety: string;
72
- finalizeStateWriteFailed?: boolean;
73
- }
74
- interface ResetClaim {
75
- inFlight: ResetInFlight;
76
- selectedCredit: ResetSelectedCredit;
77
- }
78
- type ResetStateDecision = {
79
- kind: 'fresh';
80
- beforeState: ResetAccountState | undefined;
81
- } | {
82
- kind: 'claim';
83
- beforeState: ResetAccountState | undefined;
84
- claim: ResetClaim;
85
- } | {
86
- kind: 'expired_unreconciled';
87
- beforeState: ResetAccountState | undefined;
88
- claim: ResetClaim;
89
- } | {
90
- kind: 'cooldown';
91
- beforeState: ResetAccountState | undefined;
92
- cooldownUntil: number;
93
- } | {
94
- kind: 'corrupt';
95
- beforeState: ResetAccountState | undefined;
96
- };
97
- export type ResetCreditErrorKind = 'http_error' | 'invalid_response';
98
- export declare class ResetCreditError extends Error {
99
- readonly kind: ResetCreditErrorKind;
100
- readonly status?: number;
101
- constructor(kind: ResetCreditErrorKind, message: string, status?: number);
102
- }
103
- export declare function claimResetAttempt(deps: ResetStateDeps, accountKey: string, credits: readonly ResetCredit[]): Promise<ResetStateDecision>;
104
- export declare function finalizeResetAttempt(deps: ResetStateDeps, accountKey: string, completing: ResetInFlight, outcome: ResetConsumeOutcome): Promise<void>;
105
- export declare function resetWindowIsExhausted(window: {
106
- usedPercent: number;
107
- resetsAt?: string;
108
- } | undefined, now: number): boolean;
109
- export declare function evaluateResetPrecondition(quota: OAuthQuotaSnapshot, hasActiveRateLimitMark: boolean, now: number): ResetPrecondition;
110
- export declare function listResetCredits(fetchImpl: typeof fetch, token: string, accountId?: string): Promise<ResetCreditList>;
111
- export declare function selectCreditToSpend(credits: readonly ResetCredit[]): ResetCredit | undefined;
112
- export declare function isResetCreditEligible(credit: ResetCredit): boolean;
113
- export declare function countEligibleResetCredits(credits: readonly ResetCredit[]): number;
114
- export declare function consumeResetCredit(fetchImpl: typeof fetch, token: string, accountId: string | undefined, creditId: string, redeemRequestId: string): Promise<ResetConsumeOutcome>;
115
- export declare function runResetCreditRedemption(deps: RunResetCreditDeps, input: RunResetCreditInput): Promise<RunResetCreditResult>;
116
- export {};
@@ -1,43 +0,0 @@
1
- import { type AccountQuota, type QuotaWindow, type QuotaWindowKey } from '../sidebar-state';
2
- export declare const QUOTA_STALENESS_MS: number;
3
- export declare const MIN_RESET_HOURS: number;
4
- export declare const MIN_WEIGHT = 0.000001;
5
- export declare function snapshotCheckedAt(quota: AccountQuota | null | undefined, entryCheckedAt?: number): number | undefined;
6
- export type StickyBreakDecision = {
7
- action: 'retain';
8
- reason: 'unknown' | 'stale' | 'healthy' | 'transient';
9
- } | {
10
- action: 'migrate';
11
- reason: 'exhausted' | 'permanent' | 'killswitch';
12
- windowKey?: QuotaWindowKey;
13
- resetsAt?: string;
14
- };
15
- export declare function decideStickyBreak(input: {
16
- quota: AccountQuota | null | undefined;
17
- quotaCheckedAt?: number;
18
- status?: number;
19
- now: number;
20
- killswitchPasses?: boolean;
21
- }): StickyBreakDecision;
22
- export declare function sustainableWindowWeight(window: Pick<QuotaWindow, 'remainingPercent' | 'resetsAt'>, reservePercent: number, now: number): number;
23
- export interface StickySelectionCandidate {
24
- accountId: string;
25
- quota: AccountQuota | null | undefined;
26
- quotaCheckedAt?: number;
27
- reservePercent: Record<QuotaWindowKey, number>;
28
- configuredOrder: number;
29
- resetCreditsApplicable?: number;
30
- killswitchPasses?: boolean;
31
- }
32
- export interface StickySelectionInput {
33
- candidates: readonly StickySelectionCandidate[];
34
- pendingBytes: ReadonlyMap<string, number>;
35
- requestBytes: number;
36
- now: number;
37
- onEmptyWeightedSet?: () => void;
38
- }
39
- export declare function selectStickyCandidate(input: StickySelectionInput): {
40
- accountId: string;
41
- quotaCheckedAt?: number;
42
- source: 'weighted' | 'mode-fallback';
43
- } | undefined;
package/dist/dump.d.ts DELETED
@@ -1,20 +0,0 @@
1
- export declare const DUMP_SESSION_HEADER = "x-cortexkit-openai-auth-dump-session";
2
- type DumpHeaders = ConstructorParameters<typeof Headers>[0];
3
- type DumpTransport = 'http' | 'websocket';
4
- declare const DUMP_PHASES: readonly ['http', 'prewarm', 'main'];
5
- type DumpPhase = (typeof DUMP_PHASES)[number];
6
- export declare function dumpCodexRequest(input: {
7
- sessionID?: string | null;
8
- transport: DumpTransport;
9
- phase: DumpPhase;
10
- bodyText: string;
11
- accountId?: string;
12
- url?: string;
13
- method?: string;
14
- headers?: DumpHeaders;
15
- status?: number;
16
- error?: string;
17
- }): Promise<void>;
18
- export declare function dumpDiagnostic(event: Record<string, unknown>): Promise<void>;
19
- export declare function resetDumpStateForTest(): void;
20
- export {};
@@ -1,5 +0,0 @@
1
- import { type ToolDefinition } from '@opencode-ai/plugin';
2
- export declare const HostedWebSearchTool: ToolDefinition;
3
- export declare function translateHostedWebSearchEvent(event: Record<string, unknown>): Record<string, unknown> | undefined;
4
- export declare function translateHostedWebSearchResponse(response: Response): Response;
5
- export declare function rewriteHostedWebSearchReplay(body: Record<string, unknown>): boolean;
@@ -1,2 +0,0 @@
1
- function K(k){if(k==null||k==="")return;let q=typeof k==="number"?k:Number(k);if(Number.isFinite(q)){let B=q<100000000000?q*1000:q,G=new Date(B);return Number.isNaN(G.getTime())?void 0:G.toISOString()}let z=new Date(k);return Number.isNaN(z.getTime())?void 0:z.toISOString()}function L(k){let q=Number(k);return Number.isFinite(q)&&q>0?q:void 0}function X(k){return typeof k==="number"&&Number.isFinite(k)&&k>=0?k:void 0}function Y(k,q){let z=k.get(q);if(z===null||z.trim()==="")return;let B=Number(z);if(!Number.isFinite(B)||B<0||B>100)return;let G=q.slice(0,-13),J=L(k.get(`${G}-window-minutes`)),V=K(k.get(`${G}-reset-at`)??void 0);if(B===0&&k.get(`${G}-window-minutes`)==="0"&&!V)return;return{usedPercent:B,remainingPercent:100-B,resetsAt:V,checkedAt:Date.now(),...J!==void 0?{windowMinutes:J}:{}}}var O=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function Q(k,q){let z=k.get(q);if(z===null)return"absent";if(z.trim()==="")return"invalid";let B=Number(z);return Number.isFinite(B)&&B>=0&&B<=100?"valid":"invalid"}function g(k){if(O.some((G)=>Q(k,G)==="invalid"))return{};let q={},z=Y(k,"x-codex-primary-used-percent");if(z)q.primary=z;let B=Y(k,"x-codex-secondary-used-percent");if(B)q.secondary=B;return q}function I(k){let q=O.map((z)=>Q(k,z));return q.includes("valid")&&!q.includes("invalid")}function Z(k){if(!k)return;if(!Number.isFinite(k.used_percent)||k.used_percent<0||k.used_percent>100)return;let q=L(k.window_minutes),z=K(k.reset_at);if(k.used_percent===0&&q===void 0&&!z)return;return{usedPercent:k.used_percent,remainingPercent:100-k.used_percent,resetsAt:z,checkedAt:Date.now(),...q!==void 0?{windowMinutes:q}:{}}}function f(k){let q={},z=Z(k.rate_limits?.primary);if(z)q.primary=z;let B=Z(k.rate_limits?.secondary);if(B)q.secondary=B;return q}function $(k){if(!k)return;if(!Number.isFinite(k.used_percent)||k.used_percent<0||k.used_percent>100)return;let q=L(k.limit_window_seconds),z=K(k.reset_at);if(k.used_percent===0&&q===void 0&&!z)return;return{usedPercent:k.used_percent,remainingPercent:100-k.used_percent,resetsAt:z,checkedAt:Date.now(),...q!==void 0?{windowMinutes:q/60}:{}}}function x(k){let q={},z=$(k.rate_limit?.primary_window);if(z)q.primary=z;let B=$(k.rate_limit?.secondary_window);if(B)q.secondary=B;let G=X(k.rate_limit_reset_credits?.available_count);if(G!==void 0)q.resetCreditsAvailable=G;let J=X(k.rate_limit_reset_credits?.applicable_available_count);if(J!==void 0)q.resetCreditsApplicable=J;return q}
2
- export{K as c,g as d,I as e,f,x as g};
@@ -1,6 +0,0 @@
1
- import{realpathSync as k}from"node:fs";import{homedir as i}from"node:os";import{basename as P,dirname as m,join as D,resolve as w}from"node:path";var d="openai-auth.json",r="openai-auth-state.json";function t(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return D(process.env.XDG_CONFIG_HOME||D(i(),".config"),"opencode")}function C(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||D(t(),d)}function e(B){return P(B)===d?D(m(B),r):`${B}.state.json`}function q(B,Q){let J=w(B);return Q==="win32"||Q==="darwin"?J.toLowerCase():J}function f(B){try{return k.native(B)}catch{try{return D(k.native(m(B)),P(B))}catch{return}}}function o(B,Q,J=process.platform){if(q(B,J)===q(Q,J))return!0;let j=f(B),W=f(Q);return j!==void 0&&W!==void 0&&q(j,J)===q(W,J)}function ZB(B=C()){let Q=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Q){if(o(B,Q))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${w(B)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return Q}return e(B)}import{randomUUID as y}from"node:crypto";import{mkdir as h,readFile as F,rename as BB,rm as x,stat as l,writeFile as L}from"node:fs/promises";import{dirname as GB,join as p}from"node:path";var HB=globalThis.setTimeout.bind(globalThis),JB=globalThis.clearTimeout.bind(globalThis);function KB(B){let Q=B?.code;return Q==="ENOENT"||Q==="EINVAL"||Q==="ENOTDIR"}async function DB(B){let J=`${B.path??C()}.${B.name}.lock`,j=p(J,"owner.json"),W=y(),Z=B.now??Date.now,X=null,$=!1,N=null,z=`${J}.evicting`,A=p(z,"owner.json"),I=y(),c=5000,O=8;async function b(){try{return JSON.parse(await F(J,"utf8"))}catch(G){if(G.code!=="EISDIR")throw G;return JSON.parse(await F(j,"utf8"))}}async function s(){await L(J,`${JSON.stringify({ownerId:W,expiresAt:Z()+B.ttlMs})}
2
- `,{encoding:"utf8",mode:384})}async function _(){try{return await L(J,`${JSON.stringify({ownerId:W,expiresAt:Z()+B.ttlMs})}
3
- `,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(G){let H=G.code;if(H==="EEXIST"||H==="EISDIR")return!1;if(H==="ENOENT"){await h(GB(J),{recursive:!0});try{return await L(J,`${JSON.stringify({ownerId:W,expiresAt:Z()+B.ttlMs})}
4
- `,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(K){let R=K.code;if(R==="EEXIST"||R==="EISDIR")return!1;throw K}}throw G}}async function U(){await new Promise((G)=>setTimeout(G,Math.floor(Math.random()*4)))}async function T(){try{let G=await b();return Number(G?.expiresAt)>Z()}catch{try{return(await l(J)).mtimeMs+B.ttlMs>Z()}catch{return!1}}}async function Y(){try{return JSON.parse(await F(A,"utf8"))?.ownerId===I}catch{return!1}}async function S(){if(await Y())await x(z,{recursive:!0,force:!0}).catch(()=>{})}async function M(){await h(z);try{await L(A,`${JSON.stringify({ownerId:I,createdAt:Z()})}
5
- `,{encoding:"utf8",mode:384,flag:"wx"})}catch(G){if(KB(G))return!1;throw await S(),G}if(B.onStep)await B.onStep("eviction-marker-acquired");return!0}async function g(){let G;try{G=await l(z)}catch(K){if(K.code==="ENOENT")return"missing";throw K}if(G.mtimeMs+c>Z())return"fresh";if(B.onStep)await B.onStep("stale-marker-stat");let H=`${z}.${y()}`;try{await BB(z,H)}catch(K){if(K.code==="ENOENT")return"missing";throw K}if(B.onStep)await B.onStep("stale-marker-claimed");return await x(H,{recursive:!0,force:!0}).catch(()=>{}),"recovered"}async function E(G){try{if(!await M())return!1}catch(H){if(H.code==="EEXIST")return!1;throw H}try{await G()}finally{await S()}return!0}async function a(){for(let G=0;G<O;G++){if(B.onStep)await B.onStep("relinquish-read");let H;try{H=await b()}catch{return}if(H?.ownerId!==W)return;try{await x(J,{recursive:!0,force:!0});return}catch{await U()}}}function u(){if(!B.renew||$)return;let G=B.renewIntervalMs??Math.max(1000,Math.floor(B.ttlMs/3));if(X=HB(()=>{let H=(async()=>{let K=!$;try{if(!await E(async()=>{let v=await b(),n=Z();if($||v?.ownerId!==W){K=!1;return}if(Number(v?.expiresAt)<=n){K=!1;return}if(B.onStep)await B.onStep("renewal-owner-confirmed");if($){K=!1;return}if(!await Y())return;if(B.onStep)await B.onStep("renewal-write-fenced");if($){K=!1;return}if(!await Y())return;if(B.onStep)await B.onStep("renewal-write-ready");if(await s(),!await Y()){K=!1,await a();return}})&&B.onStep)await B.onStep("renewal-marker-unavailable")}catch{}finally{if(B.onStep)try{await B.onStep("renewal-finished")}catch{}if(K&&!$)u()}})();N=H,H.finally(()=>{if(N===H)N=null})},G),"unref"in X)X.unref()}let V=await _();if(!V)for(let G=0;G<O;G++){if(V=await _(),V)break;if(await T())return null;try{if(!await M()){await U();continue}}catch(H){if(H.code!=="EEXIST")throw H;if(await g()==="fresh")return null;await U();continue}try{if(await T())return null;if(!await Y())return null;if(B.onStep)await B.onStep("stale-lock-confirmed");if(!await Y())return null;if(await x(J,{recursive:!0,force:!0}).catch(()=>{}),!await Y())return null;if(V=await _(),!V)return null;if(!await Y())return await x(J,{recursive:!0,force:!0}).catch(()=>{}),V=!1,null;break}finally{await S()}}if(!V)return null;return u(),{release:async()=>{if($=!0,X)JB(X),X=null;await N;for(let G=0;G<O;G++){try{if(await E(async()=>{if((await b())?.ownerId!==W)return;if(B.onStep)await B.onStep("release-owner-confirmed");if(!await Y())return;await x(J,{recursive:!0,force:!0}).catch(()=>{})}))return;await g()}catch{return}await U()}}}}
6
- export{C as ua,ZB as va,DB as wa};