firstchair 0.1.0a3__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.
- firstchair/__init__.py +40 -0
- firstchair/__main__.py +3 -0
- firstchair/accounts.py +239 -0
- firstchair/claude_json.py +78 -0
- firstchair/cli.py +544 -0
- firstchair/codex_jsonl.py +80 -0
- firstchair/conductor.py +799 -0
- firstchair/config.py +23 -0
- firstchair/cswap.py +290 -0
- firstchair/delegation.py +1250 -0
- firstchair/fallback.py +12 -0
- firstchair/grok_jsonl.py +86 -0
- firstchair/handoff.py +29 -0
- firstchair/inventory.py +40 -0
- firstchair/live.py +525 -0
- firstchair/parallel.py +53 -0
- firstchair/provider.py +263 -0
- firstchair/quota.py +271 -0
- firstchair/redaction.py +50 -0
- firstchair/release_tag.py +102 -0
- firstchair/rotation.py +346 -0
- firstchair/sessions.py +40 -0
- firstchair/state_listing.py +56 -0
- firstchair/strict_json.py +20 -0
- firstchair/synthetic.py +49 -0
- firstchair/usage.py +50 -0
- firstchair/versions.py +42 -0
- firstchair/workflow.py +269 -0
- firstchair-0.1.0a3.dist-info/METADATA +371 -0
- firstchair-0.1.0a3.dist-info/RECORD +34 -0
- firstchair-0.1.0a3.dist-info/WHEEL +5 -0
- firstchair-0.1.0a3.dist-info/entry_points.txt +3 -0
- firstchair-0.1.0a3.dist-info/licenses/LICENSE +21 -0
- firstchair-0.1.0a3.dist-info/top_level.txt +1 -0
firstchair/__init__.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Local orchestration for AI coding CLIs."""
|
|
2
|
+
|
|
3
|
+
import subprocess
|
|
4
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
__version__ = version("firstchair")
|
|
9
|
+
except PackageNotFoundError:
|
|
10
|
+
__version__ = "0.1.0a3"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def checkout_commit(root: Path) -> str | None:
|
|
14
|
+
"""The short commit of the Git checkout at ``root``, marked when files differ from it."""
|
|
15
|
+
if not (root / ".git").exists():
|
|
16
|
+
return None
|
|
17
|
+
try:
|
|
18
|
+
def git(*args: str) -> str:
|
|
19
|
+
return subprocess.run(
|
|
20
|
+
("git", "-C", str(root), *args), capture_output=True, text=True, timeout=5, check=True,
|
|
21
|
+
).stdout.strip()
|
|
22
|
+
commit = git("rev-parse", "--short", "HEAD")
|
|
23
|
+
return f"{commit}, modified" if git("status", "--porcelain", "--untracked-files=no") else commit
|
|
24
|
+
except (OSError, subprocess.SubprocessError):
|
|
25
|
+
return None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def build_commit() -> str | None:
|
|
29
|
+
"""The commit this copy was built from, so a stale install can be told from a current one."""
|
|
30
|
+
try:
|
|
31
|
+
from ._build import COMMIT # Written by setup.py when the package is built.
|
|
32
|
+
except ImportError:
|
|
33
|
+
# Running from the source tree: src/firstchair/__init__.py sits two levels down.
|
|
34
|
+
return checkout_commit(Path(__file__).resolve().parents[2])
|
|
35
|
+
return COMMIT if isinstance(COMMIT, str) and COMMIT else None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def describe_version() -> str:
|
|
39
|
+
commit = build_commit()
|
|
40
|
+
return f"{__version__} ({commit})" if commit else __version__
|
firstchair/__main__.py
ADDED
firstchair/accounts.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Named provider homes and native sign-in, with no Firstchair credential store."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
import stat
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import tempfile
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
HOME_VARIABLE = {"codex": "CODEX_HOME", "claude": "CLAUDE_CONFIG_DIR", "grok": "GROK_HOME"}
|
|
15
|
+
LOGIN = {
|
|
16
|
+
"codex": ("codex", "login"),
|
|
17
|
+
"claude": ("claude", "auth", "login", "--claudeai"),
|
|
18
|
+
"grok": ("grok", "login"),
|
|
19
|
+
}
|
|
20
|
+
CLAUDE_PROBE = (
|
|
21
|
+
"claude", "-p", "Reply with exactly FIRSTCHAIR_SMOKE_OK. Do not use any tools.",
|
|
22
|
+
"--tools", "", "--setting-sources", "", "--no-session-persistence",
|
|
23
|
+
"--output-format", "json",
|
|
24
|
+
)
|
|
25
|
+
CHECK = {
|
|
26
|
+
"codex": ("codex", "login", "status"),
|
|
27
|
+
"claude": ("claude", "auth", "status", "--json"),
|
|
28
|
+
"grok": ("grok", "--no-auto-update", "-p", "Reply exactly FIRSTCHAIR_AUTH_OK. Use no tools.",
|
|
29
|
+
"--output-format", "plain", "--tools", "", "--no-subagents"),
|
|
30
|
+
}
|
|
31
|
+
CREDENTIAL_OVERRIDES = {
|
|
32
|
+
"OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_ACCESS_TOKEN", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN",
|
|
33
|
+
"CLAUDE_CODE_OAUTH_TOKEN", "XAI_API_KEY", "GROK_API_KEY",
|
|
34
|
+
}
|
|
35
|
+
PROFILE_NAME = re.compile(r"[a-z0-9][a-z0-9_-]{0,31}")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def profile_root() -> Path:
|
|
39
|
+
if not hasattr(os, "getuid"):
|
|
40
|
+
raise ValueError("named accounts require POSIX directory permissions")
|
|
41
|
+
state = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state")
|
|
42
|
+
if not state.is_absolute():
|
|
43
|
+
raise ValueError("XDG_STATE_HOME must be absolute")
|
|
44
|
+
state = state.resolve()
|
|
45
|
+
if state.exists():
|
|
46
|
+
info = state.stat()
|
|
47
|
+
if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o022:
|
|
48
|
+
raise ValueError("XDG state directory must be owned by you and protected from other writers")
|
|
49
|
+
root = state / "firstchair" / "accounts"
|
|
50
|
+
markers = (parent / ".git" for parent in (root, *root.parents))
|
|
51
|
+
if any(marker.is_file() or (marker / "HEAD").is_file() for marker in markers):
|
|
52
|
+
raise ValueError("account storage must be outside Git checkouts")
|
|
53
|
+
return root
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def private_directory(path: Path, *, create: bool) -> None:
|
|
57
|
+
if create:
|
|
58
|
+
path.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
59
|
+
info = path.lstat()
|
|
60
|
+
if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
|
|
61
|
+
raise ValueError("account directories must be owned by you, private, and free of symlinks")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def profile_home(provider: str, name: str, *, create: bool = False) -> Path:
|
|
65
|
+
if not PROFILE_NAME.fullmatch(name):
|
|
66
|
+
raise ValueError("profile names use 1–32 lowercase letters, digits, hyphens, or underscores")
|
|
67
|
+
root = profile_root()
|
|
68
|
+
home = root / provider / name
|
|
69
|
+
for directory in (root.parent, root, home.parent, home):
|
|
70
|
+
try:
|
|
71
|
+
private_directory(directory, create=create)
|
|
72
|
+
except FileNotFoundError:
|
|
73
|
+
raise ValueError("unknown account profile; sign in with firstchair auth login") from None
|
|
74
|
+
return home
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def account_environment(provider: str, name: str, *, create: bool = False) -> dict[str, str]:
|
|
78
|
+
from . import cswap
|
|
79
|
+
|
|
80
|
+
if cswap.is_cswap_profile(provider, name):
|
|
81
|
+
# A claude-swap slot: cswap owns the login and `cswap run` sets the
|
|
82
|
+
# config home, so only the credential overrides are removed here.
|
|
83
|
+
if create:
|
|
84
|
+
raise ValueError("cswap accounts are added with `cswap add`, not firstchair auth login")
|
|
85
|
+
return {
|
|
86
|
+
key: value for key, value in cswap.environment().items()
|
|
87
|
+
if key not in CREDENTIAL_OVERRIDES
|
|
88
|
+
}
|
|
89
|
+
home = profile_home(provider, name, create=create)
|
|
90
|
+
env = {key: value for key, value in os.environ.items() if key not in CREDENTIAL_OVERRIDES}
|
|
91
|
+
env.update({HOME_VARIABLE[provider]: str(home)})
|
|
92
|
+
return env
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def claude_failure(stdout: str) -> str:
|
|
96
|
+
"""Report a recognized HTTP status without exposing the provider payload."""
|
|
97
|
+
try:
|
|
98
|
+
data = json.loads(stdout)
|
|
99
|
+
except (ValueError, RecursionError):
|
|
100
|
+
return "provider_exit"
|
|
101
|
+
if not isinstance(data, dict) or data.get("type") != "result" or data.get("is_error") is not True:
|
|
102
|
+
return "provider_exit"
|
|
103
|
+
status = data.get("api_error_status")
|
|
104
|
+
if status == 429:
|
|
105
|
+
return "rate_limited"
|
|
106
|
+
if status in (401, 403):
|
|
107
|
+
return "authorization_failed"
|
|
108
|
+
return "provider_exit"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def list_profiles() -> list[dict[str, str]]:
|
|
112
|
+
"""Every named sign-in on this machine, by provider then name."""
|
|
113
|
+
root = profile_root()
|
|
114
|
+
profiles: list[dict[str, str]] = []
|
|
115
|
+
if root.exists() or root.is_symlink():
|
|
116
|
+
private_directory(root.parent, create=False)
|
|
117
|
+
private_directory(root, create=False)
|
|
118
|
+
for provider in LOGIN:
|
|
119
|
+
directory = root / provider
|
|
120
|
+
if directory.exists() or directory.is_symlink():
|
|
121
|
+
private_directory(directory, create=False)
|
|
122
|
+
for candidate in sorted(directory.iterdir()):
|
|
123
|
+
profile_home(provider, candidate.name)
|
|
124
|
+
profiles.append({"provider": provider, "profile": candidate.name})
|
|
125
|
+
# claude-swap slots, when the bridge is enabled (FIRSTCHAIR_CSWAP=1).
|
|
126
|
+
from . import cswap
|
|
127
|
+
|
|
128
|
+
profiles.extend(cswap.list_profiles())
|
|
129
|
+
return profiles
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def configure_parser(parser: argparse.ArgumentParser) -> None:
|
|
133
|
+
commands = parser.add_subparsers(dest="auth_command", required=True)
|
|
134
|
+
login = commands.add_parser("login", help="Sign in through the provider CLI")
|
|
135
|
+
login.add_argument("provider", choices=LOGIN)
|
|
136
|
+
login.add_argument("profile")
|
|
137
|
+
login.add_argument("--device-auth", action="store_true", help="Use device-code sign-in over SSH (Codex and Grok)")
|
|
138
|
+
check = commands.add_parser("check", help="Check a login without printing account information")
|
|
139
|
+
check.add_argument("provider", choices=CHECK)
|
|
140
|
+
check.add_argument("profile", nargs="?")
|
|
141
|
+
check.add_argument("--probe", action="store_true", help="Also test Claude inference with a fixed prompt")
|
|
142
|
+
commands.add_parser("list", help="List local profile aliases")
|
|
143
|
+
usage = commands.add_parser("usage", help="Show what Firstchair sent through each account, and cooldowns")
|
|
144
|
+
usage.add_argument("--window", type=float, default=5 * 3600.0, help="Seconds to look back (default 18000)")
|
|
145
|
+
usage.add_argument(
|
|
146
|
+
"--refresh", action="store_true",
|
|
147
|
+
help="Ask each provider for real usage now. Claude Code is asked with one short prompt per account",
|
|
148
|
+
)
|
|
149
|
+
clear = commands.add_parser("clear-cooldown", help="Let accounts in a cooldown be used again")
|
|
150
|
+
clear.add_argument("account", nargs="*", help="PROVIDER or PROVIDER:PROFILE (default: all)")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def execute(args: argparse.Namespace) -> int:
|
|
154
|
+
try:
|
|
155
|
+
if args.auth_command == "list":
|
|
156
|
+
print(json.dumps({"profiles": list_profiles()}, indent=2))
|
|
157
|
+
return 0
|
|
158
|
+
if args.auth_command in {"usage", "clear-cooldown"}:
|
|
159
|
+
from . import rotation # Imported here: rotation imports this module.
|
|
160
|
+
|
|
161
|
+
path = rotation.ledger_path()
|
|
162
|
+
if args.auth_command == "clear-cooldown":
|
|
163
|
+
cleared = rotation.clear_cooldowns(path, args.account or None)
|
|
164
|
+
print(json.dumps({"cleared": cleared}, indent=2))
|
|
165
|
+
return 0
|
|
166
|
+
policy = rotation.Policy(window_seconds=args.window)
|
|
167
|
+
if args.refresh:
|
|
168
|
+
from .quota import READERS, read_quota
|
|
169
|
+
|
|
170
|
+
# Named sign-ins, plus the default sign-in of each provider that can be asked.
|
|
171
|
+
targets = [(item["provider"], item["profile"]) for item in list_profiles()]
|
|
172
|
+
targets += [(provider, None) for provider in READERS if shutil.which(provider)]
|
|
173
|
+
readings = {
|
|
174
|
+
rotation.account_key(provider, profile): quota
|
|
175
|
+
for provider, profile in targets
|
|
176
|
+
if (quota := read_quota(provider, profile)) is not None
|
|
177
|
+
}
|
|
178
|
+
rotation.store_quota(path, readings)
|
|
179
|
+
ledger = rotation.read_ledger(path)
|
|
180
|
+
keys = sorted({
|
|
181
|
+
*ledger,
|
|
182
|
+
*(rotation.account_key(item["provider"], item["profile"]) for item in list_profiles()),
|
|
183
|
+
})
|
|
184
|
+
now = rotation.time.time()
|
|
185
|
+
print(json.dumps({
|
|
186
|
+
"window_seconds": policy.window_seconds,
|
|
187
|
+
"accounts": [rotation.standing(key, ledger, policy, now) for key in keys],
|
|
188
|
+
}, indent=2))
|
|
189
|
+
return 0
|
|
190
|
+
provider = args.provider
|
|
191
|
+
if shutil.which(provider) is None:
|
|
192
|
+
raise ValueError(f"{provider} is not installed")
|
|
193
|
+
login = args.auth_command == "login"
|
|
194
|
+
if login and args.device_auth and provider == "claude":
|
|
195
|
+
raise ValueError("Claude Code uses its native sign-in URL and browser code over SSH")
|
|
196
|
+
if login and not sys.stdin.isatty():
|
|
197
|
+
raise ValueError("open a terminal to complete the provider's interactive sign-in")
|
|
198
|
+
probe = not login and args.probe
|
|
199
|
+
if probe and provider != "claude":
|
|
200
|
+
raise ValueError("--probe is available for Claude Code")
|
|
201
|
+
env = account_environment(provider, args.profile, create=login) if args.profile is not None else None
|
|
202
|
+
with tempfile.TemporaryDirectory(prefix="firstchair-auth-") as cwd:
|
|
203
|
+
if login:
|
|
204
|
+
command = (*LOGIN[provider], "--device-auth") if args.device_auth else LOGIN[provider]
|
|
205
|
+
return int(subprocess.run(command, cwd=cwd, env=env, umask=0o077).returncode != 0)
|
|
206
|
+
result = subprocess.run(
|
|
207
|
+
CLAUDE_PROBE if probe else CHECK[provider], cwd=cwd, env=env,
|
|
208
|
+
stdin=subprocess.DEVNULL, capture_output=True,
|
|
209
|
+
text=True, errors="replace", timeout=30, umask=0o077 if env is not None else -1,
|
|
210
|
+
)
|
|
211
|
+
if probe:
|
|
212
|
+
reason = claude_failure(result.stdout)
|
|
213
|
+
try:
|
|
214
|
+
data = json.loads(result.stdout)
|
|
215
|
+
except (ValueError, RecursionError):
|
|
216
|
+
data = None
|
|
217
|
+
ready = (result.returncode == 0 and isinstance(data, dict)
|
|
218
|
+
and data.get("type") == "result" and data.get("is_error") is False
|
|
219
|
+
and data.get("result") == "FIRSTCHAIR_SMOKE_OK")
|
|
220
|
+
status = "ready" if ready else reason
|
|
221
|
+
print(json.dumps({"provider": provider, "status": status}))
|
|
222
|
+
return int(not ready)
|
|
223
|
+
if provider == "claude":
|
|
224
|
+
data = json.loads(result.stdout)
|
|
225
|
+
if not isinstance(data, dict) or type(data.get("loggedIn")) is not bool:
|
|
226
|
+
raise ValueError("Claude login status returned an unexpected response")
|
|
227
|
+
ready = result.returncode == 0 and data["loggedIn"]
|
|
228
|
+
elif provider == "grok":
|
|
229
|
+
ready = result.returncode == 0 and result.stdout.strip() == "FIRSTCHAIR_AUTH_OK"
|
|
230
|
+
else:
|
|
231
|
+
ready = result.returncode == 0
|
|
232
|
+
print(json.dumps({"provider": provider, "status": "authenticated" if ready else "unverified"}))
|
|
233
|
+
return int(not ready)
|
|
234
|
+
except subprocess.TimeoutExpired:
|
|
235
|
+
print(json.dumps({"error": "provider authentication check timed out"}), file=sys.stderr)
|
|
236
|
+
except (OSError, ValueError) as error:
|
|
237
|
+
message = str(error) if type(error) is ValueError else "could not read account state or start provider"
|
|
238
|
+
print(json.dumps({"error": message}), file=sys.stderr)
|
|
239
|
+
return 2
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Parse the Claude Code headless text result envelope."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
from dataclasses import replace
|
|
6
|
+
|
|
7
|
+
from .provider import ProviderError
|
|
8
|
+
from .quota import parse_claude_stream
|
|
9
|
+
from .strict_json import load_json
|
|
10
|
+
from .usage import Reply, parse_usage
|
|
11
|
+
from .versions import check_version
|
|
12
|
+
|
|
13
|
+
SUPPORTED_VERSION = "2.1.328"
|
|
14
|
+
ERROR_SUBTYPES = (
|
|
15
|
+
"error_during_execution",
|
|
16
|
+
"error_max_budget_usd",
|
|
17
|
+
"error_max_structured_output_retries",
|
|
18
|
+
"error_max_turns",
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def parse_claude_json(output: bytes, *, version: str, returncode: int) -> Reply:
|
|
23
|
+
"""Extract a reply from the already bounded stdout of one JSON-mode run."""
|
|
24
|
+
check_version("claude", version)
|
|
25
|
+
invalid_result = "provider_exit" if returncode != 0 else "malformed_response"
|
|
26
|
+
try:
|
|
27
|
+
result = load_json(output.decode("utf-8"))
|
|
28
|
+
except (ValueError, RecursionError):
|
|
29
|
+
raise ProviderError(invalid_result) from None
|
|
30
|
+
if not isinstance(result, dict) or result.get("type") != "result":
|
|
31
|
+
raise ProviderError(invalid_result)
|
|
32
|
+
|
|
33
|
+
if result.get("is_error") is True:
|
|
34
|
+
status = result.get("api_error_status")
|
|
35
|
+
if status == 429:
|
|
36
|
+
raise ProviderError("rate_limited")
|
|
37
|
+
if status in (401, 403):
|
|
38
|
+
raise ProviderError("authorization_failed")
|
|
39
|
+
if returncode != 0:
|
|
40
|
+
raise ProviderError("provider_exit")
|
|
41
|
+
|
|
42
|
+
subtype = result.get("subtype")
|
|
43
|
+
is_error = result.get("is_error")
|
|
44
|
+
if is_error is True or subtype in ERROR_SUBTYPES:
|
|
45
|
+
raise ProviderError("provider_turn_failed")
|
|
46
|
+
if subtype != "success" or is_error is not False:
|
|
47
|
+
raise ProviderError("malformed_response")
|
|
48
|
+
if result.get("api_error_status") is not None or result.get("errors"):
|
|
49
|
+
raise ProviderError("provider_turn_failed")
|
|
50
|
+
|
|
51
|
+
text = result.get("result")
|
|
52
|
+
if not isinstance(text, str) or not text.strip():
|
|
53
|
+
raise ProviderError("malformed_response")
|
|
54
|
+
return Reply(text, parse_usage(result))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def parse_claude_stream_reply(output: bytes, *, version: str, returncode: int) -> Reply:
|
|
58
|
+
"""Extract a reply from one ``stream-json`` run.
|
|
59
|
+
|
|
60
|
+
The last ``result`` line is the same envelope JSON mode prints, and it is
|
|
61
|
+
held to the same rules. A ``rate_limit_event`` in the stream adds the
|
|
62
|
+
account's real usage. Output with no result line is judged as a whole,
|
|
63
|
+
so a single JSON-mode envelope is still accepted.
|
|
64
|
+
"""
|
|
65
|
+
envelope = output
|
|
66
|
+
for line in reversed(output.splitlines()):
|
|
67
|
+
try:
|
|
68
|
+
message = json.loads(line)
|
|
69
|
+
except (ValueError, RecursionError):
|
|
70
|
+
continue
|
|
71
|
+
if isinstance(message, dict) and message.get("type") == "result":
|
|
72
|
+
envelope = line
|
|
73
|
+
break
|
|
74
|
+
reply = parse_claude_json(envelope, version=version, returncode=returncode)
|
|
75
|
+
try:
|
|
76
|
+
return replace(reply, quota=parse_claude_stream(output, time.time()))
|
|
77
|
+
except ValueError:
|
|
78
|
+
return reply
|