@wengine-ai/ccr-provider-codex 0.0.0-stage → 1.0.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.
package/dist/card.js ADDED
@@ -0,0 +1,1091 @@
1
+ // src/card-types.ts
2
+ var CODEX_PROVIDER_NAME = "codex-subscription";
3
+ var CODEX_MARKER_KEY = "ccr-managed-codex";
4
+ function isRecord(value) {
5
+ return !!value && typeof value === "object" && !Array.isArray(value);
6
+ }
7
+ function finiteNumber(value) {
8
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
9
+ }
10
+ function stringArray(value) {
11
+ if (!Array.isArray(value)) return null;
12
+ const models = [];
13
+ for (const item of value) {
14
+ if (typeof item !== "string" || item.length === 0 || item.length > 200) return null;
15
+ models.push(item);
16
+ }
17
+ return models;
18
+ }
19
+ function parseCodexStatus(value) {
20
+ if (!isRecord(value)) return null;
21
+ const status = value.status;
22
+ if (status !== "not_connected" && status !== "connected" && status !== "expired" && status !== "error") return null;
23
+ const models = stringArray(value.models);
24
+ if (!models) return null;
25
+ const modelCount = finiteNumber(value.modelCount);
26
+ const next = {
27
+ status,
28
+ providerName: typeof value.providerName === "string" && value.providerName ? value.providerName : CODEX_PROVIDER_NAME,
29
+ models,
30
+ modelCount: modelCount ?? models.length
31
+ };
32
+ if (typeof value.accountId === "string" && value.accountId) next.accountId = value.accountId;
33
+ if (typeof value.email === "string" && value.email) next.email = value.email;
34
+ if (typeof value.plan === "string" && value.plan) next.plan = value.plan;
35
+ const coolingUntil = finiteNumber(value.coolingUntil);
36
+ if (coolingUntil !== null) next.coolingUntil = coolingUntil;
37
+ if (typeof value.lastError === "string") next.lastError = value.lastError;
38
+ return next;
39
+ }
40
+ function parseCodexLoginStart(value) {
41
+ if (!isRecord(value)) return null;
42
+ const { loginId, url, expiresAt, mode, redirectUri } = value;
43
+ if (typeof loginId !== "string" || !loginId || loginId.length > 256) return null;
44
+ if (typeof url !== "string" || !url) return null;
45
+ try {
46
+ if (new URL(url).protocol !== "https:") return null;
47
+ } catch {
48
+ return null;
49
+ }
50
+ const expiry = finiteNumber(expiresAt);
51
+ if (expiry === null) return null;
52
+ if (mode !== "callback" && mode !== "paste") return null;
53
+ if (typeof redirectUri !== "string" || !redirectUri) return null;
54
+ return { loginId, url, expiresAt: expiry, mode, redirectUri };
55
+ }
56
+ function parseCodexLoginPoll(value) {
57
+ if (!isRecord(value)) return null;
58
+ const status = value.status;
59
+ if (status !== "pending" && status !== "connected" && status !== "cancelled" && status !== "expired" && status !== "error") return null;
60
+ const next = { status };
61
+ if (typeof value.error === "string") next.error = value.error;
62
+ const models = stringArray(value.models);
63
+ if (models) next.models = models;
64
+ const modelCount = finiteNumber(value.modelCount);
65
+ if (modelCount !== null) next.modelCount = modelCount;
66
+ return next;
67
+ }
68
+ function parseCodexUsage(value) {
69
+ if (!isRecord(value)) return null;
70
+ const plan = typeof value.plan === "string" ? value.plan : "";
71
+ const next = { plan };
72
+ for (const key of ["primary", "secondary"]) {
73
+ const raw = value[key];
74
+ if (raw === void 0 || raw === null) continue;
75
+ if (!isRecord(raw)) return null;
76
+ const usedPercent = finiteNumber(raw.usedPercent);
77
+ const windowSeconds = finiteNumber(raw.windowSeconds);
78
+ const resetAt = finiteNumber(raw.resetAt);
79
+ if (usedPercent === null || windowSeconds === null || resetAt === null) return null;
80
+ next[key] = { usedPercent, windowSeconds, resetAt };
81
+ }
82
+ if (!next.primary && !next.secondary) return null;
83
+ return next;
84
+ }
85
+ function parseCodexMutation(value) {
86
+ if (!isRecord(value)) return { success: false };
87
+ const next = { success: value.success === true };
88
+ if (typeof value.error === "string") next.error = value.error;
89
+ const models = stringArray(value.models);
90
+ if (models) next.models = models;
91
+ const modelCount = finiteNumber(value.modelCount);
92
+ if (modelCount !== null) next.modelCount = modelCount;
93
+ return next;
94
+ }
95
+ function sanitizeCodexErrorCode(value) {
96
+ if (typeof value !== "string") return null;
97
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(value)) return null;
98
+ return value;
99
+ }
100
+ function codexStateKey(status, now = Date.now()) {
101
+ if (!status) return "loading";
102
+ if (status.status === "expired") return "needs_relogin";
103
+ if (typeof status.coolingUntil === "number" && status.coolingUntil > now) return "cooldown";
104
+ if (status.status === "connected") return "connected";
105
+ if (status.status === "error") return "error";
106
+ return "not_connected";
107
+ }
108
+ function codexConnected(status, now = Date.now()) {
109
+ return codexStateKey(status, now) === "connected";
110
+ }
111
+ function formatCodexClock(value, language) {
112
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
113
+ try {
114
+ return new Date(value).toLocaleString(language || void 0, {
115
+ month: "short",
116
+ day: "numeric",
117
+ hour: "2-digit",
118
+ minute: "2-digit"
119
+ });
120
+ } catch {
121
+ return null;
122
+ }
123
+ }
124
+ function codexWindowUnit(windowSeconds) {
125
+ const seconds = Number.isFinite(windowSeconds) && windowSeconds > 0 ? windowSeconds : 0;
126
+ if (seconds > 0 && seconds % 86400 === 0) return { unit: "days", count: seconds / 86400 };
127
+ if (seconds > 0 && seconds % 3600 === 0) return { unit: "hours", count: seconds / 3600 };
128
+ return { unit: "minutes", count: Math.max(1, Math.round(seconds / 60)) };
129
+ }
130
+ function maskCodexAccountId(value) {
131
+ if (typeof value !== "string" || !value) return null;
132
+ if (value.length <= 10) return value;
133
+ return `${value.slice(0, 6)}\u2026${value.slice(-4)}`;
134
+ }
135
+ function isValidCodexCallbackUrl(value) {
136
+ if (typeof value !== "string" || !value || value.length > 2048) return false;
137
+ let parsed;
138
+ try {
139
+ parsed = new URL(value);
140
+ } catch {
141
+ return false;
142
+ }
143
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
144
+ return typeof parsed.searchParams.get("code") === "string" && typeof parsed.searchParams.get("state") === "string" && parsed.searchParams.get("code") !== "" && parsed.searchParams.get("state") !== "";
145
+ }
146
+ function isCodexManagedProvider(provider) {
147
+ if (!provider || typeof provider !== "object") return false;
148
+ const value = provider;
149
+ if (value.codex_managed === true) return true;
150
+ if (value.name !== CODEX_PROVIDER_NAME) return false;
151
+ const marker = value.api_key ?? value.apiKey;
152
+ return marker === CODEX_MARKER_KEY;
153
+ }
154
+ function mergeCodexProvider(local, server) {
155
+ const providers = [...local.Providers || []];
156
+ const managed = (server.Providers || []).find((provider) => isCodexManagedProvider(provider));
157
+ const index = providers.findIndex((provider) => isCodexManagedProvider(provider));
158
+ if (index >= 0) {
159
+ if (managed) providers[index] = managed;
160
+ else providers.splice(index, 1);
161
+ } else if (managed && !providers.some((provider) => provider?.name === CODEX_PROVIDER_NAME)) {
162
+ providers.push(managed);
163
+ }
164
+ return { ...local, Providers: providers };
165
+ }
166
+ var CODEX_USAGE_CACHE_KEY = "codex-usage-cache-v1";
167
+ var CODEX_USAGE_CACHE_TTL_MS = 10 * 6e4;
168
+ function readUsageStore() {
169
+ try {
170
+ const raw = globalThis.sessionStorage?.getItem(CODEX_USAGE_CACHE_KEY);
171
+ if (raw) {
172
+ const parsed = JSON.parse(raw);
173
+ if (parsed && typeof parsed === "object" && "entry" in parsed) return parsed;
174
+ }
175
+ } catch {
176
+ }
177
+ return { savedAt: 0, entry: null };
178
+ }
179
+ function writeUsageStore(store) {
180
+ try {
181
+ globalThis.sessionStorage?.setItem(CODEX_USAGE_CACHE_KEY, JSON.stringify(store));
182
+ } catch {
183
+ }
184
+ }
185
+ function freshCodexUsage(now = Date.now()) {
186
+ const hit = readUsageStore().entry;
187
+ if (!hit || typeof hit.at !== "number" || !Number.isFinite(hit.at) || hit.at > now) return void 0;
188
+ if (now - hit.at > CODEX_USAGE_CACHE_TTL_MS) return void 0;
189
+ const value = parseCodexUsage(hit.value);
190
+ return value ? { value, at: hit.at } : void 0;
191
+ }
192
+ function rememberCodexUsage(value, now = Date.now()) {
193
+ if (!value) return;
194
+ writeUsageStore({ savedAt: now, entry: { value, at: now } });
195
+ }
196
+ function clearCodexUsageCache() {
197
+ try {
198
+ globalThis.sessionStorage?.removeItem(CODEX_USAGE_CACHE_KEY);
199
+ } catch {
200
+ }
201
+ }
202
+
203
+ // src/locales.ts
204
+ var codexLocales = {
205
+ en: {
206
+ codex: {
207
+ title: "Codex Subscription",
208
+ builtin: "Official plugin",
209
+ experimental: "Experimental",
210
+ managed_provider: "Managed provider: {{name}}",
211
+ description: "Uses your ChatGPT/Codex plan through browser authorization. CCR never reads ~/.codex or imports the official CLI login.",
212
+ status: {
213
+ loading: "Loading\u2026",
214
+ not_connected: "Not connected",
215
+ connected: "Connected",
216
+ cooldown: "Quota cooldown",
217
+ needs_relogin: "Sign-in expired",
218
+ error: "Error"
219
+ },
220
+ labels: {
221
+ email: "Email",
222
+ account: "Account",
223
+ plan: "Plan",
224
+ models: "Models"
225
+ },
226
+ models_count: "{{count}} models",
227
+ unknown: "Unknown",
228
+ cooldown_until: "Quota cooldown until {{time}}",
229
+ needs_relogin_help: "The sign-in has expired. Reconnect to refresh the authorization.",
230
+ browser_login: "Browser login",
231
+ reconnect: "Reconnect",
232
+ sync: "Sync models",
233
+ disconnect: "Disconnect",
234
+ refresh_usage: "Refresh quota",
235
+ working: "Working\u2026",
236
+ cancel: "Cancel",
237
+ login_pending: "Waiting for authorization in your browser\u2026",
238
+ open_login: "Open OpenAI authorization page",
239
+ paste_title: "Paste callback URL",
240
+ paste_help: "The local callback port is unavailable (another application may own it \u2014 CCR will not terminate it). After approving in the browser, copy the full address your browser was redirected to (it will fail to load; that is expected) and paste it here.",
241
+ paste_hint: "Browser did not return automatically? Paste the redirected callback address here.",
242
+ paste_placeholder: "http://127.0.0.1:1455/auth/callback?code=\u2026&state=\u2026",
243
+ paste_submit: "Complete login",
244
+ login_success: "Connected as {{email}}.",
245
+ login_success_unknown: "Connected.",
246
+ synced: "Synced {{count}} Codex models.",
247
+ disconnected: "Disconnected.",
248
+ disconnect_title: "Disconnect Codex?",
249
+ disconnect_warning: "The managed provider entry and stored authorization are removed. Your OpenAI plan itself is not touched, and Router/other providers are preserved. You can reconnect anytime.",
250
+ usage_title: "Plan quota",
251
+ usage_primary: "Primary window ({{window}})",
252
+ usage_secondary: "Secondary window ({{window}})",
253
+ usage_line: "{{percent}}% used \xB7 resets {{time}}",
254
+ usage_plan: "Plan: {{plan}}",
255
+ usage_unavailable: "Quota information is not available right now.",
256
+ usage_updated: "Updated {{time}}",
257
+ window: {
258
+ minutes: "{{count}} min",
259
+ hours: "{{count}} h",
260
+ days: "{{count}} d"
261
+ },
262
+ about: "About this integration",
263
+ about_body: "After connecting, model syncing pulls the model list your plan exposes; the managed provider serves OpenAI Codex models through CCR. Quota is shown per rate-limit window (a short primary window plus a longer secondary window) and is read at most once per visit, then cached briefly.",
264
+ disclaimer: "Experimental integration using the official Codex client identity. Fair-use outcomes under your OpenAI plan terms cannot be guaranteed \u2014 use at your own discretion.",
265
+ other_edit: "Another change is in progress \u2014 actions are paused until it finishes.",
266
+ errors: {
267
+ request_failed: "The request failed. Please try again.",
268
+ config_busy: "Another save or action is running \u2014 try again when it finishes.",
269
+ login_invalid_response: "The login response was invalid. Please retry.",
270
+ login_failed: "Login failed.",
271
+ login_expired: "The authorization window expired. Please start again.",
272
+ login_cancelled: "Login cancelled.",
273
+ sync_failed: "Model sync failed.",
274
+ disconnect_failed: "Disconnect failed.",
275
+ callback_invalid: "That does not look like a valid callback URL (expected code and state parameters).",
276
+ callback_rejected: "The callback was rejected. Please copy the full address and try again.",
277
+ reconciliation_failed: "Applied, but the local settings draft could not be refreshed \u2014 reload the page to see the change."
278
+ }
279
+ }
280
+ },
281
+ zh: {
282
+ codex: {
283
+ title: "Codex \u8BA2\u9605",
284
+ builtin: "\u5B98\u65B9\u63D2\u4EF6",
285
+ experimental: "\u5B9E\u9A8C\u6027",
286
+ managed_provider: "\u53D7\u7BA1\u4F9B\u5E94\u5546\uFF1A{{name}}",
287
+ description: "\u901A\u8FC7\u6D4F\u89C8\u5668\u6388\u6743\u4F7F\u7528\u4F60\u7684 ChatGPT/Codex \u8BA2\u9605\u3002CCR \u4E0D\u8BFB\u53D6 ~/.codex\uFF0C\u4E5F\u4E0D\u5BFC\u5165\u5B98\u65B9 CLI \u767B\u5F55\u3002",
288
+ status: {
289
+ loading: "\u52A0\u8F7D\u4E2D\u2026",
290
+ not_connected: "\u672A\u8FDE\u63A5",
291
+ connected: "\u5DF2\u8FDE\u63A5",
292
+ cooldown: "\u914D\u989D\u51B7\u5374\u4E2D",
293
+ needs_relogin: "\u767B\u5F55\u5DF2\u8FC7\u671F",
294
+ error: "\u9519\u8BEF"
295
+ },
296
+ labels: {
297
+ email: "\u90AE\u7BB1",
298
+ account: "\u8D26\u53F7",
299
+ plan: "\u5957\u9910",
300
+ models: "\u6A21\u578B"
301
+ },
302
+ models_count: "{{count}} \u4E2A\u6A21\u578B",
303
+ unknown: "\u672A\u77E5",
304
+ cooldown_until: "\u914D\u989D\u51B7\u5374\u81F3 {{time}}",
305
+ needs_relogin_help: "\u767B\u5F55\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8FDE\u63A5\u4EE5\u5237\u65B0\u6388\u6743\u3002",
306
+ browser_login: "\u6D4F\u89C8\u5668\u767B\u5F55",
307
+ reconnect: "\u91CD\u65B0\u8FDE\u63A5",
308
+ sync: "\u540C\u6B65\u6A21\u578B",
309
+ disconnect: "\u65AD\u5F00\u8FDE\u63A5",
310
+ refresh_usage: "\u5237\u65B0\u914D\u989D",
311
+ working: "\u5904\u7406\u4E2D\u2026",
312
+ cancel: "\u53D6\u6D88",
313
+ login_pending: "\u6B63\u5728\u7B49\u5F85\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u6388\u6743\u2026",
314
+ open_login: "\u6253\u5F00 OpenAI \u6388\u6743\u9875\u9762",
315
+ paste_title: "\u7C98\u8D34\u56DE\u8C03\u5730\u5740",
316
+ paste_help: "\u672C\u5730\u56DE\u8C03\u7AEF\u53E3\u4E0D\u53EF\u7528\uFF08\u53EF\u80FD\u88AB\u5176\u4ED6\u5E94\u7528\u5360\u7528\u2014\u2014CCR \u4E0D\u4F1A\u66FF\u4F60\u7ED3\u675F\u522B\u4EBA\u7684\u8FDB\u7A0B\uFF09\u3002\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u6388\u6743\u540E\uFF0C\u628A\u6D4F\u89C8\u5668\u8DF3\u8F6C\u5230\u7684\u5B8C\u6574\u5730\u5740\uFF08\u9875\u9762\u4F1A\u52A0\u8F7D\u5931\u8D25\uFF0C\u8FD9\u662F\u9884\u671F\u884C\u4E3A\uFF09\u590D\u5236\u5E76\u7C98\u8D34\u5230\u8FD9\u91CC\u3002",
317
+ paste_hint: "\u6D4F\u89C8\u5668\u6CA1\u6709\u81EA\u52A8\u8FD4\u56DE\uFF1F\u628A\u8DF3\u8F6C\u540E\u7684\u56DE\u8C03\u5730\u5740\u7C98\u8D34\u5230\u8FD9\u91CC\u3002",
318
+ paste_placeholder: "http://127.0.0.1:1455/auth/callback?code=\u2026&state=\u2026",
319
+ paste_submit: "\u5B8C\u6210\u767B\u5F55",
320
+ login_success: "\u5DF2\u8FDE\u63A5\uFF1A{{email}}\u3002",
321
+ login_success_unknown: "\u5DF2\u8FDE\u63A5\u3002",
322
+ synced: "\u5DF2\u540C\u6B65 {{count}} \u4E2A Codex \u6A21\u578B\u3002",
323
+ disconnected: "\u5DF2\u65AD\u5F00\u8FDE\u63A5\u3002",
324
+ disconnect_title: "\u65AD\u5F00 Codex\uFF1F",
325
+ disconnect_warning: "\u5C06\u79FB\u9664\u53D7\u7BA1\u4F9B\u5E94\u5546\u6761\u76EE\u548C\u5DF2\u5B58\u7684\u6388\u6743\u3002\u4E0D\u4F1A\u5F71\u54CD\u4F60\u7684 OpenAI \u8BA2\u9605\u672C\u8EAB\uFF0CRouter \u4E0E\u5176\u4ED6\u4F9B\u5E94\u5546\u4FDD\u6301\u4E0D\u53D8\u3002\u4E4B\u540E\u53EF\u968F\u65F6\u91CD\u65B0\u8FDE\u63A5\u3002",
326
+ usage_title: "\u8BA2\u9605\u914D\u989D",
327
+ usage_primary: "\u4E3B\u7A97\u53E3\uFF08{{window}}\uFF09",
328
+ usage_secondary: "\u6B21\u7A97\u53E3\uFF08{{window}}\uFF09",
329
+ usage_line: "\u5DF2\u7528 {{percent}}% \xB7 {{time}} \u91CD\u7F6E",
330
+ usage_plan: "\u5957\u9910\uFF1A{{plan}}",
331
+ usage_unavailable: "\u6682\u65F6\u65E0\u6CD5\u83B7\u53D6\u914D\u989D\u4FE1\u606F\u3002",
332
+ usage_updated: "\u66F4\u65B0\u4E8E {{time}}",
333
+ window: {
334
+ minutes: "{{count}} \u5206\u949F",
335
+ hours: "{{count}} \u5C0F\u65F6",
336
+ days: "{{count}} \u5929"
337
+ },
338
+ about: "\u5173\u4E8E\u672C\u96C6\u6210",
339
+ about_body: "\u8FDE\u63A5\u540E\uFF0C\u300C\u540C\u6B65\u6A21\u578B\u300D\u4F1A\u62C9\u53D6\u4F60\u7684\u8BA2\u9605\u53EF\u7528\u7684\u6A21\u578B\u5217\u8868\uFF0C\u7531\u53D7\u7BA1\u4F9B\u5E94\u5546\u7ECF CCR \u63D0\u4F9B OpenAI Codex \u6A21\u578B\u3002\u914D\u989D\u6309\u9650\u6D41\u7A97\u53E3\u663E\u793A\uFF08\u4E00\u4E2A\u8F83\u77ED\u7684\u4E3B\u7A97\u53E3\u52A0\u4E00\u4E2A\u8F83\u957F\u7684\u6B21\u7A97\u53E3\uFF09\uFF0C\u6BCF\u6B21\u8BBF\u95EE\u6700\u591A\u81EA\u52A8\u8BFB\u53D6\u4E00\u6B21\uFF0C\u4E4B\u540E\u77ED\u6682\u7F13\u5B58\u3002",
340
+ disclaimer: "\u5B9E\u9A8C\u6027\u96C6\u6210\uFF0C\u4F7F\u7528\u5B98\u65B9 Codex \u5BA2\u6237\u7AEF\u8EAB\u4EFD\u3002\u65E0\u6CD5\u4FDD\u8BC1\u5728\u4F60\u7684 OpenAI \u5957\u9910\u6761\u6B3E\u4E0B\u4E0D\u88AB\u5224\u4E3A\u8FDD\u89C4\uFF0C\u8BF7\u81EA\u884C\u659F\u914C\u4F7F\u7528\u3002",
341
+ other_edit: "\u53E6\u4E00\u5904\u4FEE\u6539\u6B63\u5728\u8FDB\u884C\uFF0C\u5B8C\u6210\u540E\u624D\u80FD\u64CD\u4F5C\u3002",
342
+ errors: {
343
+ request_failed: "\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002",
344
+ config_busy: "\u53E6\u4E00\u4E2A\u4FDD\u5B58\u6216\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002",
345
+ login_invalid_response: "\u767B\u5F55\u54CD\u5E94\u65E0\u6548\uFF0C\u8BF7\u91CD\u8BD5\u3002",
346
+ login_failed: "\u767B\u5F55\u5931\u8D25\u3002",
347
+ login_expired: "\u6388\u6743\u6709\u6548\u671F\u5DF2\u8FC7\uFF0C\u8BF7\u91CD\u65B0\u5F00\u59CB\u3002",
348
+ login_cancelled: "\u5DF2\u53D6\u6D88\u767B\u5F55\u3002",
349
+ sync_failed: "\u6A21\u578B\u540C\u6B65\u5931\u8D25\u3002",
350
+ disconnect_failed: "\u65AD\u5F00\u8FDE\u63A5\u5931\u8D25\u3002",
351
+ callback_invalid: "\u8FD9\u770B\u8D77\u6765\u4E0D\u662F\u6709\u6548\u7684\u56DE\u8C03\u5730\u5740\uFF08\u5E94\u5305\u542B code \u4E0E state \u53C2\u6570\uFF09\u3002",
352
+ callback_rejected: "\u56DE\u8C03\u88AB\u62D2\u7EDD\uFF0C\u8BF7\u590D\u5236\u5B8C\u6574\u5730\u5740\u540E\u91CD\u8BD5\u3002",
353
+ reconciliation_failed: "\u5DF2\u751F\u6548\uFF0C\u4F46\u672C\u5730\u8BBE\u7F6E\u8349\u7A3F\u672A\u80FD\u5237\u65B0\u2014\u2014\u5237\u65B0\u9875\u9762\u5373\u53EF\u770B\u5230\u53D8\u66F4\u3002"
354
+ }
355
+ }
356
+ }
357
+ };
358
+
359
+ // src/card-entry.ts
360
+ var CODEX_POLL_TIMEOUT = "codex_poll_timeout";
361
+ function isCodexPollTimeout(error) {
362
+ return !!error && typeof error === "object" && error.reason === CODEX_POLL_TIMEOUT;
363
+ }
364
+ function createCodexLogin(api, onReady, timing = { intervalMs: 1200, deadlineMs: 6e5 }) {
365
+ const controller = new AbortController();
366
+ let job = null;
367
+ let cancellation = null;
368
+ let expired = false;
369
+ let pasteUrl = null;
370
+ let pasteWaiter = null;
371
+ let startedAt = 0;
372
+ const wakeListeners = /* @__PURE__ */ new Set();
373
+ const invalidate = () => {
374
+ if (!job) return Promise.resolve();
375
+ return cancellation ?? (cancellation = api.cancel(job.loginId).catch(() => void 0));
376
+ };
377
+ const cancel = async () => {
378
+ controller.abort();
379
+ resolvePasteWaiter(null);
380
+ await invalidate();
381
+ };
382
+ const resolvePasteWaiter = (result) => {
383
+ const waiter = pasteWaiter;
384
+ pasteWaiter = null;
385
+ waiter?.(result);
386
+ };
387
+ const submitCallback = (callbackUrl) => {
388
+ if (!job || controller.signal.aborted) return Promise.resolve(null);
389
+ return new Promise((resolve) => {
390
+ pasteUrl = callbackUrl;
391
+ pasteWaiter?.(null);
392
+ pasteWaiter = resolve;
393
+ for (const wake of [...wakeListeners]) wake();
394
+ });
395
+ };
396
+ const hardDeadline = (login) => Math.min(login.expiresAt, startedAt + timing.deadlineMs);
397
+ const done = (async () => {
398
+ let connected = false;
399
+ try {
400
+ startedAt = Date.now();
401
+ const start = await api.start();
402
+ const parsed = parseCodexLoginStart(start);
403
+ if (!parsed) throw Object.assign(new Error("invalid login response"), { reason: "login_invalid_response" });
404
+ job = parsed;
405
+ if (controller.signal.aborted) {
406
+ await invalidate();
407
+ return null;
408
+ }
409
+ onReady(job);
410
+ while (!controller.signal.aborted) {
411
+ if (Date.now() >= hardDeadline(job)) {
412
+ expired = true;
413
+ break;
414
+ }
415
+ const paste = pasteUrl !== null ? { url: pasteUrl, waiter: pasteWaiter } : null;
416
+ if (paste) {
417
+ pasteUrl = null;
418
+ pasteWaiter = null;
419
+ }
420
+ let result;
421
+ try {
422
+ result = paste ? await api.complete(job.loginId, paste.url) : await api.poll(job.loginId, controller.signal);
423
+ } catch (error) {
424
+ if (controller.signal.aborted) {
425
+ paste?.waiter?.(null);
426
+ break;
427
+ }
428
+ if (isCodexPollTimeout(error) || paste) {
429
+ paste?.waiter?.(null);
430
+ if (Date.now() >= hardDeadline(job)) {
431
+ expired = true;
432
+ break;
433
+ }
434
+ await wait(timing.intervalMs, controller.signal, wakeListeners);
435
+ continue;
436
+ }
437
+ throw error;
438
+ }
439
+ if (controller.signal.aborted) {
440
+ paste?.waiter?.(null);
441
+ break;
442
+ }
443
+ const validated = parseCodexLoginPoll(result);
444
+ if (!validated) {
445
+ paste?.waiter?.(null);
446
+ if (Date.now() >= hardDeadline(job)) {
447
+ expired = true;
448
+ break;
449
+ }
450
+ await wait(timing.intervalMs, controller.signal, wakeListeners);
451
+ continue;
452
+ }
453
+ result = validated;
454
+ paste?.waiter?.(result);
455
+ if (result.status === "connected") {
456
+ connected = true;
457
+ return result;
458
+ }
459
+ if (result.status === "cancelled") return null;
460
+ if (result.status === "expired") {
461
+ expired = true;
462
+ break;
463
+ }
464
+ if (result.status === "error" && !paste) {
465
+ throw Object.assign(new Error("login failed"), {
466
+ reason: sanitizeCodexErrorCode(result.error) ?? "login_failed"
467
+ });
468
+ }
469
+ await wait(timing.intervalMs, controller.signal, wakeListeners);
470
+ }
471
+ return null;
472
+ } catch (error) {
473
+ if (!controller.signal.aborted) throw error;
474
+ return null;
475
+ } finally {
476
+ resolvePasteWaiter(null);
477
+ if (!connected) await invalidate();
478
+ if (expired) throw Object.assign(new Error("login expired"), { reason: "login_expired" });
479
+ }
480
+ })();
481
+ return { done, cancel, submitCallback };
482
+ }
483
+ function wait(ms, signal, wakeListeners) {
484
+ return new Promise((resolve, reject) => {
485
+ const cleanup = () => {
486
+ clearTimeout(timer);
487
+ signal.removeEventListener("abort", abort);
488
+ if (wake) wakeListeners?.delete(wake);
489
+ };
490
+ const abort = () => {
491
+ cleanup();
492
+ reject(new Error("cancelled"));
493
+ };
494
+ const wake = () => {
495
+ cleanup();
496
+ resolve();
497
+ };
498
+ const timer = setTimeout(() => {
499
+ cleanup();
500
+ resolve();
501
+ }, ms);
502
+ signal.addEventListener("abort", abort, { once: true });
503
+ wakeListeners?.add(wake);
504
+ if (signal.aborted) {
505
+ abort();
506
+ }
507
+ });
508
+ }
509
+ var mounted = /* @__PURE__ */ new WeakMap();
510
+ function mount(el, props) {
511
+ unmount(el);
512
+ const locale = props.locale.startsWith("zh") ? "zh" : "en";
513
+ const bundle = props.locales[locale]?.codex ?? codexLocales[locale].codex;
514
+ const t = (key, vars = {}) => {
515
+ const text = key.split(".").reduce((obj, k) => obj?.[k], bundle);
516
+ return (typeof text === "string" ? text : key).replace(/\{\{(\w+)\}\}/g, (_, name) => String(vars[name] ?? ""));
517
+ };
518
+ const errorText = (code) => {
519
+ const safe = sanitizeCodexErrorCode(code);
520
+ if (safe) {
521
+ const text = t(`errors.${safe}`);
522
+ if (!text.startsWith("errors.")) return text;
523
+ }
524
+ return t("errors.request_failed");
525
+ };
526
+ let alive = true;
527
+ let loading = true, loadFailed = false;
528
+ let status = null;
529
+ let locked = false;
530
+ let generation = 0;
531
+ let action = null;
532
+ let errorKey = null;
533
+ let toast = null;
534
+ let reconcileFailed = false;
535
+ let confirmDisconnect = false;
536
+ let login = null;
537
+ let cancelling = false;
538
+ let pasteField = null;
539
+ let pasteDraft = "";
540
+ let session = null;
541
+ let usage = null;
542
+ let usagePhase = "idle";
543
+ let usageUpdatedAt = null;
544
+ let release = null;
545
+ let unsubscribeHost = null;
546
+ let focusPending = props.focusKey === CODEX_PROVIDER_NAME;
547
+ if (focusPending) props.focusKey = null;
548
+ const post = (path, body = {}, signal, timeoutMs = 3e4) => props.callApi(path, { method: "POST", body: JSON.stringify(body), signal, timeoutMs });
549
+ const BUTTON_BASE = "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl text-sm font-semibold ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 active:scale-95";
550
+ const BUTTON_PRIMARY = "bg-primary text-primary-foreground shadow-lg shadow-primary/20 hover:bg-primary/90 hover:shadow-xl hover:shadow-primary/30";
551
+ const BUTTON_OUTLINE = "border border-input bg-input/50 backdrop-blur-md shadow-sm hover:bg-input/80 hover:border-primary/50 hover:shadow-md hover:text-accent-foreground";
552
+ const BUTTON_DESTRUCTIVE = "border border-destructive/50 text-destructive hover:bg-destructive hover:text-destructive-foreground";
553
+ const BADGE_BASE = "inline-flex items-center rounded-lg border px-2.5 py-0.5 text-[10px] font-bold transition-colors";
554
+ const BADGE_OUTLINE = "border-white/10 text-foreground bg-white/5";
555
+ const BADGE_SECONDARY = "border-white/5 bg-white/5 text-muted-foreground";
556
+ const node = (tag, text) => {
557
+ const result = document.createElement(tag);
558
+ if (text !== void 0) result.textContent = text;
559
+ return result;
560
+ };
561
+ const styled = (tag, className, text) => {
562
+ const result = node(tag, text);
563
+ if (className) result.className = className;
564
+ return result;
565
+ };
566
+ const icon = (paths, className) => {
567
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
568
+ svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
569
+ svg.setAttribute("width", "24");
570
+ svg.setAttribute("height", "24");
571
+ svg.setAttribute("viewBox", "0 0 24 24");
572
+ svg.setAttribute("fill", "none");
573
+ svg.setAttribute("stroke", "currentColor");
574
+ svg.setAttribute("stroke-width", "2");
575
+ svg.setAttribute("stroke-linecap", "round");
576
+ svg.setAttribute("stroke-linejoin", "round");
577
+ svg.setAttribute("aria-hidden", "true");
578
+ svg.setAttribute("class", className);
579
+ for (const d of paths) {
580
+ const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
581
+ path.setAttribute("d", d);
582
+ svg.appendChild(path);
583
+ }
584
+ return svg;
585
+ };
586
+ const shieldCheckIcon = (className) => icon([
587
+ "M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",
588
+ "m9 12 2 2 4-4"
589
+ ], className);
590
+ const refreshCwIcon = (className) => icon([
591
+ "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",
592
+ "M21 3v5h-5",
593
+ "M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",
594
+ "M8 16H3v5"
595
+ ], className);
596
+ const plugIcon = (className) => icon(["M12 22v-5", "M9 8V2", "M15 8V2", "M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z"], className);
597
+ const coinsIcon = (className) => {
598
+ const svg = icon(["M18.09 10.37A6 6 0 1 1 10.34 18", "M7 6h1v4", "m16.71 13.88.7.71-2.82 2.82"], className);
599
+ const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
600
+ circle.setAttribute("cx", "8");
601
+ circle.setAttribute("cy", "8");
602
+ circle.setAttribute("r", "6");
603
+ svg.insertBefore(circle, svg.firstChild);
604
+ return svg;
605
+ };
606
+ const xIcon = (className) => icon(["M18 6 6 18", "m6 6 12 12"], className);
607
+ const badge = (parent, text, variant, extra = "", role) => {
608
+ const result = styled("span", `${BADGE_BASE} ${variant === "outline" ? BADGE_OUTLINE : BADGE_SECONDARY} ${extra}`, text);
609
+ if (role) result.setAttribute("role", role);
610
+ parent.append(result);
611
+ return result;
612
+ };
613
+ const button = (parent, text, action2, disabled = false, variant = "outline", extra = "", iconNode) => {
614
+ const result = styled("button", `${BUTTON_BASE} ${variant === "primary" ? BUTTON_PRIMARY : variant === "destructive" ? BUTTON_DESTRUCTIVE : BUTTON_OUTLINE} ${extra}`, text);
615
+ result.type = "button";
616
+ result.disabled = disabled;
617
+ result.onclick = action2;
618
+ if (iconNode) result.prepend(iconNode);
619
+ parent.append(result);
620
+ return result;
621
+ };
622
+ const errorAlert = (text) => {
623
+ const alert = styled("p", "max-w-md rounded-lg border border-red-500/20 bg-red-500/10 px-3 py-2 text-[11px] font-medium text-red-500", text);
624
+ alert.setAttribute("role", "alert");
625
+ return alert;
626
+ };
627
+ const endBusy = () => {
628
+ release?.();
629
+ release = null;
630
+ if (locked) {
631
+ locked = false;
632
+ props.onBusy?.(false);
633
+ }
634
+ };
635
+ const readStatus = async () => {
636
+ const raw = await props.callApi("/status", { timeoutMs: 1e4 });
637
+ const parsed = parseCodexStatus(raw);
638
+ if (!parsed) throw Object.assign(new Error("invalid status"), { reason: "request_failed" });
639
+ return parsed;
640
+ };
641
+ const settle = async (id) => {
642
+ let failed = false;
643
+ try {
644
+ await props.refreshConfig?.((current, server) => mergeCodexProvider(current, server));
645
+ } catch {
646
+ failed = true;
647
+ }
648
+ const fresh = await readStatus().catch(() => null);
649
+ if (!alive || generation !== id) return { fresh, reconcileFailed: failed };
650
+ if (fresh) {
651
+ status = fresh;
652
+ loadFailed = false;
653
+ }
654
+ confirmDisconnect = false;
655
+ return { fresh, reconcileFailed: failed };
656
+ };
657
+ const showUsage = (value, at) => {
658
+ usage = value;
659
+ usageUpdatedAt = at;
660
+ usagePhase = value ? "ready" : "unavailable";
661
+ };
662
+ const readUsage = async (id, background = false) => {
663
+ if (!background) props.onBusy?.(true);
664
+ usagePhase = "reading";
665
+ try {
666
+ const raw = await post("/usage", {});
667
+ const parsed = parseCodexUsage(raw);
668
+ rememberCodexUsage(parsed);
669
+ if (alive && generation === id) showUsage(parsed, parsed ? Date.now() : null);
670
+ } catch {
671
+ if (alive && generation === id) showUsage(null, null);
672
+ } finally {
673
+ if (!background) props.onBusy?.(false);
674
+ if (alive && generation === id) {
675
+ locked = false;
676
+ if (action === "usage") action = null;
677
+ }
678
+ if (alive) render();
679
+ }
680
+ };
681
+ const autoReadUsage = async () => {
682
+ if (!alive || props.disabled || loading || usagePhase === "ready") return;
683
+ const cached = freshCodexUsage();
684
+ if (cached) {
685
+ showUsage(cached.value, cached.at);
686
+ render();
687
+ return;
688
+ }
689
+ const id = generation;
690
+ await readUsage(id, true);
691
+ };
692
+ const run = async (kind) => {
693
+ if (!alive || locked || loading || props.disabled) return;
694
+ if (kind === "usage") {
695
+ locked = true;
696
+ action = "usage";
697
+ usagePhase = "reading";
698
+ errorKey = null;
699
+ render();
700
+ return void readUsage(++generation);
701
+ }
702
+ if (props.acquireManagement) {
703
+ release = props.acquireManagement();
704
+ if (!release) {
705
+ errorKey = "config_busy";
706
+ render();
707
+ return;
708
+ }
709
+ }
710
+ locked = true;
711
+ const id = ++generation;
712
+ props.onBusy?.(true);
713
+ action = kind;
714
+ errorKey = null;
715
+ toast = null;
716
+ reconcileFailed = false;
717
+ render();
718
+ try {
719
+ if (kind === "login") {
720
+ const current = createCodexLogin({
721
+ start: () => post("/login/start", {}),
722
+ poll: async (loginId, signal) => {
723
+ try {
724
+ return await post("/login/poll", { loginId }, signal, 35e3);
725
+ } catch (error) {
726
+ if (!signal.aborted && error?.timedOut === true) {
727
+ throw Object.assign(new Error("Login poll timed out"), { reason: CODEX_POLL_TIMEOUT });
728
+ }
729
+ throw error;
730
+ }
731
+ },
732
+ complete: (loginId, callbackUrl) => post("/login/complete", { loginId, callbackUrl }, void 0, 35e3),
733
+ cancel: (loginId) => post("/login/cancel", { loginId }, void 0, 1e4)
734
+ }, (value) => {
735
+ if (!alive || generation !== id) {
736
+ void current.cancel().catch(() => {
737
+ });
738
+ return;
739
+ }
740
+ login = value;
741
+ window.open(value.url, "_blank", "noopener,noreferrer");
742
+ render();
743
+ });
744
+ session = current;
745
+ const connected = await current.done;
746
+ session = null;
747
+ if (!alive || generation !== id) return;
748
+ login = null;
749
+ pasteField = null;
750
+ if (!connected) return;
751
+ pasteDraft = "";
752
+ clearCodexUsageCache();
753
+ usage = null;
754
+ usageUpdatedAt = null;
755
+ usagePhase = "idle";
756
+ const { fresh, reconcileFailed: failed } = await settle(id);
757
+ if (!alive || generation !== id) return;
758
+ reconcileFailed = failed;
759
+ toast = fresh?.email ? t("login_success", { email: fresh.email }) : t("login_success_unknown");
760
+ void readUsage(id, true);
761
+ } else if (kind === "sync") {
762
+ const result = parseCodexMutation(await post("/sync", {}, void 0, 6e4));
763
+ if (!result.success) {
764
+ if (alive && generation === id) errorKey = result.error ?? "sync_failed";
765
+ return;
766
+ }
767
+ const { fresh, reconcileFailed: failed } = await settle(id);
768
+ if (!alive || generation !== id) return;
769
+ reconcileFailed = failed;
770
+ toast = t("synced", { count: result.modelCount ?? result.models?.length ?? 0 });
771
+ if (fresh) usagePhase = "idle";
772
+ } else {
773
+ const result = parseCodexMutation(await post("/disconnect", {}));
774
+ if (!result.success) {
775
+ if (alive && generation === id) errorKey = result.error ?? "disconnect_failed";
776
+ return;
777
+ }
778
+ clearCodexUsageCache();
779
+ const { fresh, reconcileFailed: failed } = await settle(id);
780
+ if (!alive || generation !== id) return;
781
+ reconcileFailed = failed;
782
+ usage = null;
783
+ usagePhase = "idle";
784
+ usageUpdatedAt = null;
785
+ toast = t("disconnected");
786
+ }
787
+ } catch (error) {
788
+ if (alive && generation === id) {
789
+ const reason = error?.reason;
790
+ errorKey = sanitizeCodexErrorCode(typeof reason === "string" ? reason : null) ?? (kind === "login" ? "login_failed" : kind === "sync" ? "sync_failed" : "disconnect_failed");
791
+ }
792
+ } finally {
793
+ endBusy();
794
+ session = null;
795
+ if (alive && generation === id) {
796
+ action = null;
797
+ login = null;
798
+ cancelling = false;
799
+ pasteField = null;
800
+ pasteDraft = "";
801
+ render();
802
+ }
803
+ }
804
+ };
805
+ const submitPaste = () => {
806
+ if (!alive || !session) return;
807
+ const value = pasteField?.value ?? "";
808
+ if (!isValidCodexCallbackUrl(value)) {
809
+ errorKey = "callback_invalid";
810
+ render();
811
+ return;
812
+ }
813
+ errorKey = null;
814
+ pasteDraft = "";
815
+ void session.submitCallback(value).then((result) => {
816
+ if (!alive || !result || result.status === "connected") return;
817
+ if (result.status === "error") {
818
+ errorKey = sanitizeCodexErrorCode(result.error) ?? "callback_rejected";
819
+ render();
820
+ return;
821
+ }
822
+ if (result.status === "expired") {
823
+ errorKey = "login_expired";
824
+ render();
825
+ return;
826
+ }
827
+ }).catch(() => {
828
+ if (alive) {
829
+ errorKey = "callback_rejected";
830
+ render();
831
+ }
832
+ });
833
+ };
834
+ const usageWindowLine = (label, window_) => {
835
+ const line = styled("p", "text-[11px] text-muted-foreground");
836
+ const { unit, count } = codexWindowUnit(window_.windowSeconds);
837
+ const reset = formatCodexClock(window_.resetAt, locale) ?? t("unknown");
838
+ line.append(
839
+ styled("span", "font-medium text-foreground", t(label, { window: t(`window.${unit}`, { count }) })),
840
+ document.createTextNode(` ${t("usage_line", { percent: String(Math.round(window_.usedPercent)), time: reset })}`)
841
+ );
842
+ return line;
843
+ };
844
+ const render = () => {
845
+ if (!alive) return;
846
+ el.replaceChildren();
847
+ el.dataset.testid = "codex-card";
848
+ const state = loading ? "loading" : loadFailed && !status ? "error" : codexStateKey(status);
849
+ const connected = !loading && codexConnected(status);
850
+ const canDisconnect = !!status && (status.status !== "not_connected" || status.models.length > 0);
851
+ const busy = loading || action !== null;
852
+ const disabled = busy || props.disabled;
853
+ const card = styled("div", "glass-card rounded-2xl overflow-hidden mb-4");
854
+ card.setAttribute("role", "group");
855
+ card.setAttribute("aria-busy", String(busy));
856
+ if (focusPending) {
857
+ focusPending = false;
858
+ queueMicrotask(() => {
859
+ card.scrollIntoView?.({ block: "start" });
860
+ card.focus?.();
861
+ });
862
+ }
863
+ card.tabIndex = -1;
864
+ const layout = styled("div", "flex flex-col gap-4 p-5 sm:flex-row sm:items-start sm:justify-between");
865
+ const body = styled("div", "min-w-0 flex-1 space-y-3");
866
+ const header = styled("div", "flex flex-wrap items-center gap-2");
867
+ header.append(
868
+ shieldCheckIcon("h-5 w-5 shrink-0 text-primary"),
869
+ styled("p", "text-lg font-bold tracking-tight text-foreground", t("title"))
870
+ );
871
+ badge(header, t("builtin"), "outline");
872
+ badge(header, t("experimental"), "outline", "border-amber-500/40 text-amber-600");
873
+ badge(header, t(`status.${state}`), "secondary", "", "status");
874
+ body.append(header);
875
+ body.append(styled(
876
+ "p",
877
+ "max-w-md truncate text-xs font-medium text-muted-foreground/60",
878
+ t("managed_provider", { name: status?.providerName || CODEX_PROVIDER_NAME })
879
+ ));
880
+ body.append(styled("p", "max-w-md text-xs text-muted-foreground", t("description")));
881
+ if (connected && status) {
882
+ const rows = styled("dl", "grid max-w-md grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs");
883
+ const account = maskCodexAccountId(status.accountId) ?? t("unknown");
884
+ for (const [label, value, mono] of [
885
+ ["email", status.email ?? t("unknown"), true],
886
+ ["account", account, true],
887
+ ["plan", status.plan || t("unknown"), false],
888
+ ["models", t("models_count", { count: status.modelCount }), false]
889
+ ]) {
890
+ rows.append(
891
+ styled("dt", "text-muted-foreground", t(`labels.${label}`)),
892
+ styled("dd", `break-all ${mono ? "font-mono " : ""}text-foreground`, value)
893
+ );
894
+ }
895
+ body.append(rows);
896
+ if (status.models.length > 0) {
897
+ const chips = styled("div", "flex flex-wrap gap-2 pt-1");
898
+ for (const model of status.models) {
899
+ chips.append(styled("span", "inline-flex max-w-full items-center gap-1 break-all whitespace-normal rounded-lg border border-white/5 bg-white/5 px-2 py-0.5 text-[10px] font-bold text-muted-foreground", model));
900
+ }
901
+ body.append(chips);
902
+ }
903
+ const usageBox = styled("div", "max-w-md space-y-1 rounded-lg border border-white/5 bg-white/5 px-3 py-2 text-xs");
904
+ const usageHeader = styled("div", "flex flex-wrap items-center justify-between gap-2");
905
+ usageHeader.append(styled("p", "font-medium text-foreground", t("usage_title")));
906
+ button(
907
+ usageHeader,
908
+ t("refresh_usage"),
909
+ () => void run("usage"),
910
+ disabled,
911
+ "outline",
912
+ "h-7 px-2 text-[11px]",
913
+ coinsIcon(`mr-1 h-3 w-3 ${usagePhase === "reading" ? "animate-pulse" : ""}`)
914
+ );
915
+ usageBox.append(usageHeader);
916
+ if (usagePhase === "ready" && usage) {
917
+ if (usage.plan) usageBox.append(styled("p", "text-[11px] text-muted-foreground", t("usage_plan", { plan: usage.plan })));
918
+ if (usage.primary) usageBox.append(usageWindowLine("usage_primary", usage.primary));
919
+ if (usage.secondary) usageBox.append(usageWindowLine("usage_secondary", usage.secondary));
920
+ const updated = usageUpdatedAt !== null ? formatCodexClock(usageUpdatedAt, locale) : null;
921
+ if (updated) usageBox.append(styled("p", "text-[10px] text-muted-foreground/60", t("usage_updated", { time: updated })));
922
+ } else if (usagePhase === "unavailable") {
923
+ usageBox.append(styled("p", "text-[11px] text-muted-foreground", t("usage_unavailable")));
924
+ }
925
+ body.append(usageBox);
926
+ }
927
+ const cooldown = status?.coolingUntil !== void 0 && state === "cooldown" ? formatCodexClock(status.coolingUntil, locale) : null;
928
+ if (cooldown) body.append(styled("p", "text-xs font-medium text-yellow-600", t("cooldown_until", { time: cooldown })));
929
+ if (state === "needs_relogin") body.append(styled("p", "text-xs text-yellow-600", t("needs_relogin_help")));
930
+ if (!connected && status?.lastError) body.append(errorAlert(errorText(status.lastError)));
931
+ if (errorKey) body.append(errorAlert(errorText(errorKey)));
932
+ if (reconcileFailed) body.append(errorAlert(t("errors.reconciliation_failed")));
933
+ if (login) {
934
+ const box = styled("div", "max-w-md space-y-1.5 rounded-lg border border-primary/30 bg-primary/5 px-3 py-2 text-xs");
935
+ box.setAttribute("role", "status");
936
+ box.append(styled("p", "font-medium", cancelling ? t("working") : t("login_pending")));
937
+ if (!cancelling) {
938
+ const link = styled("a", "block break-all text-primary underline");
939
+ link.href = login.url;
940
+ link.target = "_blank";
941
+ link.rel = "noopener noreferrer";
942
+ link.textContent = t("open_login");
943
+ box.append(link);
944
+ if (login.mode === "paste") {
945
+ box.append(styled("p", "leading-relaxed text-muted-foreground", t("paste_title")));
946
+ box.append(styled("p", "leading-relaxed text-muted-foreground", t("paste_help")));
947
+ } else {
948
+ box.append(styled("p", "leading-relaxed text-muted-foreground", t("paste_hint")));
949
+ }
950
+ const field = styled("input", "w-full rounded-lg border border-input bg-input/50 px-3 py-1.5 font-mono text-xs text-foreground placeholder:text-muted-foreground/50");
951
+ field.type = "text";
952
+ field.spellcheck = false;
953
+ field.setAttribute("placeholder", t("paste_placeholder"));
954
+ field.setAttribute("aria-label", t("paste_title"));
955
+ field.autocomplete = "off";
956
+ field.value = pasteDraft;
957
+ field.oninput = () => {
958
+ pasteDraft = field.value;
959
+ };
960
+ field.onkeydown = (event) => {
961
+ if (event.key === "Enter") {
962
+ event.preventDefault();
963
+ submitPaste();
964
+ }
965
+ };
966
+ pasteField = field;
967
+ box.append(field);
968
+ button(box, t("paste_submit"), submitPaste, false, "outline", "h-7 px-2 text-[11px]");
969
+ }
970
+ button(box, cancelling ? t("working") : t("cancel"), () => {
971
+ cancelling = true;
972
+ void session?.cancel().catch(() => {
973
+ if (alive) {
974
+ errorKey = "request_failed";
975
+ render();
976
+ }
977
+ });
978
+ if (alive) render();
979
+ }, cancelling, "outline", "h-7 px-2 text-xs");
980
+ body.append(box);
981
+ }
982
+ const about = styled("details", "max-w-md text-xs text-muted-foreground");
983
+ about.append(styled("summary", "cursor-pointer select-none font-medium", t("about")));
984
+ const aboutBody = styled("div", "mt-2 space-y-1 leading-relaxed");
985
+ aboutBody.append(styled("p", "", t("about_body")));
986
+ aboutBody.append(styled("p", "", t("disclaimer")));
987
+ about.append(aboutBody);
988
+ body.append(about);
989
+ if (props.disabled) body.append(styled("p", "text-xs text-muted-foreground", t("other_edit")));
990
+ const actions = styled("div", "flex shrink-0 flex-col gap-2 sm:w-[210px]");
991
+ button(
992
+ actions,
993
+ action === "login" ? t("working") : connected || state === "needs_relogin" ? t("reconnect") : t("browser_login"),
994
+ () => void run("login"),
995
+ disabled,
996
+ "primary",
997
+ "h-8 w-full text-xs",
998
+ plugIcon("mr-1 h-3.5 w-3.5")
999
+ );
1000
+ button(
1001
+ actions,
1002
+ t("sync"),
1003
+ () => void run("sync"),
1004
+ disabled || !connected,
1005
+ "outline",
1006
+ "h-8 w-full text-xs",
1007
+ refreshCwIcon(`mr-1 h-3.5 w-3.5 ${action === "sync" ? "animate-spin" : ""}`)
1008
+ );
1009
+ button(actions, t("disconnect"), () => {
1010
+ confirmDisconnect = true;
1011
+ render();
1012
+ }, disabled || !canDisconnect, "outline", "h-8 w-full text-xs");
1013
+ layout.append(body, actions);
1014
+ card.append(layout);
1015
+ el.append(card);
1016
+ if (toast) {
1017
+ const message = styled("p", "flex max-w-md items-center gap-2 rounded-lg border border-green-500/25 bg-green-500/10 px-3 py-2 text-xs font-medium text-green-600", toast);
1018
+ message.setAttribute("role", "status");
1019
+ el.append(message);
1020
+ }
1021
+ if (confirmDisconnect) {
1022
+ const panel = styled("div", "glass-card mt-3 max-w-lg space-y-3 rounded-2xl p-5");
1023
+ panel.setAttribute("role", "dialog");
1024
+ panel.append(
1025
+ styled("h3", "text-sm font-semibold tracking-tight text-foreground", t("disconnect_title")),
1026
+ styled("p", "text-xs text-muted-foreground", t("disconnect_warning"))
1027
+ );
1028
+ const footer = styled("div", "flex justify-end gap-2");
1029
+ button(footer, t("cancel"), () => {
1030
+ if (!action) {
1031
+ confirmDisconnect = false;
1032
+ render();
1033
+ }
1034
+ }, !!action, "outline", "h-8 text-xs");
1035
+ button(
1036
+ footer,
1037
+ action ? t("working") : t("disconnect"),
1038
+ () => {
1039
+ if (confirmDisconnect) void run("disconnect");
1040
+ },
1041
+ loading || action !== null || props.disabled,
1042
+ "destructive",
1043
+ "h-8 text-xs"
1044
+ );
1045
+ panel.append(footer);
1046
+ el.append(panel);
1047
+ }
1048
+ };
1049
+ mounted.set(el, () => {
1050
+ alive = false;
1051
+ confirmDisconnect = false;
1052
+ unsubscribeHost?.();
1053
+ unsubscribeHost = null;
1054
+ void session?.cancel().catch(() => {
1055
+ });
1056
+ locked = false;
1057
+ el.replaceChildren();
1058
+ });
1059
+ unsubscribeHost = props.onHostChange?.(() => {
1060
+ if (alive) render();
1061
+ }) ?? null;
1062
+ render();
1063
+ readStatus().then((value) => {
1064
+ if (alive) {
1065
+ status = value;
1066
+ loadFailed = false;
1067
+ }
1068
+ }).catch(() => {
1069
+ if (alive) {
1070
+ loadFailed = true;
1071
+ errorKey = "request_failed";
1072
+ }
1073
+ }).finally(() => {
1074
+ if (alive) {
1075
+ loading = false;
1076
+ render();
1077
+ if (codexConnected(status)) void autoReadUsage();
1078
+ }
1079
+ });
1080
+ }
1081
+ function unmount(el) {
1082
+ mounted.get(el)?.();
1083
+ mounted.delete(el);
1084
+ }
1085
+ var card_entry_default = { mount, unmount };
1086
+ export {
1087
+ createCodexLogin,
1088
+ card_entry_default as default,
1089
+ mount,
1090
+ unmount
1091
+ };