@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,583 +0,0 @@
1
- import { isJsonObject, type JsonObject, type JsonValue } from "./protocol.js";
2
-
3
- const CODEX_LIMIT_ID = "codex";
4
- const LIMIT_WINDOW_KEYS = ["primary", "secondary"] as const;
5
- const ONE_SECOND_MS = 1000;
6
- const ONE_MINUTE_MS = 60_000;
7
- const ONE_HOUR_MS = 60 * ONE_MINUTE_MS;
8
- const ONE_DAY_MS = 24 * ONE_HOUR_MS;
9
-
10
- type LimitWindowKey = (typeof LIMIT_WINDOW_KEYS)[number];
11
-
12
- type RateLimitReset = {
13
- resetsAtMs: number;
14
- usedPercent?: number;
15
- windowDurationMins?: number;
16
- };
17
-
18
- type RateLimitWindowEntry = {
19
- key: LimitWindowKey;
20
- window: RateLimitReset;
21
- };
22
-
23
- export type CodexAccountUsageSummary = {
24
- usageLine?: string;
25
- blocked: boolean;
26
- blockedUntilMs?: number;
27
- blockedUntilText?: string;
28
- blockedResetRelative?: string;
29
- blockingPeriod?: string;
30
- blockingReason?: string;
31
- };
32
-
33
- export function formatCodexUsageLimitErrorMessage(params: {
34
- message?: string | null;
35
- codexErrorInfo?: JsonValue | null;
36
- rateLimits?: JsonValue;
37
- nowMs?: number;
38
- }): string | undefined {
39
- const message = normalizeText(params.message);
40
- if (!isCodexUsageLimitError(params.codexErrorInfo, message)) {
41
- return undefined;
42
- }
43
- const nowMs = params.nowMs ?? Date.now();
44
- const nextReset = selectNextRateLimitReset(params.rateLimits, nowMs);
45
- const parts = ["You've reached your Codex subscription usage limit."];
46
- if (nextReset) {
47
- parts.push(`Next reset ${formatResetTime(nextReset.resetsAtMs, nowMs)}.`);
48
- } else {
49
- const codexRetryHint = extractCodexRetryHint(message);
50
- if (codexRetryHint) {
51
- parts.push(`Codex says to try again ${codexRetryHint}.`);
52
- } else {
53
- parts.push("Codex did not return a reset time for this limit.");
54
- }
55
- }
56
- parts.push("Run /codex account for current usage details.");
57
- return parts.join(" ");
58
- }
59
-
60
- export function shouldRefreshCodexRateLimitsForUsageLimitMessage(
61
- message: string | null | undefined,
62
- ): boolean {
63
- const text = normalizeText(message);
64
- return Boolean(
65
- text?.includes("You've reached your Codex subscription usage limit.") &&
66
- !text.includes("Next reset "),
67
- );
68
- }
69
-
70
- export function summarizeCodexRateLimits(
71
- value: JsonValue | undefined,
72
- nowMs = Date.now(),
73
- ): string | undefined {
74
- const snapshots = collectCodexRateLimitSnapshots(value).filter(snapshotHasDisplayableData);
75
- if (snapshots.length === 0) {
76
- return undefined;
77
- }
78
- const summaries = snapshots
79
- .slice(0, 4)
80
- .map((snapshot) => summarizeRateLimitSnapshot(snapshot, nowMs))
81
- .filter((summary): summary is string => summary !== undefined);
82
- return summaries.length > 0 ? summaries.join("; ") : undefined;
83
- }
84
-
85
- export function hasCodexRateLimitSnapshots(value: JsonValue | undefined): boolean {
86
- return collectCodexRateLimitSnapshots(value).length > 0;
87
- }
88
-
89
- export function summarizeCodexAccountRateLimits(
90
- value: JsonValue | undefined,
91
- nowMs = Date.now(),
92
- ): string[] | undefined {
93
- const summary = summarizeCodexAccountUsage(value, nowMs);
94
- if (!summary) {
95
- return undefined;
96
- }
97
- if (!summary.blocked) {
98
- return ["Codex is available."];
99
- }
100
- return [
101
- summary.blockedUntilText
102
- ? `Codex is paused until ${summary.blockedUntilText}.`
103
- : "Codex is paused by a usage limit.",
104
- summary.blockingReason
105
- ? `Your ${summary.blockingReason}.`
106
- : "Your Codex usage limit is reached.",
107
- ];
108
- }
109
-
110
- export function resolveCodexUsageLimitResetAtMs(
111
- value: JsonValue | undefined,
112
- nowMs = Date.now(),
113
- ): number | undefined {
114
- return selectBlockingRateLimitReset(value, nowMs)?.resetsAtMs;
115
- }
116
-
117
- export function summarizeCodexAccountUsage(
118
- value: JsonValue | undefined,
119
- nowMs = Date.now(),
120
- ): CodexAccountUsageSummary | undefined {
121
- const snapshots = collectCodexRateLimitSnapshots(value).filter(snapshotHasDisplayableData);
122
- if (snapshots.length === 0) {
123
- return undefined;
124
- }
125
- const usageSnapshot = snapshots.find(isCodexLimitSnapshot) ?? snapshots[0];
126
- const blockedSnapshots = snapshots.filter(snapshotHasLimitBlock);
127
- const blockingSnapshot =
128
- blockedSnapshots.find(isCodexLimitSnapshot) ?? blockedSnapshots[0] ?? undefined;
129
- const blockingReset = blockingSnapshot
130
- ? selectSnapshotBlockingReset(blockingSnapshot, nowMs)
131
- : undefined;
132
- const blockingPeriod = formatBlockingLimitPeriod(blockingReset?.windowDurationMins);
133
- const blockedUntilText = blockingReset
134
- ? formatAccountResetTime(blockingReset.resetsAtMs, nowMs)
135
- : undefined;
136
- const blockedResetRelative = blockingReset
137
- ? `in ${formatRelativeDuration(blockingReset.resetsAtMs - nowMs)}`
138
- : undefined;
139
- const blockingReason = blockingPeriod
140
- ? `${blockingPeriod} Codex usage limit is reached`
141
- : blockingSnapshot
142
- ? "Codex usage limit is reached"
143
- : undefined;
144
- return {
145
- usageLine: formatUsageLine(usageSnapshot),
146
- blocked: Boolean(blockingSnapshot),
147
- ...(blockingReset ? { blockedUntilMs: blockingReset.resetsAtMs } : {}),
148
- ...(blockedUntilText ? { blockedUntilText } : {}),
149
- ...(blockedResetRelative ? { blockedResetRelative } : {}),
150
- ...(blockingPeriod ? { blockingPeriod } : {}),
151
- ...(blockingReason ? { blockingReason } : {}),
152
- };
153
- }
154
-
155
- function isCodexUsageLimitError(
156
- codexErrorInfo: JsonValue | null | undefined,
157
- message: string | undefined,
158
- ): boolean {
159
- if (codexErrorInfo === "usageLimitExceeded") {
160
- return true;
161
- }
162
- if (typeof codexErrorInfo === "string") {
163
- const normalized = codexErrorInfo.replace(/[_\s-]/gu, "").toLowerCase();
164
- if (normalized === "usagelimitexceeded") {
165
- return true;
166
- }
167
- }
168
- return Boolean(message?.toLowerCase().includes("usage limit"));
169
- }
170
-
171
- function selectNextRateLimitReset(
172
- value: JsonValue | undefined,
173
- nowMs: number,
174
- ): RateLimitReset | undefined {
175
- const windows = collectCodexRateLimitSnapshots(value).flatMap((snapshot) =>
176
- LIMIT_WINDOW_KEYS.flatMap((key) => readRateLimitWindow(snapshot, key) ?? []),
177
- );
178
- const futureWindows = windows.filter((window) => window.resetsAtMs > nowMs);
179
- if (futureWindows.length === 0) {
180
- return undefined;
181
- }
182
- const exhaustedWindows = futureWindows.filter(
183
- (window) => window.usedPercent !== undefined && window.usedPercent >= 100,
184
- );
185
- const candidates = exhaustedWindows.length > 0 ? exhaustedWindows : futureWindows;
186
- return candidates.toSorted((left, right) => left.resetsAtMs - right.resetsAtMs)[0];
187
- }
188
-
189
- function selectBlockingRateLimitReset(
190
- value: JsonValue | undefined,
191
- nowMs: number,
192
- ): RateLimitReset | undefined {
193
- const snapshots = collectCodexRateLimitSnapshots(value);
194
- const blockedSnapshots = snapshots.filter(snapshotHasLimitBlock);
195
- const blockingSnapshot =
196
- blockedSnapshots.find(isCodexLimitSnapshot) ?? blockedSnapshots[0] ?? undefined;
197
- return blockingSnapshot ? selectSnapshotBlockingReset(blockingSnapshot, nowMs) : undefined;
198
- }
199
-
200
- function summarizeRateLimitSnapshot(snapshot: JsonObject, nowMs: number): string | undefined {
201
- const label = formatLimitLabel(snapshot);
202
- const windows = LIMIT_WINDOW_KEYS.flatMap((key) => {
203
- const window = readRateLimitWindow(snapshot, key);
204
- return window ? [formatRateLimitWindow(key, window, nowMs)] : [];
205
- });
206
- const reachedType =
207
- readString(snapshot, "rateLimitReachedType") ?? readString(snapshot, "rate_limit_reached_type");
208
- const suffix = reachedType ? ` (${formatReachedType(reachedType)})` : "";
209
- if (windows.length > 0) {
210
- return `${label}: ${windows.join(" · ")}${suffix}`;
211
- }
212
- if (reachedType) {
213
- return `${label}: ${formatReachedType(reachedType)}`;
214
- }
215
- return undefined;
216
- }
217
-
218
- function collectCodexRateLimitSnapshots(value: JsonValue | undefined): JsonObject[] {
219
- const snapshots: JsonObject[] = [];
220
- const seen = new Set<string>();
221
- collectRateLimitSnapshots(value, snapshots, seen);
222
- return snapshots;
223
- }
224
-
225
- function collectRateLimitSnapshots(
226
- value: JsonValue | undefined,
227
- snapshots: JsonObject[],
228
- seen: Set<string>,
229
- ): void {
230
- if (Array.isArray(value)) {
231
- for (const entry of value) {
232
- collectRateLimitSnapshots(entry, snapshots, seen);
233
- }
234
- return;
235
- }
236
- if (!isJsonObject(value)) {
237
- return;
238
- }
239
- if (isRateLimitSnapshot(value)) {
240
- addRateLimitSnapshot(value, snapshots, seen);
241
- return;
242
- }
243
- const byLimitId = value.rateLimitsByLimitId;
244
- if (isJsonObject(byLimitId)) {
245
- for (const key of sortedRateLimitKeys(Object.keys(byLimitId))) {
246
- collectRateLimitSnapshots(byLimitId[key], snapshots, seen);
247
- }
248
- }
249
- const snakeByLimitId = value.rate_limits_by_limit_id;
250
- if (isJsonObject(snakeByLimitId)) {
251
- for (const key of sortedRateLimitKeys(Object.keys(snakeByLimitId))) {
252
- collectRateLimitSnapshots(snakeByLimitId[key], snapshots, seen);
253
- }
254
- }
255
- collectRateLimitSnapshots(value.rateLimits, snapshots, seen);
256
- collectRateLimitSnapshots(value.rate_limits, snapshots, seen);
257
- collectRateLimitSnapshots(value.data, snapshots, seen);
258
- collectRateLimitSnapshots(value.items, snapshots, seen);
259
- }
260
-
261
- function sortedRateLimitKeys(keys: string[]): string[] {
262
- return keys.toSorted((left, right) => {
263
- if (left === CODEX_LIMIT_ID) {
264
- return -1;
265
- }
266
- if (right === CODEX_LIMIT_ID) {
267
- return 1;
268
- }
269
- return left.localeCompare(right);
270
- });
271
- }
272
-
273
- function addRateLimitSnapshot(
274
- snapshot: JsonObject,
275
- snapshots: JsonObject[],
276
- seen: Set<string>,
277
- ): void {
278
- const signature = [
279
- readNullableString(snapshot, "limitId") ?? readNullableString(snapshot, "limit_id") ?? "",
280
- readNullableString(snapshot, "limitName") ?? readNullableString(snapshot, "limit_name") ?? "",
281
- formatWindowSignature(snapshot.primary),
282
- formatWindowSignature(snapshot.secondary),
283
- ].join("|");
284
- if (seen.has(signature)) {
285
- return;
286
- }
287
- seen.add(signature);
288
- snapshots.push(snapshot);
289
- }
290
-
291
- function isRateLimitSnapshot(value: JsonObject): boolean {
292
- return (
293
- isJsonObject(value.primary) ||
294
- isJsonObject(value.secondary) ||
295
- value.rateLimitReachedType !== undefined ||
296
- value.rate_limit_reached_type !== undefined ||
297
- value.limitId !== undefined ||
298
- value.limit_id !== undefined ||
299
- value.limitName !== undefined ||
300
- value.limit_name !== undefined
301
- );
302
- }
303
-
304
- function readRateLimitWindow(
305
- snapshot: JsonObject,
306
- key: LimitWindowKey,
307
- ): RateLimitReset | undefined {
308
- const window = snapshot[key];
309
- if (!isJsonObject(window)) {
310
- return undefined;
311
- }
312
- const resetsAt = readNumber(window, "resetsAt") ?? readNumber(window, "resets_at");
313
- return {
314
- ...(typeof resetsAt === "number" && Number.isFinite(resetsAt) && resetsAt > 0
315
- ? { resetsAtMs: resetsAt * 1000 }
316
- : { resetsAtMs: 0 }),
317
- ...readOptionalNumberField(window, "usedPercent", "used_percent"),
318
- ...readOptionalNumberField(
319
- window,
320
- "windowDurationMins",
321
- "window_duration_mins",
322
- "windowMinutes",
323
- "window_minutes",
324
- ),
325
- };
326
- }
327
-
328
- function snapshotHasDisplayableData(snapshot: JsonObject): boolean {
329
- if (
330
- readString(snapshot, "rateLimitReachedType") ??
331
- readString(snapshot, "rate_limit_reached_type")
332
- ) {
333
- return true;
334
- }
335
- return readWindowEntries(snapshot).some(
336
- (entry) => entry.window.usedPercent !== undefined || entry.window.resetsAtMs > 0,
337
- );
338
- }
339
-
340
- function readOptionalNumberField(
341
- record: JsonObject,
342
- ...keys: string[]
343
- ): { usedPercent?: number; windowDurationMins?: number } {
344
- const value = keys.map((key) => readNumber(record, key)).find((entry) => entry !== undefined);
345
- if (value === undefined) {
346
- return {};
347
- }
348
- return keys.some((key) => key.toLowerCase().includes("window"))
349
- ? { windowDurationMins: value }
350
- : { usedPercent: value };
351
- }
352
-
353
- function formatRateLimitWindow(key: LimitWindowKey, window: RateLimitReset, nowMs: number): string {
354
- return `${key} ${formatRateLimitWindowDetails(window, nowMs)}`;
355
- }
356
-
357
- function formatRateLimitWindowDetails(window: RateLimitReset, nowMs: number): string {
358
- const remainingPercent =
359
- window.usedPercent === undefined
360
- ? "usage unknown"
361
- : `${Math.max(0, 100 - Math.round(window.usedPercent))}% left`;
362
- const reset =
363
- window.resetsAtMs > nowMs ? ` ⏱${formatResetDuration(window.resetsAtMs, nowMs)}` : "";
364
- return `${remainingPercent}${reset}`;
365
- }
366
-
367
- function formatLimitLabel(snapshot: JsonObject): string {
368
- const label =
369
- readNullableString(snapshot, "limitName") ??
370
- readNullableString(snapshot, "limit_name") ??
371
- readNullableString(snapshot, "limitId") ??
372
- readNullableString(snapshot, "limit_id");
373
- if (!label || label === CODEX_LIMIT_ID) {
374
- return "Codex";
375
- }
376
- return label.replace(/[_-]+/gu, " ").replace(/\s+/gu, " ").trim();
377
- }
378
-
379
- function formatReachedType(value: string): string {
380
- return value.replace(/[_-]+/gu, " ").replace(/\s+/gu, " ").trim();
381
- }
382
-
383
- function formatResetTime(resetsAtMs: number, nowMs: number): string {
384
- return `in ${formatRelativeDuration(resetsAtMs - nowMs)}, ${formatCalendarResetTime(
385
- resetsAtMs,
386
- nowMs,
387
- )}`;
388
- }
389
-
390
- function formatAccountResetTime(resetsAtMs: number, nowMs: number): string {
391
- return `${formatCalendarResetTime(resetsAtMs, nowMs)} (in ${formatRelativeDuration(
392
- resetsAtMs - nowMs,
393
- )})`;
394
- }
395
-
396
- function snapshotHasLimitBlock(snapshot: JsonObject): boolean {
397
- return Boolean(
398
- readString(snapshot, "rateLimitReachedType") ??
399
- readString(snapshot, "rate_limit_reached_type") ??
400
- readWindowEntries(snapshot).some(
401
- (entry) => entry.window.usedPercent !== undefined && entry.window.usedPercent >= 100,
402
- ),
403
- );
404
- }
405
-
406
- function isCodexLimitSnapshot(snapshot: JsonObject): boolean {
407
- const id = readNullableString(snapshot, "limitId") ?? readNullableString(snapshot, "limit_id");
408
- return !id || id === CODEX_LIMIT_ID;
409
- }
410
-
411
- function selectSnapshotBlockingReset(
412
- snapshot: JsonObject,
413
- nowMs: number,
414
- ): RateLimitReset | undefined {
415
- const futureWindows = readWindowEntries(snapshot)
416
- .map((entry) => entry.window)
417
- .filter((window) => window.resetsAtMs > nowMs);
418
- const exhaustedWindows = futureWindows.filter(
419
- (window) => window.usedPercent !== undefined && window.usedPercent >= 100,
420
- );
421
- const candidates = exhaustedWindows.length > 0 ? exhaustedWindows : futureWindows;
422
- const resetSort =
423
- exhaustedWindows.length > 0
424
- ? (left: RateLimitReset, right: RateLimitReset) => right.resetsAtMs - left.resetsAtMs
425
- : (left: RateLimitReset, right: RateLimitReset) => left.resetsAtMs - right.resetsAtMs;
426
- return candidates.toSorted(resetSort)[0];
427
- }
428
-
429
- function readWindowEntries(snapshot: JsonObject): RateLimitWindowEntry[] {
430
- return LIMIT_WINDOW_KEYS.flatMap((key) => {
431
- const window = readRateLimitWindow(snapshot, key);
432
- return window ? [{ key, window }] : [];
433
- });
434
- }
435
-
436
- function formatBlockingLimitPeriod(minutes: number | undefined): string | undefined {
437
- if (minutes === 7 * 24 * 60) {
438
- return "weekly";
439
- }
440
- if (minutes === 24 * 60) {
441
- return "daily";
442
- }
443
- if (minutes !== undefined && minutes > 0 && minutes < 24 * 60) {
444
- return "short-term";
445
- }
446
- return undefined;
447
- }
448
-
449
- function formatUsageLine(snapshot: JsonObject): string | undefined {
450
- const windows = readWindowEntries(snapshot)
451
- .filter((entry) => entry.window.usedPercent !== undefined)
452
- .toSorted(
453
- (left, right) =>
454
- (right.window.windowDurationMins ?? 0) - (left.window.windowDurationMins ?? 0),
455
- )
456
- .map((entry) => {
457
- const label = formatUsageWindowLabel(entry.window.windowDurationMins);
458
- return `${label} ${Math.round(entry.window.usedPercent ?? 0)}%`;
459
- });
460
- return windows.length > 0 ? windows.join(" \u00b7 ") : undefined;
461
- }
462
-
463
- function formatUsageWindowLabel(minutes: number | undefined): string {
464
- if (minutes === 7 * 24 * 60) {
465
- return "weekly";
466
- }
467
- if (minutes === 24 * 60) {
468
- return "daily";
469
- }
470
- if (minutes !== undefined && minutes > 0 && minutes < 24 * 60) {
471
- return "short-term";
472
- }
473
- if (minutes !== undefined && minutes > 0 && minutes % (24 * 60) === 0) {
474
- const days = minutes / (24 * 60);
475
- return `${days}-day`;
476
- }
477
- if (minutes !== undefined && minutes > 0 && minutes % 60 === 0) {
478
- const hours = minutes / 60;
479
- return `${hours}-hour`;
480
- }
481
- return "usage";
482
- }
483
-
484
- function formatCalendarResetTime(resetsAtMs: number, nowMs: number): string {
485
- const resetDate = new Date(resetsAtMs);
486
- const resetParts = new Intl.DateTimeFormat("en-US", {
487
- month: "short",
488
- day: "numeric",
489
- ...(resetDate.getFullYear() === new Date(nowMs).getFullYear() ? {} : { year: "numeric" }),
490
- hour: "numeric",
491
- minute: "2-digit",
492
- timeZoneName: "short",
493
- }).formatToParts(resetDate);
494
- const part = (type: Intl.DateTimeFormatPartTypes): string | undefined =>
495
- resetParts.find((entry) => entry.type === type)?.value;
496
- const dateParts = [part("month"), part("day"), part("year")].filter(Boolean);
497
- const day =
498
- dateParts.length > 1 ? `${dateParts[0]} ${dateParts.slice(1).join(", ")}` : dateParts[0];
499
- const time = [part("hour"), part("minute")].filter(Boolean).join(":");
500
- const dayPeriod = part("dayPeriod");
501
- const timeZone = part("timeZoneName");
502
- return [day, "at", [time, dayPeriod, timeZone].filter(Boolean).join(" ")]
503
- .filter(Boolean)
504
- .join(" ");
505
- }
506
-
507
- function formatRelativeDuration(durationMs: number): string {
508
- const safeMs = Math.max(1_000, durationMs);
509
- if (safeMs < ONE_MINUTE_MS) {
510
- return `${Math.ceil(safeMs / 1000)} seconds`;
511
- }
512
- if (safeMs < ONE_HOUR_MS) {
513
- const minutes = Math.ceil(safeMs / ONE_MINUTE_MS);
514
- return `${minutes} ${minutes === 1 ? "minute" : "minutes"}`;
515
- }
516
- if (safeMs < ONE_DAY_MS) {
517
- const hours = Math.ceil(safeMs / ONE_HOUR_MS);
518
- return `${hours} ${hours === 1 ? "hour" : "hours"}`;
519
- }
520
- const days = Math.ceil(safeMs / ONE_DAY_MS);
521
- return `${days} ${days === 1 ? "day" : "days"}`;
522
- }
523
-
524
- function formatResetDuration(resetsAtMs: number, nowMs: number): string {
525
- const durationMs =
526
- Math.round(Math.max(ONE_SECOND_MS, resetsAtMs - nowMs) / ONE_SECOND_MS) * ONE_SECOND_MS;
527
- const days = Math.floor(durationMs / ONE_DAY_MS);
528
- const hours = Math.floor((durationMs % ONE_DAY_MS) / ONE_HOUR_MS);
529
- const minutes = Math.floor((durationMs % ONE_HOUR_MS) / ONE_MINUTE_MS);
530
- const seconds = Math.floor((durationMs % ONE_MINUTE_MS) / ONE_SECOND_MS);
531
- if (days > 0) {
532
- return hours > 0 ? `${days}d ${hours}h` : `${days}d`;
533
- }
534
- if (hours > 0) {
535
- return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
536
- }
537
- if (minutes > 0) {
538
- return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
539
- }
540
- return `${seconds}s`;
541
- }
542
-
543
- function formatWindowSignature(value: JsonValue | undefined): string {
544
- if (!isJsonObject(value)) {
545
- return "";
546
- }
547
- return `${readNumber(value, "usedPercent") ?? readNumber(value, "used_percent") ?? ""}:${
548
- readNumber(value, "resetsAt") ?? readNumber(value, "resets_at") ?? ""
549
- }`;
550
- }
551
-
552
- function extractCodexRetryHint(message: string | undefined): string | undefined {
553
- if (!message) {
554
- return undefined;
555
- }
556
- const tryAgainAt = /\btry again\s+(at\s+[^.!?\n]+)(?:[.!?]|$)/iu.exec(message);
557
- if (tryAgainAt?.[1]) {
558
- return tryAgainAt[1].trim();
559
- }
560
- const tryAgainRelative = /\btry again\s+((?:tomorrow|in\s+[^.!?\n]+)[^.!?\n]*)(?:[.!?]|$)/iu.exec(
561
- message,
562
- );
563
- return tryAgainRelative?.[1]?.trim();
564
- }
565
-
566
- function readString(record: JsonObject, key: string): string | undefined {
567
- const value = record[key];
568
- return typeof value === "string" && value.trim() ? value.trim() : undefined;
569
- }
570
-
571
- function readNullableString(record: JsonObject, key: string): string | undefined {
572
- return readString(record, key) ?? undefined;
573
- }
574
-
575
- function readNumber(record: JsonObject, key: string): number | undefined {
576
- const value = record[key];
577
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
578
- }
579
-
580
- function normalizeText(value: string | null | undefined): string | undefined {
581
- const text = value?.trim();
582
- return text ? text : undefined;
583
- }
@@ -1,73 +0,0 @@
1
- import type { resolveCodexAppServerAuthProfileIdForAgent } from "./auth-bridge.js";
2
- import type { CodexAppServerStartOptions } from "./config.js";
3
- import type {
4
- CodexAppServerRequestMethod,
5
- CodexAppServerRequestParams,
6
- CodexAppServerRequestResult,
7
- JsonValue,
8
- } from "./protocol.js";
9
- import {
10
- createIsolatedCodexAppServerClient,
11
- getSharedCodexAppServerClient,
12
- } from "./shared-client.js";
13
- import { withTimeout } from "./timeout.js";
14
-
15
- export async function requestCodexAppServerJson<M extends CodexAppServerRequestMethod>(params: {
16
- method: M;
17
- requestParams: CodexAppServerRequestParams<M>;
18
- timeoutMs?: number;
19
- startOptions?: CodexAppServerStartOptions;
20
- authProfileId?: string | null;
21
- agentDir?: string;
22
- config?: Parameters<typeof resolveCodexAppServerAuthProfileIdForAgent>[0]["config"];
23
- isolated?: boolean;
24
- }): Promise<CodexAppServerRequestResult<M>>;
25
- export async function requestCodexAppServerJson<T = JsonValue | undefined>(params: {
26
- method: string;
27
- requestParams?: unknown;
28
- timeoutMs?: number;
29
- startOptions?: CodexAppServerStartOptions;
30
- authProfileId?: string | null;
31
- agentDir?: string;
32
- config?: Parameters<typeof resolveCodexAppServerAuthProfileIdForAgent>[0]["config"];
33
- isolated?: boolean;
34
- }): Promise<T>;
35
- export async function requestCodexAppServerJson<T = JsonValue | undefined>(params: {
36
- method: string;
37
- requestParams?: unknown;
38
- timeoutMs?: number;
39
- startOptions?: CodexAppServerStartOptions;
40
- authProfileId?: string | null;
41
- agentDir?: string;
42
- config?: Parameters<typeof resolveCodexAppServerAuthProfileIdForAgent>[0]["config"];
43
- isolated?: boolean;
44
- }): Promise<T> {
45
- const timeoutMs = params.timeoutMs ?? 60_000;
46
- return await withTimeout(
47
- (async () => {
48
- const client = await (
49
- params.isolated ? createIsolatedCodexAppServerClient : getSharedCodexAppServerClient
50
- )({
51
- startOptions: params.startOptions,
52
- timeoutMs,
53
- authProfileId: params.authProfileId,
54
- agentDir: params.agentDir,
55
- config: params.config,
56
- });
57
- try {
58
- return await client.request<T>(params.method, params.requestParams, { timeoutMs });
59
- } finally {
60
- if (params.isolated) {
61
- // Wait for the child to actually exit (with a SIGKILL fallback) so
62
- // the parent process doesn't hang on an orphaned codex app-server.
63
- // The stdio bin shim does not always propagate stdin EOF to the
64
- // underlying codex binary, so the unref'd close() path can leave
65
- // the child running and keep the parent's event loop alive.
66
- await client.closeAndWait({ exitTimeoutMs: 2_000, forceKillDelayMs: 250 });
67
- }
68
- }
69
- })(),
70
- timeoutMs,
71
- `codex app-server ${params.method} timed out`,
72
- );
73
- }