claude-dev-env 8.111.3 → 8.111.5
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 +2 -2
- package/docs/second-claude-account.md +1 -1
- package/hooks/blocking/test_code_rules_enforcer_duplicate_body.py +7 -7
- package/hooks/blocking/test_codex_apply_patch.py +1 -1
- package/hooks/blocking/test_pull_request_proof.py +4 -4
- package/hooks/blocking/test_turn_review_gate.py +9 -4
- package/hooks/lifecycle/test_nested_project_hooks.py +1 -1
- package/hooks/routing/test_spawn_readiness_hook.py +6 -2
- package/hooks/session/test_npx_pele_guidance.py +2 -2
- package/package.json +1 -1
- package/scripts/account_broker.py +72 -2
- package/scripts/dev_env_scripts_constants/account_broker_constants.py +12 -0
- package/scripts/test_account_broker.py +154 -0
package/docs/account-broker.md
CHANGED
|
@@ -20,7 +20,7 @@ printf "%s" "prompt" | python scripts/account_broker.py run --product claude --r
|
|
|
20
20
|
|
|
21
21
|
`accounts` prints the roster without reading meters. `choose` prints `decision`, `accounts`, and `state_path`. Each decision contains `action`, `account`, `profile`, `home`, `reason`, `tier`, and `resets_at`. `profile` is the name of the profile whose home the account uses, such as `editor` for a home at `~/.claude-profiles/editor`. It is null for the main account, a Codex account, a home outside the profiles root, a home whose folder name is not a valid profile name such as `main`, and a wait decision. `--spent` takes an account's name or its profile. The account order file matches the name, command, or launcher, and resume affinity stores the command, or the name for an account without one. When a mark is one account's name and another account's profile, the name wins. Every mark is read before the first one is saved, so an unreadable mark saves none. `accounts` and the `choose` account list carry the same `profile` field. A wait decision has no account or home and includes the soonest reset in UTC. An account counts as free at the latest reset of the windows that hold it, and one hour out when one of those windows has no reset time. A failed meter read reuses the account's last good reading when that reading is 30 minutes old or less, and otherwise 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. A mark splits at its last colon, so an absent name that contains a colon, such as `C:\bin\old.cmd`, takes an explicit reset, such as `C:\bin\old.cmd:1800000000`. 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. `default` is the name `choose` gives the Codex home when no roster is configured, so while a Codex roster exists `choose` neither saves a `--spent default` mark nor waits on a stored one. Meter reads younger than 60 seconds are reused.
|
|
22
22
|
|
|
23
|
-
`check` prints nothing and exits 3 while every account is below its floor. `run` sets `CLAUDE_CONFIG_DIR` or `CODEX_HOME` for each attempt. A Claude job also starts without the parent session's variables, such as `CLAUDE_CODE_SESSION_ID` and `CLAUDECODE`, so a child started from inside a Claude Code session runs as its own session. `ALL_PARENT_CLAUDE_SESSION_VARIABLES` lists them. It replays the same stdin bytes when a usage limit or
|
|
23
|
+
`check` prints nothing and exits 3 while every account is below its floor. `run` sets `CLAUDE_CONFIG_DIR` or `CODEX_HOME` for each attempt. A Claude job also starts without the parent session's variables, such as `CLAUDE_CODE_SESSION_ID` and `CLAUDECODE`, so a child started from inside a Claude Code session runs as its own session. `ALL_PARENT_CLAUDE_SESSION_VARIABLES` lists them. It replays the same stdin bytes when a usage limit, start failure, or sign-in failure leads to another account. Send the prompt on stdin. When the command resolves to a `.cmd` or `.bat` file, the broker refuses an argument that holds a cmd.exe metacharacter and records `start_failed`. 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.
|
|
24
24
|
|
|
25
25
|
The broker stores cached meters, spent marks, and Claude session bindings in one JSON file under `~/.claude/account-broker`. Every broker process for the same user reads that file, so a spent mark pauses that account for every job. A write holds an exclusive lock on the sibling `state.json.lock`, re-reads the file, merges, and swaps in a sibling temporary file with `os.replace`. The merge keeps the latest reset for each spent mark and the newest meter read for each account.
|
|
26
26
|
|
|
@@ -30,7 +30,7 @@ The broker stores cached meters, spent marks, and Claude session bindings in one
|
|
|
30
30
|
| --- | --- |
|
|
31
31
|
| `0` | `choose` or `check` found an account, or the job exited successfully. |
|
|
32
32
|
| `3` | No account clears its floor. The decision includes `resets_at`. |
|
|
33
|
-
| `4` | A Claude job stopped with `advisor_blocked
|
|
33
|
+
| `4` | A Claude job stopped with `advisor_blocked`, or every Claude account was unusable: each had no token or was signed out. |
|
|
34
34
|
| `127` | A Codex job timed out, its command could not start while no Codex roster is configured, or the command could not start on any account in the roster. |
|
|
35
35
|
| Other command code | `run` returns the command's exit code after a served response. |
|
|
36
36
|
|
|
@@ -61,4 +61,4 @@ the week. An account whose meter could not be read has `meters` of `null`, and
|
|
|
61
61
|
its `unread_reason` holds the failure text when the reader raised one. A window
|
|
62
62
|
with no data has a `null` percent inside a read `meters` object. A wait decision has
|
|
63
63
|
`action: "wait"` and a `resets_at` timestamp. The broker exits with code 3 on
|
|
64
|
-
wait. The worker writes the same reset time to its report.
|
|
64
|
+
wait, and with code 4 when every account is unusable. The worker writes the same reset time to its report.
|
|
@@ -15,6 +15,7 @@ containing a test marker as exempt — the same way it would skip a real test fi
|
|
|
15
15
|
|
|
16
16
|
from __future__ import annotations
|
|
17
17
|
|
|
18
|
+
import contextlib
|
|
18
19
|
import importlib.util
|
|
19
20
|
import pathlib
|
|
20
21
|
import shutil
|
|
@@ -261,15 +262,14 @@ def test_should_scan_explicit_sibling_directory_for_relative_path(
|
|
|
261
262
|
|
|
262
263
|
def test_should_ignore_cwd_when_explicit_sibling_directory_given(
|
|
263
264
|
module_dir: pathlib.Path,
|
|
264
|
-
monkeypatch: pytest.MonkeyPatch,
|
|
265
265
|
) -> None:
|
|
266
266
|
_write(module_dir, "existing_blocker.py", SHARED_HELPER_SOURCE)
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
267
|
+
with contextlib.chdir(module_dir.parent):
|
|
268
|
+
issues = check_duplicate_function_body_across_files(
|
|
269
|
+
SHARED_HELPER_SOURCE,
|
|
270
|
+
"package/new_blocker.py",
|
|
271
|
+
sibling_directory=module_dir,
|
|
272
|
+
)
|
|
273
273
|
assert any("strip_code_and_quotes" in each_issue for each_issue in issues), (
|
|
274
274
|
"An explicit sibling directory must anchor the scan independent of the "
|
|
275
275
|
f"process working directory, got: {issues}"
|
|
@@ -25,7 +25,7 @@ def test_codex_patch_operation_targets_names_every_section_without_reading_conte
|
|
|
25
25
|
all_targets = codex_patch_operation_targets(three_operation_patch, str(tmp_path))
|
|
26
26
|
|
|
27
27
|
all_target_names = {
|
|
28
|
-
(each_operation,
|
|
28
|
+
(each_operation, Path(each_path).name)
|
|
29
29
|
for each_operation, each_path in all_targets
|
|
30
30
|
}
|
|
31
31
|
assert all_target_names == {
|
|
@@ -527,7 +527,7 @@ def _shell_create_elsewhere(
|
|
|
527
527
|
) -> dict[str, object]:
|
|
528
528
|
body_path = tmp_path / "body.md"
|
|
529
529
|
body_path.write_text(body, encoding="utf-8")
|
|
530
|
-
return _shell(f
|
|
530
|
+
return _shell(f'gh pr create --title t --body-file "{body_path}" {extra_flags}', tmp_path)
|
|
531
531
|
|
|
532
532
|
|
|
533
533
|
def test_should_allow_a_python_only_change_the_compare_api_lists_when_git_cannot_read_it(
|
|
@@ -689,9 +689,9 @@ def test_should_report_unreadable_git_output_as_unknown() -> None:
|
|
|
689
689
|
assert gate._git_changes([":100644 100644 aaa bbb M", "a.html", "stray", ""]) is None
|
|
690
690
|
|
|
691
691
|
|
|
692
|
-
def
|
|
693
|
-
clone_path = _repository_with_change(tmp_path, '
|
|
694
|
-
assert gate.visible_changed_files(str(clone_path), "feature") == ['
|
|
692
|
+
def test_should_keep_a_page_whose_name_holds_an_apostrophe(tmp_path: Path) -> None:
|
|
693
|
+
clone_path = _repository_with_change(tmp_path, "q't.html")
|
|
694
|
+
assert gate.visible_changed_files(str(clone_path), "feature") == ["q't.html"]
|
|
695
695
|
|
|
696
696
|
|
|
697
697
|
def test_should_keep_a_page_whose_name_has_non_ascii_letters(tmp_path: Path) -> None:
|
|
@@ -57,9 +57,14 @@ def project(tmp_path: Path) -> Path:
|
|
|
57
57
|
def gate_environment(tmp_path: Path, project: Path) -> dict[str, str]:
|
|
58
58
|
stub_directory = tmp_path / "bin"
|
|
59
59
|
stub_directory.mkdir()
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
60
|
+
if os.name == "nt":
|
|
61
|
+
stub_script = stub_directory / "claude_stub.py"
|
|
62
|
+
stub_script.write_text(STUB_CLAUDE_SOURCE)
|
|
63
|
+
(stub_directory / "claude.cmd").write_text(f'@"{sys.executable}" "{stub_script}" %*\r\n')
|
|
64
|
+
else:
|
|
65
|
+
stub_claude = stub_directory / "claude"
|
|
66
|
+
stub_claude.write_text(STUB_CLAUDE_SOURCE)
|
|
67
|
+
stub_claude.chmod(0o755)
|
|
63
68
|
state_directory = tmp_path / "state"
|
|
64
69
|
state_directory.mkdir()
|
|
65
70
|
environment = {
|
|
@@ -373,7 +378,7 @@ def test_should_share_one_review_time_budget_across_the_checkouts(
|
|
|
373
378
|
monkeypatch.setenv(each_name, gate_environment[each_name])
|
|
374
379
|
monkeypatch.setenv("STUB_REVIEW_SECONDS", "5")
|
|
375
380
|
monkeypatch.setattr(tempfile, "tempdir", gate_environment["TMPDIR"])
|
|
376
|
-
monkeypatch.setattr(turn_review_gate, "REVIEW_TIMEOUT_SECONDS",
|
|
381
|
+
monkeypatch.setattr(turn_review_gate, "REVIEW_TIMEOUT_SECONDS", 4)
|
|
377
382
|
all_roots = turn_review_gate._opted_in_repository_roots(
|
|
378
383
|
turn_review_gate._opted_in_repository_slugs()
|
|
379
384
|
)
|
|
@@ -77,7 +77,7 @@ def test_should_run_a_child_session_start_hook_inside_that_child(
|
|
|
77
77
|
"SessionStart": [
|
|
78
78
|
_command_group(
|
|
79
79
|
"",
|
|
80
|
-
f'echo "$CLAUDE_PROJECT_DIR|$(pwd)" > "{record_path}"',
|
|
80
|
+
f'echo "$CLAUDE_PROJECT_DIR|$(pwd -W 2>/dev/null || pwd)" > "{record_path}"',
|
|
81
81
|
)
|
|
82
82
|
]
|
|
83
83
|
},
|
|
@@ -83,6 +83,10 @@ def _write_transcript(tmp_path: Path, all_entries: list[dict[str, object]]) -> P
|
|
|
83
83
|
return transcript_path
|
|
84
84
|
|
|
85
85
|
|
|
86
|
+
def _hook_environment(tmp_path: Path) -> dict[str, str]:
|
|
87
|
+
return {**os.environ, "HOME": str(tmp_path), "USERPROFILE": str(tmp_path)}
|
|
88
|
+
|
|
89
|
+
|
|
86
90
|
def _run_hook(tmp_path: Path, hook_payload: dict[str, object]) -> str:
|
|
87
91
|
completed = subprocess.run(
|
|
88
92
|
[sys.executable, str(HOOK_SCRIPT)],
|
|
@@ -91,7 +95,7 @@ def _run_hook(tmp_path: Path, hook_payload: dict[str, object]) -> str:
|
|
|
91
95
|
),
|
|
92
96
|
capture_output=True,
|
|
93
97
|
text=True,
|
|
94
|
-
env=
|
|
98
|
+
env=_hook_environment(tmp_path),
|
|
95
99
|
check=True,
|
|
96
100
|
)
|
|
97
101
|
return completed.stdout
|
|
@@ -390,7 +394,7 @@ def test_should_print_nothing_for_empty_stdin(tmp_path: Path) -> None:
|
|
|
390
394
|
input="",
|
|
391
395
|
capture_output=True,
|
|
392
396
|
text=True,
|
|
393
|
-
env=
|
|
397
|
+
env=_hook_environment(tmp_path),
|
|
394
398
|
check=True,
|
|
395
399
|
)
|
|
396
400
|
assert completed.stdout == ""
|
|
@@ -211,7 +211,7 @@ def test_installed_snippet_renders_an_svg_file(
|
|
|
211
211
|
monkeypatch.setenv(CLAUDE_CONFIG_DIRECTORY_VARIABLE, str(claude_root))
|
|
212
212
|
work_directory = tmp_path / "work"
|
|
213
213
|
work_directory.mkdir()
|
|
214
|
-
(work_directory / "diagram.mmd").
|
|
214
|
+
(work_directory / "diagram.mmd").write_bytes(CHAIN_TEXT.encode("utf-8"))
|
|
215
215
|
context_text = npx_pele_guidance.guidance_text()
|
|
216
216
|
snippet = context_text.split(JS_FENCE_OPEN, 1)[1].split(JS_FENCE_CLOSE, 1)[0]
|
|
217
217
|
(work_directory / "pele-render.mjs").write_text(snippet, encoding="utf-8")
|
|
@@ -270,7 +270,7 @@ def test_installed_guidance_points_at_the_manifest_main_entry(
|
|
|
270
270
|
entry_path.write_text("export function render(text) {\n return { svg: '' };\n}\n", encoding="utf-8")
|
|
271
271
|
manifest = npx_pele_guidance.installed_pele_manifest(package_directory)
|
|
272
272
|
assert npx_pele_guidance.installed_pele_entry(package_directory, manifest) == entry_path
|
|
273
|
-
assert str(entry_path) in npx_pele_guidance.guidance_text()
|
|
273
|
+
assert json.dumps(str(entry_path)) in npx_pele_guidance.guidance_text()
|
|
274
274
|
assert "pele.run" not in npx_pele_guidance.guidance_text()
|
|
275
275
|
|
|
276
276
|
|
package/package.json
CHANGED
|
@@ -8,7 +8,7 @@ import json
|
|
|
8
8
|
import os
|
|
9
9
|
import subprocess
|
|
10
10
|
import sys
|
|
11
|
-
from dataclasses import dataclass
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
12
|
from datetime import datetime, timedelta, timezone
|
|
13
13
|
from pathlib import Path
|
|
14
14
|
from typing import Mapping, Sequence
|
|
@@ -46,9 +46,15 @@ from dev_env_scripts_constants.account_broker_constants import (
|
|
|
46
46
|
_choose_codex,
|
|
47
47
|
_wait_decision,
|
|
48
48
|
ALL_PARENT_CLAUDE_SESSION_VARIABLES,
|
|
49
|
+
ALL_SIGN_IN_FAILURE_SIGNATURES,
|
|
49
50
|
COMMAND_MISSING_EXIT_CODE,
|
|
51
|
+
NO_USABLE_ACCOUNT_EXIT_CODE,
|
|
52
|
+
NO_USABLE_REASON_SEPARATOR,
|
|
53
|
+
NO_USABLE_ACCOUNT_STATUS,
|
|
54
|
+
NO_USABLE_TOKEN_REASON_PREFIX,
|
|
50
55
|
PLACEHOLDER_NAME_SLOT,
|
|
51
56
|
REPORT_INDENT_SPACES,
|
|
57
|
+
SIGN_IN_FAILED_STATUS,
|
|
52
58
|
TIMEOUT_EXIT_CODE,
|
|
53
59
|
WAIT_EXIT_CODE,
|
|
54
60
|
utc_time_text as _time_text,
|
|
@@ -230,6 +236,7 @@ class _RunContext:
|
|
|
230
236
|
all_spent_resets: dict[Account, datetime]
|
|
231
237
|
start_failure_text: str = ""
|
|
232
238
|
live_log: Path | None = None
|
|
239
|
+
all_sign_in_failures: dict[str, str] = field(default_factory=dict)
|
|
233
240
|
|
|
234
241
|
|
|
235
242
|
def _prepare_run(
|
|
@@ -249,11 +256,71 @@ def _prepare_run(
|
|
|
249
256
|
)
|
|
250
257
|
|
|
251
258
|
|
|
259
|
+
def _is_sign_in_failure(completion: subprocess.CompletedProcess[str]) -> bool:
|
|
260
|
+
if completion.returncode == 0:
|
|
261
|
+
return False
|
|
262
|
+
stderr_text = completion.stderr.casefold()
|
|
263
|
+
return any(signature in stderr_text for signature in ALL_SIGN_IN_FAILURE_SIGNATURES)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _sign_in_failure_text(completion: subprocess.CompletedProcess[str]) -> str:
|
|
267
|
+
all_lines = [
|
|
268
|
+
each_line.strip()
|
|
269
|
+
for each_line in f"{completion.stderr}\n{completion.stdout}".splitlines()
|
|
270
|
+
if each_line.strip()
|
|
271
|
+
]
|
|
272
|
+
all_matching = [
|
|
273
|
+
each_line
|
|
274
|
+
for each_line in all_lines
|
|
275
|
+
if any(signature in each_line.casefold() for signature in ALL_SIGN_IN_FAILURE_SIGNATURES)
|
|
276
|
+
]
|
|
277
|
+
return (all_matching or all_lines or ["sign-in failed"])[0]
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _record_sign_in_failure(context: _RunContext, account: Account, completion: subprocess.CompletedProcess[str]) -> None:
|
|
281
|
+
reason = _sign_in_failure_text(completion)
|
|
282
|
+
context.all_sign_in_failures[account.name] = reason
|
|
283
|
+
context.report.events.append({"type": "sign_in_failure", "account": account.name, "reason": reason})
|
|
284
|
+
_record_spent_attempt(context, account, SIGN_IN_FAILED_STATUS, completion.returncode)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _skip_notes(context: _RunContext) -> str:
|
|
288
|
+
return "".join(
|
|
289
|
+
f"skipped {each_name}: {each_reason}\n" for each_name, each_reason in context.all_sign_in_failures.items()
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _is_no_token_reading(reading: Reading) -> bool:
|
|
294
|
+
return (
|
|
295
|
+
reading.meters is None
|
|
296
|
+
and reading.unread_reason is not None
|
|
297
|
+
and reading.unread_reason.startswith(NO_USABLE_TOKEN_REASON_PREFIX)
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _no_usable_account_reasons(context: _RunContext) -> list[str]:
|
|
302
|
+
all_reasons: list[str] = []
|
|
303
|
+
for each_reading in context.all_readings:
|
|
304
|
+
name = each_reading.account.name
|
|
305
|
+
if name in context.all_sign_in_failures:
|
|
306
|
+
reason = context.all_sign_in_failures[name]
|
|
307
|
+
elif _is_no_token_reading(each_reading):
|
|
308
|
+
reason = each_reading.unread_reason
|
|
309
|
+
else:
|
|
310
|
+
return []
|
|
311
|
+
all_reasons.append(f"{name}: {reason}")
|
|
312
|
+
return all_reasons
|
|
313
|
+
|
|
314
|
+
|
|
252
315
|
def _wait_outcome(context: _RunContext, decision: Decision) -> JobOutcome:
|
|
253
316
|
context.report.final_decision = decision
|
|
254
317
|
all_attempt_statuses = {each_status for _, each_status in context.all_attempts}
|
|
255
318
|
if all_attempt_statuses == {"start_failed"}:
|
|
256
319
|
return JobOutcome(COMMAND_MISSING_EXIT_CODE, "", context.start_failure_text, None, tuple(context.all_attempts), "start_failed", None, None)
|
|
320
|
+
all_no_usable_reasons = _no_usable_account_reasons(context)
|
|
321
|
+
if all_no_usable_reasons:
|
|
322
|
+
no_usable_text = "no usable account: " + NO_USABLE_REASON_SEPARATOR.join(all_no_usable_reasons)
|
|
323
|
+
return JobOutcome(NO_USABLE_ACCOUNT_EXIT_CODE, "", no_usable_text, None, tuple(context.all_attempts), NO_USABLE_ACCOUNT_STATUS, None, None, no_usable_text)
|
|
257
324
|
status = "exhausted" if context.all_attempts else "wait"
|
|
258
325
|
return JobOutcome(WAIT_EXIT_CODE, "", "", None, tuple(context.all_attempts), status, None, decision.resets_at, decision.reason)
|
|
259
326
|
|
|
@@ -297,7 +364,7 @@ def _finish_attempt(context: _RunContext, decision: Decision, completion: subpro
|
|
|
297
364
|
if context.product is Product.CLAUDE and session_id:
|
|
298
365
|
context.all_state["affinity"][session_id] = account.command or account.name
|
|
299
366
|
_save_state(broker_state_path(), context.all_state)
|
|
300
|
-
return JobOutcome(completion.returncode, completion.stdout, completion.stderr, account.name, tuple(context.all_attempts), status, session_id, None)
|
|
367
|
+
return JobOutcome(completion.returncode, completion.stdout, _skip_notes(context) + completion.stderr, account.name, tuple(context.all_attempts), status, session_id, None)
|
|
301
368
|
|
|
302
369
|
|
|
303
370
|
def _attempt_once(context: _RunContext, decision: Decision) -> JobOutcome | None:
|
|
@@ -326,6 +393,9 @@ def _attempt_once(context: _RunContext, decision: Decision) -> JobOutcome | None
|
|
|
326
393
|
waiting = Decision("wait", None, context.now + timedelta(hours=1), "no account has room", "wait")
|
|
327
394
|
return _wait_outcome(context, waiting)
|
|
328
395
|
return None
|
|
396
|
+
if context.product is Product.CLAUDE and _is_sign_in_failure(completion):
|
|
397
|
+
_record_sign_in_failure(context, account, completion)
|
|
398
|
+
return None
|
|
329
399
|
return _finish_attempt(context, decision, completion)
|
|
330
400
|
|
|
331
401
|
|
|
@@ -20,6 +20,7 @@ from dev_env_scripts_constants.claude_account_constants import (
|
|
|
20
20
|
SECOND_SESSION_USED_CEILING_PERCENT,
|
|
21
21
|
SECOND_WEEKLY_USED_CEILING_PERCENT,
|
|
22
22
|
)
|
|
23
|
+
from dev_env_scripts_constants.claude_chain_usage_constants import NO_ACCESS_TOKEN_ERROR_TEMPLATE
|
|
23
24
|
from dev_env_scripts_constants.codex_account_constants import (
|
|
24
25
|
ALL_PRO_PLAN_TYPES,
|
|
25
26
|
CODEX_ACCOUNT_PROFILES_ENVIRONMENT_VARIABLE,
|
|
@@ -62,6 +63,17 @@ METER_RATE_LIMIT_COOLDOWN_SECONDS = 300.0
|
|
|
62
63
|
WAIT_EXIT_CODE = 3
|
|
63
64
|
COMMAND_MISSING_EXIT_CODE = 127
|
|
64
65
|
TIMEOUT_EXIT_CODE = 124
|
|
66
|
+
NO_USABLE_ACCOUNT_EXIT_CODE = 4
|
|
67
|
+
NO_USABLE_ACCOUNT_STATUS = "no_usable_account"
|
|
68
|
+
NO_USABLE_REASON_SEPARATOR = "; "
|
|
69
|
+
SIGN_IN_FAILED_STATUS = "sign_in_failed"
|
|
70
|
+
ALL_SIGN_IN_FAILURE_SIGNATURES: tuple[str, ...] = (
|
|
71
|
+
"stored token expired",
|
|
72
|
+
"authorization failed",
|
|
73
|
+
"organization has status: canceled",
|
|
74
|
+
)
|
|
75
|
+
"""Case-insensitive substrings that mark a failed Claude run as a sign-in failure of its account."""
|
|
76
|
+
NO_USABLE_TOKEN_REASON_PREFIX = NO_ACCESS_TOKEN_ERROR_TEMPLATE.partition("{")[0]
|
|
65
77
|
REPORT_INDENT_SPACES = 2
|
|
66
78
|
PLACEHOLDER_NAME_SLOT = "{name}"
|
|
67
79
|
BROKER_STATE_DIRECTORY_NAME = "account-broker"
|
|
@@ -4,6 +4,7 @@ import json
|
|
|
4
4
|
import io
|
|
5
5
|
import shutil
|
|
6
6
|
import subprocess
|
|
7
|
+
from collections.abc import Callable
|
|
7
8
|
from datetime import datetime, timedelta, timezone
|
|
8
9
|
from pathlib import Path
|
|
9
10
|
|
|
@@ -22,6 +23,7 @@ from account_broker import (
|
|
|
22
23
|
run_job,
|
|
23
24
|
)
|
|
24
25
|
from dev_env_scripts_constants.account_broker_constants import WAIT_EXIT_CODE
|
|
26
|
+
from dev_env_scripts_constants.claude_chain_usage_constants import NO_ACCESS_TOKEN_ERROR_TEMPLATE
|
|
25
27
|
|
|
26
28
|
|
|
27
29
|
NOW = datetime(2026, 10, 3, tzinfo=timezone.utc)
|
|
@@ -1513,3 +1515,155 @@ def test_should_save_every_spent_mark_in_one_write(
|
|
|
1513
1515
|
|
|
1514
1516
|
assert len(all_saved_marks) == 1
|
|
1515
1517
|
assert len(all_saved_marks[0]) == 2
|
|
1518
|
+
|
|
1519
|
+
|
|
1520
|
+
def _claude_adapter(accounts: tuple[Account, ...], read_meters: Callable[[Account], Meters | None]) -> ProductAdapter:
|
|
1521
|
+
return ProductAdapter(
|
|
1522
|
+
load_accounts=lambda: accounts,
|
|
1523
|
+
read_meters=read_meters,
|
|
1524
|
+
environment_variable="CLAUDE_CONFIG_DIR",
|
|
1525
|
+
usage_limit_signatures=("rate limit",),
|
|
1526
|
+
)
|
|
1527
|
+
|
|
1528
|
+
|
|
1529
|
+
def _execute_claude(
|
|
1530
|
+
monkeypatch: pytest.MonkeyPatch,
|
|
1531
|
+
accounts: tuple[Account, ...],
|
|
1532
|
+
read_meters: Callable[[Account], Meters | None],
|
|
1533
|
+
completions_by_name: dict[str, tuple[int, str, str]],
|
|
1534
|
+
attempted: list[str],
|
|
1535
|
+
) -> tuple[account_broker.JobOutcome, account_broker.Report]:
|
|
1536
|
+
def runner(command: object, **options: object) -> subprocess.CompletedProcess[str]:
|
|
1537
|
+
selected = Path(options["env"]["CLAUDE_CONFIG_DIR"]).name
|
|
1538
|
+
attempted.append(selected)
|
|
1539
|
+
returncode, stdout, stderr = completions_by_name[selected]
|
|
1540
|
+
return subprocess.CompletedProcess(command, returncode, stdout, stderr)
|
|
1541
|
+
|
|
1542
|
+
monkeypatch.setitem(account_broker.all_product_adapters, Product.CLAUDE, _claude_adapter(accounts, read_meters))
|
|
1543
|
+
with account_broker.override_subprocess_runner(runner):
|
|
1544
|
+
return account_broker._execute(Product.CLAUDE, ("job",), now=NOW)
|
|
1545
|
+
|
|
1546
|
+
|
|
1547
|
+
def test_should_skip_an_account_whose_sign_in_fails_and_run_the_next_account(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
1548
|
+
accounts = (_account("first", Product.CLAUDE), _account("second", Product.CLAUDE))
|
|
1549
|
+
meters_by_name = {"first": _meters(90, 90), "second": _meters(70, 70)}
|
|
1550
|
+
attempted: list[str] = []
|
|
1551
|
+
|
|
1552
|
+
outcome, report = _execute_claude(
|
|
1553
|
+
monkeypatch,
|
|
1554
|
+
accounts,
|
|
1555
|
+
lambda account: meters_by_name[account.name],
|
|
1556
|
+
{"first": (1, "", "Stored token expired"), "second": (0, "served", "")},
|
|
1557
|
+
attempted,
|
|
1558
|
+
)
|
|
1559
|
+
|
|
1560
|
+
assert outcome.returncode == 0
|
|
1561
|
+
assert attempted == ["first", "second"]
|
|
1562
|
+
assert "skipped first: Stored token expired" in outcome.stderr
|
|
1563
|
+
assert any(
|
|
1564
|
+
each_event.get("type") == "sign_in_failure" and each_event.get("account") == "first"
|
|
1565
|
+
for each_event in report.events
|
|
1566
|
+
)
|
|
1567
|
+
|
|
1568
|
+
|
|
1569
|
+
def test_should_exit_four_and_name_each_account_when_every_sign_in_fails(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
1570
|
+
accounts = (_account("first", Product.CLAUDE), _account("second", Product.CLAUDE))
|
|
1571
|
+
meters_by_name = {"first": _meters(90, 90), "second": _meters(70, 70)}
|
|
1572
|
+
attempted: list[str] = []
|
|
1573
|
+
|
|
1574
|
+
outcome, _ = _execute_claude(
|
|
1575
|
+
monkeypatch,
|
|
1576
|
+
accounts,
|
|
1577
|
+
lambda account: meters_by_name[account.name],
|
|
1578
|
+
{
|
|
1579
|
+
"first": (1, "", "Organization has status: canceled"),
|
|
1580
|
+
"second": (1, "", "Stored token expired"),
|
|
1581
|
+
},
|
|
1582
|
+
attempted,
|
|
1583
|
+
)
|
|
1584
|
+
|
|
1585
|
+
assert outcome.returncode == 4
|
|
1586
|
+
assert outcome.status == "no_usable_account"
|
|
1587
|
+
assert attempted == ["first", "second"]
|
|
1588
|
+
assert "first: Organization has status: canceled" in outcome.stderr
|
|
1589
|
+
assert "second: Stored token expired" in outcome.stderr
|
|
1590
|
+
|
|
1591
|
+
|
|
1592
|
+
def test_should_exit_four_when_a_signed_out_account_and_a_failed_sign_in_leave_no_usable_account(
|
|
1593
|
+
monkeypatch: pytest.MonkeyPatch,
|
|
1594
|
+
) -> None:
|
|
1595
|
+
accounts = (_account("first", Product.CLAUDE), _account("second", Product.CLAUDE))
|
|
1596
|
+
signed_out_path = Path("/profiles/second/.credentials.json")
|
|
1597
|
+
attempted: list[str] = []
|
|
1598
|
+
|
|
1599
|
+
def read_meters(account: Account) -> Meters | None:
|
|
1600
|
+
if account.name == "second":
|
|
1601
|
+
raise account_broker_support.ClaudeSignedOutError(
|
|
1602
|
+
NO_ACCESS_TOKEN_ERROR_TEMPLATE.format(credentials_path=signed_out_path)
|
|
1603
|
+
)
|
|
1604
|
+
return _meters(90, 90)
|
|
1605
|
+
|
|
1606
|
+
outcome, _ = _execute_claude(
|
|
1607
|
+
monkeypatch,
|
|
1608
|
+
accounts,
|
|
1609
|
+
read_meters,
|
|
1610
|
+
{"first": (1, "", "stored token expired")},
|
|
1611
|
+
attempted,
|
|
1612
|
+
)
|
|
1613
|
+
|
|
1614
|
+
assert outcome.returncode == 4
|
|
1615
|
+
assert attempted == ["first"]
|
|
1616
|
+
assert "second: " + NO_ACCESS_TOKEN_ERROR_TEMPLATE.format(credentials_path=signed_out_path) in outcome.stderr
|
|
1617
|
+
|
|
1618
|
+
|
|
1619
|
+
def test_should_wait_with_exit_three_when_a_failed_sign_in_leaves_a_usage_limited_account(
|
|
1620
|
+
monkeypatch: pytest.MonkeyPatch,
|
|
1621
|
+
) -> None:
|
|
1622
|
+
accounts = (_account("first", Product.CLAUDE), _account("second", Product.CLAUDE))
|
|
1623
|
+
meters_by_name = {"first": _meters(90, 90), "second": _meters(70, 70)}
|
|
1624
|
+
attempted: list[str] = []
|
|
1625
|
+
|
|
1626
|
+
outcome, _ = _execute_claude(
|
|
1627
|
+
monkeypatch,
|
|
1628
|
+
accounts,
|
|
1629
|
+
lambda account: meters_by_name[account.name],
|
|
1630
|
+
{"first": (1, "", "Stored token expired"), "second": (1, "", "rate limit")},
|
|
1631
|
+
attempted,
|
|
1632
|
+
)
|
|
1633
|
+
|
|
1634
|
+
assert outcome.returncode == WAIT_EXIT_CODE
|
|
1635
|
+
assert attempted == ["first", "second"]
|
|
1636
|
+
|
|
1637
|
+
|
|
1638
|
+
def test_should_not_skip_an_account_when_only_stdout_quotes_a_sign_in_message(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
1639
|
+
accounts = (_account("first", Product.CLAUDE), _account("second", Product.CLAUDE))
|
|
1640
|
+
meters_by_name = {"first": _meters(90, 90), "second": _meters(70, 70)}
|
|
1641
|
+
attempted: list[str] = []
|
|
1642
|
+
|
|
1643
|
+
outcome, _ = _execute_claude(
|
|
1644
|
+
monkeypatch,
|
|
1645
|
+
accounts,
|
|
1646
|
+
lambda account: meters_by_name[account.name],
|
|
1647
|
+
{"first": (1, "stored token expired", ""), "second": (0, "served", "")},
|
|
1648
|
+
attempted,
|
|
1649
|
+
)
|
|
1650
|
+
|
|
1651
|
+
assert outcome.returncode == 1
|
|
1652
|
+
assert attempted == ["first"]
|
|
1653
|
+
|
|
1654
|
+
|
|
1655
|
+
def test_should_stop_on_a_failure_that_is_not_a_sign_in(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
1656
|
+
accounts = (_account("first", Product.CLAUDE), _account("second", Product.CLAUDE))
|
|
1657
|
+
meters_by_name = {"first": _meters(90, 90), "second": _meters(70, 70)}
|
|
1658
|
+
attempted: list[str] = []
|
|
1659
|
+
|
|
1660
|
+
outcome, _ = _execute_claude(
|
|
1661
|
+
monkeypatch,
|
|
1662
|
+
accounts,
|
|
1663
|
+
lambda account: meters_by_name[account.name],
|
|
1664
|
+
{"first": (1, "", "boom"), "second": (0, "served", "")},
|
|
1665
|
+
attempted,
|
|
1666
|
+
)
|
|
1667
|
+
|
|
1668
|
+
assert outcome.returncode == 1
|
|
1669
|
+
assert attempted == ["first"]
|