Wait out a usage limit and retry, without counting it as a failed run

This commit is contained in:
2026-10-02 22:45:27 +02:00
parent 796d7d4901
commit e7ff869398
11 changed files with 106 additions and 23 deletions
+19 -3
View File
@@ -1,21 +1,37 @@
import sys
import time
import typing
from loop_claude.effects import Effects
from loop_claude.failure import Failure
from loop_claude.failure import Failure, Limited
from loop_claude.stop import Stop
T = typing.TypeVar("T")
PAST_RESET = 120
UNKNOWN_RESET_POLL = 600
def retried(who: str, attempt: typing.Callable[[], T | Failure], effects: Effects) -> T | Stop:
def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effects: Effects) -> T | Stop:
failures = 0
while True:
failures += 1
result = attempt()
if isinstance(result, Limited):
due = retry_due(result, effects.now())
print(f"the {who} hit a usage limit; retrying at {time.strftime('%Y-%m-%d %H:%M', time.localtime(due))}", file=sys.stderr, flush=True)
effects.sleep(due - effects.now())
continue
if not isinstance(result, Failure):
return result
failures += 1
if failures == 3:
return Stop(1, f"the {who} failed three times running: {result.reason}")
print(f"retrying the {who} in a minute: {result.reason}", file=sys.stderr)
effects.sleep(60)
def retry_due(limited: Limited, now: float) -> float:
# A retry before the reset fails (https://platform.claude.com/docs/en/api/rate-limits), so polling sooner only spends requests.
if limited.resets_at is not None and limited.resets_at + PAST_RESET > now:
return limited.resets_at + PAST_RESET
return now + UNKNOWN_RESET_POLL