@botiverse/oar 0.101.1 → 0.103.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +7 -4
  2. package/dist/contracts/account-usage.d.ts +134 -3
  3. package/dist/contracts/account-usage.d.ts.map +1 -1
  4. package/dist/contracts/index.d.ts +1 -1
  5. package/dist/contracts/index.d.ts.map +1 -1
  6. package/dist/contracts/index.js.map +1 -1
  7. package/dist/contracts/runtime.d.ts +7 -1
  8. package/dist/contracts/runtime.d.ts.map +1 -1
  9. package/dist/contracts/runtime.js.map +1 -1
  10. package/dist/runtimes/antigravity/account-usage.d.ts +14 -0
  11. package/dist/runtimes/antigravity/account-usage.d.ts.map +1 -0
  12. package/dist/runtimes/antigravity/account-usage.js +134 -0
  13. package/dist/runtimes/antigravity/account-usage.js.map +1 -0
  14. package/dist/runtimes/antigravity/index.d.ts +1 -0
  15. package/dist/runtimes/antigravity/index.d.ts.map +1 -1
  16. package/dist/runtimes/antigravity/index.js +1 -0
  17. package/dist/runtimes/antigravity/index.js.map +1 -1
  18. package/dist/runtimes/antigravity/options.js +1 -1
  19. package/dist/runtimes/antigravity/options.js.map +1 -1
  20. package/dist/runtimes/antigravity/session.d.ts.map +1 -1
  21. package/dist/runtimes/antigravity/session.js +4 -0
  22. package/dist/runtimes/antigravity/session.js.map +1 -1
  23. package/dist/runtimes/claude/account-usage.d.ts.map +1 -1
  24. package/dist/runtimes/claude/account-usage.js +9 -6
  25. package/dist/runtimes/claude/account-usage.js.map +1 -1
  26. package/dist/runtimes/claude/index.d.ts +2 -0
  27. package/dist/runtimes/claude/index.d.ts.map +1 -1
  28. package/dist/runtimes/claude/index.js +3 -0
  29. package/dist/runtimes/claude/index.js.map +1 -1
  30. package/dist/runtimes/claude/limit-reset/driver.d.ts +148 -0
  31. package/dist/runtimes/claude/limit-reset/driver.d.ts.map +1 -0
  32. package/dist/runtimes/claude/limit-reset/driver.js +867 -0
  33. package/dist/runtimes/claude/limit-reset/driver.js.map +1 -0
  34. package/dist/runtimes/claude/limit-reset/index.d.ts +6 -0
  35. package/dist/runtimes/claude/limit-reset/index.d.ts.map +1 -0
  36. package/dist/runtimes/claude/limit-reset/index.js +58 -0
  37. package/dist/runtimes/claude/limit-reset/index.js.map +1 -0
  38. package/dist/runtimes/claude/limit-reset/screens.d.ts +109 -0
  39. package/dist/runtimes/claude/limit-reset/screens.d.ts.map +1 -0
  40. package/dist/runtimes/claude/limit-reset/screens.js +246 -0
  41. package/dist/runtimes/claude/limit-reset/screens.js.map +1 -0
  42. package/dist/runtimes/claude/limit-reset/terminal-screen.d.ts +38 -0
  43. package/dist/runtimes/claude/limit-reset/terminal-screen.d.ts.map +1 -0
  44. package/dist/runtimes/claude/limit-reset/terminal-screen.js +391 -0
  45. package/dist/runtimes/claude/limit-reset/terminal-screen.js.map +1 -0
  46. package/dist/runtimes/codex/account-usage.d.ts.map +1 -1
  47. package/dist/runtimes/codex/account-usage.js +6 -0
  48. package/dist/runtimes/codex/account-usage.js.map +1 -1
  49. package/dist/runtimes/grok/account-usage.d.ts.map +1 -1
  50. package/dist/runtimes/grok/account-usage.js +2 -0
  51. package/dist/runtimes/grok/account-usage.js.map +1 -1
  52. package/dist/runtimes/kimi/account-usage.d.ts.map +1 -1
  53. package/dist/runtimes/kimi/account-usage.js +3 -0
  54. package/dist/runtimes/kimi/account-usage.js.map +1 -1
  55. package/dist/shared/acp/profile.d.ts +1 -0
  56. package/dist/shared/acp/profile.d.ts.map +1 -1
  57. package/dist/shared/acp/profile.js.map +1 -1
  58. package/dist/shared/acp/terminal.js +3 -3
  59. package/dist/shared/acp/terminal.js.map +1 -1
  60. package/dist/shared/acp/turns.d.ts.map +1 -1
  61. package/dist/shared/acp/turns.js +4 -3
  62. package/dist/shared/acp/turns.js.map +1 -1
  63. package/dist/shared/control-input.d.ts +5 -0
  64. package/dist/shared/control-input.d.ts.map +1 -1
  65. package/dist/shared/control-input.js +14 -0
  66. package/dist/shared/control-input.js.map +1 -1
  67. package/dist/shared/executable/environment-marker.d.ts +2 -2
  68. package/dist/shared/executable/environment-marker.d.ts.map +1 -1
  69. package/dist/shared/executable/environment-marker.js +3 -3
  70. package/dist/shared/executable/environment-marker.js.map +1 -1
  71. package/dist/shared/executable/host-watchdog.d.ts.map +1 -1
  72. package/dist/shared/executable/host-watchdog.js +11 -1
  73. package/dist/shared/executable/host-watchdog.js.map +1 -1
  74. package/dist/shared/executable/index.d.ts +1 -0
  75. package/dist/shared/executable/index.d.ts.map +1 -1
  76. package/dist/shared/executable/index.js +1 -0
  77. package/dist/shared/executable/index.js.map +1 -1
  78. package/dist/shared/executable/isolated.d.ts.map +1 -1
  79. package/dist/shared/executable/isolated.js +3 -2
  80. package/dist/shared/executable/isolated.js.map +1 -1
  81. package/dist/shared/executable/node-script.js +3 -3
  82. package/dist/shared/executable/node-script.js.map +1 -1
  83. package/dist/shared/executable/process-table-command.d.ts.map +1 -1
  84. package/dist/shared/executable/process-table-command.js +2 -1
  85. package/dist/shared/executable/process-table-command.js.map +1 -1
  86. package/dist/shared/executable/run.d.ts.map +1 -1
  87. package/dist/shared/executable/run.js +3 -3
  88. package/dist/shared/executable/run.js.map +1 -1
  89. package/dist/shared/executable/script-terminal.d.ts +92 -0
  90. package/dist/shared/executable/script-terminal.d.ts.map +1 -0
  91. package/dist/shared/executable/script-terminal.js +330 -0
  92. package/dist/shared/executable/script-terminal.js.map +1 -0
  93. package/dist/shared/login.js +3 -3
  94. package/dist/shared/login.js.map +1 -1
  95. package/dist/shared/shell-environment.d.ts.map +1 -1
  96. package/dist/shared/shell-environment.js +2 -1
  97. package/dist/shared/shell-environment.js.map +1 -1
  98. package/package.json +1 -1
@@ -0,0 +1,867 @@
1
+ /* oxlint-disable eslint/max-lines -- One driver: the session, its key rules and both flows read together. */
2
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { CLAUDE_LIMIT_RESET_KINDS, claudeLimitResetCommand, bannerVersion, commandScreen, confirmDialog, hasDialogFooter, inputLine, isSignInScreen, promptInput, trustScreen, } from "./screens.js";
6
+ import { openScriptTerminal } from "../../../shared/executable/script-terminal.js";
7
+ import { TerminalScreen } from "./terminal-screen.js";
8
+ /**
9
+ * Claude Code's limit resets, used and read by driving its own terminal UI.
10
+ *
11
+ * Claude Code has no non-interactive way to spend or list limit resets: only
12
+ * the hidden `/limit-reset` command of the interactive UI. So this starts the
13
+ * person's own `claude` in a pseudo-terminal, types the command, and reads
14
+ * the screen. It runs only on the account owner's explicit request, one
15
+ * session at a time in this process, and it fails closed:
16
+ *
17
+ * - No version list: any Claude Code is driven whose banner shows a version,
18
+ * and every screen must match the recorded text word for word. A version
19
+ * that changed a screen ends the attempt there (`unknown`, or
20
+ * `unsupported_version` before the command).
21
+ * - The command always names a kind. A bare `/limit-reset` can spend a reset
22
+ * with no confirmation.
23
+ * - Enter is sent in three places only (`ClaudeSession`): to accept the
24
+ * folder-trust screen, to submit a command whose text the input box shows
25
+ * exactly, and (redeem only) once on the confirmation dialog for the kind
26
+ * the person chose. A read's session cannot send the third.
27
+ * - From the moment a command is submitted until a screen that is positively
28
+ * recognised shows it finished, the only key that can be sent is Esc (or
29
+ * that one Yes). A session is ended by killing it, never by typing.
30
+ * - Any screen that is not positively recognised ends the attempt with Esc.
31
+ *
32
+ * One hazard cannot be closed from here. An account on Claude's older
33
+ * program (one 5-hour reset a week, no kinds) spends that reset as soon as ANY
34
+ * `/limit-reset …` is submitted while Claude Code is at the 5-hour limit,
35
+ * with no dialog. So:
36
+ *
37
+ * - A redeem of any kind but the 5-hour one is refused unless Claude Code's
38
+ * cached feature flags say the newer program is on. (A fresh flag fetch can
39
+ * still disagree with that cache.) A 5-hour redeem runs either way: spending
40
+ * the 5-hour reset is what the person clicked.
41
+ * - A read on an account at its 5-hour limit is refused without the person's
42
+ * consent to that risk (see `read`), and stops at the first line the older
43
+ * program prints.
44
+ * - What the server said about the 5-hour limit can be minutes old. So right
45
+ * before the first command of a read without that consent, or of a redeem
46
+ * of any kind but the 5-hour one, OAR reads usage again itself and
47
+ * types only if that read shows the account NOT at its 5-hour limit.
48
+ * - When the older program did spend its reset for something else, the answer
49
+ * says so (`fiveHourSpent`).
50
+ */
51
+ /** The Claude Code version whose `/limit-reset` screens the recognisers were recorded from. */
52
+ export const CLAUDE_LIMIT_RESET_RECORDED_VERSION = "2.1.322";
53
+ /** The whole budget of one call, from its arrival, unless the caller gives one. */
54
+ export const CLAUDE_LIMIT_RESET_TIMEOUT_MS = 75_000;
55
+ const TERMINAL_COLS = 120;
56
+ const TERMINAL_ROWS = 45;
57
+ /** Claude Code ignores keys for about 250 ms after a dialog opens; wait well past that before any key. */
58
+ export const CLAUDE_DIALOG_KEY_GUARD_MS = 600;
59
+ /**
60
+ * What must be left of the attempt's time before Yes is sent: Claude Code's
61
+ * own claim request can take 25 s, and an answer that comes after the
62
+ * deadline is a spent reset reported as unknown.
63
+ */
64
+ export const CLAUDE_CLAIM_WINDOW_MS = 30_000;
65
+ /** After the prompt first shows, Claude Code is still fetching the flags that decide what `/limit-reset` does. */
66
+ const STARTUP_SETTLE_MS = 3000;
67
+ const STARTUP_TIMEOUT_MS = 30_000;
68
+ const TYPE_SETTLE_MS = 400;
69
+ const TYPE_TIMEOUT_MS = 5000;
70
+ const COMMAND_TIMEOUT_MS = 20_000;
71
+ const CLOSE_TIMEOUT_MS = 5000;
72
+ /** How many times the dialog may still be repainting when its key guard ends before the attempt gives up. */
73
+ const STABLE_SCREEN_TRIES = 5;
74
+ /** A request that would start with less than this left is not started: a redeem must still reach its dialog with the claim window to spare. */
75
+ const REDEEM_MIN_START_MS = CLAUDE_CLAIM_WINDOW_MS + COMMAND_TIMEOUT_MS + STARTUP_SETTLE_MS;
76
+ const READ_MIN_START_MS = 20_000;
77
+ /**
78
+ * What must be left right before a command is submitted. On the older program
79
+ * the submission itself spends the 5-hour reset, so a redeem must still have
80
+ * the command's time and the claim window ahead of it, or its answer is cut
81
+ * into an unknown; a read must still have the command's time.
82
+ */
83
+ export const CLAUDE_REDEEM_MIN_SUBMIT_MS = CLAUDE_CLAIM_WINDOW_MS + COMMAND_TIMEOUT_MS;
84
+ const READ_MIN_SUBMIT_MS = COMMAND_TIMEOUT_MS;
85
+ /** How long the fresh usage read before the first command may take. */
86
+ const FIVE_HOUR_CHECK_TIMEOUT_MS = 15_000;
87
+ /** Requests that may wait behind the running one; more are refused at once. */
88
+ const MAX_WAITING = 2;
89
+ const ENTER = "\r";
90
+ const ESCAPE = "\u001B";
91
+ const ARROW_DOWN = "\u001B[B";
92
+ /** The kinds a read opens, in order; the 5-hour kind last and only when asked. */
93
+ const READ_ORDER = ["weekly", "fable", "full", "five_hour"];
94
+ /** The 5-hour limit as a usage snapshot shows it: one `five_hour` window. */
95
+ export function claudeFiveHourLimitOf(snapshot) {
96
+ if (snapshot.kind !== "available") {
97
+ return "unknown";
98
+ }
99
+ const windows = snapshot.windows.filter((window) => window.id === "five_hour");
100
+ const [window] = windows;
101
+ if (windows.length !== 1 || window === undefined) {
102
+ return "unknown";
103
+ }
104
+ return window.usedRatio >= 1 ? "at_limit" : "not_at_limit";
105
+ }
106
+ /**
107
+ * Linux only. macOS's BSD `script` refuses a socket as its stdin, which is
108
+ * what Node's pipes are there (seen on macOS 27.0, #752), so it exits
109
+ * before starting the program; Windows has neither `script` nor a POSIX
110
+ * shell.
111
+ */
112
+ function isDrivablePlatform(platform) {
113
+ return platform === "linux";
114
+ }
115
+ /**
116
+ * Claude Code keeps the feature flags it last fetched in its config file. Only
117
+ * the one boolean is read; the file's account fields are not touched.
118
+ */
119
+ async function readCachedFlags(env) {
120
+ const configDir = env.CLAUDE_CONFIG_DIR;
121
+ const configPath = configDir !== undefined && configDir !== ""
122
+ ? path.join(configDir, ".claude.json")
123
+ : path.join(env.HOME ?? os.homedir(), ".claude.json");
124
+ try {
125
+ const config = JSON.parse(await readFile(configPath, "utf8"));
126
+ // cachedGrowthBookFeatures.tengu_cedar_ember.enabled; anything else on the way is no answer.
127
+ const features = typeof config === "object" && config !== null && "cachedGrowthBookFeatures" in config ? config.cachedGrowthBookFeatures : undefined;
128
+ const flag = typeof features === "object" && features !== null && "tengu_cedar_ember" in features ? features.tengu_cedar_ember : undefined;
129
+ const enabled = typeof flag === "object" && flag !== null && "enabled" in flag ? flag.enabled : undefined;
130
+ return { limitResets: typeof enabled === "boolean" ? enabled : null };
131
+ }
132
+ catch {
133
+ return { limitResets: null };
134
+ }
135
+ }
136
+ /**
137
+ * A new empty directory for the session, so no project settings or hooks
138
+ * apply. Claude Code asks once to trust each new directory (accepted below,
139
+ * it is empty) and keeps one entry for it in its config.
140
+ */
141
+ async function makeWorkDir() {
142
+ const directory = await mkdtemp(path.join(os.tmpdir(), "oar-claude-limit-reset-"));
143
+ return {
144
+ path: directory,
145
+ remove: async () => {
146
+ await rm(directory, { recursive: true, force: true });
147
+ },
148
+ };
149
+ }
150
+ /**
151
+ * One running Claude Code UI: its screen, its keyboard, and the attempt's
152
+ * deadline. Every key goes through here, and what may be sent depends on two
153
+ * facts it keeps:
154
+ *
155
+ * - `commandOutstanding`: a command was submitted and no recognised screen
156
+ * has shown it finished. Until then nothing can be typed; only Esc, and
157
+ * the one Yes.
158
+ * - `yesSent`: the confirmation was accepted. After that the command stays
159
+ * outstanding for good, so nothing but Esc is ever sent again.
160
+ */
161
+ class ClaudeSession {
162
+ terminal;
163
+ deadlineAt;
164
+ mayConfirm;
165
+ onScreen;
166
+ screen = new TerminalScreen(TERMINAL_COLS, TERMINAL_ROWS);
167
+ wakers = new Set();
168
+ exited = false;
169
+ changedAt = 0;
170
+ commandOutstanding = false;
171
+ yesSent = false;
172
+ /** The version the banner showed, once the prompt was reached. */
173
+ version;
174
+ constructor(terminal, deadlineAt,
175
+ /** False for a read: its session has no way to send the confirmation. */
176
+ mayConfirm, onScreen) {
177
+ this.terminal = terminal;
178
+ this.deadlineAt = deadlineAt;
179
+ this.mayConfirm = mayConfirm;
180
+ this.onScreen = onScreen;
181
+ terminal.onData((chunk) => {
182
+ const before = this.screen.text();
183
+ this.screen.write(chunk);
184
+ if (this.screen.text() !== before) {
185
+ this.changedAt = Date.now();
186
+ }
187
+ this.wake();
188
+ });
189
+ terminal.onExit(() => {
190
+ this.exited = true;
191
+ this.wake();
192
+ });
193
+ }
194
+ wake() {
195
+ // oxlint-disable-next-line unicorn/no-useless-spread -- A snapshot: each waker that finishes removes itself from the set.
196
+ for (const waker of [...this.wakers]) {
197
+ waker();
198
+ }
199
+ }
200
+ text() {
201
+ return this.screen.text();
202
+ }
203
+ note(step) {
204
+ this.onScreen?.(step, this.text());
205
+ }
206
+ remainingMs() {
207
+ return this.deadlineAt - Date.now();
208
+ }
209
+ /** Keys at a screen that is not a command's: the folder-trust screen, or text into the empty prompt. Refused while a command is outstanding. */
210
+ type(keys) {
211
+ if (this.exited || this.commandOutstanding) {
212
+ return false;
213
+ }
214
+ this.terminal.write(keys);
215
+ return true;
216
+ }
217
+ /** The Enter that submits the typed command. From here the command is outstanding. */
218
+ submit() {
219
+ if (this.exited || this.commandOutstanding) {
220
+ return false;
221
+ }
222
+ this.commandOutstanding = true;
223
+ this.terminal.write(ENTER);
224
+ return true;
225
+ }
226
+ /** A recognised screen showed the command finished with the prompt back, so the next one may be typed. Never after a Yes. */
227
+ commandSettled() {
228
+ if (!this.yesSent) {
229
+ this.commandOutstanding = false;
230
+ }
231
+ }
232
+ /** Esc cancels whatever is open and confirms nothing; always allowed. */
233
+ escape() {
234
+ if (!this.exited) {
235
+ this.terminal.write(ESCAPE);
236
+ }
237
+ }
238
+ /** The Yes: Enter on the open confirmation dialog, at most once in a session, and never in a read's. */
239
+ confirmOnce() {
240
+ if (this.exited || !this.mayConfirm || !this.commandOutstanding || this.yesSent) {
241
+ return false;
242
+ }
243
+ this.yesSent = true;
244
+ this.terminal.write(ENTER);
245
+ return true;
246
+ }
247
+ /** The first non-null `probe` of the screen; null when `withinMs` or the attempt's deadline passes, or Claude Code exits. */
248
+ // oxlint-disable-next-line typescript/promise-function-async -- Settled by the screen's wakers and a timer, not by awaiting.
249
+ waitFor(probe, withinMs) {
250
+ return new Promise((resolve) => {
251
+ const finish = (value) => {
252
+ clearTimeout(timer);
253
+ this.wakers.delete(check);
254
+ resolve(value);
255
+ };
256
+ const check = () => {
257
+ const value = probe(this.text());
258
+ if (value !== null) {
259
+ finish(value);
260
+ }
261
+ else if (this.exited) {
262
+ finish(null);
263
+ }
264
+ };
265
+ const withinDeadlineMs = Math.max(0, Math.min(withinMs, this.remainingMs()));
266
+ const timer = setTimeout(() => { finish(null); }, withinDeadlineMs);
267
+ this.wakers.add(check);
268
+ check();
269
+ });
270
+ }
271
+ /** Waits `ms`; false when the attempt's deadline would pass first or Claude Code has exited. */
272
+ async pause(ms) {
273
+ if (this.exited || ms > this.remainingMs()) {
274
+ return false;
275
+ }
276
+ await new Promise((resolve) => { setTimeout(resolve, ms); });
277
+ return !this.exited;
278
+ }
279
+ /**
280
+ * Waits out the dialog key guard until nothing on the screen has changed
281
+ * for one whole guard, so a key never lands on a dialog that is still being
282
+ * drawn or was just redrawn. False when the deadline comes first or the
283
+ * screen never holds still.
284
+ */
285
+ async pauseUntilStable() {
286
+ for (let tries = 0; tries < STABLE_SCREEN_TRIES; tries += 1) {
287
+ if (!await this.pause(CLAUDE_DIALOG_KEY_GUARD_MS)) {
288
+ return false;
289
+ }
290
+ if (Date.now() - this.changedAt >= CLAUDE_DIALOG_KEY_GUARD_MS) {
291
+ return true;
292
+ }
293
+ }
294
+ return false;
295
+ }
296
+ /** Ends the session by ending its processes; nothing is typed to leave. */
297
+ async close() {
298
+ await this.terminal.kill();
299
+ }
300
+ }
301
+ /**
302
+ * Brings Claude Code to its prompt. A working directory it has not seen gets
303
+ * the folder-trust screen, which opens on "No, exit": Yes is selected first
304
+ * and Enter sent only once the screen shows it selected. The directory is
305
+ * one this driver just made empty. A sign-in screen means no usable login.
306
+ * The prompt counts only under the banner of a tested version (the trust
307
+ * screen comes before any banner).
308
+ */
309
+ async function openPrompt(session) {
310
+ let trustAccepted = false;
311
+ for (;;) {
312
+ // Fixed for this wait; it changes only once the wait is over.
313
+ const lookForTrust = !trustAccepted;
314
+ const seen = await session.waitFor((screen) => {
315
+ if (isSignInScreen(screen)) {
316
+ return "sign_in";
317
+ }
318
+ if (lookForTrust && trustScreen(screen)) {
319
+ return "trust";
320
+ }
321
+ return promptInput(screen) === "" ? "prompt" : null;
322
+ }, STARTUP_TIMEOUT_MS);
323
+ if (seen === null) {
324
+ return "failed";
325
+ }
326
+ if (seen === "sign_in") {
327
+ return "sign_in";
328
+ }
329
+ if (seen === "trust") {
330
+ session.note("trust");
331
+ if (!await session.pauseUntilStable()) {
332
+ return "failed";
333
+ }
334
+ if (trustScreen(session.text()) === "no_selected") {
335
+ session.type(ARROW_DOWN);
336
+ if (await session.waitFor((screen) => (trustScreen(screen) === "yes_selected" ? true : null), CLOSE_TIMEOUT_MS) === null) {
337
+ return "failed";
338
+ }
339
+ if (!await session.pauseUntilStable()) {
340
+ return "failed";
341
+ }
342
+ }
343
+ if (trustScreen(session.text()) !== "yes_selected") {
344
+ return "failed";
345
+ }
346
+ session.type(ENTER);
347
+ trustAccepted = true;
348
+ continue;
349
+ }
350
+ if (!await session.pause(STARTUP_SETTLE_MS)) {
351
+ return "failed";
352
+ }
353
+ const screen = session.text();
354
+ if (isSignInScreen(screen)) {
355
+ return "sign_in";
356
+ }
357
+ if (promptInput(screen) !== "") {
358
+ continue;
359
+ }
360
+ const banner = bannerVersion(screen);
361
+ if (banner === null) {
362
+ return "wrong_version";
363
+ }
364
+ session.version = banner;
365
+ return "ready";
366
+ }
367
+ }
368
+ /**
369
+ * Types `command` at the empty prompt and submits it, only once the input box
370
+ * shows exactly that text: a keystroke lost on the way must not turn it into
371
+ * a bare `/limit-reset`.
372
+ */
373
+ async function submitCommand(session, command) {
374
+ if (promptInput(session.text()) !== "") {
375
+ return false;
376
+ }
377
+ if (!session.type(command)) {
378
+ return false;
379
+ }
380
+ if (!await session.pause(TYPE_SETTLE_MS)) {
381
+ return false;
382
+ }
383
+ if (!await session.waitFor((screen) => (inputLine(screen) === command ? true : null), TYPE_TIMEOUT_MS)) {
384
+ return false;
385
+ }
386
+ return session.submit();
387
+ }
388
+ /**
389
+ * Checked right before a command is submitted. `checkFiveHourLimit`: the
390
+ * submission could spend the older program's 5-hour reset unasked, so usage
391
+ * is read again now and the command goes only if it shows the account not at
392
+ * that limit. The time left is checked before and after that read.
393
+ */
394
+ async function maySubmit(session, minRemainingMs, fiveHourLimit) {
395
+ if (session.remainingMs() < minRemainingMs) {
396
+ return "budget";
397
+ }
398
+ if (fiveHourLimit) {
399
+ let timer = undefined;
400
+ const limit = await Promise.race([
401
+ fiveHourLimit().catch(() => "unknown"),
402
+ new Promise((resolve) => { timer = setTimeout(() => { resolve("unknown"); }, FIVE_HOUR_CHECK_TIMEOUT_MS); }),
403
+ ]);
404
+ clearTimeout(timer);
405
+ if (limit === "at_limit") {
406
+ return "at_limit";
407
+ }
408
+ if (limit !== "not_at_limit") {
409
+ return "usage_unread";
410
+ }
411
+ if (session.remainingMs() < minRemainingMs) {
412
+ return "budget";
413
+ }
414
+ }
415
+ return null;
416
+ }
417
+ /**
418
+ * What the submitted command led to; `pending` when nothing recognisable came
419
+ * in time. A result line or "unknown command" under a returned prompt is the
420
+ * recognised end of the command.
421
+ */
422
+ async function awaitCommand(session, command, withinMs, settled) {
423
+ const seen = await session.waitFor((screen) => {
424
+ const shown = commandScreen(screen, command);
425
+ return settled(shown) ? shown : null;
426
+ }, withinMs);
427
+ if (seen?.is === "result" || seen?.is === "no_command") {
428
+ session.commandSettled();
429
+ }
430
+ return seen ?? { is: "pending" };
431
+ }
432
+ /** Esc, after the dialog key guard; whether no dialog is left afterwards. */
433
+ async function cancelWithEscape(session) {
434
+ if (!await session.pause(CLAUDE_DIALOG_KEY_GUARD_MS)) {
435
+ return false;
436
+ }
437
+ session.escape();
438
+ return await session.waitFor((screen) => (hasDialogFooter(screen) ? null : true), CLOSE_TIMEOUT_MS) === true;
439
+ }
440
+ /** Esc on the confirmation dialog, then whether Claude Code said the reset was kept. */
441
+ async function cancelAndSeeKept(session, command) {
442
+ await cancelWithEscape(session);
443
+ const closed = await awaitCommand(session, command, CLOSE_TIMEOUT_MS, (screen) => screen.is === "result");
444
+ return closed.is === "result" && closed.line.is === "kept";
445
+ }
446
+ const BUSY = { kind: "not_attempted", reason: "busy" };
447
+ const DEADLINE = { kind: "not_attempted", reason: "deadline" };
448
+ const STARTUP_FAILED = { kind: "not_attempted", reason: "startup_failed" };
449
+ const CONSENT_REQUIRED = { kind: "unsupported", reason: "consent_required" };
450
+ const NO_COMMAND = { kind: "unsupported", reason: "endpoint_unavailable" };
451
+ /** What a refusal before the first command answers; nothing was typed. */
452
+ function refusalResult(refused) {
453
+ return refused === "budget" ? DEADLINE : (refused === "at_limit" ? CONSENT_REQUIRED : { kind: "not_attempted", reason: "usage_unread" });
454
+ }
455
+ function unknownAt(step) {
456
+ return { result: { kind: "unknown" }, step, remember: true };
457
+ }
458
+ async function redeemInSession(session, kind, fiveHourLimit) {
459
+ const opened = await openPrompt(session);
460
+ session.note("startup");
461
+ if (opened === "sign_in") {
462
+ return { result: { kind: "reauth_required", reason: "not_authenticated" }, step: "sign_in", remember: false };
463
+ }
464
+ if (opened === "wrong_version") {
465
+ return { result: { kind: "unsupported", reason: "unsupported_version" }, step: "version", remember: false };
466
+ }
467
+ if (opened === "failed") {
468
+ return { result: STARTUP_FAILED, step: "startup", remember: false };
469
+ }
470
+ // Nothing has been typed yet: a refusal here spent nothing, and the same click may try again.
471
+ const refused = await maySubmit(session, CLAUDE_REDEEM_MIN_SUBMIT_MS, kind === "five_hour" ? null : fiveHourLimit);
472
+ if (refused) {
473
+ return { result: refusalResult(refused), step: refused === "budget" ? "budget" : "usage", remember: false };
474
+ }
475
+ const command = claudeLimitResetCommand(kind);
476
+ if (!await submitCommand(session, command)) {
477
+ return { result: { kind: "unknown" }, step: "type_command", remember: false };
478
+ }
479
+ const shown = await awaitCommand(session, command, COMMAND_TIMEOUT_MS, (screen) => screen.is !== "pending");
480
+ session.note("command");
481
+ switch (shown.is) {
482
+ case "pending":
483
+ await cancelWithEscape(session);
484
+ return unknownAt("command");
485
+ case "no_command":
486
+ return { result: NO_COMMAND, step: "command", remember: true };
487
+ case "other_dialog":
488
+ await cancelWithEscape(session);
489
+ return unknownAt("dialog");
490
+ case "confirm":
491
+ break;
492
+ case "result":
493
+ switch (shown.line.is) {
494
+ case "none":
495
+ return { result: { kind: "no_reset" }, remember: true };
496
+ case "legacy_unavailable":
497
+ // The older program's "isn't available right now" may only mean the
498
+ // account is not at its 5-hour limit yet, not that it holds none. It
499
+ // has no other kinds at all.
500
+ return { result: kind === "five_hour" ? { kind: "nothing_to_reset" } : { kind: "no_reset" }, remember: true };
501
+ case "needs_limit":
502
+ return { result: { kind: "nothing_to_reset" }, remember: true };
503
+ case "legacy_reset":
504
+ // The older program spent its 5-hour reset with no dialog. That is
505
+ // what a 5-hour click asked for; for any other kind it is not, and
506
+ // the answer says what was spent instead.
507
+ return kind === "five_hour"
508
+ ? { result: { kind: "reset" }, remember: true }
509
+ : { result: { kind: "unknown", fiveHourSpent: true }, step: "result", remember: true };
510
+ case "kept":
511
+ case "reset":
512
+ case "unrecognised":
513
+ return unknownAt("result");
514
+ }
515
+ }
516
+ if (shown.dialog.kind !== kind) {
517
+ await cancelWithEscape(session);
518
+ return unknownAt("dialog");
519
+ }
520
+ if (!await session.pauseUntilStable()) {
521
+ session.escape();
522
+ return unknownAt("confirm");
523
+ }
524
+ if (confirmDialog(session.text())?.kind !== kind) {
525
+ await cancelWithEscape(session);
526
+ return unknownAt("confirm");
527
+ }
528
+ if (session.remainingMs() < CLAUDE_CLAIM_WINDOW_MS) {
529
+ // Too late to wait for the claim's answer: keep the reset and say nothing was done.
530
+ return await cancelAndSeeKept(session, command)
531
+ ? { result: DEADLINE, step: "confirm", remember: false }
532
+ : unknownAt("confirm");
533
+ }
534
+ // The one Yes of the attempt: the dialog names the chosen kind, its Yes row is selected, and it has held still.
535
+ if (!session.confirmOnce()) {
536
+ return unknownAt("confirm");
537
+ }
538
+ const after = await awaitCommand(session, command, CLAUDE_CLAIM_WINDOW_MS, (screen) => screen.is === "result" || screen.is === "other_dialog" || screen.is === "no_command");
539
+ session.note("result");
540
+ if (after.is === "result" && after.line.is === "reset" && after.line.kind === kind) {
541
+ return { result: { kind: "reset" }, remember: true };
542
+ }
543
+ return unknownAt("result");
544
+ }
545
+ /**
546
+ * Opens each kind's command and cancels it with Esc. Its session is made
547
+ * with `mayConfirm` off, so `confirmOnce` sends nothing, and this function
548
+ * does not call it. The Enters it does send are the folder-trust accept and
549
+ * `submitCommand`'s at a prompt that shows exactly the typed command; neither
550
+ * can be sent while a command is outstanding. (On Claude's older program the
551
+ * submission itself is what spends: see the consent in `read`.)
552
+ */
553
+ async function readInSession(session, kinds, fiveHourLimit) {
554
+ const opened = await openPrompt(session);
555
+ session.note("startup");
556
+ if (opened === "sign_in") {
557
+ return { result: { kind: "reauth_required", reason: "not_authenticated" }, step: "sign_in" };
558
+ }
559
+ if (opened === "wrong_version") {
560
+ return { result: { kind: "unsupported", reason: "unsupported_version" }, step: "version" };
561
+ }
562
+ if (opened === "failed") {
563
+ return { result: STARTUP_FAILED, step: "startup" };
564
+ }
565
+ const found = new Map();
566
+ let stoppedAt = undefined;
567
+ for (const kind of kinds) {
568
+ // After a screen that was not recognised nothing more is typed.
569
+ if (stoppedAt) {
570
+ found.set(kind, { id: kind, state: "unknown" });
571
+ continue;
572
+ }
573
+ // The usage check only before the first command: on the older program
574
+ // that is the only one ever submitted (its line ends the read).
575
+ const refused = await maySubmit(session, READ_MIN_SUBMIT_MS, found.size === 0 ? fiveHourLimit : null);
576
+ if (refused) {
577
+ if (found.size > 0) {
578
+ // Too little time for another command: the kinds left stay not_checked.
579
+ stoppedAt = "budget";
580
+ break;
581
+ }
582
+ return { result: refusalResult(refused), step: refused === "budget" ? "budget" : "usage" };
583
+ }
584
+ const command = claudeLimitResetCommand(kind);
585
+ if (!await submitCommand(session, command)) {
586
+ found.set(kind, { id: kind, state: "unknown" });
587
+ stoppedAt = "type_command";
588
+ continue;
589
+ }
590
+ const shown = await awaitCommand(session, command, COMMAND_TIMEOUT_MS, (screen) => screen.is !== "pending");
591
+ session.note(`command:${kind}`);
592
+ if (shown.is === "no_command") {
593
+ return { result: NO_COMMAND, step: "command" };
594
+ }
595
+ if (shown.is === "result" && (shown.line.is === "legacy_unavailable" || shown.line.is === "legacy_reset")) {
596
+ // The older program answered: it ignores the kind, so every further
597
+ // command would get the same answer, or at the limit spend its reset.
598
+ // `legacy_reset` means it just spent one, which only consent allows.
599
+ // Its "isn't available right now" may only mean the account is not at
600
+ // the 5-hour limit yet, so it is not read as holding none.
601
+ const spent = shown.line.is === "legacy_reset";
602
+ const fiveHour = { id: "five_hour", state: "unknown" };
603
+ return {
604
+ result: {
605
+ kind: "inspected",
606
+ program: "legacy",
607
+ ...(spent ? { fiveHourSpent: true } : {}),
608
+ resets: CLAUDE_LIMIT_RESET_KINDS.map((each) => (each === "five_hour" ? fiveHour : { id: each, state: "not_offered" })),
609
+ ...(session.version === undefined ? {} : { version: session.version }),
610
+ },
611
+ ...(spent ? { step: "result" } : {}),
612
+ };
613
+ }
614
+ if (shown.is === "result" && shown.line.is === "none") {
615
+ found.set(kind, { id: kind, state: "none" });
616
+ }
617
+ else if (shown.is === "result" && shown.line.is === "needs_limit") {
618
+ // Held, but usable only at a limit; that line's count is not per kind.
619
+ found.set(kind, { id: kind, state: "available" });
620
+ }
621
+ else if (shown.is === "confirm" && shown.dialog.kind === kind) {
622
+ found.set(kind, {
623
+ id: kind,
624
+ state: "available",
625
+ resetsLeft: shown.dialog.resetsLeft,
626
+ expiresText: shown.dialog.expiresText,
627
+ });
628
+ const kept = await cancelAndSeeKept(session, command);
629
+ session.note(`cancel:${kind}`);
630
+ if (!kept) {
631
+ stoppedAt = "dialog";
632
+ }
633
+ }
634
+ else {
635
+ found.set(kind, { id: kind, state: "unknown" });
636
+ stoppedAt = shown.is === "result" ? "result" : (shown.is === "pending" ? "command" : "dialog");
637
+ if (shown.is !== "result") {
638
+ await cancelWithEscape(session);
639
+ }
640
+ }
641
+ }
642
+ return {
643
+ result: {
644
+ kind: "inspected",
645
+ resets: CLAUDE_LIMIT_RESET_KINDS.map((kind) => found.get(kind) ?? { id: kind, state: "not_checked" }),
646
+ ...(session.version === undefined ? {} : { version: session.version }),
647
+ },
648
+ ...(stoppedAt ? { step: stoppedAt } : {}),
649
+ };
650
+ }
651
+ export function createClaudeLimitResetDriver(deps = {}) {
652
+ const defaultTimeoutMs = deps.timeoutMs ?? CLAUDE_LIMIT_RESET_TIMEOUT_MS;
653
+ // One Claude Code session at a time in this process. A request that
654
+ // arrives while another runs waits its turn, but its clock started when it
655
+ // arrived: if too little of its budget is left when its turn comes it is
656
+ // refused without starting anything (`not_attempted: deadline`), and so is
657
+ // one that finds MAX_WAITING already waiting (`not_attempted: busy`).
658
+ // Nothing was spent either way; try again.
659
+ let tail = Promise.resolve();
660
+ let queued = 0;
661
+ /**
662
+ * Runs `run` when the session slot is free. A call that is still waiting at
663
+ * `deadlineAt` answers `expired()` then and never starts; it frees its
664
+ * waiting place at once.
665
+ */
666
+ const exclusive = (run, deadlineAt, expired) => {
667
+ if (queued > MAX_WAITING) {
668
+ return null;
669
+ }
670
+ queued += 1;
671
+ // An object, so the timer's and the turn's changes are seen by each other's checks.
672
+ const entry = { state: "waiting" };
673
+ const answer = Promise.withResolvers();
674
+ const timer = setTimeout(() => {
675
+ if (entry.state !== "waiting") {
676
+ return;
677
+ }
678
+ entry.state = "expired";
679
+ queued -= 1;
680
+ answer.resolve(expired());
681
+ }, Math.max(0, deadlineAt - Date.now()));
682
+ const turn = async () => {
683
+ if (entry.state === "expired") {
684
+ return;
685
+ }
686
+ entry.state = "running";
687
+ clearTimeout(timer);
688
+ try {
689
+ answer.resolve(await run());
690
+ }
691
+ catch (error) {
692
+ answer.reject(error);
693
+ }
694
+ finally {
695
+ queued -= 1;
696
+ }
697
+ };
698
+ // oxlint-disable-next-line promise/prefer-await-to-then -- A queue: the turn is chained now, so the tail is set before this returns.
699
+ tail = tail.then(turn, turn);
700
+ return answer.promise;
701
+ };
702
+ // The wire to Claude Code has no idempotency key, so this remembers each
703
+ // key's attempt, in memory: a retry with the same key gets the first
704
+ // attempt's answer instead of a second Yes. It does not survive the
705
+ // process; after a restart, a retry of an attempt whose answer was lost is
706
+ // a new attempt. Nothing is dropped: an attempt that may have spent a
707
+ // reset must never become executable again within the process. Only
708
+ // attempts that typed a command are kept, each one person's request.
709
+ const attempts = new Map();
710
+ const preflight = async (input, needsNewerProgram) => {
711
+ const platform = deps.platform ?? process.platform;
712
+ if (!isDrivablePlatform(platform)) {
713
+ return { ok: false, refusal: { kind: "unsupported", reason: "unsupported_platform" }, step: "platform" };
714
+ }
715
+ const env = { ...(input.env ?? process.env) };
716
+ // A host started from inside Claude Code must not hand that marker down.
717
+ delete env.CLAUDECODE;
718
+ // Without consent, a kind but the 5-hour one goes only where Claude Code's
719
+ // last fetched flags say the newer program is on (a fresh fetch can still
720
+ // disagree, which the usage read before the command covers).
721
+ if (needsNewerProgram) {
722
+ const flags = await (deps.cachedFlags ?? readCachedFlags)(env);
723
+ if (flags.limitResets !== true) {
724
+ return { ok: false, refusal: { kind: "unsupported", reason: "consent_required" }, step: "flags" };
725
+ }
726
+ }
727
+ return { ok: true, command: input.command, env, platform };
728
+ };
729
+ /**
730
+ * Runs `drive` against a new Claude Code session in a new empty directory.
731
+ * The session's processes are ended, and that is waited for, before the
732
+ * directory is removed and before the next request's turn.
733
+ */
734
+ const withSession = async (ready, deadlineAt, mayConfirm, drive) => {
735
+ const workDir = await (deps.workDir ?? makeWorkDir)();
736
+ try {
737
+ const terminal = (deps.openTerminal ?? openScriptTerminal)({
738
+ command: ready.command,
739
+ cwd: workDir.path,
740
+ env: ready.env,
741
+ cols: TERMINAL_COLS,
742
+ rows: TERMINAL_ROWS,
743
+ platform: ready.platform,
744
+ });
745
+ if (!terminal) {
746
+ return null;
747
+ }
748
+ const session = new ClaudeSession(terminal, deadlineAt, mayConfirm, deps.onScreen);
749
+ try {
750
+ return await drive(session);
751
+ }
752
+ finally {
753
+ await session.close().catch(() => { });
754
+ }
755
+ }
756
+ finally {
757
+ await workDir.remove().catch(() => { });
758
+ }
759
+ };
760
+ const fiveHourCheck = (input, ready) =>
761
+ // oxlint-disable-next-line typescript/promise-function-async -- Hands on the caller's own usage read as it is.
762
+ () => input.fiveHourLimit ? input.fiveHourLimit() : (deps.fiveHourLimit ? deps.fiveHourLimit(ready.command, ready.env) : Promise.resolve("unknown"));
763
+ const redeemOnce = async (input, deadlineAt, timeoutMs) => {
764
+ if (deadlineAt - Date.now() < Math.min(REDEEM_MIN_START_MS, timeoutMs)) {
765
+ return { result: DEADLINE, step: "queue", remember: false };
766
+ }
767
+ const consent = input.fiveHourLimitConsent === true;
768
+ const ready = await preflight(input, input.kind !== "five_hour" && !consent);
769
+ if (!ready.ok) {
770
+ return { result: ready.refusal, step: ready.step, remember: false };
771
+ }
772
+ // oxlint-disable-next-line eslint/init-declarations -- Set in the session's finally; an initial undefined would read as always undefined to TypeScript.
773
+ let version;
774
+ const outcome = await withSession(ready, deadlineAt, true, async (session) => {
775
+ try {
776
+ return await redeemInSession(session, input.kind, consent ? null : fiveHourCheck(input, ready));
777
+ }
778
+ finally {
779
+ version = session.version;
780
+ }
781
+ });
782
+ if (!outcome) {
783
+ return { result: { kind: "unsupported", reason: "unsupported_platform" }, step: "terminal", remember: false };
784
+ }
785
+ return { result: outcome.result, ...(outcome.step ? { step: outcome.step } : {}), ...(version === undefined || version === "" ? {} : { claudeVersion: version }), remember: outcome.remember };
786
+ };
787
+ return {
788
+ // oxlint-disable-next-line typescript/promise-function-async -- A retry with the same key gets the first attempt's very promise.
789
+ redeem: (input) => {
790
+ const timeoutMs = input.timeoutMs ?? defaultTimeoutMs;
791
+ const deadlineAt = Date.now() + timeoutMs;
792
+ const earlier = attempts.get(input.idempotencyKey);
793
+ if (earlier) {
794
+ // One key is one request for one kind. The same key naming another
795
+ // kind is not a retry, and the first attempt's answer is not its answer.
796
+ if (earlier.kind !== input.kind) {
797
+ return Promise.reject(new Error("Claude limit reset: this idempotencyKey was used for another resetId"));
798
+ }
799
+ return earlier.report;
800
+ }
801
+ const attempt = { kind: input.kind, inFlight: true, report: Promise.resolve({ result: BUSY }) };
802
+ const report = exclusive(async () => {
803
+ // A throw after the session opened leaves it unknown what was sent.
804
+ const { remember, ...outcome } = await redeemOnce(input, deadlineAt, timeoutMs).catch(() => ({ result: { kind: "unknown" }, remember: true }));
805
+ attempt.inFlight = false;
806
+ if (!remember && attempts.get(input.idempotencyKey) === attempt) {
807
+ attempts.delete(input.idempotencyKey);
808
+ }
809
+ return outcome;
810
+ }, deadlineAt, () => {
811
+ // Never started: nothing was sent, so the same key may try again.
812
+ attempt.inFlight = false;
813
+ if (attempts.get(input.idempotencyKey) === attempt) {
814
+ attempts.delete(input.idempotencyKey);
815
+ }
816
+ return { result: DEADLINE, step: "queue" };
817
+ });
818
+ if (!report) {
819
+ return Promise.resolve({ result: BUSY, step: "queue" });
820
+ }
821
+ attempt.report = report;
822
+ attempts.set(input.idempotencyKey, attempt);
823
+ return report;
824
+ },
825
+ // oxlint-disable-next-line typescript/promise-function-async -- Answers with the queued run's own promise, as redeem does.
826
+ read: (input) => {
827
+ const timeoutMs = input.timeoutMs ?? defaultTimeoutMs;
828
+ const deadlineAt = Date.now() + timeoutMs;
829
+ // Refused before anything runs; see ClaudeLimitResetsReadInput. A caller that does not say counts as at the limit.
830
+ // oxlint-disable-next-line typescript/no-unnecessary-boolean-literal-compare -- JavaScript callers can omit it; only an explicit false goes on.
831
+ if (input.atFiveHourLimit !== false && input.atFiveHourLimitConsent !== true) {
832
+ return Promise.resolve({ result: CONSENT_REQUIRED, step: "consent" });
833
+ }
834
+ const kinds = READ_ORDER.filter((kind) => kind !== "five_hour" || input.includeFiveHour === true);
835
+ const report = exclusive(async () => {
836
+ try {
837
+ if (deadlineAt - Date.now() < Math.min(READ_MIN_START_MS, timeoutMs)) {
838
+ return { result: DEADLINE, step: "queue" };
839
+ }
840
+ const ready = await preflight(input, false);
841
+ if (!ready.ok) {
842
+ return { result: ready.refusal, step: ready.step };
843
+ }
844
+ // oxlint-disable-next-line eslint/init-declarations -- As in redeemOnce.
845
+ let version;
846
+ const outcome = await withSession(ready, deadlineAt, false, async (session) => {
847
+ try {
848
+ return await readInSession(session, kinds, input.atFiveHourLimitConsent === true ? null : fiveHourCheck(input, ready));
849
+ }
850
+ finally {
851
+ version = session.version;
852
+ }
853
+ });
854
+ if (!outcome) {
855
+ return { result: { kind: "unsupported", reason: "unsupported_platform" }, step: "terminal" };
856
+ }
857
+ return { result: outcome.result, ...(outcome.step ? { step: outcome.step } : {}), ...(version === undefined || version === "" ? {} : { claudeVersion: version }) };
858
+ }
859
+ catch {
860
+ return { result: { kind: "unknown" } };
861
+ }
862
+ }, deadlineAt, () => ({ result: DEADLINE, step: "queue" }));
863
+ return report ?? Promise.resolve({ result: BUSY, step: "queue" });
864
+ },
865
+ };
866
+ }
867
+ //# sourceMappingURL=driver.js.map