@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,48 +0,0 @@
1
- import type { JsonValue } from "./protocol.js";
2
-
3
- const DEFAULT_CODEX_RATE_LIMIT_CACHE_MAX_AGE_MS = 10 * 60_000;
4
- const CODEX_RATE_LIMIT_CACHE_STATE = Symbol.for("autobot.codexRateLimitCacheState");
5
-
6
- type CodexRateLimitCacheState = {
7
- value?: JsonValue;
8
- updatedAtMs?: number;
9
- };
10
-
11
- function getCodexRateLimitCacheState(): CodexRateLimitCacheState {
12
- const globalState = globalThis as typeof globalThis & {
13
- [CODEX_RATE_LIMIT_CACHE_STATE]?: CodexRateLimitCacheState;
14
- };
15
- globalState[CODEX_RATE_LIMIT_CACHE_STATE] ??= {};
16
- return globalState[CODEX_RATE_LIMIT_CACHE_STATE];
17
- }
18
-
19
- export function rememberCodexRateLimits(value: JsonValue | undefined, nowMs = Date.now()): void {
20
- if (value === undefined) {
21
- return;
22
- }
23
- const state = getCodexRateLimitCacheState();
24
- state.value = value;
25
- state.updatedAtMs = nowMs;
26
- }
27
-
28
- export function readRecentCodexRateLimits(options?: {
29
- nowMs?: number;
30
- maxAgeMs?: number;
31
- }): JsonValue | undefined {
32
- const state = getCodexRateLimitCacheState();
33
- if (state.value === undefined || state.updatedAtMs === undefined) {
34
- return undefined;
35
- }
36
- const nowMs = options?.nowMs ?? Date.now();
37
- const maxAgeMs = options?.maxAgeMs ?? DEFAULT_CODEX_RATE_LIMIT_CACHE_MAX_AGE_MS;
38
- if (maxAgeMs >= 0 && nowMs - state.updatedAtMs > maxAgeMs) {
39
- return undefined;
40
- }
41
- return state.value;
42
- }
43
-
44
- export function resetCodexRateLimitCacheForTests(): void {
45
- const state = getCodexRateLimitCacheState();
46
- state.value = undefined;
47
- state.updatedAtMs = undefined;
48
- }
@@ -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
- }