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.
fairshare/cli.py ADDED
@@ -0,0 +1,3266 @@
1
+ """fairshare CLI: status | capture | run (the default) | prefer | pickup | handoff | transcript |
2
+ trust | worker | checkpoint | watch | setup | join | leave | uninstall | doctor."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import contextlib
7
+ import json
8
+ import os
9
+ import re
10
+ import shlex
11
+ import select
12
+ import shutil
13
+ import signal
14
+ import subprocess
15
+ import sys
16
+
17
+ if sys.platform == "win32": # termios, tty and POSIX job control below: macOS and Linux only
18
+ sys.exit("fairshare runs on macOS and Linux; Windows is not supported")
19
+
20
+ import termios
21
+ import time
22
+ import tomllib
23
+ import tty
24
+ from concurrent.futures import ThreadPoolExecutor
25
+ from dataclasses import dataclass, field, replace
26
+ from pathlib import Path
27
+
28
+ from . import browser
29
+ from . import hub as hub_mod
30
+ from . import providers, session, store
31
+ from .model import (ACCOUNT_ID, DEFAULT_HUB, EFFORT_NONE, NOTE_THINKING, NOTE_WRITING,
32
+ ROLE_WORKER, USAGE_MODEL_TURN, Account,
33
+ AccountStatus, ConfigError, Request, SessionRecord, SessionSeen, Snapshot,
34
+ Tuning, Window, Worker,
35
+ load_accounts, load_plan, window_model, with_account, with_hub,
36
+ without_account)
37
+ from .policy import HOUR, Verdict, prefer, rank
38
+
39
+
40
+ def _load():
41
+ path = store.config_path()
42
+ if not path.exists():
43
+ raise SystemExit(f"fairshare: no config at {path} (run `fairshare setup`)")
44
+ try:
45
+ return load_accounts(path)
46
+ except ConfigError as e:
47
+ raise SystemExit(f"fairshare: {path}: {e}")
48
+
49
+
50
+ def _now() -> float:
51
+ return time.time()
52
+
53
+
54
+ def _sleep(seconds: float) -> None:
55
+ time.sleep(seconds)
56
+
57
+
58
+ def _probe(accounts: list[Account]) -> list[AccountStatus | None]:
59
+ """Ask every account's provider who is signed in, all at once."""
60
+ if not accounts:
61
+ return []
62
+ with ThreadPoolExecutor(len(accounts)) as pool:
63
+ return list(pool.map(lambda a: providers.get(a.provider).account_status(a), accounts))
64
+
65
+
66
+ def _check(accounts: list[Account], now: float
67
+ ) -> list[tuple[AccountStatus | None, dict[str, Window] | str | None]]:
68
+ """Ask every account's provider who is signed in and what it has used, all at once: the wait
69
+ is the slowest answer, not their sum. Per account: its status, and its usage (windows, a
70
+ reason it could not be read, or None when the account turned the probe off)."""
71
+ if not accounts:
72
+ return []
73
+ with ThreadPoolExecutor(2 * len(accounts)) as pool:
74
+ asked = [(pool.submit(providers.get(a.provider).account_status, a),
75
+ pool.submit(providers.get(a.provider).read_usage, a, now)) for a in accounts]
76
+ return [(st.result(), use.result()) for st, use in asked]
77
+
78
+
79
+ def _record_usage(acct: Account, use: dict[str, Window] | str | None, now: float) -> str | None:
80
+ """Record a probe's windows in the account's snapshot (same lock and merge as capture). Why
81
+ its numbers did not come from the probe, or None when they did (or the probe is off)."""
82
+ if not isinstance(use, dict):
83
+ return use
84
+ try:
85
+ store.record(acct.id, use, now, probe=True)
86
+ except OSError as e:
87
+ return f"not recorded: {e.strerror or type(e).__name__}"
88
+ return None
89
+
90
+
91
+ @dataclass
92
+ class Survey:
93
+ verdicts: list[Verdict] # ranked, one per quota
94
+ out: list[tuple[Account, str]] # left out of the ranking, and why
95
+ twins: list[tuple[Account, str]] # folders sharing a login, and the id ranked for them
96
+ notes: dict[str, list[str]] # remarks per account id
97
+ failed: list[str] # ids whose sign-in check could not be answered
98
+ snaps: dict[str, Snapshot]
99
+ tuning: Tuning
100
+ now: float
101
+ preference: tuple[str, float] | None = None # the user's (account id, until), if any
102
+ usage: dict[str, str | None] = field(default_factory=dict) # probed ids: None = answered,
103
+ # else why it failed
104
+ expires: dict[str, float] = field(default_factory=dict) # signed-in ids: sign-in's end
105
+
106
+
107
+ def _with_detected_plan(a: Account, plan_name: str) -> Account:
108
+ """`a` on the plan the provider reported, keeping the account's own capacity override."""
109
+ return replace(a, plan=load_plan(plan_name, a.capacity))
110
+
111
+
112
+ def _unconfirmed(a: Account) -> str | None:
113
+ """Why an account whose sign-in check failed cannot be used, or None when it can: the last
114
+ successful check must have said "subscription". A login never confirmed as one might be
115
+ billed per use. (A login file is no evidence: a sign-in may store none.)"""
116
+ seen = store.subscription_seen(a.id)
117
+ if not (seen and seen[0]):
118
+ return f"sign-in check failed and {a.id} was never confirmed as a subscription login"
119
+ return None
120
+
121
+
122
+ NOT_SIGNED_IN = "not signed in"
123
+ NO_ACCOUNTS = "no accounts yet: `fairshare join <name>` signs one in"
124
+ FALLBACK = "went by its last confirmation as a subscription login and the plan in accounts.toml"
125
+
126
+
127
+ def _no_hub(hub: Path) -> str:
128
+ return f"no hub at {hub}; if you moved it, run `fairshare doctor --fix`"
129
+
130
+
131
+ def _require_hub(hub: Path) -> None:
132
+ """Stop before anything runs against a hub that is not there (a sign-in check would create
133
+ folders at the old path)."""
134
+ if not hub_mod.present(hub):
135
+ raise SystemExit(f"fairshare: {_no_hub(hub)}")
136
+
137
+
138
+ def _survey() -> Survey:
139
+ """Check every account once, then rank those that can take work."""
140
+ accounts, tuning, hub = _load()
141
+ if not accounts: # before the hub: none to start, nothing to create
142
+ raise SystemExit(f"fairshare: {NO_ACCOUNTS}")
143
+ _require_hub(hub)
144
+ now = _now()
145
+ live, twins, notes, failed, usage, expires = [], [], {}, [], {}, {}
146
+ out = [(a, a.plan_error) for a in accounts if a.plan is None] # no plan file: not ranked
147
+ planned = [a for a in accounts if a.plan is not None]
148
+ for a, (st, use) in zip(planned, _check(planned, now)):
149
+ if use is not None:
150
+ usage[a.id] = _record_usage(a, use, now)
151
+ if st is None:
152
+ failed.append(a.id)
153
+ if why := _unconfirmed(a):
154
+ out.append((a, why))
155
+ else:
156
+ when = time.strftime("%Y-%m-%d", time.localtime(store.subscription_seen(a.id)[1]))
157
+ notes[a.id] = [f"sign-in check failed; last confirmed as a subscription login "
158
+ f"on {when}; plan {a.plan.name} from config"]
159
+ live.append((a, None))
160
+ continue
161
+ store.record_subscription(a.id, st.logged_in and st.usable, now)
162
+ if not st.logged_in:
163
+ out.append((a, NOT_SIGNED_IN))
164
+ elif not st.usable:
165
+ out.append((a, "not a subscription login"))
166
+ else:
167
+ if st.plan and st.plan != a.plan.name:
168
+ notes[a.id] = [f"plan {a.plan.name} in config, detected {st.plan}"]
169
+ a = _with_detected_plan(a, st.plan)
170
+ if st.expires_at is not None:
171
+ expires[a.id] = st.expires_at
172
+ live.append((a, st))
173
+ snaps = {a.id: s for a in accounts if (s := store.load(a.id))} # with this run's probes
174
+ # One login in several folders is one quota: rank it once, by its freshest snapshot.
175
+ ranked, seen = [], {}
176
+ for a, st in sorted(live, key=lambda x: x[0].id):
177
+ if st is None or st.identity is None:
178
+ ranked.append(a)
179
+ continue
180
+ key = (a.provider, st.identity)
181
+ same = [m for m, ms in live if ms and (m.provider, ms.identity) == key]
182
+ rep = max(sorted(same, key=lambda m: m.id),
183
+ key=lambda m: snaps[m.id].captured_at if m.id in snaps else -1.0)
184
+ if seen.setdefault(key, rep).id == a.id:
185
+ ranked.append(a)
186
+ else:
187
+ twins.append((a, seen[key].id))
188
+ verdicts = rank(ranked, snaps, now, tuning)
189
+ if pref := store.preference(now):
190
+ verdicts = prefer(verdicts, pref[0])
191
+ return Survey(verdicts, out, twins, notes, failed, snaps, tuning, now, pref, usage, expires)
192
+
193
+
194
+ def _in(h: float | None) -> str:
195
+ return "-" if h is None else f"{int(h)}h{int(h % 1 * 60):02d}m"
196
+
197
+
198
+ def _clock(t: float, now: float) -> str:
199
+ """A local clock time, with the day name when it is not today. Unlike "in 2h", it stays true
200
+ on a line that is not redrawn."""
201
+ lt = time.localtime(t)
202
+ return time.strftime("%H:%M" if lt[:3] == time.localtime(now)[:3] else "%a %H:%M", lt)
203
+
204
+
205
+ def _day_clock(t: float) -> str:
206
+ """A local clock time, always with the day name."""
207
+ return time.strftime("%a %H:%M", time.localtime(t))
208
+
209
+
210
+ LOGIN_WARN_DAYS = 3 # a sign-in ending this soon is named at every run and status
211
+
212
+
213
+ def _expiry_lines(expires: dict[str, float], now: float) -> dict[str, str]:
214
+ """For each account whose sign-in ends within LOGIN_WARN_DAYS: one line saying when, and the
215
+ fix."""
216
+ return {i: f"{i}: sign-in ends {_day_clock(t)}; `fairshare join {i}` signs it in again"
217
+ for i, t in expires.items() if t - now < LOGIN_WARN_DAYS * 24 * HOUR}
218
+
219
+
220
+ def _probe_line(acct_id: str, reason: str, snap: Snapshot | None, now: float) -> str:
221
+ """What a failed usage probe means for the ranking. A probe that ran as a model turn spent
222
+ usage, so it says so loudly, every time, with the way to stop it."""
223
+ where = (f"using its snapshot from {_clock(snap.captured_at, now)}" if snap
224
+ else "no snapshot; ranked as a fresh window")
225
+ if reason == USAGE_MODEL_TURN:
226
+ return (f"warning: the usage probe for {acct_id} ran as a model turn and may spend usage "
227
+ f"at every launch; its answer is not used, {where}; set `usage_args = []` in "
228
+ f"{acct_id}'s accounts.toml table to stop it")
229
+ return f"usage probe failed for {acct_id} ({reason}); {where}"
230
+
231
+
232
+ def _probe_lines(s: Survey) -> dict[str, str]:
233
+ """A line for each ranked account whose usage probe failed."""
234
+ return {v.account.id: _probe_line(v.account.id, why, s.snaps.get(v.account.id), s.now)
235
+ for v in s.verdicts if (why := s.usage.get(v.account.id))}
236
+
237
+
238
+ def _age(s: Survey, acct_id: str) -> str:
239
+ """For a row whose numbers did not come from this run's probe: how old they are."""
240
+ snap = s.snaps.get(acct_id)
241
+ if not snap or (acct_id in s.usage and s.usage[acct_id] is None):
242
+ return ""
243
+ return f" (usage as of {_clock(snap.captured_at, s.now)})"
244
+
245
+
246
+ def _spent_models(acct_id: str, snap: Snapshot | None, t: Tuning, now: float) -> list[str]:
247
+ """A warning for each per-model week of the account that is spent and not yet reset. It
248
+ changes nothing in the ranking: model choice is the user's."""
249
+ return [f"warning: {acct_id}'s {model} week is spent until {_clock(w.resets_at, now)}; "
250
+ "other models are unaffected"
251
+ for k, w in sorted((snap.windows if snap else {}).items())
252
+ if (model := window_model(k)) and w.used_pct >= t.long_exhausted_pct
253
+ and w.resets_at > now]
254
+
255
+
256
+ def _usable(v: Verdict, now: float) -> str:
257
+ """When a spent account can take work again."""
258
+ return f"usable at {_clock(now + v.usable_in * HOUR, now)}"
259
+
260
+
261
+ def _honoured(s: Survey) -> bool:
262
+ return bool(s.preference and s.verdicts and s.verdicts[0].account.id == s.preference[0])
263
+
264
+
265
+ def _preference_note(s: Survey) -> str | None:
266
+ if not s.preference:
267
+ return None
268
+ who, until = s.preference
269
+ note = f"preferring {who} until {_clock(until, s.now)}"
270
+ if not _honoured(s):
271
+ note += "; it cannot take work now, so the best account is used"
272
+ return note
273
+
274
+
275
+ LIVE_S = 600 # a session seen this recently is live (status's sessions block)
276
+ SPEND_SPAN_S = 3600 # spend is shown and compared over this span: the last hour
277
+ SESSIONS_SHOWN = 5 # status shows at most this many sessions per account
278
+
279
+
280
+ def _hour_spend(recs: list[SessionRecord], now: float) -> dict[str, float | None]:
281
+ """Each session's spend in the last hour (None: no cost data), by id."""
282
+ return {r.id: store.spend(r.costs, now - SPEND_SPAN_S, now) for r in recs}
283
+
284
+
285
+ def _role(rec: SessionRecord) -> str:
286
+ """main, or a worker's name."""
287
+ if rec.role != ROLE_WORKER:
288
+ return "main"
289
+ return w.name if (w := _worker_of(rec.id)) else ROLE_WORKER
290
+
291
+
292
+ def _about(rec: SessionRecord) -> tuple[str, str]:
293
+ """A session's model (display name) and folder (its last part), `-` when unknown."""
294
+ return rec.model_name or rec.model or "-", (Path(rec.cwd).name if rec.cwd else "") or "-"
295
+
296
+
297
+ def _sessions_block(acct_id: str, recs: list[SessionRecord], now: float) -> list[str]:
298
+ """status's lines for an account's live sessions, heaviest in the last hour first, at most
299
+ SESSIONS_SHOWN, then `+N more`: id start, model, folder, role, spend and its share of the
300
+ account's last-hour spend; `-` with no cost data. A session that went on under a new id
301
+ (`moved_to`) is not listed; its spend still counts for its own account."""
302
+ mine = [r for r in recs if r.account == acct_id]
303
+ spent = _hour_spend(mine, now)
304
+ total = sum(x for x in spent.values() if x)
305
+ live = sorted((r for r in mine if now - r.seen <= LIVE_S and not r.moved_to),
306
+ key=lambda r: (-(spent[r.id] if spent[r.id] is not None else -1), r.id))
307
+ lines = []
308
+ for r in live[:SESSIONS_SHOWN]:
309
+ x = spent[r.id]
310
+ model, folder = _about(r)
311
+ lines.append(f"session {r.id[:8]} · {model} · {folder} · {_role(r)} · " + (
312
+ "-" if x is None else f"${x:.2f}" + (f" ({100 * x / total:.0f}%)" if total else "")))
313
+ if len(live) > SESSIONS_SHOWN:
314
+ lines.append(f"+{len(live) - SESSIONS_SHOWN} more")
315
+ return lines
316
+
317
+
318
+ def _heaviest(rec: SessionRecord, acct_id: str, now: float) -> str:
319
+ """One sentence naming another session of the account that drew at least half of its
320
+ last-hour spend; "" when none did."""
321
+ mine = [r for r in store.sessions() if r.account == acct_id]
322
+ spent = _hour_spend(mine, now)
323
+ total = sum(x for x in spent.values() if x)
324
+ heavy = max(((spent[r.id], r.id, r) for r in mine if r.id != rec.id and spent[r.id]
325
+ and 2 * spent[r.id] >= total), default=None, key=lambda h: h[:2])
326
+ if not heavy:
327
+ return ""
328
+ model, folder = _about(heavy[2])
329
+ return (f" Heaviest in the last hour: session {heavy[1][:8]} ({model}, {folder}, "
330
+ f"{100 * heavy[0] / total:.0f}%).")
331
+
332
+
333
+ def cmd_status(_a) -> int:
334
+ s = _survey()
335
+ if s.preference and not _honoured(s):
336
+ print(_preference_note(s))
337
+ probes, expiring = _probe_lines(s), _expiry_lines(s.expires, s.now)
338
+ recs = store.sessions()
339
+ for i, v in enumerate(s.verdicts):
340
+ mark, aid = (">" if i == 0 else " "), v.account.id
341
+ flag = "" if v.eligible else f" [avoid] {_usable(v, s.now)}"
342
+ if i == 0 and _honoured(s):
343
+ flag = f" [preferred until {_clock(s.preference[1], s.now)}]"
344
+ print(f"{mark} {aid:<12} {v.account.plan.name:<14} score {v.score:6.2f} "
345
+ f"{v.reason}{_age(s, aid)}{flag}")
346
+ for note in [*s.notes.get(aid, []), *([probes[aid]] if aid in probes else []),
347
+ *_spent_models(aid, s.snaps.get(aid), s.tuning, s.now),
348
+ *([expiring[aid]] if aid in expiring else []),
349
+ *_sessions_block(aid, recs, s.now)]:
350
+ print(f" {note}")
351
+ for a, why in s.out:
352
+ print(f" {a.id:<12} {a.plan.name if a.plan else '-':<14} left out: {why}")
353
+ for note in [*s.notes.get(a.id, []), *_sessions_block(a.id, recs, s.now)]:
354
+ print(f" {note}")
355
+ for a, rep in s.twins:
356
+ print(f" {a.id:<12} {a.plan.name:<14} same login as {rep}")
357
+ for note in [*([expiring[a.id]] if a.id in expiring else []),
358
+ *_sessions_block(a.id, recs, s.now)]:
359
+ print(f" {note}")
360
+ return 0
361
+
362
+
363
+ def _nothing_to_rank(s: Survey) -> None:
364
+ if not s.verdicts:
365
+ why = "; ".join(f"{a.id}: {w}" for a, w in s.out)
366
+ raise SystemExit(f"fairshare: no account can take work ({why})")
367
+
368
+
369
+ def _session_account(accounts: list[Account]) -> Account | None:
370
+ """The account whose hub folder this process's session runs in, else None (a session started
371
+ some other way, outside the hub)."""
372
+ for a in accounts:
373
+ prov = providers.REGISTRY.get(a.provider)
374
+ d = prov and prov.session_dir()
375
+ if d and os.path.realpath(d) == os.path.realpath(a.config_dir):
376
+ return a
377
+ return None
378
+
379
+
380
+ TIGHT, SPENT, PLAIN = "\033[33m", "\033[31m", "\033[0m" # yellow, red, reset
381
+
382
+
383
+ def _span(hours: float) -> str:
384
+ return f"{hours / 24:g}d" if hours % 24 == 0 else f"{hours:g}h"
385
+
386
+
387
+ def _stale(snap: Snapshot | None, t: Tuning, now: float) -> bool:
388
+ """Whether an account's usage is old enough to ask for again (or unknown)."""
389
+ return snap is None or now - snap.captured_at > t.refresh_minutes * 60
390
+
391
+
392
+ def _status_line(acct: Account, snap: Snapshot | None, now: float, live: bool,
393
+ t: Tuning) -> str:
394
+ """The account and its windows, shortest first, named by their length (`5h 23%`). A window
395
+ at the hot mark turns yellow, red once spent, and shows when it resets: a tight account
396
+ about to reset is still worth using. A window the plan has but whose usage is unknown (none
397
+ seen yet, or reset since: nothing is known until the next exchange) shows `-`, so the line
398
+ keeps its shape. A per-model week shows only once hot, named by its model (`Fable 96%`). A
399
+ session's first redraws carry no usage yet, so the saved snapshot stands in, marked with
400
+ when it was taken; so are numbers older than `refresh_minutes` (an idle session redraws
401
+ them unchanged)."""
402
+ p = acct.plan
403
+ hours = {p.short_name: p.short_hours, p.long_name: p.long_hours} if p else {}
404
+ known = {k: w for k, w in (snap.windows if snap else {}).items() if w.resets_at > now}
405
+ names = [k for k in hours if k] + [k for k in known if k not in hours and (
406
+ not window_model(k) or known[k].used_pct >= t.short_hot_pct)]
407
+ parts = [acct.id]
408
+ for k in sorted(names, key=lambda k: (bool(window_model(k)), hours.get(k) or 0)):
409
+ label = _span(hours[k]) if hours.get(k) else window_model(k) or k
410
+ w = known.get(k)
411
+ if w is None:
412
+ parts.append(f"{label} -")
413
+ continue
414
+ text = f"{label} {w.used_pct:.0f}%"
415
+ if w.used_pct >= t.short_hot_pct:
416
+ colour = SPENT if w.used_pct >= t.long_exhausted_pct else TIGHT
417
+ text = f"{colour}{text} ({_clock(w.resets_at, now)}){PLAIN}"
418
+ parts.append(text)
419
+ if known and (not live or _stale(snap, t, now)):
420
+ parts.append(f"as of {_clock(snap.captured_at, now)}")
421
+ return " · ".join(parts)
422
+
423
+
424
+ def cmd_capture(a) -> int:
425
+ """Runs as the provider's usage hook. Must never raise or print noise. The account is the
426
+ session's own folder in the hub; a session outside the hub records nothing. With --then, the
427
+ user's own command for that hook gets the same stdin and prints the line. An account id after
428
+ `capture` (the form before the hub) is ignored. When the session was stopped by its
429
+ account's limit and that account still cannot take work, the line ends in the pickup hint
430
+ (on a line of its own after the user's)."""
431
+ raw = sys.stdin.buffer.read()
432
+ out = None
433
+ try:
434
+ accounts, tuning, _ = _load()
435
+ acct = _session_account(accounts)
436
+ prov = acct and providers.get(acct.provider)
437
+ payload = json.loads(raw)
438
+ fresh = acct and prov.parse_capture(payload)
439
+ now = _now()
440
+ seen = acct and prov.session_of(payload)
441
+ if fresh and seen:
442
+ fresh = store.drawn_news(seen, acct.id, fresh, now)
443
+ snap = store.record(acct.id, fresh, now) if fresh else acct and store.load(acct.id)
444
+ if seen:
445
+ with contextlib.suppress(OSError):
446
+ out = _stranded(acct, seen, snap, tuning, now)
447
+ if acct and _stale(snap, tuning, now):
448
+ _start_probe(acct, seen and seen.cwd, now)
449
+ if acct and not a.then:
450
+ print(_status_line(acct, snap, now, bool(fresh), tuning) + (f" · {out}" if out else ""))
451
+ except (Exception, SystemExit): # whatever is wrong, the user's own line must still run
452
+ pass
453
+ if a.then:
454
+ sys.stdout.flush()
455
+ code = subprocess.run(a.then, shell=True, input=raw).returncode
456
+ if out:
457
+ print(out)
458
+ return code
459
+ return 0
460
+
461
+
462
+ PICKUP_MARK = f"{SPENT}out · ! fairshare pickup{PLAIN}"
463
+
464
+
465
+ def _pickup_mark(rec: SessionRecord, now: float) -> str:
466
+ """The bar's mark for a stranded session: when it waits for the provider's own resume,
467
+ when that is and how to move now instead."""
468
+ if rec.waiting_until is not None and rec.waiting_until > now:
469
+ return (f"{SPENT}out · resumes {_clock(rec.waiting_until, now)} · ! fairshare pickup to "
470
+ f"move now{PLAIN}")
471
+ return PICKUP_MARK
472
+
473
+
474
+ def _limit_reset(acct: Account, snap: Snapshot | None, t: Tuning, now: float) -> float | None:
475
+ """When the account's limit lifts: the latest reset among its plan windows at their limit (a
476
+ week at `long_exhausted_pct`, a short window at `short_hot_pct`) still running; None when no
477
+ window says."""
478
+ p = acct.plan
479
+ return max((w.resets_at for name, full in ((p.long_name, t.long_exhausted_pct),
480
+ (p.short_name, t.short_hot_pct))
481
+ if name and snap and (w := snap.windows.get(name)) and w.used_pct >= full
482
+ and w.resets_at > now), default=None) if p else None
483
+
484
+
485
+ def _spent_now(acct: Account, snap: Snapshot | None, t: Tuning, now: float) -> bool:
486
+ """Whether one of the account's plan windows is spent and not yet reset. The policy calls a
487
+ full short window usable inside its grace hour; for a session the provider already stopped,
488
+ that is still out: it should be picked up, not wait for the reset."""
489
+ p = acct.plan
490
+ return bool(p and snap) and any(
491
+ w.used_pct >= t.long_exhausted_pct and w.resets_at > now
492
+ for k, w in snap.windows.items() if k in (p.short_name, p.long_name))
493
+
494
+
495
+ def _stranded(acct: Account, seen, snap: Snapshot | None, t: Tuning, now: float) -> str | None:
496
+ """Record the session; the pickup hint when its limit stopped it and its account still
497
+ cannot take work by the policy. Numbers newer than the stop that say it can work again (a
498
+ window reset) clear the mark, and any wait for the provider's own resume with it."""
499
+ _continuation(seen, acct, now)
500
+ rec = store.note_session(seen, acct.id, now)
501
+ if rec is None or rec.stranded_at is None or acct.plan is None:
502
+ return None
503
+ if (_spent_now(acct, snap, t, now)
504
+ or not rank([acct], {acct.id: snap} if snap else {}, now, t)[0].eligible):
505
+ return _pickup_mark(rec, now)
506
+ if snap and snap.captured_at > rec.stranded_at:
507
+ store.note_session(seen, acct.id, now, stranded=False)
508
+ return None
509
+
510
+
511
+ def _fairshare_argv() -> list[str]:
512
+ """This very fairshare, as a command a child process can run (not through PATH; `-P`: not
513
+ from the folder it runs in)."""
514
+ return [sys.executable, "-P", "-m", "fairshare.cli"]
515
+
516
+
517
+ def _start_probe(acct: Account, cwd: str | None, now: float) -> bool:
518
+ """Start one detached `fairshare probe <id>` and never wait for it: its own session, stdin
519
+ and output on /dev/null, in the session's folder (as the launch probe runs in the launch's).
520
+ At most one per account at a time (`store.claim_probe`). True when one was started."""
521
+ try:
522
+ if not store.claim_probe(acct.id, now, 2 * providers.get(acct.provider).usage_timeout):
523
+ return False
524
+ subprocess.Popen([*_fairshare_argv(), "probe", acct.id],
525
+ cwd=cwd if cwd and os.path.isdir(cwd) else None,
526
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
527
+ stderr=subprocess.DEVNULL, start_new_session=True)
528
+ except OSError:
529
+ return False
530
+ return True
531
+
532
+
533
+ def _quietly(work) -> int:
534
+ """Run `work()` printing nothing and raising nothing; exit 0. For what the provider runs on
535
+ its own (hooks) and what runs detached (the background probe)."""
536
+ with open(os.devnull, "w") as quiet, contextlib.redirect_stdout(quiet), \
537
+ contextlib.redirect_stderr(quiet):
538
+ try:
539
+ work()
540
+ except (Exception, SystemExit):
541
+ pass
542
+ return 0
543
+
544
+
545
+ def cmd_probe(a) -> int:
546
+ """Hidden, started by capture: ask the provider for one account's usage now and record it
547
+ as a probe. A probe that fails records nothing, so the bar ages honestly."""
548
+ def work():
549
+ accounts, _, hub = _load()
550
+ acct = next(x for x in accounts if x.id == a.id)
551
+ if not hub_mod.present(hub, acct.id): # it would create folders at the old path
552
+ return
553
+ now = _now()
554
+ if (use := providers.get(acct.provider).read_usage(acct, now)) and isinstance(use, dict):
555
+ store.record(acct.id, use, now, probe=True)
556
+ return _quietly(work)
557
+
558
+
559
+ def cmd_hook(a) -> int:
560
+ """Runs as one of fairshare's own hooks in the provider's settings (`hook <name>`), with the
561
+ hook's input on stdin. Never raises and exits 0. It prints only what a handler gives (the
562
+ provider's own answer that puts a line in the model's context), else nothing."""
563
+ said: list[str | None] = []
564
+
565
+ def work():
566
+ raw = json.loads(sys.stdin.buffer.read())
567
+ if handle := HOOKS.get(a.name):
568
+ said.append(handle(a.name, raw))
569
+ _quietly(work)
570
+ if said and said[0]:
571
+ print(said[0])
572
+ return 0
573
+
574
+
575
+ LAUNCHER_ENV = "FAIRSHARE_LAUNCHER" # set by the launcher for its child: its own process id
576
+
577
+
578
+ def _ancestors() -> set[int]:
579
+ """The process ids above this one, up to (not including) init. Empty when `ps` cannot say."""
580
+ try:
581
+ r = subprocess.run([shutil.which("ps", path="/bin:/usr/bin") or "ps", "-A", "-o",
582
+ "pid=,ppid="], stdin=subprocess.DEVNULL, capture_output=True,
583
+ text=True, timeout=5)
584
+ except (OSError, subprocess.SubprocessError):
585
+ return set()
586
+ parent = {int(a): int(b) for a, b in (line.split() for line in r.stdout.splitlines()
587
+ if len(line.split()) == 2) if a.isdigit() and b.isdigit()}
588
+ found, p = set(), os.getppid()
589
+ while p > 1 and p not in found:
590
+ found.add(p)
591
+ p = parent.get(p, 0)
592
+ return found
593
+
594
+
595
+ def _launcher() -> int | None:
596
+ """The fairshare launcher this process runs under: LAUNCHER_ENV, when it names one of this
597
+ process's ancestors (so a stale or inherited value never signals a stranger)."""
598
+ try:
599
+ pid = int(os.environ.get(LAUNCHER_ENV, ""))
600
+ except ValueError:
601
+ return None
602
+ return pid if pid > 1 and pid in _ancestors() else None
603
+
604
+
605
+ CONTINUES_ENV = "FAIRSHARE_CONTINUES" # set by the launcher for a resume: "<its pid>:<old id>"
606
+ COPY = ":copy" # after the old id in CONTINUES_ENV: the resume is a copy (`_may_run`)
607
+
608
+
609
+ def _continuation(seen: SessionSeen, acct: Account, now: float) -> None:
610
+ """Called before a session is recorded from inside it: when the launcher resumed a session
611
+ and it goes on under a new id (another account: decision 23, or a copy: `_may_run`), link the
612
+ two (`store.link_session`; a copy as a copy). Only when CONTINUES_ENV names one of this
613
+ process's ancestors (a value leaked into a nested session never links a stranger), its old
614
+ id is not `seen`'s, and `seen` has no record or one not yet linked. Never raises."""
615
+ try:
616
+ pid, _, old = os.environ.get(CONTINUES_ENV, "").partition(":")
617
+ old, copy = old.removesuffix(COPY), old.endswith(COPY)
618
+ if not old or old == seen.id or ((rec := store.session(seen.id)) and rec.continues):
619
+ return
620
+ if int(pid) > 1 and int(pid) in _ancestors():
621
+ store.link_session(old, seen, acct.id, now, copy)
622
+ except (Exception, SystemExit):
623
+ pass
624
+
625
+
626
+ # What a request asks the launcher to do after it stopped its child: resume the same session on
627
+ # the best account; start a fresh one that reads the checkpoint (written, or to be written by
628
+ # the launcher first); start a fresh one with nothing (a switch).
629
+ PICKUP, HANDOFF, HANDOFF_NOTE, SWITCH = "pickup", "handoff", "handoff-note", "switch"
630
+
631
+
632
+ def _request(launcher: int, req: Request) -> None:
633
+ """Ask the launcher to stop its child and act on its session."""
634
+ store.save_request(launcher, req)
635
+ os.kill(launcher, signal.SIGUSR1)
636
+
637
+
638
+ def _stop_failure(name: str, raw: object) -> None:
639
+ """`hook stop-failure`: the account's limit ended a turn. Mark the session stranded, ask for
640
+ the account's usage in the background (the bar's mark and the launcher's check need it), and
641
+ when a launcher started this session, ask it for a pickup. Says nothing."""
642
+ accounts, _, _ = _load()
643
+ if (acct := _session_account(accounts)) is None:
644
+ return
645
+ prov = providers.get(acct.provider)
646
+ if (seen := prov.hook_session(name, raw)) is None:
647
+ return
648
+ now = _now()
649
+ _continuation(seen, acct, now)
650
+ store.note_session(seen, acct.id, now, stranded=True)
651
+ _start_probe(acct, seen.cwd, now)
652
+ if launcher := _launcher():
653
+ _request(launcher, Request(seen.id, False, prov.session_pid()))
654
+
655
+
656
+ # --- What the hooks say (decision 22): percent crossings, once each per window per session,
657
+ # and a main session's request for a checkpoint, passed on to its worker.
658
+
659
+ WARN_LEVELS = (90, 95) # a plan window crossing one of these is said once per window and session
660
+
661
+
662
+ def _crossing(rec: SessionRecord, acct: Account, snap: Snapshot, now: float
663
+ ) -> tuple[tuple[str, Window, int] | None, dict]:
664
+ """The highest crossing of WARN_LEVELS in the account's plan windows not yet warned for this
665
+ session in that window (by its reset), as (window, its numbers, level); and the session's
666
+ warned levels with every new crossing marked (a higher one covers the lower)."""
667
+ p, best, warned = acct.plan, None, dict(rec.warned)
668
+ for k in (p.short_name, p.long_name):
669
+ w = k and snap.windows.get(k)
670
+ if not w or w.resets_at <= now:
671
+ continue
672
+ level = max((x for x in WARN_LEVELS if w.used_pct >= x), default=0)
673
+ old = rec.warned.get(k)
674
+ same = (isinstance(old, list) and len(old) == 2
675
+ and abs(float(old[0]) - w.resets_at) <= store.SAME_WINDOW_S)
676
+ if not level or (same and float(old[1]) >= level):
677
+ continue
678
+ warned[k] = [w.resets_at, level]
679
+ if best is None or (level, w.used_pct) > (best[2], best[1].used_pct):
680
+ best = (k, w, level)
681
+ return best, warned
682
+
683
+
684
+ def _tell_crossing(session_id: str, acct: Account, t: Tuning, now: float
685
+ ) -> tuple[str, Window, int] | None:
686
+ """A crossing to say for the session, marked as said on its record in the same locked step
687
+ (a hook and `watch` both ask: whichever comes first says it). Numbers older than twice
688
+ `refresh_minutes` say nothing new (stale numbers must not move anyone) and start the
689
+ background probe, as capture does."""
690
+ snap = store.load(acct.id)
691
+ if snap is None or now - snap.captured_at > 2 * t.refresh_minutes * 60:
692
+ _start_probe(acct, None, now)
693
+ return None
694
+ got = []
695
+
696
+ def change(old: SessionRecord | None) -> SessionRecord | None:
697
+ best, warned = _crossing(old, acct, snap, now) if old else (None, {})
698
+ if best is None:
699
+ return None
700
+ got.append(best)
701
+ return replace(old, warned=warned)
702
+ store.update_session(session_id, change)
703
+ return got[0] if got else None
704
+
705
+
706
+ def _short_state(acct: Account, snap: Snapshot | None, now: float) -> str:
707
+ """An account's plan windows in a few words (`5h 10% · 7d 40%`), unknown ones as `-`."""
708
+ p = acct.plan
709
+ parts = []
710
+ for k, hours in ((p.short_name, p.short_hours), (p.long_name, p.long_hours)):
711
+ w = k and snap and snap.windows.get(k)
712
+ if k:
713
+ parts.append(f"{_span(hours) if hours else k} "
714
+ + (f"{w.used_pct:.0f}%" if w and w.resets_at > now else "-"))
715
+ return " · ".join(parts)
716
+
717
+
718
+ def _best_other(acct: Account, accounts: list[Account], t: Tuning, now: float) -> str:
719
+ """The best other account by the local snapshots alone (no sign-in check, no probe)."""
720
+ others = [a for a in accounts if a.plan is not None and a.id != acct.id]
721
+ snaps = {a.id: s for a in others if (s := store.load(a.id))}
722
+ v = next((v for v in rank(others, snaps, now, t) if v.eligible), None)
723
+ return (f"{v.account.id} ({_short_state(v.account, snaps.get(v.account.id), now)})" if v
724
+ else "none can take work now")
725
+
726
+
727
+ def _warning_text(rec: SessionRecord, acct: Account, crossing: tuple[str, Window, int],
728
+ accounts: list[Account], t: Tuning, now: float) -> str:
729
+ """What a crossing says, by the session's role. Provider-neutral."""
730
+ k, w, _ = crossing
731
+ p = acct.plan
732
+ hours = p.short_hours if k == p.short_name else p.long_hours
733
+ window = _span(hours) if hours else k
734
+ if rec.role == ROLE_WORKER:
735
+ return (f"fairshare: this account is at {w.used_pct:.0f}% of its {window} window. You are "
736
+ 'a worker: finish your current step, then run fairshare checkpoint "<what is '
737
+ 'done, what is next>". Do not start a big new step; your main session decides '
738
+ "what happens next.")
739
+ workers = ", ".join(x.name for x in store.workers(rec.id)) or "none"
740
+ return (f"fairshare: account {acct.id} is at {w.used_pct:.0f}% of its {window} window (resets "
741
+ f"{_clock(w.resets_at, now)}).{_heaviest(rec, acct.id, now)} Best other account: "
742
+ f"{_best_other(acct, accounts, t, now)}"
743
+ ". If what is left of your work is small, carry on. Otherwise, at the next stopping "
744
+ 'point: write a checkpoint (fairshare checkpoint "<where you stand>") and run '
745
+ "fairshare pickup to continue on the best account. Workers you started: "
746
+ f"{workers}; to have them checkpoint: fairshare checkpoint --request all.")
747
+
748
+
749
+ CHECKPOINT_ASK = ("fairshare: your main session asks for a checkpoint now: finish your current "
750
+ 'step and run fairshare checkpoint "<what is done, what is next>".')
751
+
752
+
753
+ def _ask_checkpoint(session_id: str) -> bool:
754
+ """Whether a worker's pending checkpoint request is to be passed on now: once per request,
755
+ marked in the same locked step."""
756
+ got = []
757
+
758
+ def change(old: SessionRecord | None) -> SessionRecord | None:
759
+ if (old is None or old.role != ROLE_WORKER or old.checkpoint_requested is None
760
+ or old.request_said == old.checkpoint_requested):
761
+ return None
762
+ got.append(True)
763
+ return replace(old, request_said=old.checkpoint_requested)
764
+ store.update_session(session_id, change)
765
+ return bool(got)
766
+
767
+
768
+ def _speak(name: str, raw: object) -> str | None:
769
+ """`hook post-tool` and `hook prompt`: what to put in the session's context, as the
770
+ provider's hook answer, or None. Silent inside a subagent. A worker with a pending request
771
+ hears it; otherwise a new crossing of its account is said for the session's role. Reads only
772
+ local files, except that the prompt hook looks pending workers up by name."""
773
+ accounts, tuning, _ = _load()
774
+ if (acct := _session_account(accounts)) is None or acct.plan is None:
775
+ return None
776
+ prov = providers.get(acct.provider)
777
+ if (seen := prov.hook_session(name, raw)) is None:
778
+ return None
779
+ now = _now()
780
+ _continuation(seen, acct, now)
781
+ rec = store.session(seen.id)
782
+ if name == PROMPT_HOOK and (rec is None or rec.role is None):
783
+ if _join_pending(store.workers(), accounts, now):
784
+ rec = store.session(seen.id)
785
+ rec = rec or store.note_session(seen, acct.id, now)
786
+ if rec is None:
787
+ return None
788
+ if name == PROMPT_HOOK and rec.role != ROLE_WORKER:
789
+ _measure_still(store.workers(rec.id), now)
790
+ if _ask_checkpoint(rec.id):
791
+ return prov.hook_output(name, CHECKPOINT_ASK)
792
+ if crossing := _tell_crossing(rec.id, acct, tuning, now):
793
+ return prov.hook_output(name, _warning_text(rec, acct, crossing, accounts, tuning, now))
794
+ return None
795
+
796
+
797
+ STOP_FAILURE, POST_TOOL_HOOK, PROMPT_HOOK = "stop-failure", "post-tool", "prompt"
798
+ HOOKS = {STOP_FAILURE: _stop_failure, # fairshare's hook name -> handler(name, input): what to
799
+ POST_TOOL_HOOK: _speak, # print, or None
800
+ PROMPT_HOOK: _speak}
801
+
802
+
803
+ def _say(text: str) -> None:
804
+ print(f"fairshare: {text}", file=sys.stderr)
805
+
806
+
807
+ def _interactive() -> bool:
808
+ return sys.stdin.isatty() and sys.stderr.isatty()
809
+
810
+
811
+ def _grace_warning(v: Verdict, snaps: dict[str, Snapshot], tuning: Tuning, now: float) -> bool:
812
+ """An account that is eligible only because its hot short window resets soon. True when
813
+ the warning was said."""
814
+ w = (snap := snaps.get(v.account.id)) and snap.windows.get(v.account.plan.short_name)
815
+ if w and w.used_pct >= tuning.short_hot_pct and 0 < w.resets_at - now:
816
+ left = (w.resets_at - now) / HOUR
817
+ if left < tuning.grace_hours:
818
+ _say(f"warning: {v.account.id} {v.account.plan.short_name} window "
819
+ f"{w.used_pct:.0f}% used, resets in {int(left * 60)}m")
820
+ return True
821
+ return False
822
+
823
+
824
+ def _choose(prompt: str, valid: set[str]) -> str | None:
825
+ """One of `valid`, asked until given: there is no default. None at end of input."""
826
+ while True:
827
+ try:
828
+ answer = input(prompt).strip().lower()
829
+ except EOFError:
830
+ print(file=sys.stderr)
831
+ return None
832
+ if answer in valid:
833
+ return answer
834
+
835
+
836
+ def _offer_trust(start: Account, explicit: bool) -> bool:
837
+ """On a terminal, before the start check: offer to trust this folder for the accounts that
838
+ lack it, as the provider's own dialog would. False when the user says no (exit 1, nothing
839
+ written). Never in HOME (the provider keeps trust there per session), never without a
840
+ terminal (the provider then asks for itself). `run -a` asks about its account only; a plain
841
+ launch asks about every account, unless the starting one is trusted and an earlier "only"
842
+ answer for this folder stands."""
843
+ if not _interactive():
844
+ return True
845
+ here = Path(os.getcwd())
846
+ accounts, _, hub = _load()
847
+ pool = [start] if explicit else [a for a in accounts if a.plan is not None]
848
+ lacking = [a for a in pool if providers.get(a.provider).trusts(a.config_dir, here) is not True]
849
+ if not lacking:
850
+ return True
851
+ tool = providers.get(start.provider).tool
852
+ if here == Path.home().resolve():
853
+ _say(f"In HOME, fairshare does not ask; {tool}'s own per-session question applies")
854
+ return True
855
+ starts = start.id in {a.id for a in lacking}
856
+ if not explicit and not starts and store.trust_only(here):
857
+ return True
858
+ _say(f"{tool} will be able to read, edit and execute files in {here}.")
859
+ if explicit:
860
+ options = {"y": [start]}
861
+ print(f" [y] trust it for {start.id}\n [n] no, exit", file=sys.stderr)
862
+ else:
863
+ options = {"a": lacking, "o": [start] if starts else []}
864
+ print(f" [a] trust it for all accounts lacking it ({', '.join(a.id for a in lacking)})\n"
865
+ + (f" [o] only {start.id}\n [n] no, exit" if starts
866
+ else " [o] only the accounts that already trust it"), file=sys.stderr)
867
+ keys = [*options, *(["n"] if starts else [])]
868
+ answer = _choose(f"Trust {here}? [{'/'.join(keys)}] ", set(keys))
869
+ if answer in (None, "n"):
870
+ if not starts:
871
+ return True # nothing to trust for the account starting: it starts
872
+ _say(f"{start.id} not started; nothing written")
873
+ return False
874
+ if answer == "o" and not explicit:
875
+ store.remember_trust_only(here)
876
+ for a in options[answer]:
877
+ try:
878
+ key = providers.get(a.provider).trust(a.config_dir, here,
879
+ hub_mod.backup_dir(hub, f"trust-{a.id}"))
880
+ _say(f"{a.id} now trusts {key}")
881
+ except (OSError, UnicodeDecodeError, ValueError) as e:
882
+ _say(f"{a.id}: trust not written ({e}); {tool} will ask for itself")
883
+ return True
884
+
885
+
886
+ def _args_for(args, acct: Account) -> list[str]:
887
+ """A session's arguments: a list, or built once its account is known (a function of it)."""
888
+ return args(acct) if callable(args) else args
889
+
890
+
891
+ def _launch(v: Verdict, args, explicit: bool = False, continues: str | None = None) -> int:
892
+ """Check the hub is there, offer folder trust, run the start check on the account's hub
893
+ folder, then start the provider as a child, in its clean environment (with the account's
894
+ browser and LAUNCHER_ENV naming this process), and return its exit code. `args`: a list, or
895
+ a function of the account that builds them now. `continues`: the id of the session this
896
+ start resumes, passed as CONTINUES_ENV (with this process's id) so a new id links to it;
897
+ any inherited value is dropped otherwise. A request (SIGUSR1, `_pickup_request`) stops
898
+ the child and acts on its session (`_continue`), with this process still the parent, so a
899
+ later limit picks up again."""
900
+ prov, acct = providers.get(v.account.provider), v.account
901
+ hub = acct.config_dir.parent.parent
902
+ if not hub_mod.present(hub, acct.id):
903
+ _say(_no_hub(hub))
904
+ return 1
905
+ print(f"fairshare -> {acct.id} ({v.reason})", file=sys.stderr)
906
+ if not _offer_trust(acct, explicit):
907
+ return 1
908
+ try:
909
+ for note in hub_mod.check(hub, acct.id, prov):
910
+ _say(note)
911
+ except OSError as e:
912
+ _say(f"cannot prepare {acct.id}'s folder in the hub ({e}); not started")
913
+ return 1
914
+ cmd, env = prov.launch(acct)
915
+ env = {**{k: x for k, x in env.items() if k != CONTINUES_ENV}, **_browser_env(hub, acct),
916
+ LAUNCHER_ENV: str(os.getpid())}
917
+ if continues:
918
+ env[CONTINUES_ENV] = f"{os.getpid()}:{continues}"
919
+ if dropped := prov.dropped_login_vars():
920
+ _say(f"ignoring {', '.join(dropped)} from the environment; the account's own login is used")
921
+ if passed := prov.passed_session_vars():
922
+ _say(f"passing {', '.join(passed)} through from the surrounding session")
923
+ asked: list[tuple[SessionRecord, Survey | None, Request]] = []
924
+
925
+ def requested(child: int) -> bool:
926
+ if got := _pickup_request(child):
927
+ asked.append(got)
928
+ return bool(got)
929
+ code = session.run_child(cmd + _args_for(args, acct), env, requested)
930
+ if code != session.PICKUP:
931
+ return code
932
+ return _continue(*asked[-1])
933
+
934
+
935
+ COUNTDOWN_S = 10 # seconds the launcher shows before an automatic pickup starts
936
+
937
+
938
+ def _can_work(s: Survey, acct_id: str) -> bool:
939
+ """Whether the account (or the twin ranked for its login) can take work in the survey. A plan
940
+ window spent right now says no even inside the policy's grace hour: the provider is already
941
+ refusing, so a session stopped by it should not wait for the reset."""
942
+ rep = next((r for a, r in s.twins if a.id == acct_id), acct_id)
943
+ v = next((v for v in s.verdicts if v.account.id == rep and v.eligible), None)
944
+ return v is not None and not _spent_now(v.account, s.snaps.get(rep), s.tuning, s.now)
945
+
946
+
947
+ def _pickup_request(child: int) -> tuple[SessionRecord, Survey | None, Request] | None:
948
+ """Called in the launcher's wait on SIGUSR1. The request for this launcher, when it is for
949
+ its own child's session and stands: a manual one (`fairshare pickup`, `handoff`, a switch)
950
+ as it is; an automatic one only when the session is marked stranded, a fresh survey (probes
951
+ included) confirms its account cannot take work, and the limit does not reset within
952
+ `resume_wait_minutes` (then the session is left for the provider's own resume, the wait
953
+ written on its record as `waiting_until`). Otherwise None: back to waiting, nothing printed
954
+ (the session owns the terminal)."""
955
+ try:
956
+ got = store.take_request(os.getpid())
957
+ if got is None or (got.pid is not None and got.pid != child):
958
+ return None
959
+ rec = store.session(got.session)
960
+ if rec is None or got.manual:
961
+ return (rec, None, got) if rec else None
962
+ if rec.stranded_at is None:
963
+ return None
964
+ s = _survey()
965
+ if _can_work(s, rec.account):
966
+ return None
967
+ if (until := _resume_soon(s, rec.account)) is not None:
968
+ store.update_session(rec.id, lambda old: old and replace(old, waiting_until=until))
969
+ return None
970
+ return rec, s, got
971
+ except (Exception, SystemExit):
972
+ return None
973
+
974
+
975
+ def _resume_soon(s: Survey, acct_id: str) -> float | None:
976
+ """The reset to leave a stopped session waiting for, when it is within `resume_wait_minutes`
977
+ (0: never): the provider resumes the session itself then, with its whole context and no
978
+ re-read. None: pick it up."""
979
+ rep = next((r for a, r in s.twins if a.id == acct_id), acct_id)
980
+ v = next((v for v in s.verdicts if v.account.id == rep), None)
981
+ if v is None or not providers.get(v.account.provider).resumes_at_reset:
982
+ return None
983
+ reset = _limit_reset(v.account, s.snaps.get(rep), s.tuning, s.now)
984
+ wait = s.tuning.resume_wait_minutes * 60
985
+ return reset if reset and wait > 0 and reset - s.now <= wait else None
986
+
987
+
988
+ def _limit_text(s: Survey, acct_id: str) -> str:
989
+ """Which window stopped the account and when it resets, for the countdown line."""
990
+ v = next((v for v in s.verdicts if v.account.id == acct_id), None)
991
+ if v is None:
992
+ return next((why for a, why in s.out if a.id == acct_id), "no usage known")
993
+ p, snap = v.account.plan, s.snaps.get(acct_id)
994
+ for name, hours, full in ((p.long_name, p.long_hours, s.tuning.long_exhausted_pct),
995
+ (p.short_name, p.short_hours, s.tuning.short_hot_pct)):
996
+ w = name and snap and snap.windows.get(name)
997
+ if w and w.resets_at > s.now and w.used_pct >= full:
998
+ return f"{_span(hours) if hours else name} resets {_clock(w.resets_at, s.now)}"
999
+ return _usable(v, s.now)
1000
+
1001
+
1002
+ def _read_key(text, seconds: int, keys: bytes) -> bytes | None:
1003
+ """On the terminal: `text(seconds left)` on one line, counting down, until Enter (b"\\n"),
1004
+ one of `keys` (that key, lower case) or the time is up (None). Keys are read one by one
1005
+ (cbreak mode, what was typed before is dropped) and the terminal is always restored."""
1006
+ fd = sys.stdin.fileno()
1007
+ saved = termios.tcgetattr(fd)
1008
+ try:
1009
+ tty.setcbreak(fd)
1010
+ termios.tcflush(fd, termios.TCIFLUSH)
1011
+ for left in range(seconds, 0, -1):
1012
+ print(f"\r{text(left)}", end="", file=sys.stderr, flush=True)
1013
+ end = time.monotonic() + 1
1014
+ while (wait := end - time.monotonic()) > 0:
1015
+ if select.select([fd], [], [], wait)[0]:
1016
+ key = os.read(fd, 1)
1017
+ if key in (b"\r", b"\n"):
1018
+ return b"\n"
1019
+ if key.lower() in [bytes([k]) for k in keys]:
1020
+ return key.lower()
1021
+ return None
1022
+ finally:
1023
+ termios.tcsetattr(fd, termios.TCSADRAIN, saved)
1024
+ print(file=sys.stderr)
1025
+
1026
+
1027
+ def _countdown(text, seconds: int = COUNTDOWN_S) -> bool:
1028
+ """`_read_key` for a pickup: False when the user types `c`; True on Enter or when the time
1029
+ is up."""
1030
+ return _read_key(text, seconds, b"c") != b"c"
1031
+
1032
+
1033
+ TIGHT_WEEK_PCT = 90 # a chosen account whose week is this full makes a launch pause
1034
+ CLOSE_SCORE = 0.10 # so does a second-best account within this fraction of its score
1035
+
1036
+
1037
+ def _worth_pausing(s: Survey, top: Verdict, warned: bool) -> bool:
1038
+ """Whether the choice is worth a pause: the chosen account is tight (week at
1039
+ TIGHT_WEEK_PCT, a hot short window, or a spent model week), the second-best eligible one is
1040
+ close behind, or a `warning:` line was said for this launch."""
1041
+ p, snap = top.account.plan, s.snaps.get(top.account.id)
1042
+ wins = {k: w for k, w in (snap.windows if snap else {}).items() if w.resets_at > s.now}
1043
+ tight = (wins.get(p.long_name) and wins[p.long_name].used_pct >= TIGHT_WEEK_PCT) or (
1044
+ p.short_name in wins and wins[p.short_name].used_pct >= s.tuning.short_hot_pct)
1045
+ spent = _spent_models(top.account.id, snap, s.tuning, s.now)
1046
+ second = next((v for v in s.verdicts if v.eligible and v is not top), None)
1047
+ close = second is not None and top.score > 0 and second.score >= top.score * (1 - CLOSE_SCORE)
1048
+ return bool(tight or spent or close or warned)
1049
+
1050
+
1051
+ def _pause(s: Survey, top: Verdict) -> Verdict | None:
1052
+ """Show the eligible accounts, then count down `launch_pause` seconds: Enter or the time
1053
+ running out starts `top`, a digit starts that account, q quits (None)."""
1054
+ eligible = [v for v in s.verdicts if v.eligible][:9]
1055
+ for i, v in enumerate(eligible, 1):
1056
+ print(f" {i} {'>' if v is top else ' '} {v.account.id:<12} {v.reason}{_age(s, v.account.id)}",
1057
+ file=sys.stderr)
1058
+ digits = "".join(str(i) for i in range(1, len(eligible) + 1))
1059
+ which = digits if len(digits) == 1 else f"{digits[0]}-{digits[-1]}"
1060
+ try:
1061
+ key = _read_key(lambda left: f"starting {top.account.id} in {left} s · Enter = now · "
1062
+ f"{which} = that account · q = quit", max(1, round(s.tuning.launch_pause)),
1063
+ digits.encode() + b"q")
1064
+ except (OSError, termios.error): # not a terminal after all: no pause
1065
+ return top
1066
+ if key == b"q":
1067
+ return None
1068
+ return eligible[int(key) - 1] if key and key.isdigit() else top
1069
+
1070
+
1071
+ def _pickup_prompt(rec: SessionRecord, now: float, handed: bool = False) -> str:
1072
+ """The first prompt of the session that continues `rec`. Provider-neutral. `first` is the
1073
+ one place a step that comes before the rest goes. `handed`: `rec` handed over with nothing
1074
+ to stop it (no launcher), so it may still run."""
1075
+ if handed:
1076
+ why = f"which handed over at {_clock(now, now)} and may still be running"
1077
+ elif rec.stranded_at is not None:
1078
+ why = (f"which stopped at {_clock(rec.stranded_at, now)} because account {rec.account} "
1079
+ "hit its usage limit")
1080
+ else:
1081
+ why = f"which was stopped at {_clock(now, now)} on account {rec.account} to move it"
1082
+ note = store.checkpoint_path(rec.id)
1083
+ first = [f"Read its checkpoint note {note} first; it is the session's own account of where "
1084
+ "it stood."] if note and note.is_file() else []
1085
+ return " ".join([
1086
+ f"This session continues session {rec.id}, {why}. Its folder: {rec.cwd}.", *first,
1087
+ f"Run `fairshare transcript {rec.id} --tail 40` to see where it "
1088
+ f"{'left off' if handed else 'stopped'}; read the full "
1089
+ f"transcript at {rec.transcript} only if something is unclear. Then continue the work. "
1090
+ "First say in one line what you are picking up."])
1091
+
1092
+
1093
+ MOVED_PROMPT = ("fairshare moved this session from account {old} to account {new} because "
1094
+ "{why}. Continue where you left off.")
1095
+ RESTARTED_PROMPT = ("fairshare restarted this session on account {new} because {why}; it is still "
1096
+ "the best account. Continue where you left off.")
1097
+
1098
+
1099
+ def _moved_prompt(rec: SessionRecord, new: str) -> str:
1100
+ """The first prompt of a session resumed on another account, or on the same one when that
1101
+ is still the best. Provider-neutral."""
1102
+ why = (f"{rec.account} hit its usage limit" if rec.stranded_at is not None
1103
+ else "a move was asked for")
1104
+ text = RESTARTED_PROMPT if new == rec.account else MOVED_PROMPT
1105
+ return text.format(old=rec.account, new=new, why=why)
1106
+
1107
+
1108
+ def _resumed(rec: SessionRecord, copy: bool = False):
1109
+ """The arguments that resume `rec` on the chosen account, with the moved prompt (`_start`
1110
+ passes `continues` with them). Building them, just before the start, clears its stranded
1111
+ mark and wait; the account stays: the first capture writes it under the same id, and a new
1112
+ id (another account) is linked to this one (`_continuation`). `copy`: a copy under a new id
1113
+ instead (the provider's fork argument), and the record is left as it is."""
1114
+ def build(acct: Account) -> list[str]:
1115
+ prompt = _moved_prompt(rec, acct.id)
1116
+ if not copy:
1117
+ store.update_session(rec.id, lambda old: old and replace(
1118
+ old, stranded_at=None, waiting_until=None))
1119
+ return [*providers.get(acct.provider).resume_args(rec.id, copy), prompt]
1120
+ return build
1121
+
1122
+
1123
+ def _may_run(rec: SessionRecord) -> bool:
1124
+ """Whether a pickup of `rec` continues a copy under a new id rather than the session in
1125
+ place: when it was not stopped by its limit it may still run, fairshare stops no session it
1126
+ did not start, and two processes on one session would interleave its transcript. Said in
1127
+ one line when true."""
1128
+ if rec.stranded_at is not None:
1129
+ return False
1130
+ _say(f"{rec.id[:8]} was not stopped by its limit and may still be running; continuing a copy "
1131
+ "under a new id (the original is left as it is)")
1132
+ return True
1133
+
1134
+
1135
+ def _worker_of(session_id: str) -> Worker | None:
1136
+ return next((w for w in store.workers() if w.session == session_id), None)
1137
+
1138
+
1139
+ def _carry(rec: SessionRecord | None, req: Request) -> tuple[str | None, str | None]:
1140
+ """The model and effort a session started in place of `rec` keeps: the latest a usage hook
1141
+ recorded, else (a worker no usage hook saw) what its main session chose for it, else none
1142
+ (the account's default). The request's flags override each."""
1143
+ model = effort = None
1144
+ if rec and rec.model:
1145
+ model, effort = rec.model, rec.effort
1146
+ elif rec and (w := _worker_of(rec.id)):
1147
+ model, effort = w.model, w.effort
1148
+ return req.model or model, req.effort or effort
1149
+
1150
+
1151
+ def _with_model(args, model: str | None, effort: str | None):
1152
+ """`args` after the provider's arguments for `model` and `effort` (a function of the
1153
+ account, as `_launch` takes it); `args` itself when there are none."""
1154
+ if not model and not effort:
1155
+ return args
1156
+ return lambda acct: [*providers.get(acct.provider).model_args(model, effort),
1157
+ *_args_for(args, acct)]
1158
+
1159
+
1160
+ def _lacks_model(acct: Account, snap: Snapshot | None, model: str, t: Tuning,
1161
+ now: float) -> bool:
1162
+ """Whether the account's own week for `model` is spent and not yet reset (stage 4's model
1163
+ weeks, as `_spent_models` reads them)."""
1164
+ prov = providers.get(acct.provider)
1165
+ return any((wm := window_model(k)) and prov.uses_week(model, wm)
1166
+ and w.used_pct >= t.long_exhausted_pct and w.resets_at > now
1167
+ for k, w in (snap.windows if snap else {}).items())
1168
+
1169
+
1170
+ def _having_model(s: Survey, model: str | None) -> list[Verdict]:
1171
+ """The eligible verdicts, less those whose account has `model`'s week spent."""
1172
+ return [v for v in s.verdicts if v.eligible and not (
1173
+ model and _lacks_model(v.account, s.snaps.get(v.account.id), model, s.tuning, s.now))]
1174
+
1175
+
1176
+ def _no_model_line(model: str) -> str:
1177
+ return f"no account that can take work has {model} left this week"
1178
+
1179
+
1180
+ def _start(rec: SessionRecord, req: Request, args, moving: str | None = None,
1181
+ pause: bool = False, continues: str | None = None) -> int:
1182
+ """Start a session in place of `rec`, in the current folder, with `args` (a list or a
1183
+ function of the account), keeping its model and effort (`_carry`): on the request's account
1184
+ (`-a`: no ranking, the trust check kept) or on the best one. `continues` as `_launch`
1185
+ takes it."""
1186
+ model, effort = _carry(rec, req)
1187
+ if req.account:
1188
+ return _run_account(req.account, args, model, effort, continues)
1189
+ return _route(args, moving=moving, pause=pause, model=model, effort=effort,
1190
+ continues=continues)
1191
+
1192
+
1193
+ def _to_folder(rec: SessionRecord) -> None:
1194
+ if rec.cwd and os.path.isdir(rec.cwd):
1195
+ os.chdir(rec.cwd)
1196
+
1197
+
1198
+ def _resume_line(rec: SessionRecord) -> str:
1199
+ """How to resume `rec` later, on its own account (the countdown's cancel, a switch)."""
1200
+ prov = next((providers.get(a.provider) for a in _load()[0] if a.id == rec.account),
1201
+ _provider())
1202
+ return f"fairshare run -a {rec.account} -- {shlex.join(prov.resume_args(rec.id))}"
1203
+
1204
+
1205
+ def _continue(rec: SessionRecord, s: Survey | None, req: Request) -> int:
1206
+ """After the launcher stopped its child, in the session's folder, by the request's kind:
1207
+ - a switch: one line to resume the old session, then a fresh session (the launch pause
1208
+ applies);
1209
+ - a handoff: a fresh session with the pickup prompt, which reads the checkpoint first; for
1210
+ HANDOFF_NOTE the launcher has the stopped session write that note first, and anything
1211
+ wrong there is a pickup instead (one line why);
1212
+ - a pickup: for an automatic one on a terminal, a countdown (cancel says how to resume
1213
+ later); then the same session resumed on the best account (`_resumed`).
1214
+ First one line says what is happening (`_notice`), so the terminal is never blank."""
1215
+ _notice(rec, req)
1216
+ if req.kind == SWITCH:
1217
+ _say(f"to resume the old session: {_resume_line(rec)}")
1218
+ _to_folder(rec)
1219
+ return _start(rec, req, [], pause=True)
1220
+ if req.kind == HANDOFF or (req.kind == HANDOFF_NOTE and _write_note(rec, req)):
1221
+ _to_folder(rec)
1222
+ return _start(rec, req, [_pickup_prompt(rec, _now())])
1223
+ if s is not None and _interactive():
1224
+ best = next((v.account.id for v in s.verdicts if v.eligible), None)
1225
+ where = f"on {best}" if best else "(no account can take work now)"
1226
+ if not _countdown(lambda left: f"{rec.account} hit its limit ({_limit_text(s, rec.account)}"
1227
+ f"). Continuing {where} in {left} s · Enter = now · c = cancel"):
1228
+ _say(f"not continued; to resume it later: {_resume_line(rec)}")
1229
+ return 0
1230
+ _to_folder(rec)
1231
+ return _start(rec, req, _resumed(rec), moving=None if s or req.kind != PICKUP
1232
+ else rec.account, continues=rec.id)
1233
+
1234
+
1235
+ VERBS = {PICKUP: "picking up", HANDOFF: "handing off", HANDOFF_NOTE: "handing off",
1236
+ SWITCH: "switching from"}
1237
+
1238
+
1239
+ def _notice(rec: SessionRecord, req: Request) -> None:
1240
+ """The launcher's first line after it stopped its child for `req`: the verb, the session's
1241
+ first 8 characters, and the model's display name and effort it keeps, when known. Ends in
1242
+ `…`, except for a note to write, whose phases follow on their own line."""
1243
+ model, effort = _carry(rec, req)
1244
+ name = rec.model_name if model and model == rec.model and rec.model_name else model
1245
+ what = " · ".join(x for x in (name, effort if effort != EFFORT_NONE else None) if x)
1246
+ print(f"fairshare · {VERBS.get(req.kind, req.kind)} {rec.id[:8]}"
1247
+ f"{f' ({what})' if what else ''}{'' if req.kind == HANDOFF_NOTE else '…'}",
1248
+ file=sys.stderr, flush=True)
1249
+
1250
+
1251
+ def _browser_env(hub: Path, acct: Account) -> dict[str, str]:
1252
+ """BROWSER for the account's sign-in and sessions: its launcher, rewritten when missing."""
1253
+ try:
1254
+ return browser.env(hub, acct.id, acct.browser)
1255
+ except OSError as e:
1256
+ _say(f"cannot write {acct.id}'s browser launcher ({e}); links open in the default browser")
1257
+ return {}
1258
+
1259
+
1260
+ def _wait_until(t: float) -> None:
1261
+ while (left := t - _now()) > 0:
1262
+ _sleep(min(left, 60.0)) # short naps: a sleeping laptop must not oversleep the target
1263
+
1264
+
1265
+ def _run_account(account_id: str, args, model: str | None = None,
1266
+ effort: str | None = None, continues: str | None = None) -> int:
1267
+ """The user's explicit choice: no ranking, no refusal, no model filter. Only an account that
1268
+ is not signed in with a subscription is stopped; a signed-out one is offered a sign-in on a
1269
+ terminal. `args` as `_launch` takes them, after the arguments for `model` and `effort`;
1270
+ `continues` as `_launch` takes it."""
1271
+ accounts, tuning, hub = _load()
1272
+ acct = next((x for x in accounts if x.id == account_id), None)
1273
+ if acct is None:
1274
+ _say(f"no account '{account_id}' (configured: {', '.join(x.id for x in accounts)})")
1275
+ return 2
1276
+ if acct.plan is None:
1277
+ _say(f"{acct.id}: {acct.plan_error}")
1278
+ return 1
1279
+ _require_hub(hub)
1280
+ prov = providers.get(acct.provider)
1281
+ ((st, use),) = _check([acct], _now())
1282
+ if st is None:
1283
+ if why := _unconfirmed(acct):
1284
+ _say(f"{acct.id}: {why}")
1285
+ return 1
1286
+ _say(f"sign-in check failed for {acct.id}; {FALLBACK}")
1287
+ else:
1288
+ store.record_subscription(acct.id, st.logged_in and st.usable, _now())
1289
+ if not st.logged_in:
1290
+ asked = _interactive() and _ask_yes(f"{acct.id} is signed out. Sign in now?")
1291
+ if not asked:
1292
+ _say(f"{acct.id} is not signed in; `fairshare join {acct.id}` signs it in again")
1293
+ return 1
1294
+ if (st := _resign(acct, accounts, hub)) is None:
1295
+ return 1
1296
+ use = prov.read_usage(acct, _now()) # the first answer was signed out
1297
+ if not st.usable:
1298
+ _say(f"{acct.id} is not a subscription login")
1299
+ return 1
1300
+ if st.plan and st.plan != acct.plan.name:
1301
+ acct = _with_detected_plan(acct, st.plan)
1302
+ if line := _expiry_lines({acct.id: st.expires_at} if st.expires_at else {},
1303
+ _now()).get(acct.id):
1304
+ _say(line)
1305
+ now = _now()
1306
+ why = _record_usage(acct, use, now)
1307
+ snaps = {acct.id: s} if (s := store.load(acct.id)) else {}
1308
+ if why:
1309
+ _say(_probe_line(acct.id, why, snaps.get(acct.id), now))
1310
+ v = rank([acct], snaps, now, tuning)[0]
1311
+ if v.eligible:
1312
+ _grace_warning(v, snaps, tuning, now)
1313
+ else:
1314
+ _say(f"warning: {acct.id} is near a limit: {v.reason}; {_usable(v, now)}")
1315
+ for line in _spent_models(acct.id, snaps.get(acct.id), tuning, now):
1316
+ _say(line)
1317
+ return _launch(v, _with_model(args, model, effort), explicit=True, continues=continues)
1318
+
1319
+
1320
+ def _no_tool(then: str = "try again") -> bool:
1321
+ """Whether the provider's command is missing from PATH (said, ending with `then`): checked
1322
+ first by every command that starts a session or signs one in, before any sign-in check,
1323
+ probe or folder, so the cause is the one line shown."""
1324
+ prov = _provider()
1325
+ if prov.find_binary() is not None:
1326
+ return False
1327
+ _say(f"no {prov.tool} command found on PATH; install it, then {then}")
1328
+ return True
1329
+
1330
+
1331
+ def cmd_run(a) -> int:
1332
+ if _no_tool():
1333
+ return 1
1334
+ if a.account:
1335
+ return _run_account(a.account, a.args)
1336
+ return _route(a.args, pause=True)
1337
+
1338
+
1339
+ def _route(args, moving: str | None = None, pause: bool = False, model: str | None = None,
1340
+ effort: str | None = None, continues: str | None = None) -> int:
1341
+ """Start a session with `args` (as `_launch` takes them) on the best account (decision 11).
1342
+ `moving`: the account of a session picked up by request, named in one note when it could
1343
+ still take work. `pause`: on a terminal, a choice worth making waits `launch_pause` seconds
1344
+ for a key (`_pause`). `model`, `effort`: the session keeps them; an eligible account whose
1345
+ week for that model is spent is skipped, and when every eligible one is, a terminal asks
1346
+ whether to start the top one on its default model, and no terminal refuses. `continues` as
1347
+ `_launch` takes it."""
1348
+ try:
1349
+ while True:
1350
+ s = _survey()
1351
+ warned = False
1352
+ if moving and _can_work(s, moving):
1353
+ _say(f"note: {moving} can still take work; the session is picked up as asked")
1354
+ moving = None
1355
+ if s.out:
1356
+ _say("skipped " + ", ".join(f"{x.id} ({why})" for x, why in s.out))
1357
+ if signed_out := [x.id for x, why in s.out if why == NOT_SIGNED_IN]:
1358
+ _say("; ".join(f"`fairshare join {i}`" for i in signed_out)
1359
+ + " signs " + ("it" if len(signed_out) == 1 else "them") + " in again")
1360
+ if fallback := [v.account.id for v in s.verdicts if v.account.id in s.failed]:
1361
+ _say(f"sign-in check failed for {', '.join(fallback)}; {FALLBACK}")
1362
+ for line in [*_probe_lines(s).values(), *_expiry_lines(s.expires, s.now).values()]:
1363
+ _say(line)
1364
+ warned = warned or line.startswith("warning:")
1365
+ if note := _preference_note(s):
1366
+ _say(note)
1367
+ _nothing_to_rank(s)
1368
+ if model and any(v.eligible for v in s.verdicts):
1369
+ having = _having_model(s, model)
1370
+ if having:
1371
+ s = replace(s, verdicts=[v for v in s.verdicts
1372
+ if v in having or not v.eligible])
1373
+ elif not _interactive():
1374
+ _say(f"{_no_model_line(model)}; name another with --model")
1375
+ return 1
1376
+ elif (_say(_no_model_line(model)) or _choose(
1377
+ f"[d] start on {s.verdicts[0].account.id} with its default model, "
1378
+ "[q] quit: ", {"d", "q"})) != "d":
1379
+ _say("not started")
1380
+ return 0
1381
+ else:
1382
+ model = effort = None
1383
+ top = s.verdicts[0]
1384
+ spent = _spent_models(top.account.id, s.snaps.get(top.account.id), s.tuning, s.now)
1385
+ if top.eligible:
1386
+ warned = _grace_warning(top, s.snaps, s.tuning, s.now) or warned
1387
+ for line in spent:
1388
+ _say(line)
1389
+ if (pause and s.tuning.launch_pause > 0 and _interactive()
1390
+ and _worth_pausing(s, top, warned)):
1391
+ if (top := _pause(s, top)) is None:
1392
+ _say("not started")
1393
+ return 0
1394
+ return _launch(top, _with_model(args, model, effort), continues=continues)
1395
+ _say("no account is eligible:")
1396
+ for v in s.verdicts:
1397
+ print(f" {v.account.id:<12} {v.reason}; {_usable(v, s.now)} (in {_in(v.usable_in)})"
1398
+ f"{_age(s, v.account.id)}", file=sys.stderr)
1399
+ if not _interactive():
1400
+ return 75
1401
+ soon = min(s.verdicts, key=lambda v: (v.usable_in, v.account.id))
1402
+ print(f"[w]ait for {soon.account.id} ({_usable(soon, s.now)}), "
1403
+ f"[s]tart on {top.account.id} now, [q]uit [q]: ", end="", file=sys.stderr)
1404
+ try:
1405
+ choice = input().strip().lower()[:1]
1406
+ except EOFError:
1407
+ choice = "q"
1408
+ if choice == "s":
1409
+ _say(f"starting on {top.account.id}, which is near a limit")
1410
+ for line in spent:
1411
+ _say(line)
1412
+ return _launch(top, _with_model(args, model, effort), continues=continues)
1413
+ if choice != "w":
1414
+ return 75
1415
+ _say(f"waiting for {soon.account.id}, {_usable(soon, s.now)} (Ctrl-C to quit)")
1416
+ _wait_until(s.now + soon.usable_in * HOUR + 1)
1417
+ except KeyboardInterrupt:
1418
+ print(file=sys.stderr)
1419
+ return 130
1420
+
1421
+
1422
+ def _find_session(text: str) -> SessionRecord | None:
1423
+ """The session record whose id is `text`, or the only one it starts, each taken at the end of
1424
+ its chain (`store.latest`: a session that went on under a new id is that one); None (said
1425
+ why, with the matches) otherwise."""
1426
+ recs = store.sessions()
1427
+ found = [r for r in recs if r.id == text] or [r for r in recs if r.id.startswith(text)]
1428
+ ends = dict.fromkeys(store.latest(r.id) for r in found)
1429
+ found = [r for i in ends if (r := store.session(i))]
1430
+ if len(found) == 1:
1431
+ return found[0]
1432
+ if not found:
1433
+ _say(f"no session recorded starts with {text!r}")
1434
+ else:
1435
+ _say(f"{text!r} matches {len(found)} sessions; give more of the id:")
1436
+ now = _now()
1437
+ for r in found:
1438
+ print(f" {r.id} {r.account:<12} {r.cwd} (seen {_clock(r.seen, now)})",
1439
+ file=sys.stderr)
1440
+ return None
1441
+
1442
+
1443
+ def _unknown_account(account_id: str | None) -> bool:
1444
+ """Whether `-a` names no configured account (said, with the configured ids). Checked before
1445
+ a request goes to the launcher, which would otherwise stop the session for nothing."""
1446
+ if account_id is None:
1447
+ return False
1448
+ accounts = _load()[0]
1449
+ if any(x.id == account_id for x in accounts):
1450
+ return False
1451
+ _say(f"no account '{account_id}' (configured: {', '.join(x.id for x in accounts)})")
1452
+ return True
1453
+
1454
+
1455
+ def cmd_pickup(a) -> int:
1456
+ """Continue a session on the best account (or `-a`), resumed under its own id with its
1457
+ model and effort (`--model`, `--effort` override them). Inside a session with no SESSION:
1458
+ this one; its launcher, when it has one, stops it and resumes it (a manual request: no check
1459
+ that the account is out), otherwise it resumes in the background. A SESSION (full id or
1460
+ unique prefix) from a terminal outside a session resumes in the foreground in its folder;
1461
+ inside a session or with --bg, in the background. fairshare never stops a session it did
1462
+ not start."""
1463
+ prov = _provider()
1464
+ if _no_tool():
1465
+ return 1
1466
+ if _unknown_account(a.account):
1467
+ return 2
1468
+ here = prov.current_session()
1469
+ if a.session is None:
1470
+ if here is None:
1471
+ _say("not inside a session; name one: fairshare pickup SESSION")
1472
+ return 2
1473
+ if (rec := store.session(here)) is None:
1474
+ _say(f"no record of this session ({here}) yet; it appears once its status line ran")
1475
+ return 1
1476
+ req = Request(rec.id, True, prov.session_pid(), PICKUP, a.model, a.effort, a.account)
1477
+ if launcher := _launcher():
1478
+ _request(launcher, req)
1479
+ print("the launcher will stop this session and continue on the best account")
1480
+ return 0
1481
+ return _pickup_background(rec, req)
1482
+ if (rec := _find_session(a.session)) is None:
1483
+ return 2
1484
+ req = Request(rec.id, True, None, PICKUP, a.model, a.effort, a.account)
1485
+ if here or a.bg or not _interactive():
1486
+ return _pickup_background(rec, req)
1487
+ if not (rec.cwd and os.path.isdir(rec.cwd)):
1488
+ _say(f"the session's folder {rec.cwd} is gone; not picked up")
1489
+ return 1
1490
+ os.chdir(rec.cwd)
1491
+ copy = _may_run(rec)
1492
+ return _start(rec, req, _resumed(rec, copy), moving=rec.account,
1493
+ continues=rec.id + (COPY if copy else ""))
1494
+
1495
+
1496
+ def _pickup_background(rec: SessionRecord, req: Request, fresh: bool = False) -> int:
1497
+ """Continue `rec` with no terminal, in its folder, on the request's account or the top
1498
+ eligible one that has its model (`_carry`) and trusts that folder or can get its trust by
1499
+ copy (nothing can ask); the tool's own output passes through. It resumes the session under
1500
+ its own id, or, when it was not stopped by its limit (it may still run, and fairshare stops
1501
+ no session it did not start), a copy under a new id with the record copied. `fresh`: a new
1502
+ session with the pickup prompt instead (a handoff)."""
1503
+ if not (rec.cwd and os.path.isdir(rec.cwd)):
1504
+ _say(f"the session's folder {rec.cwd} is gone; not picked up")
1505
+ return 1
1506
+ s = _survey()
1507
+ if not fresh and _can_work(s, rec.account):
1508
+ _say(f"note: {rec.account} can still take work; the session is picked up as asked")
1509
+ here = Path(rec.cwd).resolve()
1510
+ accounts, _, hub = _load()
1511
+ model, effort = _carry(rec, req)
1512
+ if req.account:
1513
+ candidates = [x for x in accounts if x.id == req.account]
1514
+ eligible = [v for v in s.verdicts if v.account.id == req.account]
1515
+ else:
1516
+ eligible = _having_model(s, model)
1517
+ if model and not eligible and any(v.eligible for v in s.verdicts):
1518
+ _say(f"{_no_model_line(model)}; name another with --model")
1519
+ return 1
1520
+ candidates = [v.account for v in eligible]
1521
+ acct = _start_here(candidates, here, accounts, hub)
1522
+ if acct is None:
1523
+ _say("no account can take it in the background: "
1524
+ + (f"eligible: {', '.join(v.account.id for v in eligible)}, none of which trusts "
1525
+ f"{here} ({_why_untrusted(here, accounts)}); or use `fairshare pickup "
1526
+ f"{rec.id}` from a terminal" if eligible else "none is eligible now"))
1527
+ return 1
1528
+ v = next((v for v in eligible if v.account.id == acct.id), None)
1529
+ _say(f"handing off {rec.id[:8]} to a fresh session on {acct.id}, in the background" if fresh
1530
+ else f"picking up {rec.id} on {acct.id}" + (f" ({v.reason})" if v else "")
1531
+ + ", in the background")
1532
+ prov, w = providers.get(acct.provider), _worker_of(rec.id)
1533
+ name = w.name if w else f"pickup-{rec.id[:8]}"
1534
+ extra = prov.model_args(model, effort)
1535
+ if fresh:
1536
+ return _start_background(acct, name, _pickup_prompt(rec, s.now, handed=True), rec.cwd,
1537
+ extra)
1538
+ fork = _may_run(rec)
1539
+ before = _live_named(acct, name)
1540
+ if code := _start_background(acct, name, _moved_prompt(rec, acct.id), rec.cwd,
1541
+ [*prov.resume_args(rec.id, fork), *extra]):
1542
+ return code
1543
+ new = _named_session(acct, name, before)
1544
+ if new == rec.id: # it went on under its own id
1545
+ new = None
1546
+ if new is None and not fork:
1547
+ store.move_session(rec.id, acct.id)
1548
+ elif new is None:
1549
+ print(f"the copy's session id is not known yet ({name}); fairshare finds it by name later"
1550
+ if w else f"the copy runs as {name}; its session id is not known yet")
1551
+ else:
1552
+ _copied(rec, new, acct, model, effort, w, fork)
1553
+ print(f"continued as session {new} on {acct.id}")
1554
+ return 0
1555
+
1556
+
1557
+ def _live_named(acct: Account, name: str) -> set[str] | None:
1558
+ """The ids of the sessions running under `name` now, taken before a background start that
1559
+ is joined by that name (`_named_session`); None when the list cannot be had."""
1560
+ live = providers.get(acct.provider).list_sessions(acct)
1561
+ return None if live is None else {x.id for x in live if x.name == name}
1562
+
1563
+
1564
+ def _named_session(acct: Account, name: str, before: set[str] | None) -> str | None:
1565
+ """The id of the session that a background start named `name` began: one listed under
1566
+ that name that was not among `before` (`_live_named`, taken before the start), looked for
1567
+ in the provider's list of running sessions for up to JOIN_WAIT seconds. None when nothing
1568
+ new is found, or when `before` could not be had: an earlier session of that name (an
1569
+ earlier pickup of the same session, a worker picked up twice) is never taken."""
1570
+ if before is None:
1571
+ return None
1572
+ end = _now() + JOIN_WAIT
1573
+ prov = providers.get(acct.provider)
1574
+ while True:
1575
+ live = prov.list_sessions(acct) or []
1576
+ if found := next((x.id for x in live if x.name == name and x.id not in before), None):
1577
+ return found
1578
+ if _now() >= end:
1579
+ return None
1580
+ _sleep(JOIN_POLL)
1581
+
1582
+
1583
+ def _copied(rec: SessionRecord, new: str, acct: Account, model: str | None,
1584
+ effort: str | None, w: Worker | None, fork: bool) -> None:
1585
+ """A copy of `rec` runs as `new` on `acct`: link the two (`store.link_session`: role,
1586
+ parent, model and effort as carried, the checkpoint note copied; workers re-parented only
1587
+ when `rec` stopped, not for a `fork` of a session that may still run), and a worker's name
1588
+ now joins it."""
1589
+ store.link_session(rec.id, SessionSeen(
1590
+ new, rec.cwd, None, model, rec.model_name if model and model == rec.model else None,
1591
+ effort), acct.id, _now(), copy=fork)
1592
+ if w:
1593
+ store.join_worker(w.name, new)
1594
+
1595
+
1596
+ # --- Handoff: a checkpoint, then a fresh session that reads it first (decision 23).
1597
+
1598
+ HANDOFF_NOTE_ASK = ("fairshare is handing this session over to a fresh session, which reads your "
1599
+ "note first. Write that note now, as plain text: what was done, what is "
1600
+ "next, the open decisions, and the files touched. Use no tools; answer with "
1601
+ "the note alone.")
1602
+ HANDOFF_WAIT_S = 300 # seconds the launcher waits for the handoff note before a pickup instead
1603
+
1604
+
1605
+ def _write_checkpoint(session_id: str, text: str) -> Path:
1606
+ """Append `text` to the session's checkpoint note, dated, and clear its pending request."""
1607
+ stamp = time.strftime("%Y-%m-%d %H:%M", time.localtime(_now()))
1608
+ path = store.append_checkpoint(session_id, f"## {stamp}\n{text}\n")
1609
+ store.update_session(session_id, lambda old: old and old.checkpoint_requested is not None
1610
+ and replace(old, checkpoint_requested=None, request_said=None) or None)
1611
+ return path
1612
+
1613
+
1614
+ def cmd_handoff(a) -> int:
1615
+ """Hand the current session over to a fresh session that reads its checkpoint first. With
1616
+ NOTE: the note is appended, then the launcher stops this session and starts the fresh one
1617
+ (without a launcher, in the background). Without NOTE (the user's `!`): the launcher stops
1618
+ this session, has it write the note in one headless turn, then starts the fresh one."""
1619
+ prov = _provider()
1620
+ if _no_tool():
1621
+ return 1
1622
+ if (here := prov.current_session()) is None:
1623
+ _say("not inside a session: handoff is for the session it runs in; to move another "
1624
+ "one: fairshare pickup SESSION")
1625
+ return 2
1626
+ if _unknown_account(a.account):
1627
+ return 2
1628
+ if (rec := store.session(here)) is None:
1629
+ _say(f"no record of this session ({here}) yet; it appears once its status line ran")
1630
+ return 1
1631
+ launcher = _launcher()
1632
+ req = Request(rec.id, True, prov.session_pid(), HANDOFF if a.note else HANDOFF_NOTE,
1633
+ a.model, a.effort, a.account)
1634
+ if a.note:
1635
+ print(_write_checkpoint(rec.id, a.note))
1636
+ if launcher is None:
1637
+ if code := _pickup_background(rec, req, fresh=True):
1638
+ return code
1639
+ print("this session keeps running: stop here and leave the work to the new session")
1640
+ return 0
1641
+ _request(launcher, req)
1642
+ print("the launcher will stop this session and start a fresh one that reads the note first")
1643
+ return 0
1644
+ if launcher is None:
1645
+ _say("this session was not started by fairshare, so nothing can write its note while it "
1646
+ "waits; ask the session's agent instead: /fairshare handoff")
1647
+ return 1
1648
+ _request(launcher, req)
1649
+ print("the launcher will stop this session, have it write its handoff note, and start a "
1650
+ "fresh one that reads it first")
1651
+ return 0
1652
+
1653
+
1654
+ def _write_note(rec: SessionRecord, req: Request) -> bool:
1655
+ """In the launcher, after it stopped its child: resume that session headless for one turn
1656
+ that writes its handoff note (no tools, its model and effort), on its own account when it
1657
+ can take work (its cache is warm), else the top eligible one; append the answer as its
1658
+ checkpoint. A status line shows each step (`_Status`); on a terminal, `c` skips. False,
1659
+ with one line why, when no note was written: the caller picks the session up instead."""
1660
+ status = _Status(_interactive())
1661
+
1662
+ def fail(why: str) -> bool:
1663
+ status.clear()
1664
+ _say(f"no handoff note ({why}); picking the session up instead")
1665
+ return False
1666
+ status.show("checking accounts…")
1667
+ try:
1668
+ s = _drawing(status, _survey)
1669
+ except SystemExit as e:
1670
+ return fail(str(e))
1671
+ own = next((v.account for v in s.verdicts if v.account.id == rec.account), None)
1672
+ acct = own if own and _can_work(s, rec.account) else next(
1673
+ (v.account for v in s.verdicts if v.eligible), None)
1674
+ if acct is None:
1675
+ return fail("no account can take work")
1676
+ prov = providers.get(acct.provider)
1677
+ model, effort = _carry(rec, req)
1678
+ cmd, env = prov.note_command(acct, rec.id, prov.model_args(model, effort), HANDOFF_NOTE_ASK)
1679
+ try:
1680
+ proc = subprocess.Popen(cmd, env=_background_env(env), stdin=subprocess.DEVNULL,
1681
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
1682
+ cwd=rec.cwd if rec.cwd and os.path.isdir(rec.cwd) else None)
1683
+ except OSError as e:
1684
+ return fail(f"cannot start {cmd[0]}: {e.strerror}")
1685
+ try:
1686
+ how, text = _note_wait(proc, prov, acct.id, status)
1687
+ finally:
1688
+ if proc.poll() is None:
1689
+ proc.kill()
1690
+ proc.wait()
1691
+ proc.stdout.close()
1692
+ if how != "done":
1693
+ return fail("skipped" if how == "skip" else f"no answer in {HANDOFF_WAIT_S} s")
1694
+ if proc.returncode or not text:
1695
+ return fail(f"the turn failed (exit {proc.returncode})" if proc.returncode
1696
+ else "the answer held no note")
1697
+ path = _write_checkpoint(rec.id, text)
1698
+ status.clear()
1699
+ print(f"✓ note saved, {len(text.split())} words → {path}", file=sys.stderr, flush=True)
1700
+ return True
1701
+
1702
+
1703
+ TICK_S = 0.1 # the status line's redraw interval
1704
+ SPIN_UTF8, SPIN_ASCII = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏", "|/-\\"
1705
+ STATUS_PHASE_WIDTH = 44 # the phase's column, so the clock stays put
1706
+
1707
+
1708
+ def _width() -> int:
1709
+ try:
1710
+ return max(os.get_terminal_size(sys.stderr.fileno()).columns, 20)
1711
+ except (OSError, ValueError):
1712
+ return 80
1713
+
1714
+
1715
+ class _Status:
1716
+ """One status line on stderr. On a terminal (`tty`): a spinner, the phase, the time since
1717
+ it began (m:ss) and a tail, redrawn in place by `draw`, cut to the terminal's width.
1718
+ Otherwise each phase once, as a plain line, as it starts."""
1719
+
1720
+ def __init__(self, tty: bool):
1721
+ self.tty, self.start = tty, time.monotonic()
1722
+ self.phase = self.detail = self.tail = ""
1723
+ utf8 = (getattr(sys.stderr, "encoding", None) or "").lower().replace("-", "") == "utf8"
1724
+ self.frames = SPIN_UTF8 if utf8 else SPIN_ASCII
1725
+
1726
+ def show(self, phase: str, detail: str = "", tail: str = "") -> None:
1727
+ """Show `phase` (with `detail` and `tail`, on a terminal only)."""
1728
+ if phase != self.phase and not self.tty:
1729
+ print(phase, file=sys.stderr, flush=True)
1730
+ self.phase, self.detail, self.tail = phase, detail, tail
1731
+ self.draw()
1732
+
1733
+ def draw(self) -> None:
1734
+ if not self.tty:
1735
+ return
1736
+ t = time.monotonic() - self.start
1737
+ line = (f"{self.frames[int(t / TICK_S) % len(self.frames)]} "
1738
+ f"{self.phase + self.detail:<{STATUS_PHASE_WIDTH}} "
1739
+ f"{int(t) // 60}:{int(t) % 60:02d}{self.tail}")
1740
+ print(f"\r{line[:_width() - 1]}\x1b[K", end="", file=sys.stderr, flush=True)
1741
+
1742
+ def clear(self) -> None:
1743
+ if self.tty:
1744
+ print("\r\x1b[K", end="", file=sys.stderr, flush=True)
1745
+
1746
+
1747
+ def _drawing(status: _Status, fn):
1748
+ """`fn()` in a worker thread while this one redraws `status`: its result, or its exception
1749
+ (a SystemExit too)."""
1750
+ with ThreadPoolExecutor(1) as pool:
1751
+ future = pool.submit(fn)
1752
+ while True:
1753
+ try:
1754
+ return future.result(TICK_S)
1755
+ except TimeoutError:
1756
+ status.draw()
1757
+
1758
+
1759
+ def _note_wait(proc: subprocess.Popen, prov, where: str, status: _Status,
1760
+ seconds: float | None = None) -> tuple[str, str | None]:
1761
+ """Wait for `proc`, the note turn, reading its output pipe as it comes (so it never fills)
1762
+ and showing its phase on `status`: reading the session on `where` until the model's first
1763
+ event, thinking, then writing the note with its words so far (`Provider.note_event`). The
1764
+ phase never goes back; a line that says nothing keeps it. "done" and the answer's text
1765
+ (`Provider.note_text` of the final line; None without one) when the turn ended; "skip"
1766
+ when `c` was typed (on a terminal: cbreak mode, always restored); "timeout" after `seconds`
1767
+ (HANDOFF_WAIT_S)."""
1768
+ end = time.monotonic() + (HANDOFF_WAIT_S if seconds is None else seconds)
1769
+ tty_fd = sys.stdin.fileno() if status.tty else None
1770
+ tail = " · c = skip" if tty_fd is not None else ""
1771
+ pipe, buf, last, phase, written = proc.stdout.fileno(), b"", "", 0, ""
1772
+
1773
+ def show() -> None:
1774
+ status.show(*((f"reading the session on {where}…", ""), ("thinking…", ""),
1775
+ ("writing the note", f" · {len(written.split())} words"))[phase], tail)
1776
+
1777
+ def read(lines: list[bytes]) -> None:
1778
+ nonlocal last, phase, written
1779
+ for raw in lines:
1780
+ if not (line := raw.decode("utf-8", "replace").strip()):
1781
+ continue
1782
+ last, ev = line, prov.note_event(line)
1783
+ if ev and ev.kind == NOTE_THINKING:
1784
+ phase = max(phase, 1)
1785
+ elif ev and ev.kind == NOTE_WRITING:
1786
+ phase, written = 2, written + ev.text
1787
+ saved = None
1788
+ try:
1789
+ if tty_fd is not None:
1790
+ saved = termios.tcgetattr(tty_fd)
1791
+ tty.setcbreak(tty_fd)
1792
+ termios.tcflush(tty_fd, termios.TCIFLUSH)
1793
+ show()
1794
+ while not ((done := proc.poll() is not None) and pipe is None):
1795
+ if not done and (left := end - time.monotonic()) <= 0:
1796
+ return "timeout", None
1797
+ ready = select.select([f for f in (pipe, tty_fd) if f is not None], [], [],
1798
+ 0 if done else min(left, TICK_S))[0]
1799
+ if pipe is not None and pipe in ready:
1800
+ if chunk := os.read(pipe, 65536):
1801
+ *lines, buf = (buf + chunk).split(b"\n")
1802
+ read(lines)
1803
+ else: # the end of the output
1804
+ pipe = None
1805
+ elif done: # ended, and its pipe held open elsewhere
1806
+ break
1807
+ if tty_fd is not None and tty_fd in ready and os.read(tty_fd, 1).lower() == b"c":
1808
+ return "skip", None
1809
+ show()
1810
+ read([buf])
1811
+ return "done", prov.note_text(last) if last else None
1812
+ finally:
1813
+ if saved is not None:
1814
+ termios.tcsetattr(tty_fd, termios.TCSADRAIN, saved)
1815
+ status.clear()
1816
+
1817
+
1818
+ # --- Switch: bare `fairshare` inside a session started by the launcher (decision 23).
1819
+
1820
+ SWITCH_FLAGS = ("--model", "--effort", "-a", "--account")
1821
+
1822
+
1823
+ def cmd_switch(a) -> int:
1824
+ """Inside a session: ask its launcher to stop it and start a fresh session on the best
1825
+ account (or `-a`) in the same folder, keeping its model and effort. Never a nested launch."""
1826
+ prov = _provider()
1827
+ here = prov.current_session()
1828
+ if (launcher := _launcher()) is None:
1829
+ _say("this session was not started by fairshare's launcher, so it cannot switch from "
1830
+ "inside; /exit, then fairshare")
1831
+ return 1
1832
+ if _unknown_account(a.account):
1833
+ return 2
1834
+ accounts = _load()[0]
1835
+ rec = store.session(here) or ((acct := _session_account(accounts)) and store.note_session(
1836
+ SessionSeen(here, os.getcwd()), acct.id, _now()))
1837
+ if rec is None:
1838
+ _say(f"no record of this session ({here}); nothing switched")
1839
+ return 1
1840
+ _request(launcher, Request(rec.id, True, prov.session_pid(), SWITCH, a.model, a.effort,
1841
+ a.account))
1842
+ print("the launcher will stop this session and start a fresh one on the best account")
1843
+ return 0
1844
+
1845
+
1846
+ def _background_env(env: dict[str, str]) -> dict[str, str]:
1847
+ """A background session's environment: no launcher of ours, and no BROWSER, which would not
1848
+ reach it anyway (the provider starts background sessions from its own pool): it uses the
1849
+ system browser."""
1850
+ return {k: v for k, v in env.items() if k not in (LAUNCHER_ENV, browser.ENV)}
1851
+
1852
+
1853
+ def _start_background(acct: Account, name: str, prompt: str, cwd: str,
1854
+ extra: list[str] = ()) -> int:
1855
+ """The start check on the account's hub folder, then a session with no terminal named
1856
+ `name`, in `cwd`, with `extra` arguments (a resume, a model), whose first message is
1857
+ `prompt`; the tool's own output passes through."""
1858
+ prov = providers.get(acct.provider)
1859
+ hub = acct.config_dir.parent.parent
1860
+ if not hub_mod.present(hub, acct.id):
1861
+ _say(_no_hub(hub))
1862
+ return 1
1863
+ try:
1864
+ for note in hub_mod.check(hub, acct.id, prov):
1865
+ _say(note)
1866
+ except OSError as e:
1867
+ _say(f"cannot prepare {acct.id}'s folder in the hub ({e}); not started")
1868
+ return 1
1869
+ cmd, env = prov.background(acct, name, prompt, list(extra))
1870
+ try:
1871
+ return subprocess.run(cmd, env=_background_env(env), cwd=cwd,
1872
+ stdin=subprocess.DEVNULL).returncode
1873
+ except OSError as e:
1874
+ _say(f"cannot start {cmd[0]}: {e.strerror}")
1875
+ return 127 if isinstance(e, FileNotFoundError) else 126
1876
+
1877
+
1878
+ # --- Folder trust without a terminal: copy, never create (decision 21).
1879
+
1880
+ def _copy_refused(here: Path) -> str | None:
1881
+ """Why trust for the canonical folder `here` may not be copied, else None: never in HOME
1882
+ (the provider keeps trust there per session), never where the user answered "only"."""
1883
+ if here == Path.home().resolve():
1884
+ return "fairshare writes no trust in HOME"
1885
+ if store.trust_only(here):
1886
+ return f"you answered \"only\" for {here} before, so fairshare copies no trust there"
1887
+ return None
1888
+
1889
+
1890
+ def _trusting(accounts: list[Account], here: Path) -> list[Account]:
1891
+ """The joined accounts (with a plan) whose state trusts `here`."""
1892
+ return [a for a in accounts if a.plan is not None
1893
+ and providers.get(a.provider).trusts(a.config_dir, here) is True]
1894
+
1895
+
1896
+ def _copy_trust(to: Account, source: Account, here: Path, hub: Path, tell) -> bool:
1897
+ """Write trust for `here` into `to`'s state, as the provider's own dialog would (lock,
1898
+ backup, read back), because `source` already trusts it. One line: through `tell` when
1899
+ written, on stderr when not."""
1900
+ try:
1901
+ key = providers.get(to.provider).trust(to.config_dir, here,
1902
+ hub_mod.backup_dir(hub, f"trust-{to.id}"))
1903
+ except (OSError, UnicodeDecodeError, ValueError) as e:
1904
+ _say(f"{to.id}: trust not written ({e})")
1905
+ return False
1906
+ tell(f"{to.id} now trusts {key} (copied from {source.id})")
1907
+ return True
1908
+
1909
+
1910
+ def _start_here(candidates: list[Account], here: Path, accounts: list[Account],
1911
+ hub: Path) -> Account | None:
1912
+ """The first of `candidates` that trusts `here`, or that can get trust by copy (copied now,
1913
+ one line); None when none can."""
1914
+ refused, sources = _copy_refused(here), _trusting(accounts, here)
1915
+ for c in candidates:
1916
+ if any(t.id == c.id for t in sources):
1917
+ return c
1918
+ src = None if refused else next((t for t in sources if t.provider == c.provider), None)
1919
+ if src and _copy_trust(c, src, here, hub, _say):
1920
+ return c
1921
+ return None
1922
+
1923
+
1924
+ def _why_untrusted(here: Path, accounts: list[Account]) -> str:
1925
+ """Why trust could not be had for `here` without a terminal."""
1926
+ if refused := _copy_refused(here):
1927
+ return refused
1928
+ if not _trusting(accounts, here):
1929
+ return ("no account trusts it, so there is nothing to copy: start a session there from a "
1930
+ "terminal and answer the trust question")
1931
+ return "copying trust failed"
1932
+
1933
+
1934
+ def cmd_trust(a) -> int:
1935
+ """Copy folder trust for PATH (default: here) from an account that trusts it to every
1936
+ joined account that lacks it. Never creates trust, never in HOME, never where the user
1937
+ answered "only". Needs no terminal."""
1938
+ here = Path(a.path or os.getcwd()).expanduser().resolve()
1939
+ if not here.is_dir():
1940
+ _say(f"{here} is not a folder")
1941
+ return 2
1942
+ accounts, _, hub = _load()
1943
+ _require_hub(hub)
1944
+ if here == Path.home().resolve():
1945
+ _say(f"{here} is HOME: {_copy_refused(here)} (each session there asks for itself)")
1946
+ return 1
1947
+ sources = _trusting(accounts, here)
1948
+ lacking = [x for x in accounts if x.plan is not None and x not in sources]
1949
+ if not lacking:
1950
+ print(f"every account already trusts {here}; nothing to copy")
1951
+ return 0
1952
+ if refused := _copy_refused(here):
1953
+ _say(f"{refused}; nothing copied")
1954
+ return 1
1955
+ if not sources:
1956
+ _say(f"no account trusts {here}, and fairshare never creates trust: start a session "
1957
+ "there from a terminal (`fairshare`) and answer the question")
1958
+ return 1
1959
+ failed = 0
1960
+ for x in lacking:
1961
+ src = next((t for t in sources if t.provider == x.provider), None)
1962
+ if src is None:
1963
+ _say(f"{x.id}: no account of its provider trusts {here}; nothing copied")
1964
+ failed += 1
1965
+ elif not _copy_trust(x, src, here, hub, print):
1966
+ failed += 1
1967
+ return 1 if failed else 0
1968
+
1969
+
1970
+ # --- Workers: background sessions a main session starts (decision 22).
1971
+
1972
+ WORKER_LINE = ("You are a worker for session {parent}. When fairshare asks for a checkpoint, run "
1973
+ 'fairshare checkpoint "<what is done, what is next>".')
1974
+ JOIN_WAIT = 10.0 # seconds a new worker's session id is looked for by its name
1975
+ JOIN_POLL = 0.5 # seconds between looks
1976
+ JOIN_RETRY_S = 3600 # a worker still unjoined this long after its start is no longer looked for
1977
+
1978
+
1979
+ def _joined(w: Worker, session_id: str, now: float) -> None:
1980
+ """Note a worker's session id, and mark its session record as a worker's."""
1981
+ store.join_worker(w.name, session_id)
1982
+ store.update_session(session_id, lambda old: replace(
1983
+ old or SessionRecord(session_id, w.account, w.cwd, None, now),
1984
+ role=ROLE_WORKER, parent=w.parent))
1985
+
1986
+
1987
+ def _join_pending(pending: list[Worker], accounts: list[Account], now: float) -> dict[str, str]:
1988
+ """Look the unjoined workers among `pending` up by name, with one listing of the running
1989
+ sessions; join each one found. {name: session id} of those joined."""
1990
+ todo = [w for w in pending if w.session is None and now - w.started < JOIN_RETRY_S]
1991
+ acct = next((a for w in todo for a in accounts if a.id == w.account), None)
1992
+ live = acct and providers.get(acct.provider).list_sessions(acct)
1993
+ found = {}
1994
+ for w in todo:
1995
+ if sid := next((x.id for x in live or [] if x.name == w.name), None):
1996
+ _joined(w, sid, now)
1997
+ found[w.name] = sid
1998
+ return found
1999
+
2000
+
2001
+ def _new_worker(parent: str, acct: Account, cwd: str, name: str | None, model: str,
2002
+ effort: str) -> Worker | None:
2003
+ """Record a new worker under `name`, or under the first free `w-<parent's first 8>-<n>`;
2004
+ None when `name` is taken."""
2005
+ now = _now()
2006
+ for n in range(1, 10_000):
2007
+ w = Worker(name or f"w-{parent[:8]}-{n}", parent, acct.id, cwd, now, model=model,
2008
+ effort=effort)
2009
+ if store.add_worker(w):
2010
+ return w
2011
+ if name:
2012
+ return None
2013
+ return None
2014
+
2015
+
2016
+ def cmd_worker(a) -> int:
2017
+ """Start a background session for the calling session, on the model and effort the main
2018
+ session chose (`--effort none` for a model without one): on --account, else the top
2019
+ eligible account that has that model's week left and trusts this folder or can get its
2020
+ trust by copy; named, recorded, and joined to its session id by that name."""
2021
+ prov = _provider()
2022
+ if (parent := prov.current_session()) is None:
2023
+ _say("not inside a session: a worker belongs to the session that starts it")
2024
+ return 2
2025
+ if a.name is not None and not ACCOUNT_ID.fullmatch(a.name):
2026
+ _say(f"worker name {a.name!r}: use letters, digits, '.', '-' or '_'")
2027
+ return 2
2028
+ here = Path(os.getcwd()).resolve()
2029
+ accounts, _, hub = _load()
2030
+ _require_hub(hub)
2031
+ if a.account:
2032
+ chosen = next((x for x in accounts if x.id == a.account), None)
2033
+ if chosen is None:
2034
+ _say(f"no account '{a.account}' (configured: {', '.join(x.id for x in accounts)})")
2035
+ return 2
2036
+ if chosen.plan is None:
2037
+ _say(f"{chosen.id}: {chosen.plan_error}")
2038
+ return 1
2039
+ candidates, why = [chosen], ""
2040
+ else:
2041
+ s = _survey()
2042
+ if not any(v.eligible for v in s.verdicts):
2043
+ _say("no account can take work now; no worker started")
2044
+ return 1
2045
+ candidates = [v.account for v in _having_model(s, a.model)]
2046
+ if not candidates:
2047
+ _say(f"{_no_model_line(a.model)}; name another with --model; no worker started")
2048
+ return 1
2049
+ why = {v.account.id: f" ({v.reason})" for v in s.verdicts}
2050
+ acct = _start_here(candidates, here, accounts, hub)
2051
+ if acct is None:
2052
+ _say(f"{', '.join(c.id for c in candidates)} cannot work in {here}: "
2053
+ f"{_why_untrusted(here, accounts)}; no worker started")
2054
+ return 1
2055
+ w = _new_worker(parent, acct, str(here), a.name, a.model, a.effort)
2056
+ if w is None:
2057
+ _say(f"a worker named {a.name} is recorded already; choose another --name")
2058
+ return 2
2059
+ _say(f"starting worker {w.name} on {acct.id}{why and why[acct.id]}")
2060
+ prompt = WORKER_LINE.format(parent=parent) + "\n\n" + a.prompt
2061
+ before = _live_named(acct, w.name)
2062
+ if code := _start_background(acct, w.name, prompt, str(here),
2063
+ providers.get(acct.provider).model_args(a.model, a.effort)):
2064
+ store.drop_worker(w.name)
2065
+ return code
2066
+ if sid := _named_session(acct, w.name, before):
2067
+ _joined(w, sid, _now())
2068
+ print(f"worker {w.name} started on {acct.id} (session {sid[:8]})")
2069
+ else:
2070
+ print(f"worker {w.name} started on {acct.id}; its session id is not known yet "
2071
+ "(fairshare finds it by name later)")
2072
+ return 0
2073
+
2074
+
2075
+ WORKER_STILL_S = 1800 # a worker whose cost has not moved this long has its cost recorded
2076
+
2077
+
2078
+ def _measure(w: Worker, rec: SessionRecord | None) -> bool:
2079
+ """Record a worker's measured cost (its session's, as far as the series knows) and duration
2080
+ (its start to its last cost movement) on its worker record. Nothing reads them yet: data for
2081
+ sizing work later. False when there is no cost data or nothing changed."""
2082
+ if rec is None or not rec.costs:
2083
+ return False
2084
+ return store.finish_worker(w.name, store.total_cost(rec.costs),
2085
+ max(0.0, rec.costs[-1][-1][0] - w.started))
2086
+
2087
+
2088
+ def _measure_still(workers: list[Worker], now: float) -> None:
2089
+ """`_measure` each worker whose cost has not moved for WORKER_STILL_S."""
2090
+ for w in workers:
2091
+ if w.session and (rec := store.session(w.session)) and rec.costs \
2092
+ and now - rec.costs[-1][-1][0] >= WORKER_STILL_S:
2093
+ _measure(w, rec)
2094
+
2095
+
2096
+ # --- Checkpoints: a session's own notes of where it stands, as files (decision 22).
2097
+
2098
+ def _target_workers(target: str, here: str | None) -> list[Worker] | None:
2099
+ """The workers `target` names: `all` (the calling session's), a worker's name, or its
2100
+ session id or the start of one. A session that went on under a new id counts as that one
2101
+ (`store.latest`). None (said why) when it names none."""
2102
+ if target == "all":
2103
+ if here is None:
2104
+ _say("`all` means this session's workers, and this is not inside a session")
2105
+ return None
2106
+ return store.workers(store.latest(here))
2107
+ if w := store.worker(target):
2108
+ return [w]
2109
+ ends = {store.latest(r.id) for r in store.sessions() if r.id.startswith(target)}
2110
+ found = [w for w in store.workers() if w.session
2111
+ and (w.session.startswith(target) or w.session in ends)]
2112
+ if len(found) != 1:
2113
+ _say(f"no worker is named {target!r} or has a session starting with it"
2114
+ if not found else f"{target!r} matches {len(found)} workers; give more of the id")
2115
+ return None
2116
+ return found
2117
+
2118
+
2119
+ def _request_checkpoints(target: str, here: str | None) -> int:
2120
+ """Ask each named worker for a checkpoint: its hooks pass it on at its next event."""
2121
+ found = _target_workers(target, here)
2122
+ if found is None:
2123
+ return 2
2124
+ if not found:
2125
+ print("this session has no workers")
2126
+ return 0
2127
+ accounts, now, left = _load()[0], _now(), 0
2128
+ joined = _join_pending(found, accounts, now)
2129
+ for w in found:
2130
+ if (sid := w.session or joined.get(w.name)) is None:
2131
+ print(f"{w.name}: its session id is not known yet; not asked (try again shortly)")
2132
+ left += 1
2133
+ continue
2134
+ store.update_session(sid, lambda old: replace(
2135
+ old or SessionRecord(sid, w.account, w.cwd, None, now, role=ROLE_WORKER,
2136
+ parent=w.parent),
2137
+ checkpoint_requested=now, request_said=None))
2138
+ print(f"{w.name} (session {sid[:8]}): asked for a checkpoint")
2139
+ return 1 if left else 0
2140
+
2141
+
2142
+ def _show_checkpoint(target: str) -> int:
2143
+ """Print the checkpoint note of a session (its id or start) or of a worker (its name)."""
2144
+ w = store.worker(target)
2145
+ ids = [w.session] if w and w.session else [i for i in store.checkpointed()
2146
+ if i.startswith(target)]
2147
+ if len(ids) != 1 or not (path := store.checkpoint_path(ids[0])) or not path.is_file():
2148
+ _say(f"no checkpoint note for {target!r}" if len(ids) < 2
2149
+ else f"{target!r} matches {len(ids)} notes; give more of the id")
2150
+ return 1
2151
+ print(path.read_text(encoding="utf-8"), end="")
2152
+ return 0
2153
+
2154
+
2155
+ def cmd_checkpoint(a) -> int:
2156
+ """`checkpoint TEXT`: append a note to this session's checkpoint file and clear its pending
2157
+ request. `--request X`: ask workers for one. `--show X`: print a session's note."""
2158
+ here = _provider().current_session()
2159
+ if a.request:
2160
+ return _request_checkpoints(a.request, here)
2161
+ if a.show:
2162
+ return _show_checkpoint(a.show)
2163
+ if not a.text:
2164
+ _say('say where you stand: fairshare checkpoint "<what is done, what is next>"')
2165
+ return 2
2166
+ if here is None:
2167
+ _say("not inside a session: a checkpoint belongs to the session that writes it")
2168
+ return 2
2169
+ print(_write_checkpoint(here, a.text))
2170
+ return 0
2171
+
2172
+
2173
+ # --- `fairshare watch`: a main session waits on it as a background command (decision 22).
2174
+
2175
+ WATCH_LOCAL_S = 5.0 # seconds between looks at local state (snapshot, records, notes)
2176
+ WATCH_LIST_S = 15.0 # seconds between listings of the running sessions (a subprocess)
2177
+
2178
+
2179
+ def _watch_local(here: str, acct: Account | None, accounts: list[Account], t: Tuning,
2180
+ now: float) -> list[str]:
2181
+ """What concerns the session `here` in local state: a new crossing of its account, and per
2182
+ worker a checkpoint written or a stop by its limit, since watch last said so. Said things
2183
+ are marked on the session's record."""
2184
+ events = []
2185
+ _measure_still(store.workers(here), now)
2186
+ if acct and acct.plan and (c := _tell_crossing(here, acct, t, now)):
2187
+ events.append(_warning_text(store.session(here), acct, c, accounts, t, now))
2188
+ found = []
2189
+ for w in store.workers(here):
2190
+ if not w.session:
2191
+ continue
2192
+ note = store.checkpoint_path(w.session)
2193
+ size = note.stat().st_size if note and note.is_file() else 0
2194
+ rec = store.session(w.session)
2195
+ found.append((w, note, size, rec and rec.stranded_at, rec and rec.account))
2196
+ resets = {}
2197
+ for x in {f[4] for f in found if f[3]}:
2198
+ a = next((a for a in accounts if a.id == x), None)
2199
+ if a and providers.get(a.provider).resumes_at_reset and (
2200
+ r := _limit_reset(a, store.load(x), t, now)):
2201
+ resets[x] = (f"resets {_clock(r, now)} ({providers.get(a.provider).tool} resumes it "
2202
+ "then); ")
2203
+
2204
+ def change(old: SessionRecord | None) -> SessionRecord | None:
2205
+ if old is None:
2206
+ return None
2207
+ seen, said = dict(old.reported), []
2208
+ for w, note, size, stranded, account in found:
2209
+ if size > seen.get(f"checkpoint:{w.session}", 0):
2210
+ seen[f"checkpoint:{w.session}"] = size
2211
+ said.append(f"worker {w.name} wrote a checkpoint: {note}")
2212
+ if stranded and seen.get(f"stranded:{w.session}") != stranded:
2213
+ seen[f"stranded:{w.session}"] = stranded
2214
+ said.append(f"worker {w.name} was stopped by {account}'s limit: "
2215
+ f"{resets.get(account, '')}fairshare pickup {w.session}")
2216
+ events.extend(said)
2217
+ return replace(old, reported=seen) if said else None
2218
+ store.update_session(here, change)
2219
+ return events
2220
+
2221
+
2222
+ def _watch_live(here: str, accounts: list[Account], now: float) -> list[str]:
2223
+ """From the running sessions: each worker of `here` that ended (no longer listed) or went
2224
+ idle after it was seen busy, once each; pending joins are retried first."""
2225
+ mine = store.workers(here)
2226
+ if not mine:
2227
+ return []
2228
+ joined = _join_pending(mine, accounts, now)
2229
+ mine = [replace(w, session=w.session or joined.get(w.name)) for w in mine]
2230
+ acct = next((a for w in mine for a in accounts if a.id == w.account), None)
2231
+ live = acct and providers.get(acct.provider).list_sessions(acct)
2232
+ if live is None:
2233
+ return []
2234
+ state = {x.id: x.busy for x in live}
2235
+ events, ended_now = [], []
2236
+
2237
+ def change(old: SessionRecord | None) -> SessionRecord | None:
2238
+ if old is None:
2239
+ return None
2240
+ seen, said = dict(old.reported), []
2241
+ for w in (w for w in mine if w.session):
2242
+ ended, busy = f"ended:{w.session}", f"busy:{w.session}"
2243
+ if w.session not in state:
2244
+ ended_now.append(w)
2245
+ if not seen.get(ended):
2246
+ seen[ended] = 1
2247
+ said.append(f"worker {w.name} ended")
2248
+ continue
2249
+ seen.pop(ended, None)
2250
+ if state[w.session]:
2251
+ seen[busy] = 1
2252
+ elif state[w.session] is False and seen.pop(busy, None):
2253
+ said.append(f"worker {w.name} went idle")
2254
+ events.extend(said)
2255
+ return replace(old, reported=seen) if seen != old.reported else None
2256
+ store.update_session(here, change)
2257
+ for w in ended_now:
2258
+ _measure(w, store.session(w.session))
2259
+ return events
2260
+
2261
+
2262
+ def cmd_watch(a) -> int:
2263
+ """Block until something concerns the calling session, print one line per event and exit 0;
2264
+ `nothing happened` when --timeout runs out. Local state every WATCH_LOCAL_S seconds, the
2265
+ running sessions every WATCH_LIST_S. Writes only what it said (and joins) on the session's
2266
+ record, so a restarted watch does not repeat itself."""
2267
+ if (here := _provider().current_session()) is None:
2268
+ _say("not inside a session: watch waits for what concerns the session that runs it")
2269
+ return 2
2270
+ here = store.latest(here)
2271
+ accounts, tuning, _ = _load()
2272
+ start = _now()
2273
+ rec = store.session(here)
2274
+ acct = next((x for x in accounts if rec and x.id == rec.account), None) \
2275
+ or _session_account(accounts)
2276
+ if rec is None:
2277
+ rec = store.note_session(SessionSeen(here), acct.id if acct else "", start)
2278
+ next_list = start
2279
+ while True:
2280
+ now = _now()
2281
+ events = _watch_local(here, acct, accounts, tuning, now)
2282
+ if now >= next_list:
2283
+ events += _watch_live(here, accounts, now)
2284
+ next_list = now + WATCH_LIST_S
2285
+ if events:
2286
+ print("\n".join(events))
2287
+ return 0
2288
+ if a.timeout is not None and now >= start + a.timeout:
2289
+ print("nothing happened")
2290
+ return 0
2291
+ _sleep(WATCH_LOCAL_S if a.timeout is None else min(WATCH_LOCAL_S,
2292
+ start + a.timeout - now))
2293
+
2294
+
2295
+ def cmd_transcript(a) -> int:
2296
+ """The main conversation of a recorded session, oldest first: one block per message, the
2297
+ last N, each prefixed `user:` or `assistant:`. Never a raw record."""
2298
+ if (rec := _find_session(a.session)) is None:
2299
+ return 2
2300
+ if not rec.transcript:
2301
+ _say(f"no transcript recorded for {rec.id[:8]}")
2302
+ return 1
2303
+ said = _provider().transcript_text(Path(rec.transcript))
2304
+ if not said:
2305
+ _say(f"{rec.transcript}: could not be read, or its layout was not understood; "
2306
+ "nothing shown")
2307
+ return 1
2308
+ print("\n\n".join(_block(role, text) for role, text in said[-a.tail:]))
2309
+ return 0
2310
+
2311
+
2312
+ OUTPUT_LINES = 20 # a command's output in `fairshare transcript` shows at most this many lines
2313
+
2314
+
2315
+ def _block(role: str, text: str) -> str:
2316
+ """One message of `fairshare transcript`; a command the user ran and its output, shortened."""
2317
+ if role == "command":
2318
+ return f"user ran: {text}"
2319
+ if role == "output":
2320
+ lines = text.splitlines()
2321
+ more = len(lines) - OUTPUT_LINES
2322
+ return "output:\n" + "\n".join(lines[:OUTPUT_LINES]) + (
2323
+ f"\n… ({more} more lines)" if more > 0 else "")
2324
+ return f"{role}: {text}"
2325
+
2326
+
2327
+ def _duration(text: str) -> float:
2328
+ """Seconds in `30m`, `3h`, `2d` (decimals allowed)."""
2329
+ m = re.fullmatch(r"(\d+(?:\.\d+)?)([mhd])", text.strip())
2330
+ if not m or float(m[1]) <= 0:
2331
+ raise SystemExit(f"fairshare: --for takes a length such as 30m, 3h or 2d, not '{text}'")
2332
+ return float(m[1]) * {"m": 60, "h": HOUR, "d": 24 * HOUR}[m[2]]
2333
+
2334
+
2335
+ def _midnight(now: float) -> float:
2336
+ """The start of tomorrow, local time."""
2337
+ t = time.localtime(now)
2338
+ return time.mktime((t.tm_year, t.tm_mon, t.tm_mday + 1, 0, 0, 0, 0, 0, -1))
2339
+
2340
+
2341
+ def cmd_prefer(a) -> int:
2342
+ """Prefer one account for a while: launches, and later handoffs and briefings, go to it while
2343
+ it can take work. It ends on its own (default: the end of today), so it never pins."""
2344
+ now = _now()
2345
+ if a.off:
2346
+ store.clear_preference()
2347
+ print("no preferred account; the best account is used")
2348
+ return 0
2349
+ if a.id is None:
2350
+ pref = store.preference(now)
2351
+ print(f"preferring {pref[0]} until {_clock(pref[1], now)}" if pref
2352
+ else "no preferred account")
2353
+ return 0
2354
+ accounts = _load()[0]
2355
+ if a.id not in {x.id for x in accounts}:
2356
+ _say(f"no account '{a.id}' (configured: {', '.join(x.id for x in accounts)})")
2357
+ return 2
2358
+ until = now + _duration(a.duration) if a.duration else _midnight(now)
2359
+ store.save_preference(a.id, until)
2360
+ print(f"preferring {a.id} until {_clock(until, now)}"
2361
+ + ("" if a.duration else " (--for sets how long)")
2362
+ + "; `fairshare prefer --off` ends it")
2363
+ return 0
2364
+
2365
+
2366
+ def _tilde(p: Path, home: Path) -> str:
2367
+ return f"~/{p.relative_to(home)}" if p.is_relative_to(home) and p != home else str(p)
2368
+
2369
+
2370
+ def _yes(question: str) -> bool:
2371
+ return input(f"{question} [y/N] ").strip().lower() == "y"
2372
+
2373
+
2374
+ def _ask_yes(question: str) -> bool:
2375
+ """`_yes` on stderr's side of a launch; end of input is no."""
2376
+ try:
2377
+ print(f"fairshare: {question} [y/N] ", end="", file=sys.stderr)
2378
+ return input().strip().lower() == "y"
2379
+ except EOFError:
2380
+ return False
2381
+
2382
+
2383
+ def _needs_terminal(command: str) -> int:
2384
+ _say(f"{command} asks questions and there is no terminal to answer them")
2385
+ return 2
2386
+
2387
+
2388
+ def _by_provider(accounts: list[Account]):
2389
+ """(provider, its accounts) for each provider that has any."""
2390
+ for prov in providers.REGISTRY.values():
2391
+ if mine := [x for x in accounts if x.provider == prov.name]:
2392
+ yield prov, mine
2393
+
2394
+
2395
+ def _provider():
2396
+ """The provider a new account joins. There is one; a second will need a flag on join."""
2397
+ (prov,) = providers.REGISTRY.values()
2398
+ return prov
2399
+
2400
+
2401
+ def _read(p: Path) -> str | None:
2402
+ try:
2403
+ return p.read_text()
2404
+ except (OSError, UnicodeDecodeError):
2405
+ return None
2406
+
2407
+
2408
+ def _installed() -> str | None:
2409
+ """Absolute path of the installed `fairshare` command, as the shell would find it."""
2410
+ found = shutil.which("fairshare")
2411
+ return os.path.abspath(found) if found else None
2412
+
2413
+
2414
+ def _need_installed(command: str) -> str:
2415
+ if not (installed := _installed()):
2416
+ raise SystemExit("fairshare: no installed `fairshare` found on PATH; install it first "
2417
+ f"(pipx install fairshare-cli), then run `fairshare {command}` again")
2418
+ return installed
2419
+
2420
+
2421
+ def _config_text(path: Path) -> str:
2422
+ """accounts.toml as text ("" when there is none). A file that cannot be read or parsed is
2423
+ refused, never taken for empty."""
2424
+ if not path.exists():
2425
+ return ""
2426
+ try:
2427
+ text = path.read_text(encoding="utf-8")
2428
+ tomllib.loads(text)
2429
+ except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as e:
2430
+ raise SystemExit(f"fairshare: {path}: {e}; fix it or move it aside, then run this again")
2431
+ return text
2432
+
2433
+
2434
+ def _edit_config(change) -> None:
2435
+ """Apply `change` (text -> text) to accounts.toml: under a lock, re-read just before writing,
2436
+ back up, write atomically, read back. Only the lines of the change differ."""
2437
+ path = store.config_path()
2438
+ with store.locked(path.with_name(path.name + ".lock")):
2439
+ old = _config_text(path)
2440
+ try:
2441
+ new = change(old)
2442
+ except ValueError as e:
2443
+ raise SystemExit(f"fairshare: {path}: {e}; nothing written")
2444
+ if new != old:
2445
+ backup = store.write_with_backup(path, new)
2446
+ print(f"Wrote {path}" + (f" (backup: {backup})" if backup else ""))
2447
+
2448
+
2449
+ def _wire(prov, hub: Path, installed: str) -> str | None:
2450
+ """The hub's settings carry the usage hook: the installed fairshare by absolute path, then
2451
+ the user's own hook, if any (`--then`). What happened, or None when nothing changed."""
2452
+ return hub_mod.edit_shared(hub, prov.capture_file(hub_mod.shared_dir(hub)),
2453
+ lambda text: prov.wire(text, shlex.quote(installed)), "settings")
2454
+
2455
+
2456
+ def _wire_hub(prov, hub: Path, installed: str) -> None:
2457
+ if note := _wire(prov, hub, installed):
2458
+ print(f"usage hook: {note}")
2459
+ if note := _install_skill(prov, hub):
2460
+ print(f"skill: {note}")
2461
+
2462
+
2463
+ def _skill_state(prov, hub: Path) -> tuple[Path, str, str | None, str]:
2464
+ """fairshare's skill in the hub: its place, the shipped text, what is there (None: nothing),
2465
+ and a word for it: current, missing, outdated or foreign (someone else's skill)."""
2466
+ dest, text = prov.skill(hub_mod.shared_dir(hub))
2467
+ there = _read(dest) if dest.exists() else None
2468
+ word = ("missing" if there is None else "current" if there == text
2469
+ else "outdated" if prov.own_skill(there) else "foreign")
2470
+ return dest, text, there, word
2471
+
2472
+
2473
+ def _install_skill(prov, hub: Path) -> str | None:
2474
+ """Install fairshare's skill in the hub (one line), or refresh it (its diff shown first);
2475
+ another skill of that name is never touched. What happened ("installed in …", "updated …"),
2476
+ or None when it was current."""
2477
+ dest, text, there, word = _skill_state(prov, hub)
2478
+ if word == "current":
2479
+ return None
2480
+ if word == "foreign":
2481
+ return f"{dest} is not fairshare's skill; left alone"
2482
+ if there is not None:
2483
+ print(hub_mod.diff(prov, dest.name, there.encode(), text.encode(),
2484
+ f"{dest.name} (fairshare's skill)").rstrip("\n"))
2485
+
2486
+ def change(old: str | None) -> str | None:
2487
+ if old == text:
2488
+ return None
2489
+ if old is not None and not prov.own_skill(old):
2490
+ raise ValueError("not fairshare's skill")
2491
+ return text
2492
+ note = hub_mod.edit_shared(hub, dest, change, "skill")
2493
+ return f"installed in {dest}" if there is None and note == f"updated {dest}" else note
2494
+
2495
+
2496
+ def _copy_state(prov, source: Path, account: Account, hub: Path) -> None:
2497
+ """After asking, carry over the few keys of the user's folder's state file that the
2498
+ provider allows (trust, user MCP servers, onboarding) into the new account's. The user's
2499
+ file is only read."""
2500
+ home = Path.home()
2501
+ src_path, dest = prov.state_file(source, home), prov.state_file(account.config_dir, home)
2502
+ if not src_path.exists():
2503
+ return
2504
+ try:
2505
+ src = json.loads(src_path.read_text(encoding="utf-8"))
2506
+ if not isinstance(src, dict):
2507
+ raise ValueError("not an object")
2508
+ except (OSError, UnicodeDecodeError, ValueError) as e:
2509
+ _say(f"{src_path} cannot be read ({e}); nothing copied from it")
2510
+ return
2511
+
2512
+ def current() -> dict:
2513
+ if not dest.exists():
2514
+ return {}
2515
+ d = json.loads(dest.read_text(encoding="utf-8"))
2516
+ if not isinstance(d, dict):
2517
+ raise ValueError("not an object")
2518
+ return d
2519
+
2520
+ shown = None
2521
+ try:
2522
+ while True:
2523
+ new, what = prov.merge_state(current(), src)
2524
+ if not what:
2525
+ return
2526
+ if what != shown:
2527
+ print(f"From {src_path}, {account.id} can take: {'; '.join(what)}.")
2528
+ if not _yes("Copy these?"):
2529
+ print(" not copied")
2530
+ return
2531
+ shown = what
2532
+ with prov.hold_state(dest):
2533
+ new, what = prov.merge_state(current(), src)
2534
+ if what != shown:
2535
+ continue # it changed meanwhile: show it and ask again
2536
+ store.write_with_backup(dest, json.dumps(new, indent=2, ensure_ascii=False)
2537
+ + "\n", hub_mod.backup_dir(hub, account.id))
2538
+ if json.loads(dest.read_text(encoding="utf-8")) != new:
2539
+ raise OSError(f"{dest} did not read back as written")
2540
+ print(" copied")
2541
+ return
2542
+ except (OSError, UnicodeDecodeError, ValueError) as e:
2543
+ _say(f"{dest}: {e}; nothing copied")
2544
+
2545
+
2546
+ def _default_id(source: Path | None, taken: set[str], hub: Path) -> str:
2547
+ """The alias or folder name of `source` (as setup shows it), else the lowest free
2548
+ account-N. Never anything from the login."""
2549
+ if source is not None:
2550
+ for prov in providers.REGISTRY.values():
2551
+ for c in prov.discover(Path.home()):
2552
+ if c.config_dir.resolve() == source.resolve():
2553
+ return c.id
2554
+ return source.name.lstrip(".")
2555
+ n = 1
2556
+ while f"account-{n}" in taken or hub_mod.account_dir(hub, f"account-{n}").exists():
2557
+ n += 1
2558
+ return f"account-{n}"
2559
+
2560
+
2561
+ def _twins(acct: Account, st: AccountStatus, accounts: list[Account]) -> list[str]:
2562
+ """The other configured accounts signed in as the same login as `acct` (one quota)."""
2563
+ others = [a for a in accounts if a.provider == acct.provider and a.plan is not None
2564
+ and a.id != acct.id]
2565
+ return [a.id for a, s in zip(others, _probe(others))
2566
+ if s and st.identity and s.identity == st.identity]
2567
+
2568
+
2569
+ def _resign(acct: Account, accounts: list[Account], hub: Path) -> AccountStatus | None:
2570
+ """Sign an account that is already joined in again: only the provider's own sign-in in its
2571
+ folder (with its browser), then the sign-in check. Nothing else changes. Its status when it
2572
+ is signed in as a subscription login, else None (said why)."""
2573
+ prov = providers.get(acct.provider)
2574
+ print(f"Signing in {acct.id} again: follow the sign-in the provider opens. Nothing else "
2575
+ "changes.")
2576
+ cmd, env = prov.login_command(acct.config_dir)
2577
+ if code := session.run_child(cmd, {**env, **_browser_env(hub, acct)}):
2578
+ _say(f"the sign-in did not finish (exit {code}); nothing changed")
2579
+ return None
2580
+ st = prov.account_status(acct)
2581
+ if st is None:
2582
+ _say(f"the sign-in check for {acct.id} gave no answer; `fairshare status` checks it again")
2583
+ return None
2584
+ store.record_subscription(acct.id, st.logged_in and st.usable, _now())
2585
+ if not (st.logged_in and st.usable):
2586
+ _say(f"{acct.id} is {'not a subscription login' if st.logged_in else 'not signed in'}")
2587
+ return None
2588
+ if twins := _twins(acct, st, accounts):
2589
+ _say(f"same login as {twins[0]}: one quota")
2590
+ print(f"{acct.id} is signed in")
2591
+ return st
2592
+
2593
+
2594
+ def _ask_browser(account_id: str) -> str | None:
2595
+ """Which browser the account's sign-in opens in, as a `browser` line; None: the default."""
2596
+ profiles = browser.chrome_profiles(Path.home())
2597
+ picks = [None, *(f"{browser.CHROME}{d}" for d, _ in profiles), browser.COMMAND]
2598
+ print(f"Which browser should {account_id}'s sign-in links open in?")
2599
+ print(" 1 the default browser")
2600
+ for i, (_, display) in enumerate(profiles, 2):
2601
+ print(f" {i} Chrome profile {display}")
2602
+ print(f" {len(picks)} a command (an executable that takes the link)")
2603
+ while True:
2604
+ answer = input("Choose [1]: ").strip()
2605
+ if not answer:
2606
+ return None
2607
+ if answer.isdigit() and 1 <= int(answer) <= len(picks):
2608
+ break
2609
+ if (pick := picks[int(answer) - 1]) != browser.COMMAND:
2610
+ return pick
2611
+ while path := input("Absolute path of the command (Enter for the default browser): ").strip():
2612
+ try:
2613
+ browser.parse(browser.COMMAND + path)
2614
+ return browser.COMMAND + path
2615
+ except ValueError as e:
2616
+ print(e)
2617
+ return None
2618
+
2619
+
2620
+ def _ask_name(where: str, default: str, taken: set[str], hub: Path) -> str:
2621
+ """A name for the account joined from `where`, asked until it is a valid id that no
2622
+ configured account and no hub folder has. The default may name a hub folder: join reuses it,
2623
+ as it does without the question."""
2624
+ while True:
2625
+ name = input(f"Name for {where} [{default}]: ").strip() or default
2626
+ if not ACCOUNT_ID.fullmatch(name):
2627
+ print(f"account id {name!r}: use letters, digits, '.', '-' or '_'")
2628
+ elif name in taken:
2629
+ print(f"{name} is already joined")
2630
+ elif name != default and hub_mod.account_dir(hub, name).exists():
2631
+ print(f"{name} is taken by a folder already in the hub")
2632
+ else:
2633
+ return name
2634
+
2635
+
2636
+ def _same_login(account_id: str, twin: str, prov) -> str:
2637
+ """On a terminal, what to do with an account that signed in as `twin`'s login: "" (sign in
2638
+ again), "k" (keep anyway) or "n" (don't add)."""
2639
+ print(f"{account_id} signed in as the same account as {twin}, so they share one quota: "
2640
+ "keeping both adds nothing.")
2641
+ print(f"Usually the browser was still signed in to that account. Sign out on {prov.web}, "
2642
+ "or choose another browser profile, then:")
2643
+ while (choice := input("[Enter] sign in again · k = keep anyway · n = don't add "
2644
+ ).strip().lower()) not in ("", "k", "n"):
2645
+ pass
2646
+ return choice
2647
+
2648
+
2649
+ def _join(account_id: str | None, source: Path | None) -> int:
2650
+ """Create the account's folder in the hub with its links, run the provider's own sign-in in
2651
+ it, check who signed in, copy from the user's folder when asked, and add it to the config.
2652
+ An id already joined is only signed in again. With no id, a terminal is asked for one."""
2653
+ accounts, _, hub = _load()
2654
+ if account_id in {a.id for a in accounts}:
2655
+ acct = next(a for a in accounts if a.id == account_id)
2656
+ if source is not None:
2657
+ _say(f"{account_id} is already joined; --from is for a new account")
2658
+ return 2
2659
+ if not hub_mod.present(hub, account_id):
2660
+ _say(_no_hub(hub))
2661
+ return 1
2662
+ return 0 if _resign(acct, accounts, hub) else 1
2663
+ installed = _need_installed("join")
2664
+ prov = _provider()
2665
+ if source is not None:
2666
+ if not source.is_dir():
2667
+ _say(f"{source} is not a folder")
2668
+ return 2
2669
+ if source.resolve().is_relative_to(hub.resolve()):
2670
+ _say(f"{source} is inside the hub; name one of your own folders")
2671
+ return 2
2672
+ taken = {a.id for a in accounts}
2673
+ if account_id is None:
2674
+ account_id = _default_id(source, taken, hub)
2675
+ if _interactive():
2676
+ where = _tilde(source, Path.home()) if source is not None else "the new account"
2677
+ account_id = _ask_name(where, account_id, taken, hub)
2678
+ if not ACCOUNT_ID.fullmatch(account_id):
2679
+ _say(f"account id {account_id!r}: use letters, digits, '.', '-' or '_'")
2680
+ return 2
2681
+ if account_id in taken:
2682
+ _say(f"{account_id} is already joined (configured: {', '.join(sorted(taken))}); "
2683
+ f"`fairshare join {account_id}` signs it in again")
2684
+ return 2
2685
+ folder = hub_mod.account_dir(hub, account_id)
2686
+ if folder.exists():
2687
+ print(f"{account_id}: using the folder already in the hub, {folder}")
2688
+ for note in hub_mod.check(hub, account_id, prov):
2689
+ print(note)
2690
+ spec = _ask_browser(account_id) if _interactive() else None
2691
+ while True: # again while the login is another account's
2692
+ print(f"Signing in {account_id}: follow the sign-in the provider opens.")
2693
+ cmd, env = prov.login_command(folder)
2694
+ if code := session.run_child(cmd, {**env, **browser.env(hub, account_id, spec)}):
2695
+ _say(f"the sign-in did not finish (exit {code}); {account_id} not added; its folder "
2696
+ f"stays at {folder}")
2697
+ return 1
2698
+ acct = Account(account_id, prov.name, load_plan(prov.default_plan), folder, browser=spec)
2699
+ st = prov.account_status(acct)
2700
+ if st is None:
2701
+ _say(f"the sign-in check for {account_id} gave no answer; it is added with plan "
2702
+ f"{prov.default_plan}, and `fairshare status` checks it again")
2703
+ break
2704
+ store.record_subscription(account_id, st.logged_in and st.usable, _now())
2705
+ if not (st.logged_in and st.usable):
2706
+ _say(f"{account_id} is {'not a subscription login' if st.logged_in else 'not signed in'}"
2707
+ f"; not added; its folder stays at {folder}")
2708
+ return 1
2709
+ if not (twins := _twins(acct, st, accounts)):
2710
+ break
2711
+ if not _interactive():
2712
+ print(f"same login as {twins[0]}: one quota")
2713
+ choice = "n"
2714
+ else:
2715
+ choice = _same_login(account_id, twins[0], prov)
2716
+ if choice == "k":
2717
+ break
2718
+ if choice == "n":
2719
+ print(f"{account_id} not added; its folder stays at {folder}")
2720
+ return 1
2721
+ spec = _ask_browser(account_id)
2722
+ if source is not None:
2723
+ settings = prov.capture_file(hub_mod.shared_dir(hub)).name
2724
+ prepare = {settings: lambda text: prov.wire(text, shlex.quote(installed)) or text}
2725
+ for note in hub_mod.seed(hub, source, account_id, prov, prepare):
2726
+ print(f"from {_tilde(source, Path.home())}: {note}")
2727
+ _wire_hub(prov, hub, installed)
2728
+ if source is not None:
2729
+ _copy_state(prov, source, acct, hub)
2730
+ plan = (st and st.plan) or prov.default_plan
2731
+ entry = {"id": account_id, "plan": plan, **({"browser": spec} if spec else {})}
2732
+ _edit_config(lambda text: with_account(text, entry))
2733
+ print(f"joined {account_id} ({plan})")
2734
+ return 0
2735
+
2736
+
2737
+ def cmd_join(a) -> int:
2738
+ if _no_tool():
2739
+ return 1
2740
+ try:
2741
+ return _join(a.id, Path(a.source).expanduser() if a.source else None)
2742
+ except EOFError:
2743
+ return _needs_terminal("join")
2744
+
2745
+
2746
+ def cmd_leave(a) -> int:
2747
+ """Stop routing to an account. Its folder and login stay; --logout signs it out first."""
2748
+ accounts, _, _ = _load()
2749
+ acct = next((x for x in accounts if x.id == a.id), None)
2750
+ if acct is None:
2751
+ _say(f"no account '{a.id}' (configured: {', '.join(x.id for x in accounts)})")
2752
+ return 2
2753
+ if a.logout:
2754
+ cmd, env = providers.get(acct.provider).logout_command(acct.config_dir)
2755
+ if code := session.run_child(cmd, env):
2756
+ _say(f"signing out {acct.id} failed (exit {code}); nothing changed")
2757
+ return 1
2758
+ _edit_config(lambda text: without_account(text, acct.id))
2759
+ print(f"left {acct.id}: no session is routed to it. Its folder"
2760
+ + (" stays" if a.logout else " and login stay") + f" at {acct.config_dir}")
2761
+ return 0
2762
+
2763
+
2764
+ def _sign_in_labels(found, home: Path) -> list[str]:
2765
+ """What the sign-in check says of each of the user's own folders, all at once: "" when signed
2766
+ in with a subscription. A folder with no state file is not checked (the check would create
2767
+ one there): "sign-in unknown", as for a check that gives no answer."""
2768
+ accounts = [Account(c.id, c.provider, None, c.config_dir) for c in found]
2769
+ checked = [a for a in accounts
2770
+ if providers.get(a.provider).state_file(a.config_dir, home).exists()]
2771
+ answers = dict(zip((a.config_dir for a in checked), _probe(checked)))
2772
+ labels = []
2773
+ for a in accounts:
2774
+ st = answers.get(a.config_dir)
2775
+ labels.append("sign-in unknown" if st is None else "signed out" if not st.logged_in
2776
+ else "not a subscription login" if not st.usable else "")
2777
+ return labels
2778
+
2779
+
2780
+ def _setup() -> int:
2781
+ path, home = store.config_path(), Path.home()
2782
+ installed = _need_installed("setup")
2783
+ parsed = tomllib.loads(_config_text(path))
2784
+ if "hub" in parsed:
2785
+ print(f"Hub: {parsed['hub']}")
2786
+ else:
2787
+ hub_text = input(f"Hub folder (holds what every account shares) [{DEFAULT_HUB}]: ").strip()
2788
+ _edit_config(lambda text: with_hub(text, hub_text or DEFAULT_HUB))
2789
+ hub = _load()[2]
2790
+ hub_mod.accounts_dir(hub).mkdir(parents=True, exist_ok=True) # a hub even with none joined
2791
+ if _no_tool("run `fairshare setup` again to join accounts"):
2792
+ for prov in providers.REGISTRY.values():
2793
+ _wire_hub(prov, hub, installed)
2794
+ return 1
2795
+ found = [c for prov in providers.REGISTRY.values() for c in prov.discover(home)
2796
+ if not c.config_dir.resolve().is_relative_to(hub.resolve())]
2797
+ print("Your own folders (fairshare copies from them and never changes them):" if found else
2798
+ "Found none of your own folders. Add an account with `fairshare join`.")
2799
+ joined = {a.id for a in _load()[0]}
2800
+ labels = _sign_in_labels(found, home)
2801
+ for i, (c, label) in enumerate(zip(found, labels), 1):
2802
+ print(f" {i} {c.id:<12} {_tilde(c.config_dir, home):<24} {c.found}"
2803
+ + (f" ({label})" if label else "") + (" (joined)" if c.id in joined else ""))
2804
+ # `all`: the signed-in folders first (the provider's default one leads discover's order)
2805
+ every = [c for c, label in sorted(zip(found, labels), key=lambda x: x[1] != "")]
2806
+ if found:
2807
+ seeded = dict.fromkeys(f for c in found for f in _seeded_files(providers.get(c.provider)))
2808
+ print(f"The first folder joined decides the shared {', '.join(seeded)}; "
2809
+ f"'all' joins in this order: {', '.join(c.id for c in every)}")
2810
+ answer = input("Join which? Numbers separated by spaces, 'all', or Enter for none: "
2811
+ ) if found else ""
2812
+ words = answer.replace(",", " ").split()
2813
+ try:
2814
+ picked = every if words == ["all"] else [found[int(w) - 1] for w in words]
2815
+ except (ValueError, IndexError):
2816
+ _say(f"not a choice: {answer.strip()!r}; nothing joined")
2817
+ return 2
2818
+ for c in [c for c in picked if c.id in joined]:
2819
+ print(f"{c.id} is already joined; skipped (`fairshare join {c.id}` signs it in again)")
2820
+ failed = [c.id for c in picked if c.id not in joined and _join(None, c.config_dir) != 0]
2821
+ for prov in providers.REGISTRY.values(): # each join did this; also with none picked
2822
+ _wire_hub(prov, hub, installed)
2823
+ if failed:
2824
+ _say(f"not joined: {', '.join(failed)}")
2825
+ prov = _provider()
2826
+ print(f"start sessions with `fairshare`; plain `{prov.command}` still uses {prov.default_dir}, "
2827
+ "outside the hub")
2828
+ return 1 if failed else 0
2829
+
2830
+
2831
+ def cmd_setup(_a) -> int:
2832
+ """Ask where the hub goes, then join each of the user's own folders they pick."""
2833
+ try:
2834
+ return _setup()
2835
+ except EOFError:
2836
+ return _needs_terminal("setup")
2837
+
2838
+
2839
+ def _offer_setup() -> int:
2840
+ """Bare `fairshare` with no config: offer setup on a terminal, else say how."""
2841
+ how = f"no config at {store.config_path()}; run `fairshare setup` to set up your accounts"
2842
+ if not _interactive():
2843
+ _say(how)
2844
+ return 2
2845
+ try:
2846
+ if input("fairshare is not set up yet. Run `fairshare setup` now? [Y/n] "
2847
+ ).strip().lower() in ("", "y", "yes"):
2848
+ return cmd_setup(None)
2849
+ except EOFError:
2850
+ pass
2851
+ _say(how)
2852
+ return 2
2853
+
2854
+
2855
+ def _seeded_files(prov) -> list[str]:
2856
+ """The provider's shared files that the first folder copied decides (a later one's are only
2857
+ shown as a diff): neither folders nor append-only `.jsonl` logs."""
2858
+ return [i for i in prov.shared if not i.endswith("/") and not i.endswith(".jsonl")]
2859
+
2860
+
2861
+ def _merge_back_prompt(prov, shared: Path, folders: list[str]) -> str:
2862
+ """What join copied in, as a prompt that copies it back: never what join never copies
2863
+ (`not_copied`) nor fairshare's own skill."""
2864
+ dirs = [i.rstrip("/") + "/" for i in prov.shared if i.endswith("/")
2865
+ and i not in prov.not_copied]
2866
+ logs = [i for i in prov.shared if i.endswith(".jsonl")]
2867
+ files = _seeded_files(prov)
2868
+ skill = prov.skill(shared)[0].parent.relative_to(shared).as_posix() + "/"
2869
+ return "\n".join([
2870
+ f"fairshare kept my {prov.name} history and settings in one shared folder, {shared}.",
2871
+ "Merge it back into my own config folders ("
2872
+ + (", ".join(folders) if folders else "ask me which") + ") without losing anything:",
2873
+ f"- folders ({', '.join(dirs)}): copy every file my folder lacks, except {skill}",
2874
+ " (fairshare's own skill); when a file is in both with different content, keep both",
2875
+ " and give the incoming one a new name;",
2876
+ f"- {', '.join(logs)}: append the lines my file lacks, in their order;",
2877
+ f"- {', '.join(files)}: show me the differences and ask before changing anything.",
2878
+ f"Never delete or change anything in {shared}, never open or copy a login file, and show",
2879
+ "me the plan and wait for my yes before you change anything."])
2880
+
2881
+
2882
+ def cmd_uninstall(_a) -> int:
2883
+ """Changes nothing: says where everything is, how to remove fairshare, and gives a prompt
2884
+ for the user's own agent to merge the hub's history back into their own folders."""
2885
+ path, home = store.config_path(), Path.home()
2886
+ hub, accounts = None, []
2887
+ if path.exists():
2888
+ try:
2889
+ accounts, _, hub = load_accounts(path)
2890
+ except ConfigError as e:
2891
+ print(f"{path}: {e}")
2892
+ print("fairshare never changed your own folders, so there is nothing to undo in them.")
2893
+ print(f"Config: {path}" + ("" if path.exists() else " (none)"))
2894
+ if olds := sorted(p.name for p in path.parent.glob(path.name + ".bak-fairshare-*")):
2895
+ print(f" backups of it, beside it: {', '.join(olds)}")
2896
+ print(f"State (usage snapshots, session records and checkpoint notes): {store.state_dir()}")
2897
+ if hub is not None:
2898
+ shared = hub_mod.shared_dir(hub)
2899
+ print(f"Hub: {hub}" + ("" if hub.exists() else " (not created)"))
2900
+ held = sorted(p.name + "/" * p.is_dir() for p in shared.iterdir()) if shared.is_dir() else []
2901
+ print(f" shared: {', '.join(held) or 'nothing'}")
2902
+ configured = {a.id for a in accounts}
2903
+ folders = sorted(p.name for p in (hub / "accounts").iterdir()) \
2904
+ if (hub / "accounts").is_dir() else []
2905
+ print(" accounts: " + (", ".join(f"{i}{'' if i in configured else ' (left)'}"
2906
+ for i in folders) or "none"))
2907
+ if folders:
2908
+ print(" each stays signed in (on macOS, one keychain entry per folder) when the hub "
2909
+ "is deleted; `fairshare leave --logout <id>` signs one out first")
2910
+ backups = hub / "backups"
2911
+ print(f" backups: {len(list(backups.iterdir())) if backups.is_dir() else 0} "
2912
+ "folder(s) of things fairshare moved aside")
2913
+ print("To remove the installed fairshare: pipx uninstall fairshare-cli (or however you installed "
2914
+ "it). The config, the state and the hub stay until you delete them yourself.")
2915
+ if hub is not None:
2916
+ for prov in providers.REGISTRY.values():
2917
+ mine = [_tilde(c.config_dir, home) for c in prov.discover(home)]
2918
+ print("To bring the hub's history back into your own folders, give your own agent "
2919
+ "this prompt:\n")
2920
+ print(_merge_back_prompt(prov, hub_mod.shared_dir(hub), mine))
2921
+ return 0
2922
+
2923
+
2924
+ def _runs(runner: tuple[str, ...]) -> bool:
2925
+ """Whether the fairshare command `runner` starts and answers --help."""
2926
+ try:
2927
+ return subprocess.run([*runner, "--help"], stdin=subprocess.DEVNULL, capture_output=True,
2928
+ timeout=10).returncode == 0
2929
+ except (OSError, subprocess.SubprocessError):
2930
+ return False
2931
+
2932
+
2933
+ def cmd_doctor(a) -> int:
2934
+ """Read-only checks; with --fix, repairs first (one line each), then the checks. Exit 0 when
2935
+ everything ends fixed."""
2936
+ if a.hub and not a.fix:
2937
+ _say("--hub goes with --fix")
2938
+ return 2
2939
+ if not a.fix:
2940
+ return _doctor()
2941
+ fixed = _fix(Path(a.hub).expanduser() if a.hub else None)
2942
+ print()
2943
+ return 0 if _doctor() == 0 and fixed else 1
2944
+
2945
+
2946
+ def _show(prov, item: str, old: str | None, new: str, name: str) -> None:
2947
+ print(hub_mod.diff(prov, item, (old or "").encode(), new.encode(), name).rstrip("\n"))
2948
+
2949
+
2950
+ def _fix(hub_arg: Path | None) -> bool:
2951
+ """doctor --fix: find a moved hub (asking, or --hub), run the start check for every account,
2952
+ rewire a stale usage hook, offer to rename the old hub path in the shared settings, and after
2953
+ a move run the sign-in check. One line per fix; True when nothing is left to do."""
2954
+ left = []
2955
+
2956
+ def report(ok: bool, text: str) -> None:
2957
+ print(f"{'fixed' if ok else 'FAIL '} {text}")
2958
+ if not ok:
2959
+ left.append(text)
2960
+
2961
+ path = store.config_path()
2962
+ try:
2963
+ accounts, _, hub = load_accounts(path)
2964
+ except (ConfigError, OSError) as e:
2965
+ report(False, f"{path.name}: {e}; fix it first")
2966
+ return False
2967
+ old = None
2968
+ if not hub_mod.present(hub):
2969
+ new = hub_arg
2970
+ if new is None and _interactive():
2971
+ while True:
2972
+ try:
2973
+ answer = input(f"No hub at {hub}. Where is it now? (Enter to stop) ").strip()
2974
+ except EOFError:
2975
+ break
2976
+ if not answer:
2977
+ break
2978
+ if hub_mod.present(Path(answer).expanduser()):
2979
+ new = Path(answer).expanduser()
2980
+ break
2981
+ print(f"{answer} holds no shared/ and accounts/ folders")
2982
+ if new is None:
2983
+ report(False, f"no hub at {hub}; run `fairshare doctor --fix --hub PATH` with where "
2984
+ "it is now")
2985
+ return False
2986
+ if not hub_mod.present(new):
2987
+ report(False, f"{new} holds no shared/ and accounts/ folders; nothing changed")
2988
+ return False
2989
+ new = Path(os.path.abspath(new))
2990
+ _edit_config(lambda text: with_hub(text, str(new)))
2991
+ report(True, f"hub: now {new} (was {hub})")
2992
+ old, hub = hub, new
2993
+ accounts = _load()[0]
2994
+ elif hub_arg is not None and Path(os.path.abspath(hub_arg)) != hub:
2995
+ print(f"note the hub at {hub} is there; --hub {hub_arg} not used")
2996
+ for prov, mine in _by_provider(accounts):
2997
+ for acct in mine:
2998
+ try:
2999
+ for note in hub_mod.check(hub, acct.id, prov):
3000
+ report(True, note)
3001
+ except OSError as e:
3002
+ report(False, f"{acct.id}: cannot repair its folder in the hub ({e})")
3003
+ installed = _installed()
3004
+ for prov, _mine in _by_provider(accounts):
3005
+ settings = prov.capture_file(hub_mod.shared_dir(hub))
3006
+ text = _read(settings)
3007
+ if installed is None:
3008
+ report(False, "no installed `fairshare` on PATH; the usage hook cannot be rewired")
3009
+ else:
3010
+ try:
3011
+ if new_text := prov.wire(text, shlex.quote(installed)):
3012
+ _show(prov, settings.name, text, new_text, f"{settings.name} (rewired)")
3013
+ note = _wire(prov, hub, installed)
3014
+ report(note is not None and note.startswith("updated"),
3015
+ f"usage hook: {note or 'unchanged'}")
3016
+ except ValueError as e:
3017
+ report(False, f"usage hook: {settings} {e}; left as it is")
3018
+ if (_skill_state(prov, hub)[3]) != "current":
3019
+ note = _install_skill(prov, hub)
3020
+ report(bool(note and note.startswith(("updated", "installed"))), f"skill: {note}")
3021
+ if old is not None:
3022
+ text = _read(settings)
3023
+ try:
3024
+ new_text, places = prov.repath(text, str(old), str(hub)) if text else (None, [])
3025
+ except ValueError as e:
3026
+ report(False, f"{settings}: {e}; it may still name the old hub")
3027
+ continue
3028
+ if not places:
3029
+ continue
3030
+ _show(prov, settings.name, text, new_text, f"{settings.name} (old hub path renamed)")
3031
+ yes = _interactive() and _ask_yes(f"{settings.name} names the old hub in "
3032
+ f"{', '.join(places)}. Rename it?")
3033
+ note = yes and hub_mod.edit_shared(hub, settings,
3034
+ lambda t: prov.repath(t, str(old), str(hub))[0],
3035
+ "settings")
3036
+ if note and note.startswith("updated"):
3037
+ report(True, f"old hub path renamed in {', '.join(places)}: {note}")
3038
+ else:
3039
+ report(False, f"{settings.name} still names the old hub in {', '.join(places)}"
3040
+ + (f" ({note})" if note else ""))
3041
+ if old is not None: # a moved login may read as signed out (keychain entries)
3042
+ planned = [a for a in accounts if a.plan is not None and a.provider in providers.REGISTRY]
3043
+ for a, st in zip(planned, _probe(planned)):
3044
+ if st is not None and not st.logged_in:
3045
+ report(False, f"{a.id} is signed out after the move; `fairshare join {a.id}` "
3046
+ "signs it in again")
3047
+ return not left
3048
+
3049
+
3050
+ def _usage_check(a: Account, use: dict[str, Window] | str | None) -> str:
3051
+ """doctor's line for one account's usage probe: what it read (names and a count, never a
3052
+ value), why it failed, or that it is off."""
3053
+ if use is None:
3054
+ return "usage probe off (usage_args = [])"
3055
+ if isinstance(use, str):
3056
+ return f"usage probe failed ({use})"
3057
+ plain = sorted(k for k in use if not window_model(k))
3058
+ models = len(use) - len(plain)
3059
+ read = [*plain, *([f"{models} model week{'s' * (models != 1)}"] if models else [])]
3060
+ return (f"usage probe answers ({', '.join(read)}), "
3061
+ + ("local command" if a.usage_args is None else "with usage_args"))
3062
+
3063
+
3064
+ def _doctor() -> int:
3065
+ """One line per check, read-only. Safe to paste: account ids and plan names only."""
3066
+ failed = []
3067
+
3068
+ def check(ok: bool, text: str) -> None:
3069
+ print(f"{'pass' if ok else 'FAIL'} {text}")
3070
+ if not ok:
3071
+ failed.append(text)
3072
+
3073
+ for prov in providers.REGISTRY.values():
3074
+ found = prov.find_binary() is not None
3075
+ check(found, f"{prov.name}: command " + (f"found, version {prov.version() or 'unknown'}"
3076
+ if found else "not found on PATH"))
3077
+ accounts: list[Account] = []
3078
+ hub = None
3079
+ path = store.config_path()
3080
+ if not path.exists():
3081
+ check(False, "accounts.toml not found (run `fairshare setup`)")
3082
+ else:
3083
+ try:
3084
+ accounts, _, hub = load_accounts(path)
3085
+ except ConfigError as e:
3086
+ check(False, f"{path.name}: {e} (fix it, or move it aside and run `fairshare setup`)")
3087
+ if hub is not None and not hub_mod.present(hub):
3088
+ check(False, "no hub at the configured path; if you moved it, run `fairshare doctor --fix`")
3089
+ accounts = [] # a sign-in check would create folders at the old path
3090
+ checkable = [a for a in accounts if a.plan is not None and a.provider in providers.REGISTRY]
3091
+ answers = iter(_check(checkable, _now()))
3092
+ for a in accounts:
3093
+ if a.plan is None:
3094
+ check(False, f"{a.id}: {a.plan_error}")
3095
+ elif a.provider not in providers.REGISTRY:
3096
+ check(False, f"{a.id}: unknown provider {a.provider}")
3097
+ else:
3098
+ st, use = next(answers)
3099
+ until = (f" until {time.strftime('%Y-%m-%d', time.localtime(st.expires_at))}"
3100
+ if st and st.expires_at else "")
3101
+ how = ("answers: " + ("signed out" if not st.logged_in else
3102
+ "not a subscription login" if not st.usable else
3103
+ f"signed in{until}, plan {st.plan or a.plan.name}")
3104
+ ) if st else "gave no answer"
3105
+ check(st is not None, f"{a.id}: sign-in check {how}")
3106
+ check(not isinstance(use, str), f"{a.id}: {_usage_check(a, use)}")
3107
+ check(*(lambda ok, text: (ok, f"{a.id}: {text}"))(
3108
+ *providers.get(a.provider).check_state(a.config_dir)))
3109
+ callers: dict[tuple[str, ...], list[str]] = {}
3110
+ for prov, _mine in _by_provider(accounts):
3111
+ text = _read(prov.capture_file(hub_mod.shared_dir(hub)))
3112
+ cap = prov.wired(text)
3113
+ check(cap is not None, f"{prov.name}: usage hook in the hub "
3114
+ + ("calls fairshare capture" if cap else "does not call fairshare capture "
3115
+ "(run `fairshare setup`)"))
3116
+ if cap:
3117
+ callers.setdefault(cap.runner, []).append(prov.name)
3118
+ runner = prov.hooked(text)
3119
+ check(runner is not None, f"{prov.name}: hooks in the hub ({', '.join(HOOKS)}) "
3120
+ + ("call fairshare hook" if runner else "do not all call fairshare hook "
3121
+ "(run `fairshare doctor --fix`)"))
3122
+ if runner and runner not in callers:
3123
+ callers[runner] = []
3124
+ where, _, _, word = _skill_state(prov, hub)
3125
+ check(word == "current", f"{prov.name}: skill in the hub is " + {
3126
+ "current": "current", "missing": "missing (run `fairshare doctor --fix`)",
3127
+ "outdated": "outdated (run `fairshare doctor --fix`)",
3128
+ "foreign": f"not fairshare's: {where.parent.name}/ holds another skill"}[word])
3129
+ if not callers and (installed := _installed()):
3130
+ callers[(installed,)] = []
3131
+ if not callers:
3132
+ check(False, "fairshare command not found on PATH")
3133
+ for runner, names in callers.items():
3134
+ who = f"called by the {', '.join(names)} usage hook" if names else "installed"
3135
+ check(_runs(runner), f"fairshare command ({who}) runs")
3136
+ return 1 if failed else 0
3137
+
3138
+
3139
+ def _positive(text: str) -> int:
3140
+ if not text.isdigit() or int(text) < 1:
3141
+ raise argparse.ArgumentTypeError(f"a whole number of 1 or more, not {text!r}")
3142
+ return int(text)
3143
+
3144
+
3145
+ def _carry_flags(p: argparse.ArgumentParser) -> None:
3146
+ """The flags of every verb that starts a session in place of another (D3)."""
3147
+ p.add_argument("--model", help="start on this model (default: the session's latest)")
3148
+ p.add_argument("--effort", help="at this effort level (default: the session's latest)")
3149
+ p.add_argument("-a", "--account", metavar="ID", help="on this account, skipping the ranking")
3150
+
3151
+
3152
+ def _run_args(parser: argparse.ArgumentParser, rest: list[str]) -> argparse.Namespace:
3153
+ """`run [-a ID | --account ID] [--] ARGS...`. Only a leading -a/--account is fairshare's;
3154
+ everything else goes to the provider unchanged (it takes a prompt as its first argument, so a
3155
+ positional id or argparse's own option handling would not do)."""
3156
+ account = None
3157
+ if rest[:1] in (["-a"], ["--account"]):
3158
+ if len(rest) < 2:
3159
+ parser.error("run: --account needs an id")
3160
+ account, rest = rest[1], rest[2:]
3161
+ elif rest and rest[0].startswith("--account="):
3162
+ account, rest = rest[0].partition("=")[2], rest[1:]
3163
+ return argparse.Namespace(account=account, args=rest[1:] if rest[:1] == ["--"] else rest)
3164
+
3165
+
3166
+ def main(argv: list[str] | None = None) -> int:
3167
+ p = argparse.ArgumentParser(prog="fairshare", description=__doc__)
3168
+ sub = p.add_subparsers(dest="cmd", required=True)
3169
+ sub.add_parser("status").set_defaults(f=cmd_status)
3170
+ cp = sub.add_parser("capture", help="the usage hook; the account is the session's own folder")
3171
+ cp.add_argument("account", nargs="?", help=argparse.SUPPRESS) # the form before the hub
3172
+ cp.add_argument("--then", help="the user's own command for this hook, run after recording")
3173
+ cp.set_defaults(f=cmd_capture)
3174
+ sub.add_parser("run", help="start a session on the best account (also: no command at all); "
3175
+ "`run [-a ID] [--] ARGS...` passes ARGS to the provider unchanged")
3176
+ pp = sub.add_parser("prefer", help="prefer one account for a while (default: the rest of "
3177
+ "today); with no id, show the current preference")
3178
+ pp.add_argument("id", nargs="?")
3179
+ pp.add_argument("--for", dest="duration", metavar="LENGTH", help="e.g. 30m, 3h, 2d")
3180
+ pp.add_argument("--off", action="store_true", help="end the preference now")
3181
+ pp.set_defaults(f=cmd_prefer)
3182
+ sub.add_parser("setup", help="choose the hub and join your own folders"
3183
+ ).set_defaults(f=cmd_setup)
3184
+ jp = sub.add_parser("join", help="add an account: sign in to it in its own hub folder")
3185
+ jp.add_argument("id", nargs="?", help="default: the --from folder's alias or name, "
3186
+ "else account-N")
3187
+ jp.add_argument("--from", dest="source", metavar="FOLDER",
3188
+ help="copy (never move) history and settings from one of your own folders")
3189
+ jp.set_defaults(f=cmd_join)
3190
+ lp = sub.add_parser("leave", help="stop routing to an account; its folder and login stay")
3191
+ lp.add_argument("id")
3192
+ lp.add_argument("--logout", action="store_true", help="also sign that account out")
3193
+ lp.set_defaults(f=cmd_leave)
3194
+ sub.add_parser("uninstall", help="say how to remove fairshare; changes nothing"
3195
+ ).set_defaults(f=cmd_uninstall)
3196
+ kp = sub.add_parser("pickup", help="continue a session on the best account (inside a "
3197
+ "session: this one)")
3198
+ kp.add_argument("session", nargs="?", metavar="SESSION", help="a session id or its start")
3199
+ kp.add_argument("--bg", action="store_true", help="in the background, with no terminal")
3200
+ _carry_flags(kp)
3201
+ kp.set_defaults(f=cmd_pickup)
3202
+ hq = sub.add_parser("handoff", help="inside a session: a checkpoint, then a fresh session "
3203
+ "that reads it first (with no NOTE, the launcher has the session write it)")
3204
+ hq.add_argument("note", nargs="?", metavar="NOTE", help="what was done, what is next, open "
3205
+ "decisions, files touched")
3206
+ _carry_flags(hq)
3207
+ hq.set_defaults(f=cmd_handoff)
3208
+ tp = sub.add_parser("transcript", help="show what a recorded session said, as text")
3209
+ tp.add_argument("session", metavar="SESSION", help="a session id or its start")
3210
+ tp.add_argument("--tail", type=_positive, default=40, metavar="N",
3211
+ help="the last N messages (default 40)")
3212
+ tp.set_defaults(f=cmd_transcript)
3213
+ sp = sub.add_parser("trust", help="copy folder trust from an account that has it to the "
3214
+ "accounts that lack it (never creates trust)")
3215
+ sp.add_argument("path", nargs="?", metavar="PATH", help="default: the current folder")
3216
+ sp.set_defaults(f=cmd_trust)
3217
+ wp = sub.add_parser("worker", help="inside a session: start a background worker session")
3218
+ wp.add_argument("--account", metavar="ID", help="default: the best account")
3219
+ wp.add_argument("--name", help="default: w-<first 8 of this session>-<n>")
3220
+ wp.add_argument("--model", required=True, help="the worker's model, fitted to its task")
3221
+ wp.add_argument("--effort", required=True, help="its effort level; `none` for a model "
3222
+ "without one")
3223
+ wp.add_argument("prompt", metavar="PROMPT")
3224
+ wp.set_defaults(f=cmd_worker)
3225
+ cq = sub.add_parser("checkpoint", help="inside a session: note where it stands; "
3226
+ "--request asks workers for one, --show prints a note")
3227
+ cq.add_argument("text", nargs="?", metavar="TEXT")
3228
+ one = cq.add_mutually_exclusive_group()
3229
+ one.add_argument("--request", metavar="SESSION|NAME|all",
3230
+ help="ask a worker (or all of this session's) for a checkpoint")
3231
+ one.add_argument("--show", metavar="SESSION|NAME", help="print a session's checkpoint note")
3232
+ cq.set_defaults(f=cmd_checkpoint)
3233
+ ap = sub.add_parser("watch", help="inside a session: wait until something concerns it "
3234
+ "(its account's limit, its workers), then say what")
3235
+ ap.add_argument("--timeout", type=_positive, metavar="SECONDS",
3236
+ help="give up after this long: `nothing happened`")
3237
+ ap.set_defaults(f=cmd_watch)
3238
+ rp = sub.add_parser("probe", help=argparse.SUPPRESS) # capture starts it in the background
3239
+ rp.add_argument("id")
3240
+ rp.set_defaults(f=cmd_probe)
3241
+ hp = sub.add_parser("hook", help=argparse.SUPPRESS) # fairshare's own hooks call it
3242
+ hp.add_argument("name")
3243
+ hp.set_defaults(f=cmd_hook)
3244
+ dp = sub.add_parser("doctor", help="check the setup, read-only; --fix repairs what it can")
3245
+ dp.add_argument("--fix", action="store_true", help="repair: find a moved hub, relink, rewire")
3246
+ dp.add_argument("--hub", metavar="PATH", help="with --fix: where the hub is now")
3247
+ dp.set_defaults(f=cmd_doctor)
3248
+ argv = sys.argv[1:] if argv is None else list(argv)
3249
+ if not argv and not store.config_path().exists():
3250
+ return _offer_setup()
3251
+ if (not argv or argv[0] in SWITCH_FLAGS) and _provider().current_session():
3252
+ sw = argparse.ArgumentParser(prog="fairshare", description="inside a session: stop it and "
3253
+ "start a fresh one on the best account (a switch)")
3254
+ _carry_flags(sw)
3255
+ return cmd_switch(sw.parse_args(argv))
3256
+ if not argv or argv[0] == "run":
3257
+ return cmd_run(_run_args(p, argv[1:]))
3258
+ if argv[0] not in sub.choices and argv[0] not in ("-h", "--help"):
3259
+ _say(f"'{argv[0]}' is not a command; did you mean: fairshare run {shlex.join(argv)}")
3260
+ return 2
3261
+ a = p.parse_args(argv)
3262
+ return a.f(a)
3263
+
3264
+
3265
+ if __name__ == "__main__":
3266
+ sys.exit(main())