agents-framework 0.3.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 (50) hide show
  1. agents_framework-0.3.0.dist-info/METADATA +1364 -0
  2. agents_framework-0.3.0.dist-info/RECORD +50 -0
  3. agents_framework-0.3.0.dist-info/WHEEL +5 -0
  4. agents_framework-0.3.0.dist-info/entry_points.txt +2 -0
  5. agents_framework-0.3.0.dist-info/licenses/LICENSE +661 -0
  6. agents_framework-0.3.0.dist-info/top_level.txt +1 -0
  7. framework/__init__.py +0 -0
  8. framework/__main__.py +9 -0
  9. framework/action_page.py +1102 -0
  10. framework/approval_buttons.py +775 -0
  11. framework/approvals.py +678 -0
  12. framework/calendar_card.py +276 -0
  13. framework/cli.py +273 -0
  14. framework/codex_llm.py +401 -0
  15. framework/config.py +126 -0
  16. framework/drafter.py +263 -0
  17. framework/interfaces.py +96 -0
  18. framework/llm.py +744 -0
  19. framework/plugins/__init__.py +147 -0
  20. framework/plugins/agentmail_source.py +355 -0
  21. framework/plugins/approval_destination.py +478 -0
  22. framework/plugins/command_action.py +248 -0
  23. framework/plugins/digest_destination.py +546 -0
  24. framework/plugins/email_destination.py +248 -0
  25. framework/plugins/fanout_destination.py +160 -0
  26. framework/plugins/github_org_source.py +226 -0
  27. framework/plugins/github_releases_source.py +420 -0
  28. framework/plugins/ics_source.py +594 -0
  29. framework/plugins/llm_scorer.py +411 -0
  30. framework/plugins/multi_source.py +241 -0
  31. framework/plugins/reddit_source.py +625 -0
  32. framework/plugins/regex_scorer.py +93 -0
  33. framework/plugins/rss_source.py +346 -0
  34. framework/plugins/signal_destination.py +133 -0
  35. framework/plugins/slack_destination.py +461 -0
  36. framework/plugins/slack_draft_action.py +137 -0
  37. framework/plugins/slack_post_action.py +65 -0
  38. framework/plugins/slack_workspace_source.py +992 -0
  39. framework/plugins/twitter_action.py +210 -0
  40. framework/plugins/websearch_source.py +761 -0
  41. framework/plugins/wordpress_action.py +413 -0
  42. framework/proposals.py +246 -0
  43. framework/registry.py +166 -0
  44. framework/runlog.py +125 -0
  45. framework/runner.py +243 -0
  46. framework/schedule.py +571 -0
  47. framework/signal_messenger.py +1418 -0
  48. framework/slack.py +801 -0
  49. framework/state.py +39 -0
  50. framework/templating.py +76 -0
framework/schedule.py ADDED
@@ -0,0 +1,571 @@
1
+ """`agent install-schedule` / `uninstall-schedule` — the plist is the scheduler (issue #10).
2
+
3
+ The framework never runs a clock of its own: every entrypoint is run-and-exit,
4
+ and launchd decides when. What used to be a hand-written plist per agent is
5
+ generated from the workspace instead, so the cadence a config declares is the
6
+ cadence that actually runs, and a new agent is deployed by one command:
7
+
8
+ agent install-schedule --workspace <dir> [--label <label>] [--venv <path>] [--force] [--dry-run]
9
+ agent uninstall-schedule --workspace <dir> [--label <label>] [--force]
10
+
11
+ Config keys read from `<dir>/config.json`:
12
+
13
+ "agent": "reddit-leads", the default label is com.agents.<agent>
14
+ "schedule": "every 4h", when `agent run` fires (required)
15
+ "approvals": {
16
+ "schedule": "every 5m", when `agent approvals` fires (default every 5m)
17
+ ...
18
+ }
19
+
20
+ A workspace gets one job, two, or three. `agent run` always, on `schedule`.
21
+ When the config has an `approvals` block (issue #21), `agent approvals` is its
22
+ own job on its own clock, labelled `<label>.approvals`: it has to answer a `do`
23
+ within minutes while the run may fire every few hours, so one plist cannot
24
+ serve both. With `"approvals": {"listen": true}` (issue #74) there is a third,
25
+ `<label>.approvals.listen`, running `agent approvals --listen`: a Socket Mode
26
+ client for approval button clicks. It is the one job with no schedule at all --
27
+ `KeepAlive` is true and launchd restarts it whenever it exits, which is how a
28
+ dropped connection or a slept laptop becomes a reconnect. `ThrottleInterval`
29
+ bounds that: a listener that cannot start at all (revoked app token, missing
30
+ dependency) retries once a minute instead of as fast as it can crash. The polling job stays
31
+ installed alongside it as the fallback that resolves a click that never arrived.
32
+ Nothing else in the `approvals` block is checked here. Its bot token lives in
33
+ the login profile the job loads, not necessarily in the shell running the
34
+ install, so validating it now would fail installs that would run fine; the
35
+ approvals pass reports its own config errors in its log.
36
+
37
+ `schedule` has two forms, and anything else is a `ConfigError`:
38
+
39
+ - `every <N>m` / `every <N>h` becomes `StartInterval` (seconds). launchd counts
40
+ from when the job was loaded, not from the top of the hour.
41
+ - A five-field cron string (`minute hour day-of-month month day-of-week`)
42
+ becomes `StartCalendarInterval`, which is clock-aligned. `*` omits the key.
43
+ A field may be a number, a range `A-B`, or a comma list of those; minute and
44
+ hour also take `*/N`. Every combination of the listed values becomes one
45
+ dict, so `0 9,17 * * 1-5` is ten dicts and `0 14 * * 3` is one. Day-of-week
46
+ 7 is Sunday, as 0 is. Not supported, and rejected rather than approximated:
47
+ `*/N` in day, month or weekday, stepped ranges (`A-B/N`), names (`MON`,
48
+ `JAN`), `@daily`-style macros, and restricting day-of-month and day-of-week
49
+ together. Cron fires when *either* of those two matches; launchd's documented
50
+ semantics for a dict carrying both are not that precise, and a schedule that
51
+ quietly fires on different days is worse than one that refuses to install.
52
+
53
+ The generated plist, per job: `ProgramArguments` is
54
+ `/bin/bash -lc "exec <venv>/bin/agent <run|approvals> --workspace <dir>"`,
55
+ because the login profile is what supplies credentials (README, "Secrets live
56
+ in the environment"). `--venv` defaults to the venv the running `agent` lives
57
+ in (`sys.prefix`), so installing from the deployment checkout's venv points
58
+ the job at that venv. `WorkingDirectory` is the workspace; stdout and stderr go
59
+ to `<dir>/logs/run.log` / `run.error.log` (or `approvals.log` /
60
+ `approvals.error.log`); `RunAtLoad` is true and `KeepAlive` false (except for the
61
+ listener job, which is the reverse of both ideas: nothing but `KeepAlive`), so an
62
+ install fires once immediately and then waits for its schedule. Every
63
+ generated plist also carries `AgentsFrameworkManaged` (true) and
64
+ `AgentsFrameworkWorkspace` (the workspace path); launchd ignores keys it does
65
+ not know.
66
+
67
+ Those two keys are how a label is known to be ours. A label is a free-form
68
+ name in a directory shared with every other LaunchAgent the user has, so a
69
+ typo or a reused name must not stop and delete somebody else's job. Before
70
+ anything is booted out, replaced or deleted, every label the command would
71
+ touch is checked: a plist at that label without the marker (or that is not a
72
+ readable plist), one marked for a different workspace (two workspaces fighting
73
+ over one label), or a job loaded under that label with no plist at the
74
+ expected path, is refused, naming the label and what it currently runs.
75
+ `--force` takes it over anyway, and says so on stderr. A hand-written plist
76
+ from before this command existed has no marker, so migrating it needs
77
+ `--force` once.
78
+
79
+ Everything that can be wrong with the config, the label, the venv or label
80
+ ownership is checked before any file is written. Then, per job: the plist is
81
+ written to a temporary file next to its destination, `plutil -lint`ed, the
82
+ bytes of the existing plist (if any) are kept, the loaded job (if any) is
83
+ booted out, the temporary file is renamed over `~/Library/LaunchAgents/
84
+ <label>.plist`, and the job is bootstrapped. Re-running is therefore an update,
85
+ and a plist that fails lint never replaces a working one. If bootstrapping the
86
+ new plist fails and an old job had been loaded, the old plist is written back
87
+ and bootstrapped, and the error says both what failed and whether the old job
88
+ is running again; a failed update should not also be an outage. Booting out a job
89
+ that is mid-pass terminates the pass: harmless for `agent run` (nothing
90
+ undelivered is marked seen), but an `agent approvals` pass killed mid-steps
91
+ leaves its proposal stuck, so re-install between passes. If the config no
92
+ longer has an `approvals` block, a previously installed `<label>.approvals`
93
+ job is removed, so an update cannot leave a stale job firing.
94
+
95
+ `uninstall-schedule` boots out and deletes both labels, whichever exist, and
96
+ does not care what the config says today, subject to the same ownership check
97
+ against the `--workspace` given. It reads the config only for the default
98
+ label; with `--label` it does not read it at all, so a workspace whose config
99
+ is broken can still be uninstalled. `--label` is needed whenever the install
100
+ used one. Finding nothing to remove is an error: a mistyped label should not
101
+ look like a successful uninstall.
102
+
103
+ `--dry-run` prints each plist, preceded by the path it would be written to,
104
+ and does nothing else: no directory, no lint, no launchctl. macOS only, by
105
+ `sys.platform`; there is no cron backend until something needs one.
106
+ """
107
+ from __future__ import annotations
108
+
109
+ import itertools
110
+ import os
111
+ import plistlib
112
+ import re
113
+ import shlex
114
+ import subprocess
115
+ import sys
116
+ import tempfile
117
+ import time
118
+ from dataclasses import dataclass
119
+ from pathlib import Path
120
+ from typing import Any
121
+ from xml.parsers.expat import ExpatError
122
+
123
+ from framework.config import AgentConfig, ConfigError, load_workspace
124
+
125
+ DEFAULT_APPROVALS_SCHEDULE = "every 5m"
126
+ APPROVALS_LABEL_SUFFIX = ".approvals"
127
+ LISTEN_LABEL_SUFFIX = ".approvals.listen"
128
+ # Seconds launchd waits before restarting the listener. A failure that cannot
129
+ # fix itself -- a revoked app token, a venv without slack_sdk, a config typo --
130
+ # would otherwise respawn as fast as the process can die, filling the error log
131
+ # with the same line and hiding it in its own noise.
132
+ LISTEN_THROTTLE_SEC = 60
133
+ LOGS_DIRNAME = "logs"
134
+ LAUNCH_AGENTS_DIR = Path.home() / "Library" / "LaunchAgents"
135
+ MANAGED_KEY = "AgentsFrameworkManaged"
136
+ WORKSPACE_KEY = "AgentsFrameworkWorkspace"
137
+
138
+ _EVERY_RE = re.compile(r"^every\s+(\d+)\s*([mh])$")
139
+ _UNIT_SECONDS = {"m": 60, "h": 3600}
140
+ _LABEL_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
141
+
142
+ # (plist key, cron field name, lowest, highest, accepts */N)
143
+ _CRON_FIELDS = (
144
+ ("Minute", "minute", 0, 59, True),
145
+ ("Hour", "hour", 0, 23, True),
146
+ ("Day", "day-of-month", 1, 31, False),
147
+ ("Month", "month", 1, 12, False),
148
+ ("Weekday", "day-of-week", 0, 7, False),
149
+ )
150
+
151
+ # How long to wait for a booted-out job to leave the domain before
152
+ # bootstrapping its replacement (bootout returns before launchd is done).
153
+ _BOOTOUT_WAIT_SECONDS = 5.0
154
+ _BOOTOUT_POLL_SECONDS = 0.1
155
+
156
+
157
+ class ScheduleError(RuntimeError):
158
+ """Raised when launchd or plutil refuses what the config asked for."""
159
+
160
+
161
+ @dataclass
162
+ class Job:
163
+ """One scheduled entrypoint of a workspace, rendered to a plist."""
164
+
165
+ label: str
166
+ plist: dict[str, Any]
167
+
168
+ @property
169
+ def path(self) -> Path:
170
+ retval = _plist_path(self.label)
171
+ return retval
172
+
173
+
174
+ def _plist_path(label: str) -> Path:
175
+ retval = LAUNCH_AGENTS_DIR / f"{label}.plist"
176
+ return retval
177
+
178
+
179
+ def _parse_cron_field(value: str, key: str, name: str, low: int, high: int, steps: bool, where: str) -> list[int] | None:
180
+ """Expand one cron field to its sorted values, or None for `*`."""
181
+
182
+ def bad(reason: str) -> ConfigError:
183
+ retval = ConfigError(f"{where}: {name} field {value!r} {reason}")
184
+ return retval
185
+
186
+ values: set[int] = set()
187
+ step_match = re.fullmatch(r"\*/(\d+)", value)
188
+ if value == "*":
189
+ pass
190
+ elif step_match:
191
+ if not steps:
192
+ raise bad("uses */N, which is only supported in minute and hour")
193
+ step = int(step_match.group(1))
194
+ if step < 1:
195
+ raise bad("has a step of 0")
196
+ values.update(range(low, high + 1, step))
197
+ else:
198
+ for part in value.split(","):
199
+ range_match = re.fullmatch(r"(\d+)-(\d+)", part)
200
+ if range_match:
201
+ start, end = int(range_match.group(1)), int(range_match.group(2))
202
+ if start > end:
203
+ raise bad(f"has a backwards range {part!r}")
204
+ elif re.fullmatch(r"\d+", part):
205
+ start = end = int(part)
206
+ else:
207
+ raise bad("is not a number, a range A-B, or a comma list of those")
208
+ if start < low or end > high:
209
+ raise bad(f"is outside {low}-{high}")
210
+ values.update(range(start, end + 1))
211
+
212
+ if key == "Weekday":
213
+ values = {0 if v == 7 else v for v in values}
214
+ retval = None if value == "*" else sorted(values)
215
+ return retval
216
+
217
+
218
+ def _parse_cron(text: str, where: str) -> dict[str, Any] | list[dict[str, Any]]:
219
+ expanded: list[tuple[str, list[int]]] = []
220
+ for raw, (key, name, low, high, steps) in zip(text.split(), _CRON_FIELDS):
221
+ values = _parse_cron_field(raw, key, name, low, high, steps, where)
222
+ if values is not None:
223
+ expanded.append((key, values))
224
+
225
+ keys = [key for key, _ in expanded]
226
+ if "Day" in keys and "Weekday" in keys:
227
+ raise ConfigError(
228
+ f"{where}: restricting both day-of-month and day-of-week is not supported "
229
+ "(cron fires when either matches); restrict one of them"
230
+ )
231
+
232
+ dicts = [dict(zip(keys, combo)) for combo in itertools.product(*(values for _, values in expanded))]
233
+ retval = dicts[0] if len(dicts) == 1 else dicts
234
+ return retval
235
+
236
+
237
+ def parse_schedule(spec: Any, where: str) -> dict[str, Any]:
238
+ """Map a config `schedule` to the plist keys that implement it.
239
+
240
+ `where` names the config file and key (`<path>: 'schedule'`) in errors.
241
+ """
242
+ if not isinstance(spec, str) or not spec.strip():
243
+ raise ConfigError(f"{where} must be a string like 'every 4h' or '0 */4 * * *'")
244
+ text = spec.strip()
245
+ where = f"{where} {spec!r}"
246
+
247
+ every = _EVERY_RE.match(text)
248
+ if every:
249
+ seconds = int(every.group(1)) * _UNIT_SECONDS[every.group(2)]
250
+ if seconds < 1:
251
+ raise ConfigError(f"{where}: the interval must be positive")
252
+ retval = {"StartInterval": seconds}
253
+ elif len(text.split()) == len(_CRON_FIELDS):
254
+ retval = {"StartCalendarInterval": _parse_cron(text, where)}
255
+ else:
256
+ raise ConfigError(f"{where} is neither 'every <N>m' / 'every <N>h' nor a five-field cron string")
257
+ return retval
258
+
259
+
260
+ def default_label(agent: str) -> str:
261
+ retval = f"com.agents.{agent}"
262
+ return retval
263
+
264
+
265
+ def _check_label(label: str) -> None:
266
+ # The label becomes a file name under ~/Library/LaunchAgents.
267
+ if not _LABEL_RE.match(label):
268
+ raise ConfigError(
269
+ f"label {label!r} must be letters, digits, '.', '_' or '-', starting with a letter or digit"
270
+ )
271
+
272
+
273
+ def _agent_binary(venv: str | Path) -> Path:
274
+ binary = Path(venv).expanduser().absolute() / "bin" / "agent"
275
+ if not (binary.is_file() and os.access(binary, os.X_OK)):
276
+ raise ConfigError(f"no executable 'agent' in the venv: {binary} (pass --venv)")
277
+ retval = binary
278
+ return retval
279
+
280
+
281
+ def _plist(
282
+ label: str,
283
+ binary: Path,
284
+ command: str,
285
+ workspace: Path,
286
+ log_stem: str,
287
+ schedule: dict[str, Any],
288
+ keep_alive: bool = False,
289
+ ) -> dict[str, Any]:
290
+ logs = workspace / LOGS_DIRNAME
291
+ shell = f"exec {shlex.quote(str(binary))} {command} --workspace {shlex.quote(str(workspace))}"
292
+ retval = {
293
+ "Label": label,
294
+ "ProgramArguments": ["/bin/bash", "-lc", shell],
295
+ "WorkingDirectory": str(workspace),
296
+ "StandardOutPath": str(logs / f"{log_stem}.log"),
297
+ "StandardErrorPath": str(logs / f"{log_stem}.error.log"),
298
+ "RunAtLoad": True,
299
+ "KeepAlive": keep_alive,
300
+ MANAGED_KEY: True,
301
+ WORKSPACE_KEY: str(workspace),
302
+ **schedule,
303
+ }
304
+ return retval
305
+
306
+
307
+ def build_jobs(cfg: AgentConfig, label: str | None, venv: str | Path | None) -> list[Job]:
308
+ """Everything install needs, validated, with nothing written yet."""
309
+ job_label = label or default_label(cfg.agent)
310
+ _check_label(job_label)
311
+ binary = _agent_binary(venv if venv is not None else sys.prefix)
312
+
313
+ run_schedule = parse_schedule(cfg.raw.get("schedule"), f"{cfg.path}: 'schedule'")
314
+ jobs = [Job(job_label, _plist(job_label, binary, "run", cfg.workspace, "run", run_schedule))]
315
+
316
+ approvals = cfg.raw.get("approvals")
317
+ if approvals is not None:
318
+ if not isinstance(approvals, dict):
319
+ raise ConfigError(f"{cfg.path}: 'approvals' must be an object")
320
+ approvals_schedule = parse_schedule(
321
+ approvals.get("schedule", DEFAULT_APPROVALS_SCHEDULE), f"{cfg.path}: 'approvals.schedule'"
322
+ )
323
+ approvals_label = job_label + APPROVALS_LABEL_SUFFIX
324
+ jobs.append(
325
+ Job(
326
+ approvals_label,
327
+ _plist(approvals_label, binary, "approvals", cfg.workspace, "approvals", approvals_schedule),
328
+ )
329
+ )
330
+ if approvals.get("listen"):
331
+ # The one job that is not a clock. `agent approvals --listen` holds
332
+ # a Socket Mode connection (issue #74), so it has no interval and
333
+ # KeepAlive instead: launchd restarts it whenever it exits, which
334
+ # is how a dropped connection, a laptop waking up, or a crash
335
+ # becomes a reconnect without anyone watching.
336
+ listen_label = job_label + LISTEN_LABEL_SUFFIX
337
+ jobs.append(
338
+ Job(
339
+ listen_label,
340
+ _plist(
341
+ listen_label,
342
+ binary,
343
+ "approvals --listen",
344
+ cfg.workspace,
345
+ "approvals.listen",
346
+ {"ThrottleInterval": LISTEN_THROTTLE_SEC},
347
+ keep_alive=True,
348
+ ),
349
+ )
350
+ )
351
+ retval = jobs
352
+ return retval
353
+
354
+
355
+ def _require_macos() -> None:
356
+ if sys.platform != "darwin":
357
+ raise ScheduleError(
358
+ f"install-schedule writes launchd plists and only works on macOS (this is {sys.platform}); "
359
+ "schedule 'agent run --workspace <dir>' with your platform's scheduler instead"
360
+ )
361
+
362
+
363
+ def _domain() -> str:
364
+ retval = f"gui/{os.getuid()}"
365
+ return retval
366
+
367
+
368
+ def _launchctl(*args: str) -> subprocess.CompletedProcess:
369
+ retval = subprocess.run(["launchctl", *args], capture_output=True, text=True)
370
+ return retval
371
+
372
+
373
+ def _is_loaded(label: str) -> bool:
374
+ retval = _launchctl("print", f"{_domain()}/{label}").returncode == 0
375
+ return retval
376
+
377
+
378
+ def _bootout(label: str) -> bool:
379
+ """Unload `label` if it is loaded; True if it was. Waits until it is gone."""
380
+ was_loaded = _is_loaded(label)
381
+ if was_loaded:
382
+ result = _launchctl("bootout", f"{_domain()}/{label}")
383
+ if result.returncode != 0 and _is_loaded(label):
384
+ raise ScheduleError(f"launchctl bootout {_domain()}/{label} failed: {result.stderr.strip()}")
385
+ deadline = time.monotonic() + _BOOTOUT_WAIT_SECONDS
386
+ while _is_loaded(label):
387
+ if time.monotonic() > deadline:
388
+ raise ScheduleError(f"{_domain()}/{label} is still loaded {_BOOTOUT_WAIT_SECONDS}s after bootout")
389
+ time.sleep(_BOOTOUT_POLL_SECONDS)
390
+ retval = was_loaded
391
+ return retval
392
+
393
+
394
+ def _foreign_reason(label: str, workspace: Path) -> str | None:
395
+ """Why the job now at `label` is not this workspace's to touch, or None."""
396
+ path = _plist_path(label)
397
+ reason = None
398
+ if path.exists():
399
+ try:
400
+ existing = plistlib.loads(path.read_bytes())
401
+ except (ValueError, ExpatError) as exc:
402
+ existing = None
403
+ reason = f"{path} is not a readable plist ({exc})"
404
+ if isinstance(existing, dict):
405
+ owner = existing.get(WORKSPACE_KEY)
406
+ if existing.get(MANAGED_KEY) is not True:
407
+ reason = (
408
+ f"{path} was not written by agent install-schedule (no {MANAGED_KEY} key); "
409
+ f"it runs {existing.get('ProgramArguments')!r}"
410
+ )
411
+ elif owner != str(workspace):
412
+ reason = f"{path} belongs to workspace {owner}, not {workspace}"
413
+ elif reason is None:
414
+ reason = f"{path} is not a plist dictionary"
415
+ elif _is_loaded(label):
416
+ reason = (
417
+ f"{_domain()}/{label} is loaded but has no plist at {path}, so install-schedule did not load it "
418
+ f"(see launchctl print {_domain()}/{label})"
419
+ )
420
+ retval = reason
421
+ return retval
422
+
423
+
424
+ def _check_ownership(labels: list[str], workspace: Path, force: bool, verb: str) -> None:
425
+ """Refuse, before anything changes, to touch a job this workspace does not own."""
426
+ reasons = [reason for reason in (_foreign_reason(label, workspace) for label in labels) if reason]
427
+ if reasons and not force:
428
+ raise ScheduleError(
429
+ f"refusing to {verb} a job install-schedule does not own for this workspace: "
430
+ + "; ".join(reasons)
431
+ + ". Pass --force to take it over."
432
+ )
433
+ for reason in reasons:
434
+ print(f"agent: --force: taking over: {reason}", file=sys.stderr)
435
+
436
+
437
+ def _temp_beside(path: Path, label: str, data: bytes) -> Path:
438
+ """Write `data` to a new 0644 temporary file in `path`'s directory."""
439
+ path.parent.mkdir(parents=True, exist_ok=True)
440
+ fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{label}.", suffix=".plist.tmp")
441
+ tmp = Path(tmp_name)
442
+ try:
443
+ with os.fdopen(fd, "wb") as handle:
444
+ handle.write(data)
445
+ # mkstemp creates 0600; a plist holds no secret and is 0644 by convention.
446
+ tmp.chmod(0o644)
447
+ except BaseException:
448
+ tmp.unlink(missing_ok=True)
449
+ raise
450
+ retval = tmp
451
+ return retval
452
+
453
+
454
+ def _write_linted(job: Job) -> Path:
455
+ """Write the plist to a temporary file beside its destination and lint it."""
456
+ tmp = _temp_beside(job.path, job.label, plistlib.dumps(job.plist, sort_keys=True))
457
+ lint = subprocess.run(["plutil", "-lint", str(tmp)], capture_output=True, text=True)
458
+ if lint.returncode != 0:
459
+ tmp.unlink(missing_ok=True)
460
+ raise ScheduleError(f"plutil -lint rejected the plist for {job.label}: {lint.stdout.strip()} {lint.stderr.strip()}")
461
+ retval = tmp
462
+ return retval
463
+
464
+
465
+ def _restore(job: Job, previous: bytes) -> str:
466
+ """Put the previous plist back and load it; say how that went."""
467
+ try:
468
+ _bootout(job.label)
469
+ os.replace(_temp_beside(job.path, job.label, previous), job.path)
470
+ except (OSError, ScheduleError) as exc:
471
+ retval = f"restoring the previous job also failed ({exc}); {job.path} is not loaded"
472
+ return retval
473
+ result = _launchctl("bootstrap", _domain(), str(job.path))
474
+ if result.returncode == 0:
475
+ retval = f"the previous plist was restored to {job.path} and its job reloaded"
476
+ else:
477
+ retval = (
478
+ f"restoring the previous job also failed: launchctl bootstrap: {result.stderr.strip()}; "
479
+ f"{job.path} holds the previous plist, not loaded"
480
+ )
481
+ return retval
482
+
483
+
484
+ def _install_job(job: Job) -> None:
485
+ tmp = _write_linted(job)
486
+ previous = job.path.read_bytes() if job.path.exists() else None
487
+ try:
488
+ was_loaded = _bootout(job.label)
489
+ os.replace(tmp, job.path)
490
+ except BaseException:
491
+ tmp.unlink(missing_ok=True)
492
+ raise
493
+ result = _launchctl("bootstrap", _domain(), str(job.path))
494
+ if result.returncode != 0:
495
+ failure = f"launchctl bootstrap {_domain()} {job.path} failed: {result.stderr.strip()}"
496
+ if was_loaded and previous is not None:
497
+ raise ScheduleError(f"{failure}; {_restore(job, previous)}")
498
+ raise ScheduleError(
499
+ f"{failure}; no job was loaded before, so nothing was restored "
500
+ f"(the new plist is in place; fix the cause and re-run install-schedule)"
501
+ )
502
+ print(f"installed {job.label}: {job.path}")
503
+ print(f" check: launchctl print {_domain()}/{job.label}")
504
+
505
+
506
+ def _remove_job(label: str) -> bool:
507
+ """Boot out and delete `label`'s job; True if there was anything to remove."""
508
+ path = _plist_path(label)
509
+ was_loaded = _bootout(label)
510
+ had_file = path.exists()
511
+ if had_file:
512
+ path.unlink()
513
+ if was_loaded or had_file:
514
+ print(f"removed {label}: {path}")
515
+ retval = was_loaded or had_file
516
+ return retval
517
+
518
+
519
+ def render(job: Job) -> str:
520
+ retval = plistlib.dumps(job.plist, sort_keys=True).decode()
521
+ return retval
522
+
523
+
524
+ def install_schedule(workspace: str | Path, label: str | None, venv: str | Path | None, force: bool, dry_run: bool) -> int:
525
+ cfg = load_workspace(workspace)
526
+ jobs = build_jobs(cfg, label, venv)
527
+
528
+ if dry_run:
529
+ for job in jobs:
530
+ print(f"# {job.path}")
531
+ print(render(job), end="")
532
+ retval = 0
533
+ return retval
534
+
535
+ _require_macos()
536
+ # Remove what an earlier install made that this config no longer asks for:
537
+ # the approvals job when the block is gone, the listener when `listen` was
538
+ # turned off. Leaving either behind means a job firing for a config that
539
+ # does not describe it any more.
540
+ installed = {job.label for job in jobs}
541
+ stale = [
542
+ jobs[0].label + suffix
543
+ for suffix in (APPROVALS_LABEL_SUFFIX, LISTEN_LABEL_SUFFIX)
544
+ if jobs[0].label + suffix not in installed
545
+ ]
546
+ _check_ownership([job.label for job in jobs] + stale, cfg.workspace, force, "replace")
547
+ (cfg.workspace / LOGS_DIRNAME).mkdir(parents=True, exist_ok=True)
548
+ for job in jobs:
549
+ _install_job(job)
550
+ for name in stale:
551
+ _remove_job(name)
552
+ retval = 0
553
+ return retval
554
+
555
+
556
+ def uninstall_schedule(workspace: str | Path, label: str | None, force: bool) -> int:
557
+ if label is None:
558
+ label = default_label(load_workspace(workspace).agent)
559
+ _check_label(label)
560
+ _require_macos()
561
+
562
+ labels = [label, label + APPROVALS_LABEL_SUFFIX, label + LISTEN_LABEL_SUFFIX]
563
+ _check_ownership(labels, Path(workspace).expanduser().resolve(), force, "remove")
564
+ removed = [_remove_job(name) for name in labels]
565
+ if not any(removed):
566
+ raise ScheduleError(
567
+ f"nothing to uninstall: none of {', '.join(labels)} "
568
+ f"is loaded or has a plist in {LAUNCH_AGENTS_DIR} (pass --label if the install used one)"
569
+ )
570
+ retval = 0
571
+ return retval