Files
claude-config/bin/loop_claude/cycle/retry.py
T

49 lines
1.6 KiB
Python

import dataclasses
import sys
import time
import typing
from loop_claude.effects import Effects
from loop_claude.failure import Failure
from loop_claude.stop import Stop
T = typing.TypeVar("T")
PAST_RESET = 120
UNKNOWN_RESET_POLL = 600
@dataclasses.dataclass(frozen=True)
class Limited:
"""claude hit a usage limit; said is claude's message about it, and resets_at is when the limit resets, in seconds since the epoch, or None when unknown."""
resets_at: int | None
said: str
def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effects: Effects) -> T | Stop:
failures = 0
while True:
result = attempt()
if isinstance(result, Limited):
# Hitting the limit proves claude started and reached the API, so the failures before it no longer run on.
failures = 0
now = effects.now()
wait = limit_wait(result, now)
print(f"the {who} hit a usage limit ({result.said}); retrying at {time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(now + wait))}", file=sys.stderr, flush=True)
effects.sleep(wait)
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 limit_wait(limited: Limited, now: float) -> float:
# The limit rejects every request until it resets, so wait for a known reset and poll rarely for an unknown one.
if limited.resets_at is not None and limited.resets_at + PAST_RESET > now:
return limited.resets_at + PAST_RESET - now
return UNKNOWN_RESET_POLL