@gakr-gakr/codex 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/dist/client-DNN2uyJW.js +642 -0
  2. package/dist/client-factory-Bu9OClHJ.js +9 -0
  3. package/dist/command-formatters-BpPOTePl.js +520 -0
  4. package/dist/command-handlers-BBs7Vws9.js +1533 -0
  5. package/dist/compact-CDboBy7o.js +329 -0
  6. package/dist/computer-use-DCZB46Sw.js +367 -0
  7. package/dist/config-CLMSw0p2.js +510 -0
  8. package/dist/doctor-contract-api.js +53 -0
  9. package/dist/harness.js +51 -0
  10. package/dist/index.js +1171 -0
  11. package/dist/media-understanding-provider.js +335 -0
  12. package/dist/models-jLA2SIvd.js +110 -0
  13. package/dist/node-cli-sessions-BLRDs_US.js +1216 -0
  14. package/dist/plugin-activation-CEy_oYpx.js +452 -0
  15. package/dist/prompt-overlay.js +12 -0
  16. package/dist/protocol-C9UWI98H.js +9 -0
  17. package/dist/protocol-validators-BGBspNmF.js +5988 -0
  18. package/dist/provider-catalog.js +84 -0
  19. package/dist/provider-discovery.js +33 -0
  20. package/dist/provider.js +150 -0
  21. package/dist/rate-limit-cache-9LxQdE0K.js +24 -0
  22. package/dist/request-DbSPeTcV.js +89 -0
  23. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  24. package/dist/run-attempt-BoEwzQCv.js +5463 -0
  25. package/dist/session-binding-e2GFp9VH.js +222 -0
  26. package/dist/shared-client-D7Vy0glq.js +631 -0
  27. package/dist/side-question-BDLuEzFP.js +668 -0
  28. package/dist/test-api.js +49 -0
  29. package/dist/thread-lifecycle-Clo0EHMk.js +1565 -0
  30. package/dist/vision-tools-Cofrv35p.js +1379 -0
  31. package/package.json +16 -1
  32. package/doctor-contract-api.ts +0 -68
  33. package/harness.ts +0 -72
  34. package/index.ts +0 -124
  35. package/media-understanding-provider.ts +0 -521
  36. package/prompt-overlay.ts +0 -21
  37. package/provider-catalog.ts +0 -83
  38. package/provider-discovery.ts +0 -45
  39. package/provider.ts +0 -243
  40. package/src/app-server/app-inventory-cache.ts +0 -324
  41. package/src/app-server/approval-bridge.ts +0 -1211
  42. package/src/app-server/auth-bridge.ts +0 -614
  43. package/src/app-server/capabilities.ts +0 -27
  44. package/src/app-server/client-factory.ts +0 -24
  45. package/src/app-server/client.ts +0 -715
  46. package/src/app-server/compact.ts +0 -512
  47. package/src/app-server/computer-use.ts +0 -683
  48. package/src/app-server/config.ts +0 -1038
  49. package/src/app-server/context-engine-projection.ts +0 -403
  50. package/src/app-server/dynamic-tool-diagnostics.ts +0 -73
  51. package/src/app-server/dynamic-tool-profile.ts +0 -70
  52. package/src/app-server/dynamic-tools.ts +0 -623
  53. package/src/app-server/elicitation-bridge.ts +0 -783
  54. package/src/app-server/event-projector.ts +0 -2065
  55. package/src/app-server/image-payload-sanitizer.ts +0 -167
  56. package/src/app-server/local-runtime-attribution.ts +0 -39
  57. package/src/app-server/managed-binary.ts +0 -193
  58. package/src/app-server/models.ts +0 -172
  59. package/src/app-server/native-hook-relay.ts +0 -150
  60. package/src/app-server/native-subagent-task-mirror.ts +0 -497
  61. package/src/app-server/plugin-activation.ts +0 -283
  62. package/src/app-server/plugin-app-cache-key.ts +0 -74
  63. package/src/app-server/plugin-approval-roundtrip.ts +0 -122
  64. package/src/app-server/plugin-inventory.ts +0 -357
  65. package/src/app-server/plugin-thread-config.ts +0 -455
  66. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +0 -33
  67. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +0 -199
  68. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +0 -102
  69. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +0 -227
  70. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +0 -2630
  71. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +0 -2630
  72. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +0 -1659
  73. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +0 -1655
  74. package/src/app-server/protocol-validators.ts +0 -203
  75. package/src/app-server/protocol.ts +0 -520
  76. package/src/app-server/rate-limit-cache.ts +0 -48
  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.ts +0 -4862
  80. package/src/app-server/session-binding.ts +0 -398
  81. package/src/app-server/session-history.ts +0 -44
  82. package/src/app-server/shared-client.ts +0 -289
  83. package/src/app-server/side-question.ts +0 -1009
  84. package/src/app-server/test-support.ts +0 -48
  85. package/src/app-server/thread-lifecycle.ts +0 -959
  86. package/src/app-server/timeout.ts +0 -9
  87. package/src/app-server/tool-progress-normalization.ts +0 -77
  88. package/src/app-server/trajectory.ts +0 -368
  89. package/src/app-server/transcript-mirror.ts +0 -208
  90. package/src/app-server/transport-stdio.ts +0 -107
  91. package/src/app-server/transport-websocket.ts +0 -90
  92. package/src/app-server/transport.ts +0 -117
  93. package/src/app-server/user-input-bridge.ts +0 -316
  94. package/src/app-server/version.ts +0 -4
  95. package/src/app-server/vision-tools.ts +0 -12
  96. package/src/command-account.ts +0 -544
  97. package/src/command-formatters.ts +0 -426
  98. package/src/command-handlers.ts +0 -2021
  99. package/src/command-plugins-management.ts +0 -137
  100. package/src/command-rpc.ts +0 -142
  101. package/src/commands.ts +0 -65
  102. package/src/conversation-binding-data.ts +0 -124
  103. package/src/conversation-binding.ts +0 -561
  104. package/src/conversation-control.ts +0 -303
  105. package/src/conversation-turn-collector.ts +0 -186
  106. package/src/conversation-turn-input.ts +0 -106
  107. package/src/migration/apply.ts +0 -501
  108. package/src/migration/helpers.ts +0 -55
  109. package/src/migration/plan.ts +0 -461
  110. package/src/migration/provider.ts +0 -41
  111. package/src/migration/source.ts +0 -643
  112. package/src/migration/targets.ts +0 -25
  113. package/src/node-cli-sessions.ts +0 -711
  114. package/test-api.ts +0 -95
  115. 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 "autobot/plugin-sdk/agent-runtime";
12
- import type { PluginCommandContext } from "autobot/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
- }