claude-dev-env 8.44.6 → 8.45.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.
package/docs/account-broker.md
CHANGED
|
@@ -14,7 +14,7 @@ python scripts/account_broker.py check --product codex
|
|
|
14
14
|
python scripts/account_broker.py run --product claude --report report.json -- claude --output-format json -p "prompt"
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
`accounts` prints the roster without reading meters. `choose` prints `decision`, `accounts`, and `state_path`. Each decision contains `action`, `account`, `home`, `reason`, `tier`, and `resets_at`. A wait decision has no account or home and includes the soonest reset in UTC. A failed meter read excludes the account for that choice. `--spent` saves an exclusion until the supplied Unix reset, the account's soonest known meter reset, or one hour when neither is available. Meter reads younger than 60 seconds are reused.
|
|
17
|
+
`accounts` prints the roster without reading meters. `choose` prints `decision`, `accounts`, and `state_path`. Each decision contains `action`, `account`, `home`, `reason`, `tier`, and `resets_at`. A wait decision has no account or home and includes the soonest reset in UTC. A failed meter read excludes the account for that choice. `--spent` saves an exclusion until the supplied Unix reset, the account's soonest known meter reset, or one hour when neither is available. A `--spent` name absent from the roster is saved until the supplied Unix reset, or for one hour when no reset is given. While any such mark is still in the future, `choose` waits until the soonest mark and exits 3, and with no Codex roster `--spent default` waits until that mark passes. Meter reads younger than 60 seconds are reused.
|
|
18
18
|
|
|
19
19
|
`check` prints nothing and exits 3 while every account is below its floor. `run` sets only `CLAUDE_CONFIG_DIR` or `CODEX_HOME` for each attempt. It replays the same stdin bytes when a usage limit or start failure leads to another account. It writes the command's stdout to stdout and diagnostics to stderr. A resumed Claude session uses the account bound to its session when that account has room.
|
|
20
20
|
|
package/package.json
CHANGED
|
@@ -127,7 +127,6 @@ def readings_payload(all_readings: Sequence[Reading]) -> list[dict[str, object]]
|
|
|
127
127
|
]
|
|
128
128
|
|
|
129
129
|
|
|
130
|
-
|
|
131
130
|
def _spent_for_readings(all_readings: Sequence[Reading], all_state: dict[str, object], now: datetime) -> tuple[frozenset[Account], dict[Account, datetime]]:
|
|
132
131
|
marks = all_state["spent"]
|
|
133
132
|
spent = {}
|
|
@@ -147,6 +146,23 @@ def _mark_spent(all_state: dict[str, object], reading: Reading, now: datetime, r
|
|
|
147
146
|
return until
|
|
148
147
|
|
|
149
148
|
|
|
149
|
+
def _outside_roster_resets(product: Product, all_readings: Sequence[Reading], all_state: Mapping[str, object], now: datetime) -> tuple[datetime, ...]:
|
|
150
|
+
marks = all_state.get("spent") if isinstance(all_state.get("spent"), dict) else {}
|
|
151
|
+
all_roster_names = {each_reading.account.name for each_reading in all_readings}
|
|
152
|
+
prefix = f"{product.value}:"
|
|
153
|
+
placeholder_suffix = f":{Path()}"
|
|
154
|
+
return tuple(datetime.fromtimestamp(float(each_raw), timezone.utc) for each_key, each_raw in marks.items() if isinstance(each_key, str) and each_key.startswith(prefix) and each_key.endswith(placeholder_suffix) and each_key[len(prefix):-len(placeholder_suffix)] not in all_roster_names and isinstance(each_raw, (int, float)) and each_raw > now.timestamp())
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _with_outside_spent_marks(decision: Decision, all_outside_resets: Sequence[datetime]) -> Decision:
|
|
158
|
+
if not all_outside_resets:
|
|
159
|
+
return decision
|
|
160
|
+
soonest = min(all_outside_resets) if decision.resets_at is None else min(decision.resets_at, *all_outside_resets)
|
|
161
|
+
if decision.action == "wait" and decision.resets_at == soonest:
|
|
162
|
+
return decision
|
|
163
|
+
return Decision("wait", None, soonest, f"no account has room; next reset at {_time_text(soonest)}", "wait")
|
|
164
|
+
|
|
165
|
+
|
|
150
166
|
def _write_report(path: Path, report: Report) -> None:
|
|
151
167
|
payload = {
|
|
152
168
|
"product": report.product.value,
|
|
@@ -268,12 +284,8 @@ def _execute(
|
|
|
268
284
|
) -> tuple[JobOutcome, Report]:
|
|
269
285
|
context = _prepare_run(product, all_argv, now, timeout_seconds, stdin_text, cwd, encoding, errors)
|
|
270
286
|
while True:
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
all_spent_accounts=frozenset(context.all_spent_accounts),
|
|
274
|
-
preferred_command=context.preferred_command, adapter=context.active,
|
|
275
|
-
all_spent_resets=context.all_spent_resets
|
|
276
|
-
)
|
|
287
|
+
picked = choose_from_readings(product, context.all_readings, now=now, all_spent_accounts=frozenset(context.all_spent_accounts), preferred_command=context.preferred_command, adapter=context.active, all_spent_resets=context.all_spent_resets)
|
|
288
|
+
decision = _with_outside_spent_marks(picked, _outside_roster_resets(product, context.all_readings, context.all_state, now))
|
|
277
289
|
context.report.events.append({"type": "pick", "decision": decision_payload(decision)})
|
|
278
290
|
if decision.account is None:
|
|
279
291
|
return _wait_outcome(context, decision), context.report
|
|
@@ -309,21 +321,20 @@ def _parser() -> argparse.ArgumentParser:
|
|
|
309
321
|
return parser
|
|
310
322
|
|
|
311
323
|
|
|
312
|
-
def _parse_spent_mark(all_accounts_by_name: Mapping[str, Reading], mark: str) -> tuple[Reading, datetime | None]:
|
|
324
|
+
def _parse_spent_mark(all_accounts_by_name: Mapping[str, Reading], mark: str, product: Product) -> tuple[Reading, datetime | None]:
|
|
313
325
|
name, separator, reset_text = mark.partition(":")
|
|
314
|
-
if name not in all_accounts_by_name:
|
|
315
|
-
raise BrokerConfigurationError(f"unknown account {name}")
|
|
316
326
|
try:
|
|
317
327
|
reset = datetime.fromtimestamp(float(reset_text), timezone.utc) if separator else None
|
|
318
|
-
except ValueError as error:
|
|
328
|
+
except (ValueError, OSError, OverflowError) as error:
|
|
319
329
|
raise BrokerConfigurationError(f"invalid reset for account {name}") from error
|
|
320
|
-
|
|
330
|
+
reading = all_accounts_by_name.get(name)
|
|
331
|
+
return reading if reading is not None else Reading(Account(product, name, Path(), False), None), reset
|
|
321
332
|
|
|
322
333
|
|
|
323
|
-
def _save_spent_arguments(all_marks: Sequence[str], all_readings: Sequence[Reading], all_state: dict[str, object], now: datetime) -> None:
|
|
334
|
+
def _save_spent_arguments(all_marks: Sequence[str], all_readings: Sequence[Reading], all_state: dict[str, object], now: datetime, product: Product) -> None:
|
|
324
335
|
all_accounts_by_name = {each_reading.account.name: each_reading for each_reading in all_readings}
|
|
325
336
|
for each_mark in all_marks:
|
|
326
|
-
reading, reset = _parse_spent_mark(all_accounts_by_name, each_mark)
|
|
337
|
+
reading, reset = _parse_spent_mark(all_accounts_by_name, each_mark, product)
|
|
327
338
|
_mark_spent(all_state, reading, now, reset)
|
|
328
339
|
|
|
329
340
|
|
|
@@ -352,9 +363,10 @@ def _choose_cli(product: Product, parsed: argparse.Namespace) -> int:
|
|
|
352
363
|
all_state = _load_state(broker_state_path())
|
|
353
364
|
all_readings = read_accounts(product, all_state=all_state, now=now)
|
|
354
365
|
if parsed.action == "choose" and parsed.spent:
|
|
355
|
-
_save_spent_arguments(parsed.spent, all_readings, all_state, now)
|
|
366
|
+
_save_spent_arguments(parsed.spent, all_readings, all_state, now, product)
|
|
356
367
|
spent, resets = _spent_for_readings(all_readings, all_state, now)
|
|
357
368
|
decision = choose_from_readings(product, all_readings, now=now, all_spent_accounts=spent, all_spent_resets=resets)
|
|
369
|
+
decision = _with_outside_spent_marks(decision, _outside_roster_resets(product, all_readings, all_state, now))
|
|
358
370
|
if parsed.action == "choose":
|
|
359
371
|
print(json.dumps({"decision": decision_payload(decision), "accounts": readings_payload(all_readings), "state_path": str(broker_state_path())}))
|
|
360
372
|
return WAIT_EXIT_CODE if decision.action == "wait" else 0
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Floors and outcome shape for the account broker."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from dev_env_scripts_constants.account_broker_constants import (
|
|
10
|
+
ALL_CLAUDE_FLOORS,
|
|
11
|
+
ALL_CODEX_FLOORS,
|
|
12
|
+
JobOutcome,
|
|
13
|
+
)
|
|
14
|
+
from dev_env_scripts_constants.claude_account_constants import (
|
|
15
|
+
MAIN_SESSION_USED_CEILING_PERCENT,
|
|
16
|
+
MAIN_SPEND_WINDOW,
|
|
17
|
+
MAIN_WEEKLY_USED_CEILING_PERCENT,
|
|
18
|
+
SECOND_SESSION_USED_CEILING_PERCENT,
|
|
19
|
+
SECOND_WEEKLY_USED_CEILING_PERCENT,
|
|
20
|
+
)
|
|
21
|
+
from dev_env_scripts_constants.codex_account_constants import (
|
|
22
|
+
LUNA_TIER_SHORT_WINDOW_MINIMUM_PERCENT_LEFT,
|
|
23
|
+
LUNA_TIER_STOP_PERCENT_LEFT,
|
|
24
|
+
NORMAL_TIER_MINIMUM_PERCENT_LEFT,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_should_keep_claude_floors_tied_to_the_account_ceilings() -> None:
|
|
29
|
+
assert ALL_CLAUDE_FLOORS == {
|
|
30
|
+
"main_weekly_used_ceiling": MAIN_WEEKLY_USED_CEILING_PERCENT,
|
|
31
|
+
"main_session_used_ceiling": MAIN_SESSION_USED_CEILING_PERCENT,
|
|
32
|
+
"main_spend_window": MAIN_SPEND_WINDOW,
|
|
33
|
+
"extra_weekly_used_ceiling": SECOND_WEEKLY_USED_CEILING_PERCENT,
|
|
34
|
+
"extra_session_used_ceiling": SECOND_SESSION_USED_CEILING_PERCENT,
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_should_keep_codex_floors_tied_to_the_tier_limits() -> None:
|
|
39
|
+
assert ALL_CODEX_FLOORS == {
|
|
40
|
+
"normal_minimum_left": NORMAL_TIER_MINIMUM_PERCENT_LEFT,
|
|
41
|
+
"luna_stop_left": LUNA_TIER_STOP_PERCENT_LEFT,
|
|
42
|
+
"luna_short_minimum_left": LUNA_TIER_SHORT_WINDOW_MINIMUM_PERCENT_LEFT,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_should_freeze_job_outcome() -> None:
|
|
47
|
+
outcome = JobOutcome(0, "", "", None, (), "served", None, None)
|
|
48
|
+
with pytest.raises(dataclasses.FrozenInstanceError):
|
|
49
|
+
outcome.status = "wait"
|
|
@@ -24,6 +24,21 @@ from dev_env_scripts_constants.account_broker_constants import WAIT_EXIT_CODE
|
|
|
24
24
|
NOW = datetime(2026, 10, 3, tzinfo=timezone.utc)
|
|
25
25
|
|
|
26
26
|
|
|
27
|
+
class _FrozenClock(datetime):
|
|
28
|
+
instant = NOW
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def now(cls, tz: timezone | None = None) -> datetime:
|
|
32
|
+
if tz is None:
|
|
33
|
+
return cls.instant.replace(tzinfo=None)
|
|
34
|
+
return cls.instant.astimezone(tz)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _freeze_clock(monkeypatch: pytest.MonkeyPatch, instant: datetime) -> None:
|
|
38
|
+
_FrozenClock.instant = instant
|
|
39
|
+
monkeypatch.setattr(account_broker, "datetime", _FrozenClock)
|
|
40
|
+
|
|
41
|
+
|
|
27
42
|
@pytest.fixture(autouse=True)
|
|
28
43
|
def isolated_state(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
|
29
44
|
monkeypatch.setattr(account_broker, "broker_state_path", lambda: tmp_path / "broker" / "state.json")
|
|
@@ -525,6 +540,112 @@ def test_should_raise_configuration_error_for_broken_list(
|
|
|
525
540
|
account_broker.load_claude_accounts()
|
|
526
541
|
|
|
527
542
|
|
|
543
|
+
def test_should_wait_when_a_spent_mark_names_an_account_outside_the_roster(
|
|
544
|
+
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
|
545
|
+
) -> None:
|
|
546
|
+
account = _account("first")
|
|
547
|
+
monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter((account,), {"first": _meters(80, 80)}))
|
|
548
|
+
_freeze_clock(monkeypatch, NOW)
|
|
549
|
+
sooner = NOW + timedelta(hours=2)
|
|
550
|
+
later = NOW + timedelta(hours=5)
|
|
551
|
+
|
|
552
|
+
code = account_broker.main((
|
|
553
|
+
"choose", "--product", "codex",
|
|
554
|
+
"--spent", f"visitor:{int(sooner.timestamp())}",
|
|
555
|
+
"--spent", f"guest:{int(later.timestamp())}",
|
|
556
|
+
))
|
|
557
|
+
|
|
558
|
+
decision = json.loads(capsys.readouterr().out)["decision"]
|
|
559
|
+
assert code == WAIT_EXIT_CODE
|
|
560
|
+
assert decision["action"] == "wait"
|
|
561
|
+
assert decision["account"] is None
|
|
562
|
+
assert decision["resets_at"] == sooner.isoformat()
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def test_should_wait_for_spent_default_home_until_the_mark_passes(
|
|
566
|
+
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
|
567
|
+
) -> None:
|
|
568
|
+
home = tmp_path / "default-home"
|
|
569
|
+
monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter((), {}))
|
|
570
|
+
monkeypatch.setenv("CODEX_HOME", str(home))
|
|
571
|
+
_freeze_clock(monkeypatch, NOW)
|
|
572
|
+
reset = NOW + timedelta(hours=2)
|
|
573
|
+
|
|
574
|
+
waiting = account_broker.main(("choose", "--product", "codex", "--spent", f"default:{int(reset.timestamp())}"))
|
|
575
|
+
waiting_decision = json.loads(capsys.readouterr().out)["decision"]
|
|
576
|
+
assert waiting == WAIT_EXIT_CODE
|
|
577
|
+
assert waiting_decision["action"] == "wait"
|
|
578
|
+
assert waiting_decision["resets_at"] == reset.isoformat()
|
|
579
|
+
|
|
580
|
+
_FrozenClock.instant = reset + timedelta(seconds=1)
|
|
581
|
+
running = account_broker.main(("choose", "--product", "codex"))
|
|
582
|
+
running_decision = json.loads(capsys.readouterr().out)["decision"]
|
|
583
|
+
assert running == 0
|
|
584
|
+
assert running_decision["action"] == "run"
|
|
585
|
+
assert running_decision["account"] == "default"
|
|
586
|
+
assert running_decision["home"] == str(home.resolve())
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def test_should_keep_a_spent_mark_without_a_reset_for_one_hour(
|
|
590
|
+
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
|
591
|
+
) -> None:
|
|
592
|
+
account = _account("first")
|
|
593
|
+
monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter((account,), {"first": _meters(80, 80)}))
|
|
594
|
+
_freeze_clock(monkeypatch, NOW)
|
|
595
|
+
|
|
596
|
+
code = account_broker.main(("choose", "--product", "codex", "--spent", "guest"))
|
|
597
|
+
|
|
598
|
+
decision = json.loads(capsys.readouterr().out)["decision"]
|
|
599
|
+
assert code == WAIT_EXIT_CODE
|
|
600
|
+
assert decision["action"] == "wait"
|
|
601
|
+
assert decision["resets_at"] == (NOW + timedelta(hours=1)).isoformat()
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def test_should_reject_an_invalid_spent_reset(
|
|
605
|
+
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
|
606
|
+
) -> None:
|
|
607
|
+
account = _account("first")
|
|
608
|
+
monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter((account,), {"first": _meters(80, 80)}))
|
|
609
|
+
|
|
610
|
+
code = account_broker.main(("choose", "--product", "codex", "--spent", "guest:tomorrow"))
|
|
611
|
+
|
|
612
|
+
assert code == 2
|
|
613
|
+
assert "invalid reset" in capsys.readouterr().err
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
@pytest.mark.parametrize("reset_text", ["inf", "1e20", "-1e20"])
|
|
617
|
+
def test_should_reject_a_spent_reset_outside_the_platform_range(
|
|
618
|
+
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], reset_text: str
|
|
619
|
+
) -> None:
|
|
620
|
+
account = _account("first")
|
|
621
|
+
monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter((account,), {"first": _meters(80, 80)}))
|
|
622
|
+
|
|
623
|
+
code = account_broker.main(("choose", "--product", "codex", "--spent", f"guest:{reset_text}"))
|
|
624
|
+
|
|
625
|
+
assert code == 2
|
|
626
|
+
assert "invalid reset" in capsys.readouterr().err
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def test_should_run_past_a_spent_mark_left_by_an_account_removed_from_the_roster(
|
|
630
|
+
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
|
631
|
+
) -> None:
|
|
632
|
+
account = _account("first")
|
|
633
|
+
monkeypatch.setitem(account_broker.all_product_adapters, Product.CODEX, _adapter((account,), {"first": _meters(80, 80)}))
|
|
634
|
+
_freeze_clock(monkeypatch, NOW)
|
|
635
|
+
retired_key = account_broker._state_key(_account("retired"))
|
|
636
|
+
account_broker._save_state(
|
|
637
|
+
account_broker.broker_state_path(),
|
|
638
|
+
{"meters": {}, "spent": {retired_key: (NOW + timedelta(days=6)).timestamp()}, "affinity": {}},
|
|
639
|
+
)
|
|
640
|
+
|
|
641
|
+
code = account_broker.main(("choose", "--product", "codex"))
|
|
642
|
+
|
|
643
|
+
decision = json.loads(capsys.readouterr().out)["decision"]
|
|
644
|
+
assert code == 0
|
|
645
|
+
assert decision["action"] == "run"
|
|
646
|
+
assert decision["account"] == "first"
|
|
647
|
+
|
|
648
|
+
|
|
528
649
|
def test_should_run_job_through_override(
|
|
529
650
|
monkeypatch: pytest.MonkeyPatch
|
|
530
651
|
) -> None:
|