quotapilot 0.1.0__py3-none-any.whl
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.
- quotapilot/__init__.py +21 -0
- quotapilot/adapters/__init__.py +0 -0
- quotapilot/adapters/claude_swap.py +92 -0
- quotapilot/core.py +264 -0
- quotapilot/py.typed +0 -0
- quotapilot-0.1.0.dist-info/METADATA +131 -0
- quotapilot-0.1.0.dist-info/RECORD +9 -0
- quotapilot-0.1.0.dist-info/WHEEL +4 -0
- quotapilot-0.1.0.dist-info/licenses/LICENSE +21 -0
quotapilot/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""quotapilot: where to burn the weekly quota of several accounts so the least expires."""
|
|
2
|
+
|
|
3
|
+
from .core import (
|
|
4
|
+
Account,
|
|
5
|
+
Config,
|
|
6
|
+
average_pace,
|
|
7
|
+
decide,
|
|
8
|
+
pace_from_history,
|
|
9
|
+
project,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"Account",
|
|
16
|
+
"Config",
|
|
17
|
+
"average_pace",
|
|
18
|
+
"decide",
|
|
19
|
+
"pace_from_history",
|
|
20
|
+
"project",
|
|
21
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Read the accounts of claude-swap (https://github.com/realiti4/claude-swap).
|
|
2
|
+
|
|
3
|
+
claude-swap holds the accounts and switches between them. This module only turns the JSON of
|
|
4
|
+
`cswap list --json` into `quotapilot.Account` rows. The primary window is the seven-day one; the
|
|
5
|
+
secondary window is the per-model weekly limit listed under `usage.scoped`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import subprocess
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from typing import Any, Callable
|
|
14
|
+
|
|
15
|
+
from ..core import Account
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def parse_at(text: Any) -> datetime | None:
|
|
19
|
+
"""An ISO stamp as an aware datetime (a naive one is read as local time), None if unreadable."""
|
|
20
|
+
try:
|
|
21
|
+
dt = datetime.fromisoformat(str(text).replace("Z", "+00:00"))
|
|
22
|
+
except (ValueError, TypeError):
|
|
23
|
+
return None
|
|
24
|
+
return dt if dt.tzinfo else dt.astimezone()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _window(usage: dict[str, Any] | None, key: str) -> tuple[float | None, datetime | None]:
|
|
28
|
+
w = (usage or {}).get(key)
|
|
29
|
+
if not isinstance(w, dict) or w.get("pct") is None:
|
|
30
|
+
return None, None
|
|
31
|
+
return float(w["pct"]), parse_at(w.get("resetsAt"))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def parse_list(
|
|
35
|
+
data: dict[str, Any] | list[Any],
|
|
36
|
+
now: datetime | None = None,
|
|
37
|
+
secondary_name: str | None = None,
|
|
38
|
+
) -> list[Account]:
|
|
39
|
+
"""The accounts of a `cswap list --json` payload (the object, or just its `accounts` list).
|
|
40
|
+
|
|
41
|
+
`secondary_name` picks the window of `usage.scoped` (the per-model weekly limits) that becomes
|
|
42
|
+
the secondary window, by its `name`. None takes the first scoped window that has a percent.
|
|
43
|
+
`now` is not used to read the rows.
|
|
44
|
+
Raises ValueError, KeyError or TypeError on a malformed row.
|
|
45
|
+
"""
|
|
46
|
+
rows = data["accounts"] if isinstance(data, dict) else data
|
|
47
|
+
accounts: list[Account] = []
|
|
48
|
+
for r in rows:
|
|
49
|
+
name = str(r["number"])
|
|
50
|
+
usage = r.get("usage") if r.get("usageStatus") == "ok" else None
|
|
51
|
+
if usage is not None and not isinstance(usage, dict):
|
|
52
|
+
raise TypeError(f"usage of {name} is {type(usage).__name__}")
|
|
53
|
+
pct, reset = _window(usage, "sevenDay")
|
|
54
|
+
secondary_pct: float | None = None
|
|
55
|
+
secondary_reset: datetime | None = None
|
|
56
|
+
for s in (usage or {}).get("scoped") or []:
|
|
57
|
+
if s.get("pct") is None or (secondary_name and s.get("name") != secondary_name):
|
|
58
|
+
continue
|
|
59
|
+
secondary_pct, secondary_reset = float(s["pct"]), parse_at(s.get("resetsAt"))
|
|
60
|
+
if not secondary_name:
|
|
61
|
+
break
|
|
62
|
+
accounts.append(
|
|
63
|
+
Account(
|
|
64
|
+
name=name,
|
|
65
|
+
used_pct=pct,
|
|
66
|
+
reset=reset,
|
|
67
|
+
secondary_pct=secondary_pct,
|
|
68
|
+
secondary_reset=secondary_reset,
|
|
69
|
+
usable=usage is not None and pct is not None,
|
|
70
|
+
)
|
|
71
|
+
)
|
|
72
|
+
return accounts
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def read(
|
|
76
|
+
run: Callable[..., Any] = subprocess.run,
|
|
77
|
+
binary: str = "cswap",
|
|
78
|
+
timeout: float = 120,
|
|
79
|
+
secondary_name: str | None = None,
|
|
80
|
+
) -> list[Account]:
|
|
81
|
+
"""Run `cswap list --json` and parse it. RuntimeError when it fails or is unreadable."""
|
|
82
|
+
try:
|
|
83
|
+
out = run([binary, "list", "--json"], capture_output=True, text=True, timeout=timeout)
|
|
84
|
+
except Exception as e:
|
|
85
|
+
raise RuntimeError(f"cswap list failed: {e}") from e
|
|
86
|
+
if out.returncode != 0:
|
|
87
|
+
raise RuntimeError(f"cswap list exit {out.returncode}: {(out.stderr or '').strip()[:120]}")
|
|
88
|
+
try:
|
|
89
|
+
data = json.loads(out.stdout)
|
|
90
|
+
return parse_list(data, datetime.now(timezone.utc), secondary_name)
|
|
91
|
+
except (ValueError, KeyError, TypeError, AttributeError) as e:
|
|
92
|
+
raise RuntimeError(f"cswap list bad json: {type(e).__name__}: {e}") from e
|
quotapilot/core.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""Pure core of quotapilot: stdlib only, every datetime timezone-aware, any zone accepted."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from datetime import datetime, timedelta, timezone
|
|
7
|
+
from typing import Any, Optional, Sequence, Tuple
|
|
8
|
+
|
|
9
|
+
Sample = Tuple[datetime, str, Optional[float]]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class Account:
|
|
14
|
+
"""One account and its quota windows, as percent used and the reset instant.
|
|
15
|
+
|
|
16
|
+
The primary window is the weekly one. The secondary window is a second, narrower window some
|
|
17
|
+
providers have (for example a per-model weekly limit).
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
name: str
|
|
21
|
+
used_pct: float | None
|
|
22
|
+
reset: datetime | None
|
|
23
|
+
secondary_pct: float | None = None
|
|
24
|
+
secondary_reset: datetime | None = None
|
|
25
|
+
usable: bool = True
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Config:
|
|
30
|
+
"""Every constant of the algorithm. Defaults: one unit is one percent point of a week."""
|
|
31
|
+
|
|
32
|
+
week_hours: float = 168
|
|
33
|
+
units_per_week: float = 100.0
|
|
34
|
+
max_units_per_h: float | None = None
|
|
35
|
+
burn_floor_units: float = 1.0
|
|
36
|
+
secondary_min_room_pct: float = 10
|
|
37
|
+
secondary_drop_pct: float = 20
|
|
38
|
+
min_span_h: float = 6
|
|
39
|
+
history_h: float = 24
|
|
40
|
+
secondary_hold_h: float = 24
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
DEFAULT = Config()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _counted(accounts: Sequence[Account]) -> list[Account]:
|
|
47
|
+
return [a for a in accounts if a.usable and a.used_pct is not None and a.reset is not None]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _iso(dt: datetime) -> str:
|
|
51
|
+
return dt.astimezone(timezone.utc).isoformat()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _hours(delta: timedelta) -> float:
|
|
55
|
+
return delta.total_seconds() / 3600
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def pace_from_history(
|
|
59
|
+
samples: Sequence[Sample], now: datetime, config: Config = DEFAULT
|
|
60
|
+
) -> float | None:
|
|
61
|
+
"""Points per hour measured over the last `history_h` hours, None when the span is too short.
|
|
62
|
+
|
|
63
|
+
Each sample is (at, account name, used percent). A drop of the percent (a reset) is skipped.
|
|
64
|
+
"""
|
|
65
|
+
kept = [
|
|
66
|
+
(s[0], s[1], s[2])
|
|
67
|
+
for s in samples
|
|
68
|
+
if s[2] is not None and timedelta(0) <= now - s[0] <= timedelta(hours=config.history_h)
|
|
69
|
+
]
|
|
70
|
+
if not kept:
|
|
71
|
+
return None
|
|
72
|
+
span = _hours(max(s[0] for s in kept) - min(s[0] for s in kept))
|
|
73
|
+
if span < config.min_span_h:
|
|
74
|
+
return None
|
|
75
|
+
by_name: dict[str, list[tuple[datetime, float]]] = {}
|
|
76
|
+
for at, name, pct in kept:
|
|
77
|
+
assert pct is not None
|
|
78
|
+
by_name.setdefault(name, []).append((at, pct))
|
|
79
|
+
total = 0.0
|
|
80
|
+
for rows in by_name.values():
|
|
81
|
+
rows.sort(key=lambda r: r[0])
|
|
82
|
+
for (_, a), (_, b) in zip(rows, rows[1:]):
|
|
83
|
+
if b - a > 0:
|
|
84
|
+
total += b - a
|
|
85
|
+
return total / span
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def average_pace(accounts: Sequence[Account], now: datetime, config: Config = DEFAULT) -> float:
|
|
89
|
+
"""Points per hour averaged over the elapsed part of each account's week."""
|
|
90
|
+
total = 0.0
|
|
91
|
+
for a in _counted(accounts):
|
|
92
|
+
assert a.reset is not None and a.used_pct is not None
|
|
93
|
+
if a.reset <= now:
|
|
94
|
+
continue # stale reading: the week already refilled, its used_pct says nothing
|
|
95
|
+
left = _hours(a.reset - now)
|
|
96
|
+
elapsed = min(float(config.week_hours), max(1.0, config.week_hours - left))
|
|
97
|
+
total += a.used_pct / elapsed
|
|
98
|
+
return total
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _walk(
|
|
102
|
+
accounts: Sequence[Account], pace: float, now: datetime
|
|
103
|
+
) -> list[tuple[Account, float, float, datetime | None]]:
|
|
104
|
+
"""Unrounded walk: (account, room, lost, empty_at) in reset order."""
|
|
105
|
+
out: list[tuple[Account, float, float, datetime | None]] = []
|
|
106
|
+
t = now
|
|
107
|
+
for a in sorted(_counted(accounts), key=lambda x: x.reset): # type: ignore[arg-type,return-value]
|
|
108
|
+
assert a.reset is not None and a.used_pct is not None
|
|
109
|
+
lost = 0.0
|
|
110
|
+
empty_at = None
|
|
111
|
+
if a.reset <= now:
|
|
112
|
+
room = 0.0
|
|
113
|
+
else:
|
|
114
|
+
room = max(0.0, 100 - a.used_pct)
|
|
115
|
+
if pace <= 0:
|
|
116
|
+
lost = room
|
|
117
|
+
else:
|
|
118
|
+
need_h = room / pace
|
|
119
|
+
avail_h = max(0.0, _hours(a.reset - t))
|
|
120
|
+
if need_h <= avail_h:
|
|
121
|
+
t = t + timedelta(hours=need_h)
|
|
122
|
+
empty_at = t
|
|
123
|
+
else:
|
|
124
|
+
lost = room - pace * avail_h
|
|
125
|
+
t = max(t, a.reset)
|
|
126
|
+
out.append((a, room, lost, empty_at))
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def project(
|
|
131
|
+
accounts: Sequence[Account], pace: float, now: datetime, config: Config = DEFAULT
|
|
132
|
+
) -> list[dict[str, Any]]:
|
|
133
|
+
"""What each counted account loses at this pace, draining in reset order."""
|
|
134
|
+
out: list[dict[str, Any]] = []
|
|
135
|
+
for a, room, lost, empty_at in _walk(accounts, pace, now):
|
|
136
|
+
assert a.reset is not None and a.used_pct is not None
|
|
137
|
+
out.append(
|
|
138
|
+
{
|
|
139
|
+
"name": a.name,
|
|
140
|
+
"used_pct": round(a.used_pct, 1),
|
|
141
|
+
"reset": _iso(a.reset),
|
|
142
|
+
"room_pct": round(room, 1),
|
|
143
|
+
"lost_pct": round(lost, 1),
|
|
144
|
+
"lost_units": round(lost / 100 * config.units_per_week, 1),
|
|
145
|
+
"empty_at": _iso(empty_at) if empty_at else None,
|
|
146
|
+
}
|
|
147
|
+
)
|
|
148
|
+
return out
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _secondary_qualifies(
|
|
152
|
+
a: Account, now: datetime, previous: dict[str, Any] | None, config: Config
|
|
153
|
+
) -> bool:
|
|
154
|
+
assert a.reset is not None and a.used_pct is not None
|
|
155
|
+
if a.secondary_reset is not None:
|
|
156
|
+
diff = abs(_hours(a.secondary_reset - a.reset))
|
|
157
|
+
if diff > 1 and _hours(a.secondary_reset - now) > config.week_hours - 24:
|
|
158
|
+
return True
|
|
159
|
+
if previous and a.secondary_pct is not None:
|
|
160
|
+
for p in previous.get("accounts") or []:
|
|
161
|
+
if p.get("name") != a.name or p.get("secondary_pct") is None:
|
|
162
|
+
continue
|
|
163
|
+
prev_used = p.get("used_pct")
|
|
164
|
+
if (
|
|
165
|
+
p["secondary_pct"] - a.secondary_pct >= config.secondary_drop_pct
|
|
166
|
+
and prev_used is not None
|
|
167
|
+
and a.used_pct >= prev_used
|
|
168
|
+
):
|
|
169
|
+
return True
|
|
170
|
+
return False
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _secondary_carried(
|
|
174
|
+
name: str, now: datetime, previous: dict[str, Any] | None, config: Config
|
|
175
|
+
) -> str | None:
|
|
176
|
+
"""The previous secondary_since of `name` when it was secondary_first less than
|
|
177
|
+
`secondary_hold_h` ago."""
|
|
178
|
+
if not previous or previous.get("secondary_first") != name:
|
|
179
|
+
return None
|
|
180
|
+
since = previous.get("secondary_since")
|
|
181
|
+
try:
|
|
182
|
+
at = datetime.fromisoformat(str(since))
|
|
183
|
+
except (TypeError, ValueError):
|
|
184
|
+
return None
|
|
185
|
+
if at.tzinfo is None:
|
|
186
|
+
return None
|
|
187
|
+
held = timedelta(0) <= now - at < timedelta(hours=config.secondary_hold_h)
|
|
188
|
+
return str(since) if held else None
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _clock(dt: datetime) -> str:
|
|
192
|
+
return dt.astimezone(timezone.utc).strftime("%H:%M")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def decide(
|
|
196
|
+
accounts: Sequence[Account],
|
|
197
|
+
history: Sequence[Sample],
|
|
198
|
+
now: datetime,
|
|
199
|
+
previous: dict[str, Any] | None = None,
|
|
200
|
+
config: Config = DEFAULT,
|
|
201
|
+
) -> dict[str, Any]:
|
|
202
|
+
"""Project the loss of every account, pick the account to drain first, say burn or normal.
|
|
203
|
+
|
|
204
|
+
`previous` is the dict a former call returned; it carries the secondary-first rule over time.
|
|
205
|
+
"""
|
|
206
|
+
measured = pace_from_history(history, now, config)
|
|
207
|
+
pace = measured if measured is not None else average_pace(accounts, now, config)
|
|
208
|
+
rows = project(accounts, pace, now, config)
|
|
209
|
+
extra = {a.name: a for a in _counted(accounts)}
|
|
210
|
+
for r in rows:
|
|
211
|
+
acc = extra[r["name"]]
|
|
212
|
+
r["secondary_pct"] = acc.secondary_pct
|
|
213
|
+
r["secondary_reset"] = _iso(acc.secondary_reset) if acc.secondary_reset else None
|
|
214
|
+
lost_units = round(sum(r["lost_units"] for r in rows))
|
|
215
|
+
unavoidable: int | None = None
|
|
216
|
+
if config.max_units_per_h is not None:
|
|
217
|
+
max_pace = config.max_units_per_h / config.units_per_week * 100
|
|
218
|
+
unavoidable = round(sum(r["lost_units"] for r in project(accounts, max_pace, now, config)))
|
|
219
|
+
raw = _walk(accounts, pace, now)
|
|
220
|
+
drain_i = next((i for i, w in enumerate(raw) if w[1] > 0), None)
|
|
221
|
+
drain_first = rows[drain_i]["name"] if drain_i is not None else None
|
|
222
|
+
|
|
223
|
+
secondary_first = None
|
|
224
|
+
# the unrounded loss: a loss that rounds to 0.0 point is still a loss
|
|
225
|
+
if drain_i is not None and raw[drain_i][2] == 0:
|
|
226
|
+
cands = [
|
|
227
|
+
r
|
|
228
|
+
for r in rows
|
|
229
|
+
if r["room_pct"] >= config.secondary_min_room_pct
|
|
230
|
+
and (
|
|
231
|
+
_secondary_carried(r["name"], now, previous, config)
|
|
232
|
+
or _secondary_qualifies(extra[r["name"]], now, previous, config)
|
|
233
|
+
)
|
|
234
|
+
]
|
|
235
|
+
if cands:
|
|
236
|
+
secondary_first = max(cands, key=lambda r: r["room_pct"])["name"]
|
|
237
|
+
secondary_since = None
|
|
238
|
+
if secondary_first:
|
|
239
|
+
secondary_since = _secondary_carried(secondary_first, now, previous, config) or _iso(now)
|
|
240
|
+
|
|
241
|
+
state = "burn" if lost_units >= config.burn_floor_units else "normal"
|
|
242
|
+
tail = f", drain {drain_first} first." if drain_first else "."
|
|
243
|
+
if state == "burn":
|
|
244
|
+
losing = [r for r in rows if r["lost_units"] > 0]
|
|
245
|
+
names = ", ".join(r["name"] for r in losing)
|
|
246
|
+
at = _clock(datetime.fromisoformat(losing[0]["reset"]))
|
|
247
|
+
summary = (
|
|
248
|
+
f"Burn: {lost_units} units expire on {names} at the {at} UTC reset "
|
|
249
|
+
f"at {pace:.1f} pts/h{tail}"
|
|
250
|
+
)
|
|
251
|
+
else:
|
|
252
|
+
summary = f"Normal: nothing expires at {pace:.1f} pts/h{tail}"
|
|
253
|
+
return {
|
|
254
|
+
"state": state,
|
|
255
|
+
"drain_first": drain_first,
|
|
256
|
+
"secondary_first": secondary_first,
|
|
257
|
+
"secondary_since": secondary_since,
|
|
258
|
+
"pace_pct_h": round(pace, 2),
|
|
259
|
+
"pace_source": "measured" if measured is not None else "average",
|
|
260
|
+
"lost_units": lost_units,
|
|
261
|
+
"unavoidable_units": unavoidable,
|
|
262
|
+
"accounts": rows,
|
|
263
|
+
"summary": summary,
|
|
264
|
+
}
|
quotapilot/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: quotapilot
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Project what expires unused across several accounts with weekly quota windows, and say which account to drain first. No dependencies, no network.
|
|
5
|
+
Project-URL: Homepage, https://github.com/DylanMerigaud/quotapilot
|
|
6
|
+
Project-URL: Source, https://github.com/DylanMerigaud/quotapilot
|
|
7
|
+
Project-URL: Issues, https://github.com/DylanMerigaud/quotapilot/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/DylanMerigaud/quotapilot/blob/main/CHANGELOG.md
|
|
9
|
+
Author: Dylan Merigaud
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: accounts,claude,claude-swap,quota,rate-limit,scheduling,usage
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.9
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: build; extra == 'dev'
|
|
27
|
+
Requires-Dist: mypy; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest>=7; extra == 'dev'
|
|
29
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
30
|
+
Provides-Extra: test
|
|
31
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# quotapilot
|
|
35
|
+
|
|
36
|
+
You have several accounts, each with a weekly quota window that resets at its own time. Whatever
|
|
37
|
+
is not used before a reset is lost. quotapilot looks at how much each account has used and how
|
|
38
|
+
fast you burn, projects what expires unused, tells you which account to drain first, and says
|
|
39
|
+
whether you are in `burn` (something will expire) or `normal` (nothing will).
|
|
40
|
+
|
|
41
|
+
Pure Python, standard library only, no network, Python 3.9 and up.
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install quotapilot
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Example
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from datetime import datetime, timedelta, timezone
|
|
51
|
+
|
|
52
|
+
from quotapilot import Account, decide
|
|
53
|
+
|
|
54
|
+
now = datetime(2026, 11, 18, 12, 0, tzinfo=timezone.utc)
|
|
55
|
+
accounts = [
|
|
56
|
+
Account("work", used_pct=80, reset=now + timedelta(hours=20)),
|
|
57
|
+
Account("personal", used_pct=10, reset=now + timedelta(hours=100)),
|
|
58
|
+
]
|
|
59
|
+
# history: (when, account name, used percent) samples of the last day, oldest first
|
|
60
|
+
history = [(now - timedelta(hours=8), "work", 72), (now, "work", 80)]
|
|
61
|
+
|
|
62
|
+
result = decide(accounts, history, now)
|
|
63
|
+
print(result["summary"])
|
|
64
|
+
print(result["state"], result["drain_first"], result["pace_pct_h"])
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`decide` returns a dict: `state` (`burn` or `normal`), `drain_first`, `pace_pct_h` and
|
|
68
|
+
`pace_source` (`measured` from your history, else the `average` over the elapsed weeks),
|
|
69
|
+
`lost_units` and `unavoidable_units`, one row per account (`room_pct`, `lost_pct`, `lost_units`,
|
|
70
|
+
`empty_at`), and a one-line English `summary` with times in UTC.
|
|
71
|
+
|
|
72
|
+
A unit is what you decide it is. By default one unit is one percent point of one account-week.
|
|
73
|
+
Set `Config(units_per_week=1000, max_units_per_h=40, burn_floor_units=10)` to count in your own
|
|
74
|
+
units, to get `unavoidable_units` (what would still expire even at your maximum pace), and to say
|
|
75
|
+
how many lost units make a `burn`.
|
|
76
|
+
|
|
77
|
+
The optional secondary window (`Account.secondary_pct`, `secondary_reset`) is a second, narrower
|
|
78
|
+
quota some providers add, such as a per-model weekly limit. When the account to drain first loses
|
|
79
|
+
nothing, the account whose secondary window just reset or dropped is named in `secondary_first`
|
|
80
|
+
and held there for `secondary_hold_h` hours; pass the last result back as `previous=` to carry it.
|
|
81
|
+
|
|
82
|
+
## With claude-swap
|
|
83
|
+
|
|
84
|
+
quotapilot is an addon above [claude-swap](https://github.com/realiti4/claude-swap), not a
|
|
85
|
+
replacement. claude-swap holds your accounts and does the switching. quotapilot only decides.
|
|
86
|
+
Feed it the output of `cswap list --json`:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from datetime import datetime, timezone
|
|
90
|
+
|
|
91
|
+
from quotapilot import decide
|
|
92
|
+
from quotapilot.adapters import claude_swap
|
|
93
|
+
|
|
94
|
+
# accounts = claude_swap.read() # runs `cswap list --json` and parses it
|
|
95
|
+
payload = { # the shape of `cswap list --json`
|
|
96
|
+
"accounts": [
|
|
97
|
+
{
|
|
98
|
+
"number": 1,
|
|
99
|
+
"usageStatus": "ok",
|
|
100
|
+
"usage": {"sevenDay": {"pct": 42, "resetsAt": "2026-11-21T09:00:00Z"}},
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
"number": 2,
|
|
104
|
+
"usageStatus": "ok",
|
|
105
|
+
"usage": {"sevenDay": {"pct": 90, "resetsAt": "2026-11-19T09:00:00Z"}},
|
|
106
|
+
},
|
|
107
|
+
]
|
|
108
|
+
}
|
|
109
|
+
accounts = claude_swap.parse_list(payload)
|
|
110
|
+
now = datetime(2026, 11, 18, 12, 0, tzinfo=timezone.utc)
|
|
111
|
+
print(decide(accounts, [], now)["summary"])
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
`parse_list(data, secondary_name=...)` picks the per-model weekly window of `usage.scoped` by
|
|
115
|
+
name for the secondary window (the first one when omitted).
|
|
116
|
+
|
|
117
|
+
## What it does not do
|
|
118
|
+
|
|
119
|
+
- It does not switch accounts. You (or claude-swap) act on `drain_first`.
|
|
120
|
+
- The core makes no network call and calls no provider API. Only `claude_swap.read()` runs
|
|
121
|
+
`cswap list --json`, and claude-swap fetches the usage itself.
|
|
122
|
+
- It stores no account, no credential and no history: you pass the samples in.
|
|
123
|
+
|
|
124
|
+
## Contributing
|
|
125
|
+
|
|
126
|
+
Changes are made in this repository, released as a new version, and the projects that use
|
|
127
|
+
quotapilot bump their pin. See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
128
|
+
|
|
129
|
+
## License
|
|
130
|
+
|
|
131
|
+
MIT
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
quotapilot/__init__.py,sha256=1zfbHrAdpgiM7xpR6k3FnqvnIMJuvG3gpGntUu0pyXU,346
|
|
2
|
+
quotapilot/core.py,sha256=1X9RVmHK6CZYwD9uKTOv5E4Eb5Eri40fGCLERqXfI6A,9618
|
|
3
|
+
quotapilot/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
quotapilot/adapters/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
quotapilot/adapters/claude_swap.py,sha256=2ikGXNaQ2FqBqu_imf2Az7Took9I7FxbHA1FVoBIzGA,3666
|
|
6
|
+
quotapilot-0.1.0.dist-info/METADATA,sha256=KCj8zZFxWtbhvvXO3ku26hGrbTroSebQM6u9EFZBT3I,5293
|
|
7
|
+
quotapilot-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
quotapilot-0.1.0.dist-info/licenses/LICENSE,sha256=DoZ1XQb8is2fW4YFjqxNUiS_Ok8MS86c8OdgjJGOOPg,1071
|
|
9
|
+
quotapilot-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dylan Merigaud
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|