llmswap-cli 1.0.0__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.
Files changed (78) hide show
  1. claude_swap/__init__.py +24 -0
  2. claude_swap/__main__.py +6 -0
  3. claude_swap/app_bundle.py +330 -0
  4. claude_swap/appearance.py +219 -0
  5. claude_swap/autoswitch.py +3065 -0
  6. claude_swap/cache.py +44 -0
  7. claude_swap/claude_locks.py +279 -0
  8. claude_swap/cli.py +2265 -0
  9. claude_swap/credentials.py +2156 -0
  10. claude_swap/exceptions.py +102 -0
  11. claude_swap/fsutil.py +409 -0
  12. claude_swap/json_output.py +455 -0
  13. claude_swap/launch_agent.py +862 -0
  14. claude_swap/lines.py +153 -0
  15. claude_swap/list_view.py +371 -0
  16. claude_swap/locking.py +87 -0
  17. claude_swap/logging_config.py +64 -0
  18. claude_swap/macos_keychain.py +240 -0
  19. claude_swap/mappings.py +127 -0
  20. claude_swap/menubar.py +1433 -0
  21. claude_swap/migrations.py +360 -0
  22. claude_swap/models.py +329 -0
  23. claude_swap/oauth.py +1628 -0
  24. claude_swap/pace.py +161 -0
  25. claude_swap/paths.py +250 -0
  26. claude_swap/poll_policy.py +337 -0
  27. claude_swap/printer.py +252 -0
  28. claude_swap/process_detection.py +370 -0
  29. claude_swap/session.py +2696 -0
  30. claude_swap/settings.py +827 -0
  31. claude_swap/signin.py +238 -0
  32. claude_swap/snapshot_source.py +121 -0
  33. claude_swap/spawn.py +135 -0
  34. claude_swap/subscription.py +349 -0
  35. claude_swap/switcher.py +9807 -0
  36. claude_swap/transfer.py +807 -0
  37. claude_swap/tui/__init__.py +43 -0
  38. claude_swap/tui/app.py +482 -0
  39. claude_swap/tui/autoview.py +381 -0
  40. claude_swap/tui/cswap.tcss +205 -0
  41. claude_swap/tui/dashboard.py +434 -0
  42. claude_swap/tui/data.py +194 -0
  43. claude_swap/tui/modals.py +159 -0
  44. claude_swap/tui/theme.py +88 -0
  45. claude_swap/tui/widgets.py +544 -0
  46. claude_swap/update_check.py +509 -0
  47. claude_swap/usage_bars.py +208 -0
  48. claude_swap/usage_rows.py +160 -0
  49. claude_swap/usage_store.py +1429 -0
  50. llmswap/AGENTS.md +11 -0
  51. llmswap/__init__.py +3 -0
  52. llmswap/__main__.py +4 -0
  53. llmswap/cli.py +535 -0
  54. llmswap/config.py +101 -0
  55. llmswap/httpjson.py +50 -0
  56. llmswap/jwt.py +20 -0
  57. llmswap/menubar.py +218 -0
  58. llmswap/model.py +172 -0
  59. llmswap/paths.py +41 -0
  60. llmswap/providers/AGENTS.md +12 -0
  61. llmswap/providers/base.py +619 -0
  62. llmswap/providers/claude.py +187 -0
  63. llmswap/providers/codex.py +274 -0
  64. llmswap/providers/gemini.py +80 -0
  65. llmswap/providers/registry.py +30 -0
  66. llmswap/render.py +127 -0
  67. llmswap/rotate.py +102 -0
  68. llmswap/store.py +138 -0
  69. llmswap/tui.py +182 -0
  70. llmswap/usage_cache.py +72 -0
  71. llmswap/warm/plan.py +118 -0
  72. llmswap/warm/runner.py +175 -0
  73. llmswap/warm/schedule.py +264 -0
  74. llmswap_cli-1.0.0.dist-info/METADATA +181 -0
  75. llmswap_cli-1.0.0.dist-info/RECORD +78 -0
  76. llmswap_cli-1.0.0.dist-info/WHEEL +4 -0
  77. llmswap_cli-1.0.0.dist-info/entry_points.txt +5 -0
  78. llmswap_cli-1.0.0.dist-info/licenses/LICENSE +22 -0
llmswap/warm/plan.py ADDED
@@ -0,0 +1,118 @@
1
+ """When is an account due a warm-up ping? Pure decisions, no I/O.
2
+
3
+ A 5-hour window starts on an account's first request and ends exactly five
4
+ hours later. An account is *cold* when it has no running 5-hour window: it
5
+ never started one, or the one it had has reset. Warming a cold account starts
6
+ its window now, so it also ends sooner and the next one can start sooner.
7
+
8
+ ``decide`` takes the reading, the settings, the clock and what the last ping
9
+ left behind, and returns whether to ping or why not, plus the earliest time
10
+ worth looking again. The scheduler ticks every few minutes regardless; this
11
+ function is what makes most ticks do nothing.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass
17
+ from datetime import datetime, timedelta
18
+
19
+ from llmswap.config import AccountWarm, WarmConfig, parse_hhmm
20
+ from llmswap.model import FIVE_HOUR_S, AccountView, Window
21
+
22
+ MIN_SPACING_S = 20 * 60 # never ping one account twice within this
23
+ WEEKLY_FULL_PCT = 99.0
24
+ BACKOFF_BASE_S = 5 * 60
25
+ BACKOFF_MAX_S = 2 * 3600
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Decision:
30
+ ping: bool
31
+ reason: str
32
+ look_again_at: float | None = None # epoch; None when nothing is pending
33
+
34
+
35
+ def in_quiet_hours(cfg: WarmConfig, now: datetime) -> datetime | None:
36
+ """The end of the quiet period ``now`` falls in, or None when it does not."""
37
+ if not (cfg.quiet_start and cfg.quiet_end):
38
+ return None
39
+ s_h, s_m = parse_hhmm(cfg.quiet_start)
40
+ e_h, e_m = parse_hhmm(cfg.quiet_end)
41
+ start = now.replace(hour=s_h, minute=s_m, second=0, microsecond=0)
42
+ end = now.replace(hour=e_h, minute=e_m, second=0, microsecond=0)
43
+ if start == end:
44
+ return None
45
+ if start < end:
46
+ return end if start <= now < end else None
47
+ # Wraps midnight: quiet from `start` today to `end` tomorrow, or from
48
+ # `start` yesterday to `end` today.
49
+ if now >= start:
50
+ return end + timedelta(days=1)
51
+ if now < end:
52
+ return end
53
+ return None
54
+
55
+
56
+ def backoff_s(fail_count: int) -> float:
57
+ if fail_count <= 0:
58
+ return 0.0
59
+ return min(BACKOFF_MAX_S, BACKOFF_BASE_S * 2 ** (fail_count - 1))
60
+
61
+
62
+ def decide(
63
+ view: AccountView,
64
+ account: AccountWarm | None,
65
+ cfg: WarmConfig,
66
+ now: datetime,
67
+ *,
68
+ last_warm: float | None = None,
69
+ fail_count: int = 0,
70
+ last_attempt: float | None = None,
71
+ ) -> Decision:
72
+ t = now.timestamp()
73
+ if account is None or not account.enabled:
74
+ return Decision(False, "warm-up not enabled for this account")
75
+ if view.disabled:
76
+ return Decision(False, "account is disabled")
77
+ if view.kind != "oauth":
78
+ return Decision(False, "api key accounts have no window")
79
+ window = view.usage.window("5h")
80
+ weekly = view.usage.window("7d")
81
+ if window is None:
82
+ # An idle account's response may omit the 5-hour window entirely. With a
83
+ # weekly window present the reading itself is sound, so a missing 5-hour
84
+ # window means none is running; with nothing at all there is no reading.
85
+ if weekly is None:
86
+ return Decision(False, "no usage windows reported for this account")
87
+ window = Window("5h", 0.0, None, FIVE_HOUR_S)
88
+ if weekly is not None and weekly.running(t) and (weekly.used_pct or 0) >= WEEKLY_FULL_PCT:
89
+ return Decision(False, "weekly limit reached", weekly.resets_at)
90
+ if window.running(t):
91
+ return Decision(False, "window already running", window.resets_at)
92
+
93
+ fetched = view.usage.fetched_at
94
+ if (
95
+ last_warm is not None
96
+ and t < last_warm + FIVE_HOUR_S
97
+ and (fetched is None or fetched <= last_warm)
98
+ ):
99
+ # The reading predates our own ping, so it cannot show the window
100
+ # that ping started.
101
+ return Decision(False, "window started by our last ping", last_warm + FIVE_HOUR_S)
102
+
103
+ # Cold from here on.
104
+ quiet_end = in_quiet_hours(cfg, now)
105
+ if quiet_end is not None:
106
+ return Decision(False, "quiet hours", quiet_end.timestamp())
107
+ if account.earliest:
108
+ e_h, e_m = parse_hhmm(account.earliest)
109
+ earliest = now.replace(hour=e_h, minute=e_m, second=0, microsecond=0)
110
+ if now < earliest:
111
+ return Decision(False, f"before {account.earliest}", earliest.timestamp())
112
+ if last_warm is not None and t - last_warm < MIN_SPACING_S:
113
+ return Decision(False, "pinged a moment ago", last_warm + MIN_SPACING_S)
114
+ if fail_count and last_attempt is not None:
115
+ retry_at = last_attempt + backoff_s(fail_count)
116
+ if t < retry_at:
117
+ return Decision(False, "retrying after a failure", retry_at)
118
+ return Decision(True, "window is cold")
llmswap/warm/runner.py ADDED
@@ -0,0 +1,175 @@
1
+ """One warm-up pass: read usage, decide, ping, remember.
2
+
3
+ ``tick`` is what the platform scheduler runs every few minutes. It is safe to
4
+ run twice at once (a lock makes the second pass return at once), never raises
5
+ for one account's failure, and keeps a small state file so a ping is not
6
+ repeated and a failing account is retried with growing delay.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import time
13
+ from dataclasses import dataclass
14
+ from datetime import datetime
15
+
16
+ from claude_swap.fsutil import atomic_write_text
17
+ from claude_swap.locking import FileLock
18
+
19
+ from llmswap import paths
20
+ from llmswap.config import WarmConfig, load_warm
21
+ from llmswap.model import AccountView
22
+ from llmswap.providers import registry
23
+ from llmswap.providers.base import ProviderError, resolve_ref
24
+ from llmswap.warm import plan
25
+
26
+ SETTLE_S = 4.0 # let the provider register the request before reading back
27
+ MAX_READING_AGE_S = 15 * 60 # a ping needs a reading at most this old, free of errors
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Line:
32
+ ref: str
33
+ action: str # "pinged" | "failed" | "skipped" | "would-ping"
34
+ detail: str
35
+ look_again_at: float | None = None
36
+
37
+
38
+ def load_state() -> dict:
39
+ try:
40
+ return json.loads(paths.warmup_state_path().read_text(encoding="utf-8"))
41
+ except (OSError, ValueError):
42
+ return {}
43
+
44
+
45
+ def _save_state(state: dict) -> None:
46
+ paths.warmup_state_path().parent.mkdir(parents=True, exist_ok=True)
47
+ atomic_write_text(paths.warmup_state_path(), json.dumps(state, indent=2, sort_keys=True))
48
+
49
+
50
+ def _log(message: str) -> None:
51
+ """One line per attempt, never a token. Kept small by rewriting past 200 KB."""
52
+ path = paths.logs_dir() / "warmup.log"
53
+ path.parent.mkdir(parents=True, exist_ok=True)
54
+ stamp = datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S%z")
55
+ try:
56
+ if path.exists() and path.stat().st_size > 200_000:
57
+ path.write_text("".join(path.read_text().splitlines(keepends=True)[-500:]))
58
+ with path.open("a", encoding="utf-8") as fh:
59
+ fh.write(f"{stamp} {message}\n")
60
+ except OSError:
61
+ pass
62
+
63
+
64
+ def _view(provider, number: str) -> AccountView | None:
65
+ return resolve_ref(provider.accounts(), number)
66
+
67
+
68
+ def tick(
69
+ *,
70
+ now: datetime | None = None,
71
+ cfg: WarmConfig | None = None,
72
+ dry_run: bool = False,
73
+ only: str | None = None,
74
+ force_enabled: bool = False,
75
+ sleep=time.sleep,
76
+ ) -> list[Line]:
77
+ cfg = cfg or load_warm()
78
+ now = now or datetime.now().astimezone()
79
+ if not (cfg.enabled or force_enabled):
80
+ return []
81
+ lock = FileLock(paths.root() / "warm.lock", timeout=0)
82
+ if not lock.acquire(timeout=0):
83
+ return [Line("-", "skipped", "another warm-up pass is running")]
84
+ try:
85
+ return _pass(cfg, now, dry_run, only, sleep)
86
+ finally:
87
+ lock.release()
88
+
89
+
90
+ def _pass(cfg, now, dry_run, only, sleep) -> list[Line]:
91
+ state = load_state()
92
+ lines: list[Line] = []
93
+ for ref, account in sorted(cfg.accounts.items()):
94
+ if only and ref != only:
95
+ continue
96
+ try:
97
+ lines.append(_one(ref, account, cfg, now, dry_run, state, sleep))
98
+ except ProviderError as exc:
99
+ lines.append(Line(ref, "failed", str(exc)[:120]))
100
+ except Exception as exc: # one account must not stop the others
101
+ lines.append(Line(ref, "failed", exc.__class__.__name__))
102
+ if not dry_run:
103
+ _save_state(state)
104
+ return lines
105
+
106
+
107
+ def _one(ref, account, cfg, now, dry_run, state, sleep) -> Line:
108
+ provider_id, _, number = ref.partition(":")
109
+ provider = registry.get(provider_id)
110
+ if not provider.installed():
111
+ return Line(ref, "skipped", f"`{provider.binary}` is not installed")
112
+ if "warm" not in provider.capabilities or "usage" not in provider.capabilities:
113
+ return Line(ref, "skipped", "this provider has no 5-hour window to warm")
114
+ view = _view(provider, number)
115
+ if view is None:
116
+ return Line(ref, "skipped", "account not found")
117
+ rec = state.get(ref, {})
118
+
119
+ def decide(v: AccountView) -> plan.Decision:
120
+ return plan.decide(
121
+ v, account, cfg, now,
122
+ last_warm=rec.get("last_warm"),
123
+ fail_count=int(rec.get("fail_count", 0)),
124
+ last_attempt=rec.get("last_attempt"),
125
+ )
126
+
127
+ # A cheap read first: usage the cache still trusts costs nothing.
128
+ provider.refresh_usage([view.number])
129
+ view = _view(provider, number) or view
130
+ decision = decide(view)
131
+ if not decision.ping:
132
+ return Line(ref, "skipped", decision.reason, decision.look_again_at)
133
+ # The reading says cold. Confirm with a fresh one before spending a request.
134
+ provider.refresh_usage([view.number], force=True)
135
+ view = _view(provider, number) or view
136
+ decision = decide(view)
137
+ if not decision.ping:
138
+ return Line(ref, "skipped", decision.reason, decision.look_again_at)
139
+ t = now.timestamp()
140
+ fetched = view.usage.fetched_at
141
+ if view.usage.error or fetched is None or t - fetched > MAX_READING_AGE_S:
142
+ why = view.usage.error or "reading is too old"
143
+ return Line(ref, "skipped", f"no fresh usage ({why})")
144
+ if dry_run:
145
+ return Line(ref, "would-ping", decision.reason)
146
+
147
+ # The guard is written before the request: a crash or a timeout mid-ping
148
+ # must not turn into a second ping on the next tick.
149
+ previous_warm = rec.get("last_warm")
150
+ rec["last_warm"] = t
151
+ rec["last_attempt"] = t
152
+ state[ref] = rec
153
+ _save_state(state)
154
+ outcome = provider.warm(view.number, prompt=cfg.prompt, model=account.model)
155
+ if not outcome.ok and not outcome.ambiguous:
156
+ # The request definitely did not go through: the guard is not needed.
157
+ if previous_warm is None:
158
+ rec.pop("last_warm", None)
159
+ else:
160
+ rec["last_warm"] = previous_warm
161
+ if outcome.ok:
162
+ rec.update(fail_count=0, last_result="ok")
163
+ _log(f"{ref} pinged ok")
164
+ sleep(SETTLE_S)
165
+ provider.refresh_usage([view.number], force=True)
166
+ after = _view(provider, number)
167
+ w = after.usage.window("5h") if after else None
168
+ if w is not None and w.running(time.time()):
169
+ return Line(ref, "pinged", "window started", w.resets_at)
170
+ return Line(ref, "pinged", "sent; the provider has not reported the new window yet")
171
+ rec["fail_count"] = int(rec.get("fail_count", 0)) + 1
172
+ rec["last_result"] = outcome.detail
173
+ state[ref] = rec
174
+ _log(f"{ref} ping failed: {outcome.detail}")
175
+ return Line(ref, "failed", outcome.detail, t + plan.backoff_s(rec["fail_count"]))
@@ -0,0 +1,264 @@
1
+ """Install ``llmswap warm tick`` under the platform's own scheduler.
2
+
3
+ * macOS: a LaunchAgent with ``StartInterval`` (the plist helpers are
4
+ claude-swap's ``launch_agent``, which already solves launchd's quirks).
5
+ * Linux: a systemd user timer; cron when systemd user units are unavailable.
6
+ * Windows: a Task Scheduler task created with ``schtasks``.
7
+
8
+ Each backend is split into a pure function that builds what gets written or
9
+ run, and a thin function that does it, so the content is testable without
10
+ touching a real scheduler.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import plistlib
17
+ import shutil
18
+ import subprocess
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ from claude_swap import launch_agent as la
23
+ from claude_swap.fsutil import atomic_write_bytes, atomic_write_text
24
+
25
+ from llmswap import paths
26
+ from llmswap.providers.base import ProviderError
27
+
28
+ LABEL = "com.llmswap.warmup"
29
+ UNIT = "llmswap-warm"
30
+ CRON_MARK = "# llmswap-warm"
31
+ TASK_NAME = "llmswap-warm"
32
+
33
+
34
+ #: Variables that decide which store and which home a run reads. A scheduled job
35
+ #: starts with almost no environment, so the ones set when it was installed are
36
+ #: written into it; otherwise the tick would read a different store than the
37
+ #: user's commands do.
38
+ FORWARDED_ENV = (
39
+ "LLMSWAP_HOME", "CODEX_HOME", "GEMINI_CLI_HOME", "CLAUDE_CONFIG_DIR",
40
+ "CLAUDE_SECURESTORAGE_CONFIG_DIR", "XDG_DATA_HOME", "XDG_CONFIG_HOME",
41
+ )
42
+
43
+
44
+ def forwarded_env() -> dict[str, str]:
45
+ return {k: os.environ[k] for k in FORWARDED_ENV if os.environ.get(k)}
46
+
47
+
48
+ def program(*, windowless: bool = False) -> list[str]:
49
+ """The argv that runs llmswap: the console script, else this interpreter.
50
+
51
+ ``windowless`` (Windows) prefers the GUI-subsystem launcher so a scheduled run
52
+ does not flash a console window.
53
+ """
54
+ if windowless and sys.platform == "win32":
55
+ gui = shutil.which("llmswap-w")
56
+ if gui:
57
+ return [gui]
58
+ pyw = Path(sys.executable).with_name("pythonw.exe")
59
+ if pyw.exists():
60
+ return [str(pyw), "-m", "llmswap"]
61
+ which = shutil.which("llmswap")
62
+ if which:
63
+ return [str(Path(os.path.abspath(which)))]
64
+ cand = Path(os.path.abspath(sys.argv[0])) if sys.argv and sys.argv[0] else None
65
+ if cand and cand.name.startswith("llmswap") and cand.is_file():
66
+ return [str(cand)]
67
+ return [sys.executable, "-m", "llmswap"]
68
+
69
+
70
+ def search_path(prog: list[str] | None = None) -> str:
71
+ """PATH for the scheduled job: the installing shell's, so `claude` and `codex`
72
+ are found wherever npm, brew or a version manager put them."""
73
+ base = la._path_env(prog or program()).split(os.pathsep)
74
+ mine = [d for d in os.environ.get("PATH", "").split(os.pathsep) if d]
75
+ seen: list[str] = []
76
+ for d in [*mine, *base]:
77
+ if d not in seen:
78
+ seen.append(d)
79
+ return os.pathsep.join(seen)
80
+
81
+
82
+ def tick_argv(prog: list[str] | None = None) -> list[str]:
83
+ return [*(prog or program()), "warm", "tick", "--quiet"]
84
+
85
+
86
+ def backend() -> str:
87
+ if sys.platform == "darwin":
88
+ return "launchd"
89
+ if sys.platform == "win32":
90
+ return "schtasks"
91
+ if shutil.which("systemctl") and _systemd_user_ok():
92
+ return "systemd"
93
+ if shutil.which("crontab"):
94
+ return "cron"
95
+ raise ProviderError("no scheduler found: need launchd, systemd --user, cron or Task Scheduler")
96
+
97
+
98
+ def _systemd_user_ok() -> bool:
99
+ try:
100
+ proc = subprocess.run(
101
+ ["systemctl", "--user", "show-environment"],
102
+ capture_output=True, timeout=5,
103
+ )
104
+ except (OSError, subprocess.TimeoutExpired):
105
+ return False
106
+ return proc.returncode == 0
107
+
108
+
109
+ # -- launchd ---------------------------------------------------------------
110
+ def launchd_plist(interval_minutes: int, prog: list[str] | None = None) -> bytes:
111
+ prog = prog or program()
112
+ log = paths.logs_dir() / "warmup-scheduler.log"
113
+ return plistlib.dumps(
114
+ {
115
+ "Label": LABEL,
116
+ "ProgramArguments": tick_argv(prog),
117
+ "StartInterval": max(60, interval_minutes * 60),
118
+ "RunAtLoad": True,
119
+ "ProcessType": "Background",
120
+ "EnvironmentVariables": {"PATH": search_path(prog), **forwarded_env()},
121
+ "StandardOutPath": str(log),
122
+ "StandardErrorPath": str(log),
123
+ }
124
+ )
125
+
126
+
127
+ # -- systemd ---------------------------------------------------------------
128
+ def systemd_units(interval_minutes: int, prog: list[str] | None = None) -> tuple[str, str]:
129
+ argv = " ".join(_quote(a.replace("%", "%%")) for a in tick_argv(prog))
130
+ env = {"PATH": search_path(prog), **forwarded_env()}
131
+ env_lines = "".join(f'Environment="{k}={v.replace("%", "%%")}"\n' for k, v in env.items())
132
+ service = (
133
+ "[Unit]\nDescription=llmswap warm-up tick\n\n"
134
+ f"[Service]\nType=oneshot\n{env_lines}ExecStart={argv}\n"
135
+ )
136
+ timer = (
137
+ "[Unit]\nDescription=llmswap warm-up schedule\n\n"
138
+ f"[Timer]\nOnBootSec=2min\nOnUnitActiveSec={interval_minutes}min\nAccuracySec=30s\n\n"
139
+ "[Install]\nWantedBy=timers.target\n"
140
+ )
141
+ return service, timer
142
+
143
+
144
+ def _quote(arg: str) -> str:
145
+ return f'"{arg}"' if " " in arg else arg
146
+
147
+
148
+ def systemd_dir() -> Path:
149
+ base = os.environ.get("XDG_CONFIG_HOME")
150
+ root = Path(base) if base and Path(base).is_absolute() else Path.home() / ".config"
151
+ return root / "systemd" / "user"
152
+
153
+
154
+ # -- cron ------------------------------------------------------------------
155
+ def cron_step(minutes: int) -> int:
156
+ """The largest divisor of 60 not above ``minutes``: cron's ``*/n`` restarts each
157
+ hour, so any other step leaves an uneven gap at the top of the hour."""
158
+ return max(d for d in (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60) if d <= max(1, minutes))
159
+
160
+
161
+ def _cron_quote(text: str) -> str:
162
+ return "'" + text.replace("'", "'\\''").replace("%", "\\%") + "'"
163
+
164
+
165
+ def cron_line(interval_minutes: int, prog: list[str] | None = None) -> str:
166
+ step = cron_step(interval_minutes)
167
+ minute = f"*/{step}" if step < 60 else "0"
168
+ env = {"PATH": search_path(prog), **forwarded_env()}
169
+ assigns = " ".join(f"{k}={_cron_quote(v)}" for k, v in env.items())
170
+ argv = " ".join(_cron_quote(a) for a in tick_argv(prog))
171
+ return f"{minute} * * * * {assigns} {argv} {CRON_MARK}"
172
+
173
+
174
+ def merge_crontab(existing: str, line: str | None) -> str:
175
+ kept = [l for l in existing.splitlines() if CRON_MARK not in l]
176
+ if line:
177
+ kept.append(line)
178
+ return "\n".join(kept).strip("\n") + "\n" if kept else ""
179
+
180
+
181
+ # -- Task Scheduler --------------------------------------------------------
182
+ def schtasks_create_args(interval_minutes: int, prog: list[str] | None = None) -> list[str]:
183
+ argv = tick_argv(prog or program(windowless=True))
184
+ cmd = subprocess.list2cmdline(argv)
185
+ env = forwarded_env()
186
+ if env: # only now is a shell needed (and a console window with it)
187
+ sets = " && ".join(f'set "{k}={v}"' for k, v in env.items())
188
+ cmd = f'cmd /c "{sets} && {cmd}"'
189
+ return ["schtasks", "/Create", "/F", "/SC", "MINUTE", "/MO", str(interval_minutes), "/TN", TASK_NAME, "/TR", cmd]
190
+
191
+
192
+ # -- public ----------------------------------------------------------------
193
+ def _run(args: list[str], *, input_text: str | None = None) -> subprocess.CompletedProcess:
194
+ return subprocess.run(args, input=input_text, capture_output=True, text=True, timeout=30)
195
+
196
+
197
+ def install(interval_minutes: int, prog: list[str] | None = None) -> str:
198
+ """Install the schedule; returns the backend used."""
199
+ kind = backend()
200
+ paths.logs_dir().mkdir(parents=True, exist_ok=True)
201
+ if kind == "launchd":
202
+ target = la.plist_path(LABEL)
203
+ target.parent.mkdir(parents=True, exist_ok=True)
204
+ atomic_write_bytes(target, launchd_plist(interval_minutes, prog))
205
+ la._reload(target, LABEL, None)
206
+ elif kind == "systemd":
207
+ d = systemd_dir()
208
+ d.mkdir(parents=True, exist_ok=True)
209
+ service, timer = systemd_units(interval_minutes, prog)
210
+ atomic_write_text(d / f"{UNIT}.service", service, mode=0o644)
211
+ atomic_write_text(d / f"{UNIT}.timer", timer, mode=0o644)
212
+ for args in (["daemon-reload"], ["enable", "--now", f"{UNIT}.timer"]):
213
+ proc = _run(["systemctl", "--user", *args])
214
+ if proc.returncode != 0:
215
+ raise ProviderError(f"systemctl {args[0]} failed: {proc.stderr.strip()[:200]}")
216
+ elif kind == "cron":
217
+ current = _run(["crontab", "-l"])
218
+ existing = current.stdout if current.returncode == 0 else ""
219
+ proc = _run(["crontab", "-"], input_text=merge_crontab(existing, cron_line(interval_minutes, prog)))
220
+ if proc.returncode != 0:
221
+ raise ProviderError(f"crontab failed: {proc.stderr.strip()[:200]}")
222
+ else:
223
+ proc = _run(schtasks_create_args(interval_minutes, prog))
224
+ if proc.returncode != 0:
225
+ raise ProviderError(f"schtasks failed: {(proc.stderr or proc.stdout).strip()[:200]}")
226
+ return kind
227
+
228
+
229
+ def uninstall() -> str | None:
230
+ """Remove the schedule; returns the backend it was removed from."""
231
+ kind = backend()
232
+ if kind == "launchd":
233
+ target = la.plist_path(LABEL)
234
+ if la.is_loaded(LABEL):
235
+ la._launchctl("bootout", la.service_target(LABEL))
236
+ if target.exists():
237
+ target.unlink()
238
+ elif kind == "systemd":
239
+ _run(["systemctl", "--user", "disable", "--now", f"{UNIT}.timer"])
240
+ for suffix in ("service", "timer"):
241
+ (systemd_dir() / f"{UNIT}.{suffix}").unlink(missing_ok=True)
242
+ _run(["systemctl", "--user", "daemon-reload"])
243
+ elif kind == "cron":
244
+ current = _run(["crontab", "-l"])
245
+ if current.returncode == 0:
246
+ _run(["crontab", "-"], input_text=merge_crontab(current.stdout, None))
247
+ else:
248
+ _run(["schtasks", "/Delete", "/F", "/TN", TASK_NAME])
249
+ return kind
250
+
251
+
252
+ def installed() -> bool:
253
+ try:
254
+ kind = backend()
255
+ except ProviderError:
256
+ return False
257
+ if kind == "launchd":
258
+ return la.plist_path(LABEL).exists() and la.is_loaded(LABEL)
259
+ if kind == "systemd":
260
+ return (systemd_dir() / f"{UNIT}.timer").exists()
261
+ if kind == "cron":
262
+ current = _run(["crontab", "-l"])
263
+ return current.returncode == 0 and CRON_MARK in current.stdout
264
+ return _run(["schtasks", "/Query", "/TN", TASK_NAME]).returncode == 0