claude-dev-env 8.111.4 → 8.112.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/.agents/skills/build-eval/evals/review/README.md +2 -2
- package/.agents/skills/build-eval/evals/review/review_eval_support/account.py +166 -0
- package/.agents/skills/build-eval/evals/review/review_eval_support/config/constants.py +26 -0
- package/.agents/skills/build-eval/evals/review/review_eval_support/execution.py +8 -0
- package/.agents/skills/build-eval/evals/review/test_run.py +261 -0
- package/_shared/advisor/reference/astra-rung.md +13 -5
- package/_shared/advisor/scripts/codex_astra_advisor.py +31 -8
- package/_shared/advisor/scripts/codex_astra_preflight.py +70 -14
- package/_shared/advisor/scripts/config/advisor_scripts_constants/astra_advisor_constants.py +7 -0
- package/_shared/advisor/scripts/tests/test_codex_astra_advisor.py +266 -2
- package/_shared/advisor/scripts/tests/test_codex_astra_preflight.py +114 -8
- package/_shared/pr-loop/scripts/check_convergence.py +5 -1
- package/_shared/pr-loop/scripts/codex_review_account.py +180 -0
- package/_shared/pr-loop/scripts/codex_review_scripts_constants/account_constants.py +28 -0
- package/_shared/pr-loop/scripts/codex_review_scripts_constants/run_constants.py +3 -1
- package/_shared/pr-loop/scripts/run_codex_review.py +144 -15
- package/_shared/pr-loop/scripts/test_check_convergence_codex.py +3 -3
- package/_shared/pr-loop/scripts/test_codex_review_account.py +355 -0
- package/_shared/pr-loop/scripts/test_run_codex_review.py +507 -6
- package/docs/account-broker.md +6 -4
- package/docs/codex-accounts.md +57 -16
- package/docs/rule-guides/question-presentation.md +4 -0
- package/docs/second-claude-account.md +1 -1
- package/hooks/blocking/final_reply_gate.py +59 -3
- package/hooks/blocking/open_tasks_transcript.py +18 -0
- package/hooks/blocking/test_final_reply_gate.py +160 -0
- package/hooks/features/conduct-gates.md +1 -4
- package/hooks/hooks.json +0 -10
- package/hooks/hooks_constants/final_reply_gate_constants.py +16 -0
- package/hooks/hooks_constants/open_tasks_stop_gate_constants.py +9 -0
- package/package.json +1 -1
- package/rules/question-presentation.md +1 -1
- package/scripts/account_broker.py +122 -27
- package/scripts/account_broker_support.py +54 -3
- package/scripts/codex_account_choice.py +12 -8
- package/scripts/codex_account_chooser.py +110 -0
- package/scripts/codex_account_meters.py +43 -4
- package/scripts/codex_plan_rules.py +156 -0
- package/scripts/dev_env_scripts_constants/account_broker_constants.py +41 -42
- package/scripts/dev_env_scripts_constants/codex_account_constants.py +62 -2
- package/scripts/dev_env_scripts_constants/test_account_broker_constants.py +359 -2
- package/scripts/dev_env_scripts_constants/test_codex_account_constants.py +213 -14
- package/scripts/policy_lint/adapter_configuration.py +0 -5
- package/scripts/policy_lint/config/constants.py +0 -1
- package/scripts/test_account_broker.py +1913 -526
- package/scripts/test_account_broker_support.py +77 -0
- package/scripts/test_codex_account_meters.py +95 -0
- package/scripts/tests/test_adapter_configuration.py +0 -8
- package/hooks/blocking/merge_over_review_offer_gate.py +0 -114
- package/hooks/blocking/test_merge_over_review_offer_gate.py +0 -138
- package/hooks/hooks_constants/merge_over_review_offer_gate_constants.py +0 -34
|
@@ -8,13 +8,14 @@ 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
|
|
15
15
|
|
|
16
16
|
import account_broker_support as support
|
|
17
17
|
import codex_account_meters
|
|
18
|
+
from codex_account_chooser import choose_codex
|
|
18
19
|
from account_broker_support import (
|
|
19
20
|
all_product_adapters,
|
|
20
21
|
Account,
|
|
@@ -43,50 +44,72 @@ from account_broker_support import (
|
|
|
43
44
|
from dev_env_scripts_constants.account_broker_constants import (
|
|
44
45
|
_account_reset,
|
|
45
46
|
_choose_claude,
|
|
46
|
-
_choose_codex,
|
|
47
47
|
_wait_decision,
|
|
48
48
|
ALL_PARENT_CLAUDE_SESSION_VARIABLES,
|
|
49
|
+
ALL_SIGN_IN_FAILURE_SIGNATURES,
|
|
50
|
+
ALL_CHOOSE_AND_CHECK_ACTIONS,
|
|
49
51
|
COMMAND_MISSING_EXIT_CODE,
|
|
52
|
+
NO_USABLE_ACCOUNT_EXIT_CODE,
|
|
53
|
+
NO_USABLE_REASON_SEPARATOR,
|
|
54
|
+
NO_USABLE_ACCOUNT_STATUS,
|
|
55
|
+
NO_USABLE_TOKEN_REASON_PREFIX,
|
|
50
56
|
PLACEHOLDER_NAME_SLOT,
|
|
51
57
|
REPORT_INDENT_SPACES,
|
|
58
|
+
SIGN_IN_FAILED_STATUS,
|
|
52
59
|
TIMEOUT_EXIT_CODE,
|
|
53
60
|
WAIT_EXIT_CODE,
|
|
54
61
|
utc_time_text as _time_text,
|
|
55
62
|
)
|
|
56
63
|
from dev_env_scripts_constants.codex_account_constants import (
|
|
57
|
-
|
|
58
|
-
|
|
64
|
+
ALL_TIERS_BEST_FIRST,
|
|
65
|
+
HOME_CODEX_ONLY_MESSAGE,
|
|
66
|
+
HOME_WITH_SPENT_MESSAGE,
|
|
59
67
|
NO_ROSTER_ACCOUNT_NAME,
|
|
60
|
-
|
|
68
|
+
REQUIRE_TIER_ARGUMENT,
|
|
61
69
|
)
|
|
62
70
|
|
|
63
71
|
|
|
72
|
+
def _holds_codex_credits(product: Product, reading: Reading) -> bool:
|
|
73
|
+
return product is Product.CODEX and reading.meters is not None and reading.meters.has_spendable_credits
|
|
74
|
+
|
|
75
|
+
|
|
64
76
|
def choose_from_readings(
|
|
65
77
|
product: Product,
|
|
66
78
|
all_readings: Sequence[Reading],
|
|
67
79
|
*,
|
|
68
80
|
now: datetime,
|
|
69
81
|
all_spent_accounts: frozenset[Account] = frozenset(),
|
|
82
|
+
all_attempted_accounts: frozenset[Account] = frozenset(),
|
|
70
83
|
preferred_command: str | None = None,
|
|
71
84
|
all_spent_resets: Mapping[Account, datetime] | None = None,
|
|
85
|
+
required_tier: str | None = None,
|
|
86
|
+
is_home_named: bool = False,
|
|
72
87
|
) -> Decision:
|
|
73
88
|
"""Choose an account or a wait.
|
|
74
89
|
|
|
75
90
|
Args:
|
|
76
91
|
product: Account product.
|
|
77
92
|
all_readings: Roster and meter readings.
|
|
93
|
+
all_spent_accounts: Accounts a saved mark holds, or that spent an attempt in this run. A Codex account with spendable credits is still chosen unless it spent an attempt in this run.
|
|
94
|
+
all_attempted_accounts: Accounts that spent an attempt in this run. Credits do not keep them.
|
|
95
|
+
required_tier: Codex tier the job needs, or None for any tier. Claude choices ignore it.
|
|
96
|
+
is_home_named: True when the caller named one Codex home, which runs on a paid plan
|
|
97
|
+
whatever its room, unless ``required_tier`` is above the tier it reaches.
|
|
98
|
+
Claude choices ignore it.
|
|
78
99
|
|
|
79
100
|
Returns:
|
|
80
101
|
A run or wait decision.
|
|
81
102
|
"""
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
103
|
+
all_available = [
|
|
104
|
+
each_reading
|
|
105
|
+
for each_reading in all_readings
|
|
106
|
+
if each_reading.account not in all_attempted_accounts
|
|
107
|
+
and (each_reading.account not in all_spent_accounts or _holds_codex_credits(product, each_reading))
|
|
108
|
+
]
|
|
86
109
|
selected = (
|
|
87
110
|
_choose_claude(all_available, preferred_command)
|
|
88
111
|
if product is Product.CLAUDE
|
|
89
|
-
else
|
|
112
|
+
else choose_codex(all_available, required_tier, is_home_named=is_home_named)
|
|
90
113
|
)
|
|
91
114
|
return selected or _wait_decision(all_readings, now, all_spent_accounts, all_spent_resets or {})
|
|
92
115
|
|
|
@@ -230,6 +253,8 @@ class _RunContext:
|
|
|
230
253
|
all_spent_resets: dict[Account, datetime]
|
|
231
254
|
start_failure_text: str = ""
|
|
232
255
|
live_log: Path | None = None
|
|
256
|
+
all_sign_in_failures: dict[str, str] = field(default_factory=dict)
|
|
257
|
+
all_attempted_accounts: set[Account] = field(default_factory=set)
|
|
233
258
|
|
|
234
259
|
|
|
235
260
|
def _prepare_run(
|
|
@@ -249,11 +274,71 @@ def _prepare_run(
|
|
|
249
274
|
)
|
|
250
275
|
|
|
251
276
|
|
|
277
|
+
def _is_sign_in_failure(completion: subprocess.CompletedProcess[str]) -> bool:
|
|
278
|
+
if completion.returncode == 0:
|
|
279
|
+
return False
|
|
280
|
+
stderr_text = completion.stderr.casefold()
|
|
281
|
+
return any(signature in stderr_text for signature in ALL_SIGN_IN_FAILURE_SIGNATURES)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _sign_in_failure_text(completion: subprocess.CompletedProcess[str]) -> str:
|
|
285
|
+
all_lines = [
|
|
286
|
+
each_line.strip()
|
|
287
|
+
for each_line in f"{completion.stderr}\n{completion.stdout}".splitlines()
|
|
288
|
+
if each_line.strip()
|
|
289
|
+
]
|
|
290
|
+
all_matching = [
|
|
291
|
+
each_line
|
|
292
|
+
for each_line in all_lines
|
|
293
|
+
if any(signature in each_line.casefold() for signature in ALL_SIGN_IN_FAILURE_SIGNATURES)
|
|
294
|
+
]
|
|
295
|
+
return (all_matching or all_lines or ["sign-in failed"])[0]
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _record_sign_in_failure(context: _RunContext, account: Account, completion: subprocess.CompletedProcess[str]) -> None:
|
|
299
|
+
reason = _sign_in_failure_text(completion)
|
|
300
|
+
context.all_sign_in_failures[account.name] = reason
|
|
301
|
+
context.report.events.append({"type": "sign_in_failure", "account": account.name, "reason": reason})
|
|
302
|
+
_record_spent_attempt(context, account, SIGN_IN_FAILED_STATUS, completion.returncode)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _skip_notes(context: _RunContext) -> str:
|
|
306
|
+
return "".join(
|
|
307
|
+
f"skipped {each_name}: {each_reason}\n" for each_name, each_reason in context.all_sign_in_failures.items()
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _is_no_token_reading(reading: Reading) -> bool:
|
|
312
|
+
return (
|
|
313
|
+
reading.meters is None
|
|
314
|
+
and reading.unread_reason is not None
|
|
315
|
+
and reading.unread_reason.startswith(NO_USABLE_TOKEN_REASON_PREFIX)
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _no_usable_account_reasons(context: _RunContext) -> list[str]:
|
|
320
|
+
all_reasons: list[str] = []
|
|
321
|
+
for each_reading in context.all_readings:
|
|
322
|
+
name = each_reading.account.name
|
|
323
|
+
if name in context.all_sign_in_failures:
|
|
324
|
+
reason = context.all_sign_in_failures[name]
|
|
325
|
+
elif _is_no_token_reading(each_reading):
|
|
326
|
+
reason = each_reading.unread_reason
|
|
327
|
+
else:
|
|
328
|
+
return []
|
|
329
|
+
all_reasons.append(f"{name}: {reason}")
|
|
330
|
+
return all_reasons
|
|
331
|
+
|
|
332
|
+
|
|
252
333
|
def _wait_outcome(context: _RunContext, decision: Decision) -> JobOutcome:
|
|
253
334
|
context.report.final_decision = decision
|
|
254
335
|
all_attempt_statuses = {each_status for _, each_status in context.all_attempts}
|
|
255
336
|
if all_attempt_statuses == {"start_failed"}:
|
|
256
337
|
return JobOutcome(COMMAND_MISSING_EXIT_CODE, "", context.start_failure_text, None, tuple(context.all_attempts), "start_failed", None, None)
|
|
338
|
+
all_no_usable_reasons = _no_usable_account_reasons(context)
|
|
339
|
+
if all_no_usable_reasons:
|
|
340
|
+
no_usable_text = "no usable account: " + NO_USABLE_REASON_SEPARATOR.join(all_no_usable_reasons)
|
|
341
|
+
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
342
|
status = "exhausted" if context.all_attempts else "wait"
|
|
258
343
|
return JobOutcome(WAIT_EXIT_CODE, "", "", None, tuple(context.all_attempts), status, None, decision.resets_at, decision.reason)
|
|
259
344
|
|
|
@@ -261,11 +346,11 @@ def _wait_outcome(context: _RunContext, decision: Decision) -> JobOutcome:
|
|
|
261
346
|
def _record_spent_attempt(context: _RunContext, account: Account, status: str, returncode: int | None) -> None:
|
|
262
347
|
context.all_attempts.append((account.name, status))
|
|
263
348
|
context.report.events.append({"type": "attempt", "account": account.name, "status": status, "exit_code": returncode})
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
349
|
+
reading = next(each_reading for each_reading in context.all_readings if each_reading.account == account)
|
|
350
|
+
context.all_spent_accounts.add(account)
|
|
351
|
+
context.all_attempted_accounts.add(account)
|
|
352
|
+
if status == "usage_limited":
|
|
353
|
+
context.all_spent_resets[account] = _mark_spent(context.all_state, reading, context.now)
|
|
269
354
|
|
|
270
355
|
|
|
271
356
|
def _invoke(context: _RunContext, account: Account) -> subprocess.CompletedProcess[str]:
|
|
@@ -297,7 +382,7 @@ def _finish_attempt(context: _RunContext, decision: Decision, completion: subpro
|
|
|
297
382
|
if context.product is Product.CLAUDE and session_id:
|
|
298
383
|
context.all_state["affinity"][session_id] = account.command or account.name
|
|
299
384
|
_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)
|
|
385
|
+
return JobOutcome(completion.returncode, completion.stdout, _skip_notes(context) + completion.stderr, account.name, tuple(context.all_attempts), status, session_id, None)
|
|
301
386
|
|
|
302
387
|
|
|
303
388
|
def _attempt_once(context: _RunContext, decision: Decision) -> JobOutcome | None:
|
|
@@ -311,10 +396,6 @@ def _attempt_once(context: _RunContext, decision: Decision) -> JobOutcome | None
|
|
|
311
396
|
except OSError as error:
|
|
312
397
|
_record_spent_attempt(context, account, "start_failed", COMMAND_MISSING_EXIT_CODE)
|
|
313
398
|
context.start_failure_text = str(error)
|
|
314
|
-
if not context.all_readings:
|
|
315
|
-
context.report.final_decision = decision
|
|
316
|
-
final_status = "advisor_blocked" if context.product is Product.CLAUDE else "start_failed"
|
|
317
|
-
return JobOutcome(COMMAND_MISSING_EXIT_CODE, "", str(error), account.name, tuple(context.all_attempts), final_status, None, None)
|
|
318
399
|
return None
|
|
319
400
|
combined = f"{completion.stdout}{completion.stderr}".casefold()
|
|
320
401
|
is_limited = completion.returncode != 0 and any(
|
|
@@ -322,9 +403,9 @@ def _attempt_once(context: _RunContext, decision: Decision) -> JobOutcome | None
|
|
|
322
403
|
)
|
|
323
404
|
if is_limited:
|
|
324
405
|
_record_spent_attempt(context, account, "usage_limited", completion.returncode)
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
406
|
+
return None
|
|
407
|
+
if context.product is Product.CLAUDE and _is_sign_in_failure(completion):
|
|
408
|
+
_record_sign_in_failure(context, account, completion)
|
|
328
409
|
return None
|
|
329
410
|
return _finish_attempt(context, decision, completion)
|
|
330
411
|
|
|
@@ -338,7 +419,7 @@ def _execute(
|
|
|
338
419
|
context = _prepare_run(product, all_argv, now, timeout_seconds, stdin_text, cwd, encoding, errors)
|
|
339
420
|
context.live_log = live_log
|
|
340
421
|
while True:
|
|
341
|
-
picked = choose_from_readings(product, context.all_readings, now=now, all_spent_accounts=frozenset(context.all_spent_accounts), preferred_command=context.preferred_command, all_spent_resets=context.all_spent_resets)
|
|
422
|
+
picked = choose_from_readings(product, context.all_readings, now=now, all_spent_accounts=frozenset(context.all_spent_accounts), all_attempted_accounts=frozenset(context.all_attempted_accounts), preferred_command=context.preferred_command, all_spent_resets=context.all_spent_resets)
|
|
342
423
|
decision = _with_outside_spent_marks(picked, _outside_roster_resets(product, context.all_readings, context.all_state, now))
|
|
343
424
|
context.report.events.append({"type": "pick", "decision": decision_payload(decision)})
|
|
344
425
|
if decision.account is None:
|
|
@@ -369,6 +450,9 @@ def _parser() -> argparse.ArgumentParser:
|
|
|
369
450
|
command = commands.add_parser(each_action)
|
|
370
451
|
all_product_choices = [Product.CODEX.value] if each_action == "limits" else [each_product.value for each_product in Product]
|
|
371
452
|
command.add_argument("--product", choices=all_product_choices, required=True)
|
|
453
|
+
if each_action in ALL_CHOOSE_AND_CHECK_ACTIONS:
|
|
454
|
+
command.add_argument(REQUIRE_TIER_ARGUMENT, choices=ALL_TIERS_BEST_FIRST, default=None)
|
|
455
|
+
command.add_argument("--home", type=Path, default=None)
|
|
372
456
|
if each_action == "choose":
|
|
373
457
|
command.add_argument("--spent", action="append", default=[])
|
|
374
458
|
if each_action == "limits":
|
|
@@ -444,15 +528,26 @@ def _run_cli(product: Product, parsed: argparse.Namespace, parser: argparse.Argu
|
|
|
444
528
|
return 4 if outcome.status == "advisor_blocked" else outcome.returncode
|
|
445
529
|
|
|
446
530
|
|
|
531
|
+
def _refuse_home_misuse(product: Product, parsed: argparse.Namespace) -> None:
|
|
532
|
+
if parsed.home is None:
|
|
533
|
+
return
|
|
534
|
+
if product is not Product.CODEX:
|
|
535
|
+
raise BrokerConfigurationError(HOME_CODEX_ONLY_MESSAGE)
|
|
536
|
+
if getattr(parsed, "spent", None):
|
|
537
|
+
raise BrokerConfigurationError(HOME_WITH_SPENT_MESSAGE)
|
|
538
|
+
|
|
539
|
+
|
|
447
540
|
def _choose_cli(product: Product, parsed: argparse.Namespace) -> int:
|
|
541
|
+
_refuse_home_misuse(product, parsed)
|
|
448
542
|
now = datetime.now(timezone.utc)
|
|
449
543
|
all_state = _load_state(broker_state_path())
|
|
450
|
-
all_readings = read_accounts(product, all_state=all_state, now=now)
|
|
544
|
+
all_readings = read_accounts(product, all_state=all_state, now=now, home=parsed.home)
|
|
451
545
|
if parsed.action == "choose" and parsed.spent:
|
|
452
546
|
_save_spent_arguments(parsed.spent, all_readings, all_state, now, product)
|
|
453
547
|
spent, resets = _spent_for_readings(all_readings, all_state, now)
|
|
454
|
-
decision = choose_from_readings(product, all_readings, now=now, all_spent_accounts=spent, all_spent_resets=resets)
|
|
455
|
-
|
|
548
|
+
decision = choose_from_readings(product, all_readings, now=now, all_spent_accounts=spent, all_spent_resets=resets, required_tier=parsed.require_tier, is_home_named=parsed.home is not None)
|
|
549
|
+
if parsed.home is None:
|
|
550
|
+
decision = _with_outside_spent_marks(decision, _outside_roster_resets(product, all_readings, all_state, now))
|
|
456
551
|
if parsed.action == "choose":
|
|
457
552
|
print(json.dumps({"decision": decision_payload(decision), "accounts": readings_payload(all_readings), "state_path": str(broker_state_path())}))
|
|
458
553
|
return WAIT_EXIT_CODE if decision.action == "wait" else 0
|
|
@@ -72,6 +72,8 @@ from dev_env_scripts_constants.codex_account_constants import (
|
|
|
72
72
|
CODEX_ACCOUNT_LAUNCHERS_FILE_NAME,
|
|
73
73
|
CODEX_ACCOUNT_PROFILES_ENVIRONMENT_VARIABLE,
|
|
74
74
|
CODEX_HOME_ENVIRONMENT_VARIABLE,
|
|
75
|
+
MAIN_CODEX_HOME_DIRECTORY_NAME,
|
|
76
|
+
NO_ROSTER_ACCOUNT_NAME,
|
|
75
77
|
)
|
|
76
78
|
from dev_env_scripts_constants.shared_tree_constants import CLAUDE_CONFIG_DIR_ENV_VAR
|
|
77
79
|
from shared_tree_paths import resolve_shared_process_tree_scripts_directory
|
|
@@ -325,6 +327,9 @@ def read_codex_account_meters(account: Account) -> Meters:
|
|
|
325
327
|
FULL_PERCENT - weekly_window.used_percent if weekly_window else None,
|
|
326
328
|
weekly_window.resets_at if weekly_window else None,
|
|
327
329
|
usage.plan_type,
|
|
330
|
+
usage.has_credits,
|
|
331
|
+
usage.is_credits_unlimited,
|
|
332
|
+
usage.credit_balance,
|
|
328
333
|
)
|
|
329
334
|
|
|
330
335
|
|
|
@@ -511,6 +516,9 @@ def _meter_payload(meters: Meters | None) -> dict[str, object] | None:
|
|
|
511
516
|
"weekly_percent_left": meters.weekly_percent_left,
|
|
512
517
|
"weekly_resets_at": utc_time_text(meters.weekly_resets_at),
|
|
513
518
|
"plan_type": meters.plan_type,
|
|
519
|
+
"has_credits": meters.has_credits,
|
|
520
|
+
"is_credits_unlimited": meters.is_credits_unlimited,
|
|
521
|
+
"credit_balance": meters.credit_balance,
|
|
514
522
|
}
|
|
515
523
|
|
|
516
524
|
|
|
@@ -521,12 +529,17 @@ def _meters_from_payload(raw_meters: object) -> Meters | None:
|
|
|
521
529
|
if any(each_percent is not None and not isinstance(each_percent, (int, float)) for each_percent in all_percentages):
|
|
522
530
|
return None
|
|
523
531
|
plan_type = raw_meters.get("plan_type")
|
|
532
|
+
credit_balance = raw_meters.get("credit_balance")
|
|
533
|
+
is_balance_number = isinstance(credit_balance, (int, float)) and not isinstance(credit_balance, bool)
|
|
524
534
|
return Meters(
|
|
525
535
|
all_percentages[0],
|
|
526
536
|
parse_utc_time(raw_meters.get("session_resets_at")),
|
|
527
537
|
all_percentages[1],
|
|
528
538
|
parse_utc_time(raw_meters.get("weekly_resets_at")),
|
|
529
539
|
plan_type if isinstance(plan_type, str) else None,
|
|
540
|
+
raw_meters.get("has_credits") is True,
|
|
541
|
+
raw_meters.get("is_credits_unlimited") is True,
|
|
542
|
+
float(credit_balance) if is_balance_number else None,
|
|
530
543
|
)
|
|
531
544
|
|
|
532
545
|
|
|
@@ -573,7 +586,42 @@ def _last_good_meters(all_cached_fields: dict[str, object], now: datetime) -> tu
|
|
|
573
586
|
return meters, measured_at
|
|
574
587
|
|
|
575
588
|
|
|
576
|
-
def
|
|
589
|
+
def codex_default_account() -> Account:
|
|
590
|
+
"""Return the account for the default Codex home, read when no roster is configured.
|
|
591
|
+
|
|
592
|
+
::
|
|
593
|
+
|
|
594
|
+
CODEX_HOME "C:/work/codex-a" -> the home C:/work/codex-a
|
|
595
|
+
CODEX_HOME unset, "" or " " -> the home ~/.codex
|
|
596
|
+
|
|
597
|
+
Returns:
|
|
598
|
+
The account named ``default``. Its home is ``CODEX_HOME`` without its
|
|
599
|
+
padding, or ``~/.codex`` when the variable is unset or blank.
|
|
600
|
+
"""
|
|
601
|
+
exported_home = os.environ.get(CODEX_HOME_ENVIRONMENT_VARIABLE, "").strip()
|
|
602
|
+
home = Path(exported_home or Path.home() / MAIN_CODEX_HOME_DIRECTORY_NAME).resolve()
|
|
603
|
+
return Account(Product.CODEX, NO_ROSTER_ACCOUNT_NAME, home, True)
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def _account_for_home(all_roster: Sequence[Account], home: Path) -> Account:
|
|
607
|
+
resolved_home = home.expanduser().resolve()
|
|
608
|
+
roster_account = next(
|
|
609
|
+
(each_account for each_account in all_roster if os.path.normcase(each_account.home) == os.path.normcase(resolved_home)),
|
|
610
|
+
None,
|
|
611
|
+
)
|
|
612
|
+
return roster_account or Account(Product.CODEX, resolved_home.name or NO_ROSTER_ACCOUNT_NAME, resolved_home)
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _accounts_to_read(product: Product, adapter: ProductAdapter, home: Path | None) -> Sequence[Account]:
|
|
616
|
+
all_roster = adapter.load_accounts()
|
|
617
|
+
if home is not None:
|
|
618
|
+
return (_account_for_home(all_roster, home),)
|
|
619
|
+
if product is Product.CODEX and not all_roster:
|
|
620
|
+
return (codex_default_account(),)
|
|
621
|
+
return all_roster
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def read_accounts(product: Product, adapter: ProductAdapter | None = None, *, all_state: dict[str, object] | None = None, now: datetime | None = None, home: Path | None = None) -> tuple[Reading, ...]:
|
|
577
625
|
"""Read account meters with a 60-second cache.
|
|
578
626
|
|
|
579
627
|
Args:
|
|
@@ -581,16 +629,19 @@ def read_accounts(product: Product, adapter: ProductAdapter | None = None, *, al
|
|
|
581
629
|
adapter: Injected account and meter readers.
|
|
582
630
|
all_state: Mutable broker state document.
|
|
583
631
|
now: Clock instant used for cache age.
|
|
632
|
+
home: Codex home to read alone, not the roster. A roster account
|
|
633
|
+
with that home keeps its name; any other home reads as one extra account.
|
|
584
634
|
|
|
585
635
|
Returns:
|
|
586
|
-
Account readings in roster order.
|
|
636
|
+
Account readings in roster order. A Codex product with no roster reads
|
|
637
|
+
its default home as the one account.
|
|
587
638
|
"""
|
|
588
639
|
active = adapter or all_product_adapters[product]
|
|
589
640
|
current = now or datetime.now(timezone.utc)
|
|
590
641
|
all_cache = all_state.get("meters", {}) if all_state is not None else {}
|
|
591
642
|
all_readings: list[Reading] = []
|
|
592
643
|
is_updated = False
|
|
593
|
-
for each_account in active
|
|
644
|
+
for each_account in _accounts_to_read(product, active, home):
|
|
594
645
|
reading, did_read = _read_one_account(each_account, active, all_cache, current)
|
|
595
646
|
all_readings.append(reading)
|
|
596
647
|
is_updated = is_updated or did_read
|
|
@@ -2,12 +2,16 @@
|
|
|
2
2
|
"""Keep each Codex account's home and launcher ready.
|
|
3
3
|
|
|
4
4
|
Each Codex account signs in under its own Codex home in
|
|
5
|
-
``~/.codex-profiles/<name>``. The account list names them
|
|
5
|
+
``~/.codex-profiles/<name>``. The account list names them. The broker ranks
|
|
6
|
+
them by plan and room, and list order breaks only an exact tie. The list is the
|
|
6
7
|
``CODEX_ACCOUNT_PROFILES`` environment variable, comma-separated, else the saved
|
|
7
|
-
``account-launchers.json`` list under the profiles root. With neither,
|
|
8
|
-
``codex-1`` through ``codex-4``
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
``account-launchers.json`` list under the profiles root. With neither, ``sync``
|
|
9
|
+
falls back to ``codex-1`` through ``codex-4`` and ``install`` has no accounts.
|
|
10
|
+
The broker's ``choose`` and ``check`` fall back to those four only when
|
|
11
|
+
``CODEX_ACCOUNT_PROFILES`` holds only separators and no saved list names an
|
|
12
|
+
account; with the variable unset or blank they read the default Codex home as
|
|
13
|
+
the account ``default``. An environment roster that differs from the saved file
|
|
14
|
+
is saved to it, so a process without the variable reads the same roster.
|
|
11
15
|
|
|
12
16
|
Three commands::
|
|
13
17
|
|
|
@@ -196,7 +200,7 @@ def _save_environment_roster(
|
|
|
196
200
|
|
|
197
201
|
|
|
198
202
|
def saved_codex_account_names(profiles_root: Path) -> tuple[str, ...]:
|
|
199
|
-
"""Name the account list, in
|
|
203
|
+
"""Name the account list, in roster order, without duplicates.
|
|
200
204
|
|
|
201
205
|
::
|
|
202
206
|
|
|
@@ -222,7 +226,7 @@ def saved_codex_account_names(profiles_root: Path) -> tuple[str, ...]:
|
|
|
222
226
|
|
|
223
227
|
|
|
224
228
|
def codex_account_names(profiles_root: Path) -> tuple[str, ...]:
|
|
225
|
-
"""Name the accounts the broker and setup commands use, in
|
|
229
|
+
"""Name the accounts the broker and setup commands use, in roster order.
|
|
226
230
|
|
|
227
231
|
Args:
|
|
228
232
|
profiles_root: The directory that holds every account's Codex home.
|
|
@@ -241,7 +245,7 @@ def save_codex_account_names(profiles_root: Path, all_names: Sequence[str]) -> N
|
|
|
241
245
|
|
|
242
246
|
Args:
|
|
243
247
|
profiles_root: The directory that holds every account's Codex home.
|
|
244
|
-
all_names: The account names in
|
|
248
|
+
all_names: The account names in roster order.
|
|
245
249
|
"""
|
|
246
250
|
profiles_root.mkdir(parents=True, exist_ok=True)
|
|
247
251
|
roster_text = json.dumps(list(all_names), indent=ROSTER_JSON_INDENT) + "\n"
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Choose the Codex account a job runs on from the readings of the roster.
|
|
2
|
+
|
|
3
|
+
::
|
|
4
|
+
|
|
5
|
+
pro 5% left, team 90% left, no tier required -> pro, tier luna
|
|
6
|
+
the same roster, normal tier required -> team, tier normal
|
|
7
|
+
named team home, 0.5% of its week left -> that home, tier luna
|
|
8
|
+
|
|
9
|
+
A Pro plan account that can run comes before every account on another plan. A
|
|
10
|
+
named home on a paid plan runs whatever its room, credits or floors. It takes
|
|
11
|
+
the tier its meters allow, or the lowest tier when none allows it. A required
|
|
12
|
+
tier still applies, so a named home below it does not run.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from collections.abc import Sequence
|
|
18
|
+
|
|
19
|
+
from codex_plan_rules import codex_tier, is_pro_plan, is_refused_plan
|
|
20
|
+
from dev_env_scripts_constants.account_broker_constants import (
|
|
21
|
+
Decision,
|
|
22
|
+
Reading,
|
|
23
|
+
_rank_key,
|
|
24
|
+
)
|
|
25
|
+
from dev_env_scripts_constants.codex_account_constants import (
|
|
26
|
+
ALL_TIERS_BEST_FIRST,
|
|
27
|
+
CREDITS_REASON_TEMPLATE,
|
|
28
|
+
NAMED_HOME_REASON_TEMPLATE,
|
|
29
|
+
NORMAL_TIER_MINIMUM_PERCENT_LEFT,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _run_reason(reading: Reading) -> str:
|
|
34
|
+
name = reading.account.name
|
|
35
|
+
percent_left = reading.meters.tightest_percent_left
|
|
36
|
+
if (
|
|
37
|
+
reading.meters.has_spendable_credits
|
|
38
|
+
and percent_left <= NORMAL_TIER_MINIMUM_PERCENT_LEFT
|
|
39
|
+
):
|
|
40
|
+
return CREDITS_REASON_TEMPLATE.format(name=name, percent=percent_left)
|
|
41
|
+
return f"{name} has {percent_left:g}% left"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _choose_tier(all_candidates: Sequence[Reading], tier: str) -> Decision | None:
|
|
45
|
+
for each_reading in all_candidates:
|
|
46
|
+
if codex_tier(each_reading.meters) == tier:
|
|
47
|
+
return Decision(
|
|
48
|
+
"run", each_reading.account, None, _run_reason(each_reading), tier
|
|
49
|
+
)
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _accepted_tiers(required_tier: str | None) -> tuple[str, ...]:
|
|
54
|
+
if required_tier is None:
|
|
55
|
+
return ALL_TIERS_BEST_FIRST
|
|
56
|
+
return ALL_TIERS_BEST_FIRST[: ALL_TIERS_BEST_FIRST.index(required_tier) + 1]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _choose_named_home(all_available: Sequence[Reading], required_tier: str | None) -> Decision | None:
|
|
60
|
+
for each_reading in all_available:
|
|
61
|
+
if each_reading.meters is None or is_refused_plan(each_reading.meters):
|
|
62
|
+
continue
|
|
63
|
+
allowed_tier = codex_tier(each_reading.meters)
|
|
64
|
+
tier = allowed_tier or ALL_TIERS_BEST_FIRST[-1]
|
|
65
|
+
if tier not in _accepted_tiers(required_tier):
|
|
66
|
+
continue
|
|
67
|
+
reason = (
|
|
68
|
+
_run_reason(each_reading)
|
|
69
|
+
if allowed_tier
|
|
70
|
+
else NAMED_HOME_REASON_TEMPLATE.format(name=each_reading.account.name)
|
|
71
|
+
)
|
|
72
|
+
return Decision("run", each_reading.account, None, reason, tier)
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def choose_codex(
|
|
77
|
+
all_available: Sequence[Reading],
|
|
78
|
+
required_tier: str | None = None,
|
|
79
|
+
*,
|
|
80
|
+
is_home_named: bool = False,
|
|
81
|
+
) -> Decision | None:
|
|
82
|
+
"""Choose the Codex account for a new job, Pro plan accounts first.
|
|
83
|
+
|
|
84
|
+
::
|
|
85
|
+
|
|
86
|
+
roster, team 0.5% of its week left -> None, the job waits
|
|
87
|
+
named home, team 0.5% of its week left -> run on that home, tier luna
|
|
88
|
+
named home, free plan or unread meters, any room -> None
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
all_available: Readings the caller left available: accounts not spent, or spent Codex accounts with spendable credits, and not already tried in this run.
|
|
92
|
+
required_tier: The lowest tier the caller accepts, or None for any tier.
|
|
93
|
+
is_home_named: True when the caller named one Codex home, so its reading
|
|
94
|
+
runs on any paid plan whatever its room, credits or floors, unless
|
|
95
|
+
``required_tier`` is above the tier it reaches.
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
A run decision, or None when no account reaches an accepted tier.
|
|
99
|
+
"""
|
|
100
|
+
if is_home_named:
|
|
101
|
+
return _choose_named_home(all_available, required_tier)
|
|
102
|
+
all_candidates = sorted(all_available, key=_rank_key)
|
|
103
|
+
all_pro_candidates = [each_reading for each_reading in all_candidates if is_pro_plan(each_reading.meters)]
|
|
104
|
+
all_other_candidates = [each_reading for each_reading in all_candidates if not is_pro_plan(each_reading.meters)]
|
|
105
|
+
for each_group in (all_pro_candidates, all_other_candidates):
|
|
106
|
+
for each_tier in _accepted_tiers(required_tier):
|
|
107
|
+
chosen = _choose_tier(each_group, each_tier)
|
|
108
|
+
if chosen is not None:
|
|
109
|
+
return chosen
|
|
110
|
+
return None
|
|
@@ -5,12 +5,15 @@ Codex reports usage through ``codex app-server`` and the JSON-RPC method
|
|
|
5
5
|
``account/rateLimits/read``. The reply names up to two windows, a short one
|
|
6
6
|
(5 hours) and a weekly one. The account broker counts the account's room as
|
|
7
7
|
the smaller of the two. The reply also names the account's plan, such as
|
|
8
|
-
``pro`` or ``team
|
|
8
|
+
``pro`` or ``team``, and the credits the account holds::
|
|
9
9
|
|
|
10
10
|
5-hour window 30% used, week 85% used -> 15% left
|
|
11
11
|
week window only, 40% used -> 60% left
|
|
12
12
|
planType "promax" -> plan_type "promax"
|
|
13
13
|
no planType -> plan_type None
|
|
14
|
+
credits hasCredits, balance "12.5" -> has_credits, credit_balance 12.5
|
|
15
|
+
credits unlimited -> is_credits_unlimited
|
|
16
|
+
no credits object -> no credits, credit_balance None
|
|
14
17
|
no window, error reply, no reply -> CodexMeterUnreadError
|
|
15
18
|
|
|
16
19
|
Every read failure raises ``CodexMeterUnreadError``. A missing Codex
|
|
@@ -44,7 +47,10 @@ from dev_env_scripts_constants.codex_account_constants import (
|
|
|
44
47
|
CLIENT_VERSION,
|
|
45
48
|
CODEX_BINARY_NAME,
|
|
46
49
|
CODEX_HOME_ENVIRONMENT_VARIABLE,
|
|
50
|
+
CREDIT_BALANCE_KEY,
|
|
51
|
+
CREDITS_KEY,
|
|
47
52
|
FULL_PERCENT,
|
|
53
|
+
HAS_CREDITS_KEY,
|
|
48
54
|
INITIALIZE_REQUEST_ID,
|
|
49
55
|
JSONRPC_VERSION,
|
|
50
56
|
METHOD_INITIALIZE,
|
|
@@ -54,6 +60,7 @@ from dev_env_scripts_constants.codex_account_constants import (
|
|
|
54
60
|
RATE_LIMITS_REQUEST_ID,
|
|
55
61
|
READER_JOIN_TIMEOUT_SECONDS,
|
|
56
62
|
TEXT_ENCODING,
|
|
63
|
+
UNLIMITED_CREDITS_KEY,
|
|
57
64
|
WEEKLY_WINDOW_MINUTES,
|
|
58
65
|
)
|
|
59
66
|
from shared_tree_paths import resolve_shared_process_tree_scripts_directory
|
|
@@ -95,10 +102,13 @@ class UsageWindow:
|
|
|
95
102
|
|
|
96
103
|
@dataclass(frozen=True)
|
|
97
104
|
class CodexAccountMeters:
|
|
98
|
-
"""One account's windows and
|
|
105
|
+
"""One account's windows, plan and credits, with its tightest short window and its tightest weekly window."""
|
|
99
106
|
|
|
100
107
|
all_windows: tuple[UsageWindow, ...]
|
|
101
108
|
plan_type: str | None = None
|
|
109
|
+
has_credits: bool = False
|
|
110
|
+
is_credits_unlimited: bool = False
|
|
111
|
+
credit_balance: float | None = None
|
|
102
112
|
|
|
103
113
|
@property
|
|
104
114
|
def short_window(self) -> UsageWindow | None:
|
|
@@ -128,6 +138,25 @@ def _finite_number(raw_number: object) -> float | None:
|
|
|
128
138
|
return float(raw_number)
|
|
129
139
|
|
|
130
140
|
|
|
141
|
+
def _credit_balance(raw_balance: object) -> float | None:
|
|
142
|
+
if not isinstance(raw_balance, str):
|
|
143
|
+
return _finite_number(raw_balance)
|
|
144
|
+
try:
|
|
145
|
+
return _finite_number(float(raw_balance))
|
|
146
|
+
except ValueError:
|
|
147
|
+
return None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _parse_credits(raw_credits: object) -> tuple[bool, bool, float | None]:
|
|
151
|
+
if not isinstance(raw_credits, Mapping):
|
|
152
|
+
return False, False, None
|
|
153
|
+
return (
|
|
154
|
+
raw_credits.get(HAS_CREDITS_KEY) is True,
|
|
155
|
+
raw_credits.get(UNLIMITED_CREDITS_KEY) is True,
|
|
156
|
+
_credit_balance(raw_credits.get(CREDIT_BALANCE_KEY)),
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
|
|
131
160
|
def _parse_resets_at(raw_resets_at: object) -> datetime | None:
|
|
132
161
|
seconds = _finite_number(raw_resets_at)
|
|
133
162
|
if seconds is None:
|
|
@@ -184,12 +213,15 @@ def parse_rate_limits_reply(reply_text: str) -> CodexAccountMeters:
|
|
|
184
213
|
"planType": "promax"}}}
|
|
185
214
|
-> CodexAccountMeters with two windows, 15% left, plan_type "promax"
|
|
186
215
|
the same reply without "planType" -> plan_type None
|
|
216
|
+
"credits": {"hasCredits": true, "unlimited": false, "balance": "12.5"}
|
|
217
|
+
-> has_credits True, is_credits_unlimited False, credit_balance 12.5
|
|
218
|
+
the same reply without "credits" -> no credits, credit_balance None
|
|
187
219
|
|
|
188
220
|
Args:
|
|
189
221
|
reply_text: One line the ``codex app-server`` process wrote.
|
|
190
222
|
|
|
191
223
|
Returns:
|
|
192
|
-
The windows
|
|
224
|
+
The windows, the plan type and the credits the reply carries.
|
|
193
225
|
|
|
194
226
|
Raises:
|
|
195
227
|
CodexMeterUnreadError: The line is no reply, an error reply, or names
|
|
@@ -204,7 +236,14 @@ def parse_rate_limits_reply(reply_text: str) -> CodexAccountMeters:
|
|
|
204
236
|
if not all_windows:
|
|
205
237
|
raise CodexMeterUnreadError("rate-limit reply names no usage window")
|
|
206
238
|
plan_type = rate_limits.get("planType")
|
|
207
|
-
|
|
239
|
+
has_credits, is_credits_unlimited, credit_balance = _parse_credits(rate_limits.get(CREDITS_KEY))
|
|
240
|
+
return CodexAccountMeters(
|
|
241
|
+
all_windows=all_windows,
|
|
242
|
+
plan_type=plan_type if isinstance(plan_type, str) else None,
|
|
243
|
+
has_credits=has_credits,
|
|
244
|
+
is_credits_unlimited=is_credits_unlimited,
|
|
245
|
+
credit_balance=credit_balance,
|
|
246
|
+
)
|
|
208
247
|
|
|
209
248
|
|
|
210
249
|
def request_messages() -> list[dict[str, object]]:
|