fairshare-cli 0.1.1__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.
@@ -0,0 +1,15 @@
1
+ # Capacity is relative to Pro (= 1.0), so 10% of a bigger plan counts for more.
2
+ # Anthropic, "What is the Max plan?" (support.claude.com, read 2026-11-09): "five times the Pro
3
+ # plan's usage every five hours and every week".
4
+ name = "claude-max"
5
+ provider = "claude"
6
+ capacity = 5.0
7
+ names = ["max"] # unverified: only "pro" has been seen from `claude auth status`
8
+
9
+ [windows.short]
10
+ name = "five_hour"
11
+ hours = 5
12
+
13
+ [windows.long]
14
+ name = "seven_day"
15
+ hours = 168
@@ -0,0 +1,13 @@
1
+ # Capacity is relative to Pro (= 1.0), so 10% of a bigger plan counts for more.
2
+ name = "claude-pro"
3
+ provider = "claude"
4
+ capacity = 1.0
5
+ names = ["pro"] # what `claude auth status` calls this plan; used to detect it
6
+
7
+ [windows.short]
8
+ name = "five_hour"
9
+ hours = 5
10
+
11
+ [windows.long]
12
+ name = "seven_day"
13
+ hours = 168
@@ -0,0 +1,17 @@
1
+ # Capacity is relative to Pro (= 1.0), so 10% of a bigger plan counts for more.
2
+ # Anthropic, "What is the Ultra plan?" (support.claude.com, read 2026-11-09): "10 times the Pro
3
+ # plan's usage every week" and no five-hour limit for verified accounts (unverified accounts get
4
+ # a temporary one). Formerly Max 20x.
5
+ name = "claude-ultra"
6
+ provider = "claude"
7
+ capacity = 10.0
8
+ names = ["ultra"] # unverified: only "pro" has been seen from `claude auth status`
9
+
10
+ # Usually absent for Ultra; an absent window counts as unused, a temporary one is honoured.
11
+ [windows.short]
12
+ name = "five_hour"
13
+ hours = 5
14
+
15
+ [windows.long]
16
+ name = "seven_day"
17
+ hours = 168
fairshare/policy.py ADDED
@@ -0,0 +1,73 @@
1
+ """The routing rule. Pure: accounts + snapshots + now in, ranked verdicts out. No I/O."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+
6
+ from .model import Account, Snapshot, Tuning
7
+
8
+ HOUR = 3600.0
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Verdict:
13
+ account: Account
14
+ eligible: bool # False = near a limit; the CLI reports it, ranking ignores it
15
+ score: float # budget units to burn per hour to use the long window fully,
16
+ # scaled down while the short window is nearly full; an
17
+ # exhausted week is -(hours until it resets), below any usable
18
+ # account
19
+ reason: str
20
+ usable_in: float # hours until it is eligible again; 0 when eligible now
21
+
22
+
23
+ def _dur(hours: float, digits: int = 0) -> str:
24
+ """A time to reset for people: minutes under an hour, else hours."""
25
+ return f"{max(0, round(hours * 60))}m" if hours < 1 else f"{hours:.{digits}f}h"
26
+
27
+
28
+ def evaluate(acct: Account, snap: Snapshot | None, now: float, t: Tuning) -> Verdict:
29
+ p = acct.plan
30
+ wins = snap.windows if snap else {}
31
+ short, long_ = wins.get(p.short_name), wins.get(p.long_name)
32
+ # A window past its reset has rolled over: treat as unused.
33
+ if short and short.resets_at <= now:
34
+ short = None
35
+ if long_ and long_.resets_at <= now:
36
+ long_ = None
37
+
38
+ short_used = short.used_pct if short else 0.0
39
+ short_in = (short.resets_at - now) / HOUR if short else None
40
+ long_used = long_.used_pct if long_ else 0.0
41
+ long_in = (long_.resets_at - now) / HOUR if long_ else p.long_hours # unknown = a fresh window
42
+ score = p.capacity * (100.0 - long_used) / max(long_in, t.min_hours)
43
+
44
+ # Near the short limit and not about to reset: only the unused part of that window is usable.
45
+ hot = short_used >= t.short_hot_pct and (short_in or 0) >= t.grace_hours
46
+ if hot:
47
+ score *= (100.0 - short_used) / 100.0
48
+ # A spent week is a fact, not a preference: nothing usable until it resets.
49
+ exhausted = long_used >= t.long_exhausted_pct
50
+ if exhausted:
51
+ score = -long_in
52
+ if long_ is None:
53
+ why = f"no active {p.long_name} window, assumed fresh"
54
+ elif hot and not exhausted:
55
+ why = f"{p.short_name} {short_used:.0f}% used, resets in {_dur(short_in, 1)}"
56
+ else:
57
+ why = f"{p.long_name} {long_used:.0f}% used, resets in {_dur(long_in)}"
58
+ # A hot short window stops counting once its reset is within the grace period.
59
+ usable_in = max(short_in - t.grace_hours if hot else 0.0, long_in if exhausted else 0.0)
60
+ return Verdict(acct, not (hot or exhausted), score, why, usable_in)
61
+
62
+
63
+ def rank(accounts: list[Account], snaps: dict[str, Snapshot], now: float,
64
+ t: Tuning = Tuning()) -> list[Verdict]:
65
+ """Best first: highest score, ties by id."""
66
+ vs = [evaluate(a, snaps.get(a.id), now, t) for a in accounts]
67
+ return sorted(vs, key=lambda v: (-v.score, v.account.id))
68
+
69
+
70
+ def prefer(verdicts: list[Verdict], account_id: str) -> list[Verdict]:
71
+ """The user's preferred account first while it is eligible; otherwise the ranking as is."""
72
+ chosen = [v for v in verdicts if v.account.id == account_id and v.eligible]
73
+ return chosen + [v for v in verdicts if v not in chosen]
@@ -0,0 +1,12 @@
1
+ from __future__ import annotations
2
+
3
+ from . import claude
4
+
5
+ REGISTRY = {claude.name: claude}
6
+
7
+
8
+ def get(name: str):
9
+ try:
10
+ return REGISTRY[name]
11
+ except KeyError:
12
+ raise SystemExit(f"fairshare: unknown provider '{name}' (known: {', '.join(REGISTRY)})")
@@ -0,0 +1,193 @@
1
+ """What a provider adapter must do. Add a provider = one new file implementing this.
2
+ Every fact about the provider that its vendor may change (binary name, arguments, environment
3
+ variables, file and folder names, JSON fields, output formats) is a named constant in that file;
4
+ nothing outside it spells one."""
5
+ from __future__ import annotations
6
+
7
+ from pathlib import Path
8
+ from typing import Protocol
9
+
10
+ from ..model import (Account, AccountStatus, Candidate, Capture, LiveSession, NoteEvent,
11
+ SessionSeen, Window)
12
+
13
+
14
+ class Provider(Protocol):
15
+ name: str
16
+ tool: str # the provider's tool as users know it, for messages
17
+ command: str # the command users type to start the tool, for messages
18
+ default_dir: str # the folder the tool uses when told none, as users write it
19
+ web: str # where users sign in and out in a browser, for messages
20
+ default_plan: str # proposed at join when the sign-in check names no plan
21
+ shared: tuple[str, ...] # what every account shares through the hub; "x/" names a folder
22
+ not_copied: tuple[str, ...] # of those, what join never copies in: live state, keys
23
+ usage_timeout: float # seconds read_usage waits at most
24
+ resumes_at_reset: bool # the tool resumes a session its limit stopped once the limit resets
25
+
26
+ def parse_capture(self, raw: dict) -> dict[str, Window]:
27
+ """Turn the provider's own usage payload into windows keyed by the plan's window names.
28
+ Return {} when the payload carries no usage."""
29
+
30
+ def session_of(self, raw: object) -> SessionSeen | None:
31
+ """The session (id, folder, transcript) the usage payload `raw` describes, with its model
32
+ and effort level when the payload names a model (`model.EFFORT_NONE`: the model takes no
33
+ effort level), else None."""
34
+
35
+ def hook_session(self, hook: str, raw: object) -> SessionSeen | None:
36
+ """For fairshare's hook named `hook` (`fairshare hook <name>`): the session its input
37
+ `raw` describes, when the input is the event that hook is wired for; else None. None too
38
+ for a hook that speaks to the model when the input comes from inside a subagent."""
39
+
40
+ def hook_output(self, hook: str, text: str) -> str:
41
+ """What fairshare's hook `hook` prints so that `text` reaches the model as context."""
42
+
43
+ def current_session(self) -> str | None:
44
+ """The id of the session this process runs inside (a command run by it), else None."""
45
+
46
+ def session_pid(self) -> int | None:
47
+ """The process id of that session, when the provider says, else None."""
48
+
49
+ def resume_args(self, session_id: str, fork: bool = False) -> list[str]:
50
+ """Arguments that continue the session `session_id` under its own id, on whichever
51
+ account starts it; `fork`: in a copy under a new id."""
52
+
53
+ def model_args(self, model: str | None, effort: str | None) -> list[str]:
54
+ """Arguments that start a session on `model` at `effort` (`model.EFFORT_NONE` or None:
55
+ no effort argument); none for what is None."""
56
+
57
+ def uses_week(self, model: str, week: str) -> bool:
58
+ """Whether the per-model week the usage report names `week` limits `model` (an id, an
59
+ alias or a display name)."""
60
+
61
+ def background(self, account: Account, name: str, prompt: str, extra: list[str] = ()
62
+ ) -> tuple[list[str], dict[str, str]]:
63
+ """The command and the clean environment (as `launch`) that start a session of
64
+ `account` with no terminal, named `name`, with `extra` arguments (resume_args,
65
+ model_args), whose first message is `prompt`."""
66
+
67
+ def note_command(self, account: Account, session_id: str, extra: list[str], prompt: str
68
+ ) -> tuple[list[str], dict[str, str]]:
69
+ """The command and clean environment of one headless turn of the stopped session
70
+ `session_id` on `account`, under the same id, with no tools and `extra` arguments
71
+ (model_args), whose message is `prompt`; its output lines are read by `note_event`,
72
+ its final line by `note_text`."""
73
+
74
+ def note_event(self, line: str) -> NoteEvent | None:
75
+ """What one output line of that command says (thinking, or writing with the new text);
76
+ None for any other line or one that does not parse. Never raises."""
77
+
78
+ def note_text(self, out: str) -> str | None:
79
+ """The answer's text in that command's final output line; None for an error or no
80
+ text."""
81
+
82
+ def list_sessions(self, account: Account) -> list[LiveSession] | None:
83
+ """The provider's sessions running now (asked through `account`'s folder), with their
84
+ names and whether each is busy; None when it could not say. Never raises."""
85
+
86
+ def transcript_text(self, path: Path) -> list[tuple[str, str]] | None:
87
+ """A session transcript's main conversation, oldest first, as (role, text) pairs:
88
+ "user" | "assistant", or "command" and "output" for a command the user ran in the
89
+ session (its output as printed). Words only. [] when it has none; None when it cannot
90
+ be read."""
91
+
92
+ def launch(self, account: Account) -> tuple[list[str], dict[str, str]]:
93
+ """The command and the complete environment that start this provider as `account`: the
94
+ provider's clean environment (see dropped_login_vars) plus the account's own variable."""
95
+
96
+ def login_command(self, config_dir: Path) -> tuple[list[str], dict[str, str]]:
97
+ """The command and environment of the provider's own interactive sign-in for the account
98
+ folder `config_dir`. fairshare runs it and never sees what it stores."""
99
+
100
+ def logout_command(self, config_dir: Path) -> tuple[list[str], dict[str, str]]:
101
+ """The same for signing that folder out."""
102
+
103
+ def session_dir(self) -> Path | None:
104
+ """The account folder of the session this process runs in (as a usage hook), else None."""
105
+
106
+ def dropped_login_vars(self) -> list[str]:
107
+ """Names (never values) of variables set in this process that could override an account's
108
+ own login and that launch() leaves out of the environment."""
109
+
110
+ def passed_session_vars(self) -> list[str]:
111
+ """Inside a running session of this provider: names (never values) of other variables
112
+ that look like session state and that launch() passes through. Empty otherwise."""
113
+
114
+ def discover(self, home: Path) -> list[Candidate]:
115
+ """The user's own folders under `home`, signed in or not, for setup to show: the
116
+ provider's default folder (the one its tool uses when told none) first. Must not read a
117
+ login."""
118
+
119
+ def account_status(self, account: Account) -> AccountStatus | None:
120
+ """Ask the provider whether `account` is signed in, with what kind of login, under which
121
+ identity and plan. None when the question could not be answered (never raise)."""
122
+
123
+ def read_usage(self, account: Account, now: float) -> dict[str, Window] | str | None:
124
+ """Ask the provider's own tool for `account`'s usage now, without a model call: the
125
+ windows it read, keyed as parse_capture keys them (per-model weeks under
126
+ `model.model_window`); else a short, value-free reason, one of `model.USAGE_*` (a detail
127
+ may follow USAGE_NO_ANSWER after a colon); None when the account turned the probe off.
128
+ Never raises."""
129
+
130
+ def find_binary(self) -> str | None:
131
+ """The provider's command-line tool on PATH, or None."""
132
+
133
+ def version(self) -> str | None:
134
+ """The tool's version line, or None when it could not be read (never raise)."""
135
+
136
+ def state_file(self, folder: Path, home: Path) -> Path:
137
+ """The provider's own state file that the user's folder `folder` uses."""
138
+
139
+ def hold_state(self, state: Path):
140
+ """A context manager holding the lock the provider itself takes while it writes the
141
+ state file `state`; raises OSError when it cannot be had."""
142
+
143
+ def trusts(self, config_dir: Path, path: Path) -> bool | None:
144
+ """Whether the account folder `config_dir` lets the tool work in the canonical folder
145
+ `path` without asking (by the provider's own lookup rule); None when it cannot tell."""
146
+
147
+ def trust(self, config_dir: Path, path: Path, backups: Path) -> Path:
148
+ """Record that trust as the provider's own dialog would, backing the file up into
149
+ `backups`, and return the folder the entry names. Raises OSError or ValueError and
150
+ writes nothing when it cannot."""
151
+
152
+ def check_state(self, config_dir: Path) -> tuple[bool, str]:
153
+ """For doctor: whether the account's state file still has the layout fairshare relies
154
+ on, and one line saying so (no paths, no values)."""
155
+
156
+ def merge_state(self, dest: dict, src: dict) -> tuple[dict, list[str]]:
157
+ """`dest` (a new account's state) plus the few keys join may carry over from `src` (a
158
+ user's folder's): never identity, tokens or account fields. Also returns what was added,
159
+ as names and counts for the user, never values."""
160
+
161
+ def masked(self, item: str, text: str) -> str:
162
+ """A shared item's text fit to show the user in a diff, with any value that may be a
163
+ secret (such as a variable's value) hidden."""
164
+
165
+ def capture_file(self, shared: Path) -> Path:
166
+ """The settings file, among the hub's shared items, in which the usage hook lives."""
167
+
168
+ def wired(self, text: str | None) -> Capture | None:
169
+ """The fairshare capture hook found in that file's text, else None."""
170
+
171
+ def repath(self, text: str, old: str, new: str) -> tuple[str | None, list[str]]:
172
+ """That file's text with every string value naming the folder `old` renamed to `new`, and
173
+ where each was (key paths only); (None, []) when nothing names it. Every other byte stays.
174
+ Raises ValueError for a text it cannot change safely."""
175
+
176
+ def wire(self, text: str | None, command: str) -> str | None:
177
+ """New text for that file so that it records usage through the shell command `command`
178
+ and then runs the user's own hook, redraws on a timer, and runs fairshare's own hooks
179
+ (`<command> hook <name>`); None when it already does. Every byte outside fairshare's own
180
+ entries stays, and no other hook is changed, moved or removed. Raises ValueError for a
181
+ text it cannot change safely."""
182
+
183
+ def skill(self, shared: Path) -> tuple[Path, str]:
184
+ """Where fairshare's skill (which teaches main sessions workers, watch and checkpoints)
185
+ goes among the hub's shared items `shared`, and the text fairshare ships for it."""
186
+
187
+ def own_skill(self, text: str) -> bool:
188
+ """Whether a file at that place is fairshare's own skill (by its declared name), so
189
+ fairshare may refresh it; anything else there is left alone."""
190
+
191
+ def hooked(self, text: str | None) -> tuple[str, ...] | None:
192
+ """The fairshare command all of fairshare's own hooks in that file's text run, else
193
+ None (one is missing)."""