@kodelyth/codex 2026.5.42 → 2026.6.2

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 (138) hide show
  1. package/package.json +17 -2
  2. package/doctor-contract-api.test.ts +0 -44
  3. package/doctor-contract-api.ts +0 -68
  4. package/harness.ts +0 -72
  5. package/index.test.ts +0 -230
  6. package/index.ts +0 -66
  7. package/media-understanding-provider.test.ts +0 -486
  8. package/media-understanding-provider.ts +0 -521
  9. package/prompt-overlay-runtime-contract.test.ts +0 -48
  10. package/prompt-overlay.ts +0 -21
  11. package/provider-catalog.ts +0 -83
  12. package/provider-discovery.ts +0 -45
  13. package/provider.test.ts +0 -384
  14. package/provider.ts +0 -243
  15. package/src/app-server/app-inventory-cache.test.ts +0 -176
  16. package/src/app-server/app-inventory-cache.ts +0 -324
  17. package/src/app-server/approval-bridge.test.ts +0 -1471
  18. package/src/app-server/approval-bridge.ts +0 -1211
  19. package/src/app-server/auth-bridge.test.ts +0 -1449
  20. package/src/app-server/auth-bridge.ts +0 -614
  21. package/src/app-server/auth-profile-runtime-contract.test.ts +0 -239
  22. package/src/app-server/capabilities.ts +0 -27
  23. package/src/app-server/client-factory.ts +0 -24
  24. package/src/app-server/client.test.ts +0 -563
  25. package/src/app-server/client.ts +0 -715
  26. package/src/app-server/compact.test.ts +0 -710
  27. package/src/app-server/compact.ts +0 -500
  28. package/src/app-server/computer-use.test.ts +0 -788
  29. package/src/app-server/computer-use.ts +0 -683
  30. package/src/app-server/config.test.ts +0 -879
  31. package/src/app-server/config.ts +0 -1038
  32. package/src/app-server/context-engine-projection.test.ts +0 -252
  33. package/src/app-server/context-engine-projection.ts +0 -403
  34. package/src/app-server/delivery-no-reply-runtime-contract.test.ts +0 -80
  35. package/src/app-server/dynamic-tool-diagnostics.ts +0 -73
  36. package/src/app-server/dynamic-tool-profile.ts +0 -69
  37. package/src/app-server/dynamic-tools.test.ts +0 -1302
  38. package/src/app-server/dynamic-tools.ts +0 -623
  39. package/src/app-server/elicitation-bridge.test.ts +0 -1056
  40. package/src/app-server/elicitation-bridge.ts +0 -783
  41. package/src/app-server/event-projector.test.ts +0 -2668
  42. package/src/app-server/event-projector.ts +0 -2057
  43. package/src/app-server/image-payload-sanitizer.test.ts +0 -49
  44. package/src/app-server/image-payload-sanitizer.ts +0 -167
  45. package/src/app-server/klaw-owned-tool-runtime-contract.test.ts +0 -456
  46. package/src/app-server/local-runtime-attribution.ts +0 -39
  47. package/src/app-server/managed-binary.test.ts +0 -139
  48. package/src/app-server/managed-binary.ts +0 -193
  49. package/src/app-server/models.test.ts +0 -246
  50. package/src/app-server/models.ts +0 -172
  51. package/src/app-server/native-hook-relay.test.ts +0 -271
  52. package/src/app-server/native-hook-relay.ts +0 -150
  53. package/src/app-server/native-subagent-task-mirror.test.ts +0 -573
  54. package/src/app-server/native-subagent-task-mirror.ts +0 -497
  55. package/src/app-server/outcome-fallback-runtime-contract.test.ts +0 -404
  56. package/src/app-server/plugin-activation.test.ts +0 -336
  57. package/src/app-server/plugin-activation.ts +0 -283
  58. package/src/app-server/plugin-app-cache-key.ts +0 -74
  59. package/src/app-server/plugin-approval-roundtrip.ts +0 -122
  60. package/src/app-server/plugin-inventory.test.ts +0 -355
  61. package/src/app-server/plugin-inventory.ts +0 -357
  62. package/src/app-server/plugin-thread-config.test.ts +0 -865
  63. package/src/app-server/plugin-thread-config.ts +0 -455
  64. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +0 -33
  65. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +0 -199
  66. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +0 -102
  67. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +0 -227
  68. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +0 -2630
  69. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +0 -2630
  70. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +0 -1659
  71. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +0 -1655
  72. package/src/app-server/protocol-validators.test.ts +0 -75
  73. package/src/app-server/protocol-validators.ts +0 -203
  74. package/src/app-server/protocol.ts +0 -520
  75. package/src/app-server/rate-limit-cache.ts +0 -48
  76. package/src/app-server/rate-limits.test.ts +0 -202
  77. package/src/app-server/rate-limits.ts +0 -583
  78. package/src/app-server/request.ts +0 -73
  79. package/src/app-server/run-attempt.context-engine.test.ts +0 -1004
  80. package/src/app-server/run-attempt.test.ts +0 -9477
  81. package/src/app-server/run-attempt.ts +0 -4683
  82. package/src/app-server/run-attempt.vision-tools.test.ts +0 -35
  83. package/src/app-server/schema-normalization-runtime-contract.test.ts +0 -206
  84. package/src/app-server/session-binding.test.ts +0 -303
  85. package/src/app-server/session-binding.ts +0 -398
  86. package/src/app-server/session-history.ts +0 -44
  87. package/src/app-server/shared-client.test.ts +0 -589
  88. package/src/app-server/shared-client.ts +0 -289
  89. package/src/app-server/side-question.test.ts +0 -1175
  90. package/src/app-server/side-question.ts +0 -1007
  91. package/src/app-server/test-support.ts +0 -48
  92. package/src/app-server/thread-lifecycle.test.ts +0 -447
  93. package/src/app-server/thread-lifecycle.ts +0 -939
  94. package/src/app-server/thread-lifecycle.user-mcp-servers.test.ts +0 -442
  95. package/src/app-server/timeout.ts +0 -9
  96. package/src/app-server/tool-progress-normalization.ts +0 -77
  97. package/src/app-server/trajectory.test.ts +0 -205
  98. package/src/app-server/trajectory.ts +0 -365
  99. package/src/app-server/transcript-mirror.test.ts +0 -524
  100. package/src/app-server/transcript-mirror.ts +0 -208
  101. package/src/app-server/transcript-repair-runtime-contract.test.ts +0 -44
  102. package/src/app-server/transport-stdio.test.ts +0 -171
  103. package/src/app-server/transport-stdio.ts +0 -107
  104. package/src/app-server/transport-websocket.test.ts +0 -69
  105. package/src/app-server/transport-websocket.ts +0 -90
  106. package/src/app-server/transport.ts +0 -117
  107. package/src/app-server/user-input-bridge.test.ts +0 -249
  108. package/src/app-server/user-input-bridge.ts +0 -316
  109. package/src/app-server/version.ts +0 -4
  110. package/src/app-server/vision-tools.ts +0 -12
  111. package/src/command-account.ts +0 -544
  112. package/src/command-formatters.ts +0 -425
  113. package/src/command-handlers.ts +0 -2004
  114. package/src/command-rpc.test.ts +0 -16
  115. package/src/command-rpc.ts +0 -142
  116. package/src/commands.test.ts +0 -3312
  117. package/src/commands.ts +0 -65
  118. package/src/conversation-binding-data.ts +0 -124
  119. package/src/conversation-binding.test.ts +0 -599
  120. package/src/conversation-binding.ts +0 -561
  121. package/src/conversation-control.test.ts +0 -126
  122. package/src/conversation-control.ts +0 -303
  123. package/src/conversation-turn-collector.test.ts +0 -191
  124. package/src/conversation-turn-collector.ts +0 -186
  125. package/src/conversation-turn-input.test.ts +0 -141
  126. package/src/conversation-turn-input.ts +0 -106
  127. package/src/manifest.test.ts +0 -20
  128. package/src/migration/apply.ts +0 -501
  129. package/src/migration/helpers.ts +0 -55
  130. package/src/migration/plan.ts +0 -461
  131. package/src/migration/provider.test.ts +0 -1741
  132. package/src/migration/provider.ts +0 -41
  133. package/src/migration/source.ts +0 -643
  134. package/src/migration/targets.ts +0 -25
  135. package/src/node-cli-sessions.test.ts +0 -180
  136. package/src/node-cli-sessions.ts +0 -711
  137. package/test-api.ts +0 -82
  138. package/tsconfig.json +0 -16
@@ -1,544 +0,0 @@
1
- import {
2
- ensureAuthProfileStore,
3
- findNormalizedProviderValue,
4
- resolveAuthProfileEligibility,
5
- resolveAuthProfileOrder,
6
- resolveDefaultAgentDir,
7
- resolveProfileUnusableUntilForDisplay,
8
- type AuthProfileCredential,
9
- type AuthProfileFailureReason,
10
- type AuthProfileStore,
11
- } from "klaw/plugin-sdk/agent-runtime";
12
- import type { PluginCommandContext } from "klaw/plugin-sdk/plugin-entry";
13
- import { CODEX_CONTROL_METHODS, type CodexControlMethod } from "./app-server/capabilities.js";
14
- import { isJsonObject, type JsonObject, type JsonValue } from "./app-server/protocol.js";
15
- import { rememberCodexRateLimits } from "./app-server/rate-limit-cache.js";
16
- import {
17
- summarizeCodexAccountUsage,
18
- type CodexAccountUsageSummary,
19
- } from "./app-server/rate-limits.js";
20
- import type { CodexControlRequestOptions, SafeValue } from "./command-rpc.js";
21
-
22
- const OPENAI_PROVIDER_ID = "openai";
23
- const OPENAI_CODEX_PROVIDER_ID = "openai-codex";
24
-
25
- type AuthProfileOrderConfig = Parameters<typeof resolveAuthProfileOrder>[0]["cfg"];
26
-
27
- type SafeCodexControlRequest = (
28
- pluginConfig: unknown,
29
- method: CodexControlMethod,
30
- requestParams: JsonValue | undefined,
31
- options?: CodexControlRequestOptions,
32
- ) => Promise<SafeValue<JsonValue | undefined>>;
33
-
34
- export type CodexAccountAuthRow = {
35
- profileId: string;
36
- label: string;
37
- kind: string;
38
- status: string;
39
- active: boolean;
40
- usage?: string;
41
- billingNote?: string;
42
- };
43
-
44
- export type CodexAccountAuthOverview = {
45
- currentLine?: string;
46
- subscriptionLabel?: string;
47
- subscriptionUsage?: string;
48
- orderTitle: string;
49
- rows: CodexAccountAuthRow[];
50
- };
51
-
52
- export async function readCodexAccountAuthOverview(params: {
53
- ctx: PluginCommandContext;
54
- pluginConfig: unknown;
55
- safeCodexControlRequest: SafeCodexControlRequest;
56
- account: SafeValue<JsonValue | undefined>;
57
- limits: SafeValue<JsonValue | undefined>;
58
- }): Promise<CodexAccountAuthOverview | undefined> {
59
- const config = params.ctx.config;
60
- const agentDir = resolveDefaultAgentDir(config);
61
- const store = ensureAuthProfileStore(agentDir, {
62
- allowKeychainPrompt: false,
63
- config,
64
- });
65
- const order = resolveDisplayAuthOrder({ config, store });
66
- if (order.length === 0) {
67
- return undefined;
68
- }
69
-
70
- const now = Date.now();
71
- const activeProfileId = resolveActiveProfileId({
72
- store,
73
- order,
74
- config,
75
- account: params.account,
76
- limits: params.limits,
77
- now,
78
- });
79
- const subscriptionProfileId = order.find((profileId) =>
80
- isChatGptSubscriptionProfile(store.profiles[profileId]),
81
- );
82
- const activeIsSubscription =
83
- activeProfileId !== undefined && isChatGptSubscriptionProfile(store.profiles[activeProfileId]);
84
- const activeUsage =
85
- activeIsSubscription && params.limits.ok
86
- ? summarizeCodexAccountUsage(params.limits.value, now)
87
- : undefined;
88
- const subscriptionUsage =
89
- subscriptionProfileId && (!activeIsSubscription || subscriptionProfileId !== activeProfileId)
90
- ? await readSubscriptionUsage({
91
- ...params,
92
- config,
93
- subscriptionProfileId,
94
- now,
95
- })
96
- : activeUsage;
97
- if (!params.account.ok && !params.limits.ok && !subscriptionUsage) {
98
- return undefined;
99
- }
100
-
101
- const rows = order.map((profileId, index) =>
102
- buildProfileRow({
103
- store,
104
- config,
105
- profileId,
106
- activeProfileId,
107
- activeIndex: activeProfileId ? order.indexOf(activeProfileId) : -1,
108
- index,
109
- now,
110
- usage: profileId === subscriptionProfileId ? subscriptionUsage : undefined,
111
- }),
112
- );
113
- const activeRow = rows.find((row) => row.active);
114
- if (!activeRow) {
115
- return {
116
- currentLine: "OpenAI credentials: no working credential",
117
- orderTitle: "Auth order",
118
- rows,
119
- };
120
- }
121
- const activeCredential = store.profiles[activeRow.profileId];
122
- const activeIsApiKey = activeCredential?.type === "api_key";
123
- const subscriptionLabel = subscriptionProfileId
124
- ? formatProfileLabel(subscriptionProfileId, store.profiles[subscriptionProfileId])
125
- : activeIsSubscription
126
- ? activeRow.label
127
- : undefined;
128
- const subscriptionUsageLine = formatSubscriptionUsageLine(subscriptionUsage);
129
- return {
130
- ...(activeIsApiKey ? { currentLine: buildApiKeyActiveLine(activeRow, subscriptionUsage) } : {}),
131
- ...(subscriptionLabel ? { subscriptionLabel } : {}),
132
- ...(subscriptionUsageLine ? { subscriptionUsage: subscriptionUsageLine } : {}),
133
- orderTitle: "Auth order",
134
- rows,
135
- };
136
- }
137
-
138
- function resolveDisplayAuthOrder(params: {
139
- config: AuthProfileOrderConfig;
140
- store: AuthProfileStore;
141
- }): string[] {
142
- const codexOrder =
143
- resolveOrder(params.store.order, OPENAI_CODEX_PROVIDER_ID) ??
144
- resolveOrder(params.config?.auth?.order, OPENAI_CODEX_PROVIDER_ID);
145
- if (codexOrder && codexOrder.length > 0) {
146
- return dedupe(codexOrder);
147
- }
148
- return resolveAuthProfileOrder({
149
- cfg: params.config,
150
- store: params.store,
151
- provider: OPENAI_CODEX_PROVIDER_ID,
152
- });
153
- }
154
-
155
- function resolveOrder(
156
- order: Record<string, string[]> | undefined,
157
- provider: string,
158
- ): string[] | undefined {
159
- return findNormalizedProviderValue(order, provider);
160
- }
161
-
162
- function resolveActiveProfileId(params: {
163
- store: AuthProfileStore;
164
- order: string[];
165
- config: AuthProfileOrderConfig;
166
- account: SafeValue<JsonValue | undefined>;
167
- limits: SafeValue<JsonValue | undefined>;
168
- now: number;
169
- }): string | undefined {
170
- const liveProfileId = resolveLiveAccountProfileId({
171
- account: params.account,
172
- store: params.store,
173
- order: params.order,
174
- });
175
- if (liveProfileId) {
176
- return liveProfileId;
177
- }
178
- const lastGood = [
179
- params.store.lastGood?.[OPENAI_PROVIDER_ID],
180
- params.store.lastGood?.[OPENAI_CODEX_PROVIDER_ID],
181
- ].find(
182
- (profileId): profileId is string =>
183
- !!profileId &&
184
- params.order.includes(profileId) &&
185
- isActiveProfileCandidate(params, profileId),
186
- );
187
- if (lastGood) {
188
- return lastGood;
189
- }
190
- const mostRecent = params.order
191
- .map((profileId) => ({
192
- profileId,
193
- lastUsed: params.store.usageStats?.[profileId]?.lastUsed ?? 0,
194
- }))
195
- .filter((entry) => entry.lastUsed > 0 && isActiveProfileCandidate(params, entry.profileId))
196
- .toSorted((left, right) => right.lastUsed - left.lastUsed)[0]?.profileId;
197
- if (mostRecent) {
198
- return mostRecent;
199
- }
200
- if (shouldInferApiKeyActiveFromRateLimitProbe(params.limits)) {
201
- const apiKeyProfile = params.order.find(
202
- (profileId) => params.store.profiles[profileId]?.type === "api_key",
203
- );
204
- if (apiKeyProfile) {
205
- return apiKeyProfile;
206
- }
207
- }
208
- return resolveAuthProfileOrder({
209
- cfg: params.config,
210
- store: params.store,
211
- provider: OPENAI_CODEX_PROVIDER_ID,
212
- })[0];
213
- }
214
-
215
- function isActiveProfileCandidate(
216
- params: { store: AuthProfileStore; now: number },
217
- profileId: string,
218
- ): boolean {
219
- const unusableUntil = resolveProfileUnusableUntilForDisplay(params.store, profileId);
220
- return !isActiveUntil(unusableUntil ?? undefined, params.now);
221
- }
222
-
223
- function resolveLiveAccountProfileId(params: {
224
- account: SafeValue<JsonValue | undefined>;
225
- store: AuthProfileStore;
226
- order: string[];
227
- }): string | undefined {
228
- if (!params.account.ok || !isJsonObject(params.account.value)) {
229
- return undefined;
230
- }
231
- const account = isJsonObject(params.account.value.account)
232
- ? params.account.value.account
233
- : params.account.value;
234
- const type = readString(account, "type")?.toLowerCase();
235
- if (type === "chatgpt") {
236
- const email = readString(account, "email")?.toLowerCase();
237
- const firstSubscription = params.order.find((profileId) =>
238
- isChatGptSubscriptionProfile(params.store.profiles[profileId]),
239
- );
240
- if (!email) {
241
- return firstSubscription;
242
- }
243
- return (
244
- params.order.find((profileId) => {
245
- const credential = params.store.profiles[profileId];
246
- if (!isChatGptSubscriptionProfile(credential)) {
247
- return false;
248
- }
249
- const profileEmail =
250
- credential.email?.trim().toLowerCase() ?? extractEmailFromProfileId(profileId);
251
- return profileEmail?.toLowerCase() === email;
252
- }) ?? firstSubscription
253
- );
254
- }
255
- if (type === "apikey" || type === "api_key") {
256
- return params.order.find((profileId) => params.store.profiles[profileId]?.type === "api_key");
257
- }
258
- return undefined;
259
- }
260
-
261
- function shouldInferApiKeyActiveFromRateLimitProbe(
262
- limits: SafeValue<JsonValue | undefined>,
263
- ): boolean {
264
- return !limits.ok && limits.error.toLowerCase().includes("chatgpt authentication required");
265
- }
266
-
267
- async function readSubscriptionUsage(params: {
268
- pluginConfig: unknown;
269
- safeCodexControlRequest: SafeCodexControlRequest;
270
- config: AuthProfileOrderConfig;
271
- subscriptionProfileId: string;
272
- now: number;
273
- }): Promise<CodexAccountUsageSummary | undefined> {
274
- const limits = await params.safeCodexControlRequest(
275
- params.pluginConfig,
276
- CODEX_CONTROL_METHODS.rateLimits,
277
- undefined,
278
- {
279
- config: params.config,
280
- authProfileId: params.subscriptionProfileId,
281
- isolated: true,
282
- },
283
- );
284
- if (!limits.ok) {
285
- return undefined;
286
- }
287
- rememberCodexRateLimits(limits.value);
288
- return summarizeCodexAccountUsage(limits.value, params.now);
289
- }
290
-
291
- function buildProfileRow(params: {
292
- store: AuthProfileStore;
293
- config: AuthProfileOrderConfig;
294
- profileId: string;
295
- activeProfileId?: string;
296
- activeIndex: number;
297
- index: number;
298
- now: number;
299
- usage?: CodexAccountUsageSummary;
300
- }): CodexAccountAuthRow {
301
- const credential = params.store.profiles[params.profileId];
302
- const label = formatProfileLabel(params.profileId, credential);
303
- const kind = formatProfileKind(credential);
304
- const active = params.profileId === params.activeProfileId;
305
- const status = active
306
- ? "active now"
307
- : params.usage?.blocked
308
- ? formatUsageBlockedStatus(params.usage)
309
- : describeInactiveProfileStatus({
310
- store: params.store,
311
- config: params.config,
312
- profileId: params.profileId,
313
- credential,
314
- now: params.now,
315
- afterActive: params.activeIndex >= 0 && params.index > params.activeIndex,
316
- });
317
- return {
318
- profileId: params.profileId,
319
- label,
320
- kind,
321
- status,
322
- active,
323
- ...(credential?.type === "api_key" && active ? { billingNote: "billed per token" } : {}),
324
- ...(params.usage?.usageLine ? { usage: params.usage.usageLine } : {}),
325
- };
326
- }
327
-
328
- function formatUsageBlockedStatus(usage: CodexAccountUsageSummary): string {
329
- return usage.blocked ? "rate-limited" : "available if needed";
330
- }
331
-
332
- function describeInactiveProfileStatus(params: {
333
- store: AuthProfileStore;
334
- config: AuthProfileOrderConfig;
335
- profileId: string;
336
- credential?: AuthProfileCredential;
337
- now: number;
338
- afterActive: boolean;
339
- }): string {
340
- const stats = params.store.usageStats?.[params.profileId];
341
- const blockedUntil = stats?.blockedUntil;
342
- if (isActiveUntil(blockedUntil, params.now)) {
343
- return `rate-limited - resets ${formatRelativeReset(blockedUntil, params.now)}`;
344
- }
345
- const unusableUntil = resolveProfileUnusableUntilForDisplay(params.store, params.profileId);
346
- if (isActiveUntil(unusableUntil ?? undefined, params.now)) {
347
- return describeFailureStatus(stats?.disabledReason ?? stats?.cooldownReason, params.credential);
348
- }
349
- const eligibility = resolveAuthProfileEligibility({
350
- cfg: params.config,
351
- store: params.store,
352
- provider: OPENAI_CODEX_PROVIDER_ID,
353
- profileId: params.profileId,
354
- now: params.now,
355
- });
356
- if (!eligibility.eligible) {
357
- return describeEligibilityStatus(eligibility.reasonCode, params.credential);
358
- }
359
- return "available if needed";
360
- }
361
-
362
- function buildApiKeyActiveLine(
363
- activeRow: CodexAccountAuthRow,
364
- subscriptionUsage: CodexAccountUsageSummary | undefined,
365
- ): string {
366
- if (subscriptionUsage?.blocked) {
367
- const switchBack = subscriptionUsage.blockedResetRelative
368
- ? ` · switches back ${subscriptionUsage.blockedResetRelative}`
369
- : " · switches back automatically";
370
- return `Now using: ${activeRow.label} - subscription rate-limited${switchBack}`;
371
- }
372
- return `Now using: ${activeRow.label} - subscription unavailable · switches back automatically`;
373
- }
374
-
375
- function formatSubscriptionUsageLine(
376
- usage: CodexAccountUsageSummary | undefined,
377
- ): string | undefined {
378
- if (!usage) {
379
- return undefined;
380
- }
381
- const parts = usage.usageLine ? [formatUsageLineForDisplay(usage.usageLine)] : [];
382
- if (usage.blockedResetRelative) {
383
- parts.push(`Resets ${usage.blockedResetRelative}`);
384
- }
385
- return parts.length > 0 ? parts.join(" · ") : undefined;
386
- }
387
-
388
- function formatUsageLineForDisplay(value: string): string {
389
- return value.replace(/^weekly\b/u, "Weekly").replace(/\bshort-term\b/u, "Short-term");
390
- }
391
-
392
- function readString(record: JsonObject, key: string): string | undefined {
393
- const value = record[key];
394
- return typeof value === "string" && value.trim() ? value.trim() : undefined;
395
- }
396
-
397
- function isChatGptSubscriptionProfile(credential: AuthProfileCredential | undefined): boolean {
398
- return credential?.type === "oauth" || credential?.type === "token";
399
- }
400
-
401
- function formatProfileKind(credential: AuthProfileCredential | undefined): string {
402
- if (!credential) {
403
- return "credential";
404
- }
405
- if (isChatGptSubscriptionProfile(credential)) {
406
- return "ChatGPT subscription";
407
- }
408
- if (credential.type === "api_key") {
409
- return "API key";
410
- }
411
- return "credential";
412
- }
413
-
414
- function formatProfileLabel(
415
- profileId: string,
416
- credential: AuthProfileCredential | undefined,
417
- ): string {
418
- const tail = profileId.includes(":") ? profileId.slice(profileId.indexOf(":") + 1) : profileId;
419
- const displayName = credential?.displayName?.trim();
420
- if (displayName) {
421
- return credential?.type === "api_key"
422
- ? simplifyApiKeyDisplayName(displayName, tail)
423
- : displayName;
424
- }
425
- const email = credential?.email?.trim() ?? extractEmailFromProfileId(profileId);
426
- if (email) {
427
- return email;
428
- }
429
- if (credential?.type === "api_key") {
430
- return tail || "API key";
431
- }
432
- return humanizeProfileTail(tail);
433
- }
434
-
435
- function simplifyApiKeyDisplayName(value: string, tail: string): string {
436
- const stripped = value.replace(/^OpenAI\s+/iu, "").trim();
437
- if (tail && stripped.toLowerCase() === humanizeApiKeyProfileTail(tail).toLowerCase()) {
438
- return tail;
439
- }
440
- return stripped || value;
441
- }
442
-
443
- function humanizeApiKeyProfileTail(tail: string): string {
444
- const words = splitProfileTail(tail);
445
- const hasBackup = words.includes("backup");
446
- const customWords = words.filter((word) => word !== "api" && word !== "key" && word !== "backup");
447
- const prefix = customWords.map(titleCase).join(" ");
448
- return [prefix, "API key", hasBackup ? "backup" : ""].filter(Boolean).join(" ");
449
- }
450
-
451
- function humanizeProfileTail(tail: string): string {
452
- const words = splitProfileTail(tail);
453
- return words.length > 0 ? words.map(titleCase).join(" ") : tail;
454
- }
455
-
456
- function splitProfileTail(tail: string): string[] {
457
- return tail
458
- .replace(/[_\s]+/gu, "-")
459
- .split("-")
460
- .map((word) => word.trim().toLowerCase())
461
- .filter(Boolean);
462
- }
463
-
464
- function titleCase(value: string): string {
465
- return value ? `${value[0]?.toUpperCase() ?? ""}${value.slice(1)}` : value;
466
- }
467
-
468
- function extractEmailFromProfileId(profileId: string): string | undefined {
469
- const tail = profileId.includes(":") ? profileId.slice(profileId.indexOf(":") + 1) : profileId;
470
- return /^[^\s@<>()[\]`]+@[^\s@<>()[\]`]+\.[^\s@<>()[\]`]+$/.test(tail) ? tail : undefined;
471
- }
472
-
473
- function describeFailureStatus(
474
- reason: AuthProfileFailureReason | undefined,
475
- credential: AuthProfileCredential | undefined,
476
- ): string {
477
- if (reason === "auth" || reason === "auth_permanent" || reason === "session_expired") {
478
- return credential?.type === "api_key" ? "auth failed - check key" : "sign-in expired";
479
- }
480
- if (reason === "billing") {
481
- return "billing unavailable";
482
- }
483
- if (reason === "rate_limit") {
484
- return "rate-limited";
485
- }
486
- return "temporarily unavailable";
487
- }
488
-
489
- function describeEligibilityStatus(
490
- reason: string,
491
- credential: AuthProfileCredential | undefined,
492
- ): string {
493
- if (reason === "profile_missing" || reason === "missing_credential") {
494
- return credential?.type === "api_key" ? "not configured" : "sign-in required";
495
- }
496
- if (reason === "expired" || reason === "invalid_expires") {
497
- return "sign-in expired";
498
- }
499
- if (reason === "unresolved_ref") {
500
- return "credential unavailable";
501
- }
502
- if (reason === "provider_mismatch") {
503
- return "wrong provider";
504
- }
505
- if (reason === "mode_mismatch") {
506
- return "wrong credential type";
507
- }
508
- return "unavailable";
509
- }
510
-
511
- function isActiveUntil(value: number | undefined, now: number): value is number {
512
- return typeof value === "number" && Number.isFinite(value) && value > now;
513
- }
514
-
515
- function formatRelativeReset(untilMs: number, nowMs: number): string {
516
- const durationMs = Math.max(1_000, untilMs - nowMs);
517
- const minuteMs = 60_000;
518
- const hourMs = 60 * minuteMs;
519
- const dayMs = 24 * hourMs;
520
- if (durationMs < hourMs) {
521
- const minutes = Math.ceil(durationMs / minuteMs);
522
- return `in ${minutes} ${minutes === 1 ? "minute" : "minutes"}`;
523
- }
524
- if (durationMs < dayMs) {
525
- const hours = Math.ceil(durationMs / hourMs);
526
- return `in ${hours} ${hours === 1 ? "hour" : "hours"}`;
527
- }
528
- const days = Math.ceil(durationMs / dayMs);
529
- return `in ${days} ${days === 1 ? "day" : "days"}`;
530
- }
531
-
532
- function dedupe(values: string[]): string[] {
533
- const seen = new Set<string>();
534
- const result: string[] = [];
535
- for (const value of values) {
536
- const trimmed = value.trim();
537
- if (!trimmed || seen.has(trimmed)) {
538
- continue;
539
- }
540
- seen.add(trimmed);
541
- result.push(trimmed);
542
- }
543
- return result;
544
- }