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
@@ -0,0 +1,276 @@
1
+ """Calendar card: the events a digest's items announce, one click each to a calendar.
2
+
3
+ A community digest reads posts such as a weekly events announcement, and the
4
+ prose digest can say that the events exist but cannot hand them over. This is
5
+ the second message a `digest` destination posts after its digest when it has a
6
+ `calendar_card` block: one row per event, with the event's title linked to its
7
+ join URL, its start in the reader's time zone, and an "Add to calendar" button.
8
+
9
+ The button is a Google Calendar template link, so a click opens the event
10
+ prefilled and the reader saves it; nothing is created without that click, and
11
+ no listener or OAuth is involved. A link button works through an incoming
12
+ webhook. `guests` is a list of addresses the link adds as guests (Google's
13
+ `add` parameter), which is how one person puts an event on several of their
14
+ own calendars; Google asks whether to send the invitations when the event is
15
+ saved. The addresses are posted inside the link, so they are visible to
16
+ everyone in the channel the card goes to.
17
+
18
+ The model extracts and code computes. The model is asked for each event's title,
19
+ calendar date, wall-clock start and IANA time zone as written in the post, and
20
+ nothing else. The UTC instant, the displayed time and the link are built here,
21
+ because a calendar entry an hour off is worse than none, and a model writing a
22
+ `dates=` parameter would get one wrong eventually. A post rarely states a year
23
+ ("Wednesday, December 2"), so each item is shown to the model with the time it
24
+ was posted (`meta["posted"]`, when the source sets it). An event the model
25
+ returns in an unreadable shape, or dated outside a window around the run
26
+ (the sign of a wrong year), is dropped and counted on the card, never guessed. Posts rarely give an end time either, so every event lasts
27
+ `duration_minutes` (default 60), and the card says so.
28
+
29
+ Config, under the digest destination:
30
+
31
+ "calendar_card": {
32
+ "timezone": "America/Los_Angeles",
33
+ "duration_minutes": 60,
34
+ "guests": ["<you>@<domain>", "<you>@<other-domain>"],
35
+ "title": "Events"
36
+ }
37
+
38
+ `timezone` is required: it is the zone the card shows times in, and a default
39
+ would silently be someone else's.
40
+ """
41
+ from __future__ import annotations
42
+
43
+ import html
44
+ import json
45
+ import sys
46
+ from dataclasses import dataclass
47
+ from datetime import date, datetime, time, timedelta, timezone
48
+ from urllib.parse import urlencode, quote
49
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
50
+
51
+ from framework.interfaces import ScoredSignal
52
+ from framework.llm import LLMClient
53
+
54
+ _DECODER = json.JSONDecoder()
55
+
56
+ _SYSTEM = (
57
+ "You extract scheduled events from community posts. Reply with one JSON "
58
+ "object and nothing else -- no code fence, no commentary:\n"
59
+ '{"events": [{"title": "...", "date": "YYYY-MM-DD", "start": "HH:MM", '
60
+ '"timezone": "<IANA zone>", "url": "<join or event link, or empty>"}]}\n'
61
+ "Rules. Only events with a stated calendar date and start time; skip "
62
+ "anything vague (\"next week\", \"soon\"). `start` is the 24-hour wall-clock "
63
+ "time exactly as the post states it, in the zone the post states. "
64
+ "`timezone` is that zone as an IANA name: EST, EDT and ET are "
65
+ "America/New_York; PST, PDT and PT are America/Los_Angeles; CST/CT "
66
+ "America/Chicago; MST/MT America/Denver. When the post gives no year, use "
67
+ "the year that puts the event on or after the date the post was made. Do "
68
+ "not convert times between zones. List an event once even if the post "
69
+ "repeats it. No events: {\"events\": []}."
70
+ )
71
+
72
+ _RETRY_REMINDER = (
73
+ "\n\n---\n\nYour previous reply could not be read. Reply with one JSON object "
74
+ 'with an "events" list and nothing else.'
75
+ )
76
+
77
+ # US abbreviations a post writes and a model may hand back despite being asked
78
+ # for IANA names. Mapped here rather than trusted to the prompt, because `EST`
79
+ # and `MST` are valid zoneinfo keys -- fixed UTC-5 and UTC-7, with no daylight
80
+ # time -- so a model that passed "EST" through would put every summer event an
81
+ # hour off without any error.
82
+ _ABBREVIATIONS = {
83
+ "ET": "America/New_York", "EST": "America/New_York", "EDT": "America/New_York",
84
+ "CT": "America/Chicago", "CST": "America/Chicago", "CDT": "America/Chicago",
85
+ "MT": "America/Denver", "MST": "America/Denver", "MDT": "America/Denver",
86
+ "PT": "America/Los_Angeles", "PST": "America/Los_Angeles", "PDT": "America/Los_Angeles",
87
+ }
88
+
89
+ # The model resolves a year the post does not state, and the card does not
90
+ # show one, so an event outside this window around the run is taken as a wrong
91
+ # year and dropped rather than filed a year off.
92
+ _PAST = timedelta(days=2)
93
+ _FUTURE = timedelta(days=180)
94
+
95
+ # Slack allows 50 blocks per message: the header and the footnote take two.
96
+ _MAX_EVENTS = 48
97
+ _ITEM_CHARS = 4000
98
+
99
+
100
+ @dataclass
101
+ class Event:
102
+ title: str
103
+ start: datetime # aware
104
+ url: str
105
+
106
+
107
+ def _first_events_object(raw: str) -> dict | None:
108
+ retval = None
109
+ pos = raw.find("{")
110
+ while pos != -1 and retval is None:
111
+ try:
112
+ candidate, _end = _DECODER.raw_decode(raw, pos)
113
+ except ValueError:
114
+ candidate = None
115
+ if isinstance(candidate, dict) and isinstance(candidate.get("events"), list):
116
+ retval = candidate
117
+ pos = raw.find("{", pos + 1)
118
+ return retval
119
+
120
+
121
+ def _event(item: object, now: datetime) -> Event | None:
122
+ """One extracted event, or None if any field is unreadable or its date implausible.
123
+
124
+ Title and URL are unescaped: Slack sends `&`, `<` and `>` as entities in
125
+ message text, and the model copies them, so "Q&A" would reach the card
126
+ escaped twice and a link with two query parameters would break.
127
+ """
128
+ retval = None
129
+ if not isinstance(item, dict):
130
+ return retval
131
+ title = item.get("title")
132
+ url = item.get("url") or ""
133
+ if not isinstance(title, str) or not title.strip() or not isinstance(url, str):
134
+ return retval
135
+ zone_name = str(item.get("timezone")).strip()
136
+ zone_name = _ABBREVIATIONS.get(zone_name.upper(), zone_name)
137
+ try:
138
+ day = date.fromisoformat(str(item.get("date")))
139
+ clock = time.fromisoformat(str(item.get("start")))
140
+ zone = ZoneInfo(zone_name)
141
+ except (ValueError, ZoneInfoNotFoundError):
142
+ return retval
143
+ start = datetime.combine(day, clock, tzinfo=zone)
144
+ if not now - _PAST <= start <= now + _FUTURE:
145
+ return retval
146
+ url = html.unescape(url.strip())
147
+ if not url.startswith(("https://", "http://")):
148
+ url = ""
149
+ retval = Event(title=html.unescape(title.strip()), start=start, url=url)
150
+ return retval
151
+
152
+
153
+ def _mrkdwn_escape(text: str) -> str:
154
+ retval = text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
155
+ return retval
156
+
157
+
158
+ class CalendarCard:
159
+ def __init__(
160
+ self,
161
+ llm: LLMClient,
162
+ display_zone: ZoneInfo,
163
+ duration_minutes: int = 60,
164
+ guests: list[str] | None = None,
165
+ title: str = "Events",
166
+ ):
167
+ self.llm = llm
168
+ self.display_zone = display_zone
169
+ self.duration = timedelta(minutes=duration_minutes)
170
+ self.guests = guests or []
171
+ self.title = title
172
+
173
+ def _items(self, buffered: list[ScoredSignal]) -> str:
174
+ parts = []
175
+ for scored in buffered:
176
+ sig = scored.signal
177
+ posted = (sig.meta or {}).get("posted", "")
178
+ head = f"posted: {posted}\n" if posted else ""
179
+ parts.append(f"{head}{sig.text.strip()[:_ITEM_CHARS]}")
180
+ retval = "\n\n---\n\n".join(parts)
181
+ return retval
182
+
183
+ def extract(self, buffered: list[ScoredSignal]) -> tuple[list[Event], int]:
184
+ """The events the items announce, deduped and in time order, and how many were unreadable."""
185
+ user = self._items(buffered)
186
+ payload = _first_events_object(self.llm.complete(_SYSTEM, user))
187
+ if payload is None:
188
+ payload = _first_events_object(self.llm.complete(_SYSTEM, user + _RETRY_REMINDER))
189
+ if payload is None:
190
+ raise RuntimeError("calendar card: no JSON object with an 'events' list in the model reply, after one retry")
191
+ events: dict[tuple[str, datetime], Event] = {}
192
+ dropped = 0
193
+ now = datetime.now(timezone.utc)
194
+ for item in payload["events"]:
195
+ event = _event(item, now)
196
+ if event is None:
197
+ dropped += 1
198
+ continue
199
+ events.setdefault((event.title.lower(), event.start), event)
200
+ retval = (sorted(events.values(), key=lambda e: e.start), dropped)
201
+ return retval
202
+
203
+ def add_link(self, event: Event) -> str:
204
+ """A Google Calendar template link for `event`, guests included."""
205
+ start = event.start.astimezone(timezone.utc)
206
+ end = start + self.duration
207
+ params = {
208
+ "action": "TEMPLATE",
209
+ "text": event.title,
210
+ "dates": f"{start:%Y%m%dT%H%M%SZ}/{end:%Y%m%dT%H%M%SZ}",
211
+ }
212
+ if event.url:
213
+ params["details"] = event.url
214
+ params["location"] = event.url
215
+ if self.guests:
216
+ params["add"] = ",".join(self.guests)
217
+ retval = "https://calendar.google.com/calendar/render?" + urlencode(params, safe="/,@:", quote_via=quote)
218
+ return retval
219
+
220
+ def blocks(self, events: list[Event], dropped: int) -> list[dict]:
221
+ shown = events[:_MAX_EVENTS]
222
+ retval: list[dict] = [{"type": "header", "text": {"type": "plain_text", "text": self.title[:150]}}]
223
+ for i, event in enumerate(shown):
224
+ local = event.start.astimezone(self.display_zone)
225
+ when = f"{local:%a %b} {local.day}, {local:%I:%M %p %Z}".replace(" 0", " ")
226
+ name = _mrkdwn_escape(event.title)
227
+ label = f"*<{event.url}|{name}>*" if event.url else f"*{name}*"
228
+ retval.append(
229
+ {
230
+ "type": "section",
231
+ "text": {"type": "mrkdwn", "text": f"{label}\n{when}"},
232
+ "accessory": {
233
+ "type": "button",
234
+ "action_id": f"calendar-add-{i}",
235
+ "text": {"type": "plain_text", "text": "Add to calendar"},
236
+ "url": self.add_link(event),
237
+ },
238
+ }
239
+ )
240
+ notes = [f"Times in {self.display_zone.key}. Each event is entered as {int(self.duration.total_seconds() // 60)} min."]
241
+ if len(events) > len(shown):
242
+ notes.append(f"{len(events) - len(shown)} more not shown.")
243
+ if dropped:
244
+ notes.append(f"{dropped} event(s) unreadable and left out.")
245
+ retval.append({"type": "context", "elements": [{"type": "mrkdwn", "text": " ".join(notes)}]})
246
+ return retval
247
+
248
+
249
+ def warn(message: str) -> None:
250
+ print(f"calendar card: {message}", file=sys.stderr)
251
+
252
+
253
+ def build_calendar_card(cfg: dict, llm: LLMClient) -> CalendarCard:
254
+ zone_name = cfg.get("timezone")
255
+ if not zone_name:
256
+ raise RuntimeError("digest destination's 'calendar_card' needs a 'timezone' (IANA name) to show times in")
257
+ try:
258
+ zone = ZoneInfo(zone_name)
259
+ except ZoneInfoNotFoundError as exc:
260
+ raise RuntimeError(f"digest destination's 'calendar_card' timezone {zone_name!r} is not an IANA zone") from exc
261
+ guests = cfg.get("guests", [])
262
+ if not isinstance(guests, list) or not all(isinstance(g, str) and "@" in g for g in guests):
263
+ raise RuntimeError("digest destination's 'calendar_card' guests must be a list of email addresses")
264
+ guests = [g.strip() for g in guests]
265
+ duration = int(cfg.get("duration_minutes", 60))
266
+ if duration <= 0:
267
+ raise RuntimeError("digest destination's 'calendar_card' duration_minutes must be positive")
268
+ retval = CalendarCard(
269
+ llm=llm,
270
+ display_zone=zone,
271
+ duration_minutes=duration,
272
+ guests=guests,
273
+ title=cfg.get("title", "Events"),
274
+ )
275
+ return retval
276
+
framework/cli.py ADDED
@@ -0,0 +1,273 @@
1
+ """`agent run` — the entrypoint contract (issue #1).
2
+
3
+ Single invocation, single pass, exits 0 (success) / nonzero (failure). Safe to
4
+ double-run because the framework dedupes via SeenStore. No daemon, no loop:
5
+ cron/launchd owns the clock.
6
+
7
+ `agent run --workspace <dir>` is the whole interface (issue #43): the workspace
8
+ holds `config.json`, and dedupe state defaults to `<dir>/state/seen.json`.
9
+ `--config` is gone rather than deprecated. There is one caller per agent and it
10
+ is a plist line, so a deprecation shim would only hide the plist that was never
11
+ updated. Passing it exits 2 with a message that names `--workspace`.
12
+
13
+ `agent approvals --workspace <dir>` is the second entrypoint (issue #21): same
14
+ contract, its own clock, executes proposals a trusted human has replied to.
15
+ With `--listen` it is instead the one long-running entrypoint (issue #74): a
16
+ Socket Mode client acting on approval button clicks until it is killed.
17
+
18
+ `agent install-schedule` / `uninstall-schedule` (issue #10) write and remove the
19
+ launchd jobs that invoke those two; see `framework/schedule.py`.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import sys
25
+ import traceback
26
+ from pathlib import Path
27
+
28
+ from framework.approval_buttons import ListenerError, run_listener
29
+ from framework.approvals import load_approvals_config, run_approvals
30
+ from framework.config import STATE_DIRNAME, ConfigError, load_workspace
31
+ from framework.plugins import PluginImportFailure
32
+ from framework.registry import (
33
+ PluginImportError,
34
+ UnknownPluginError,
35
+ build_destination,
36
+ build_scorer,
37
+ build_source,
38
+ load_plugins,
39
+ )
40
+ from framework.runlog import timestamped
41
+ from framework.runner import run
42
+ from framework.schedule import ScheduleError, install_schedule, uninstall_schedule
43
+ from framework.state import SeenStore
44
+
45
+
46
+ class _RemovedConfigOption(argparse.Action):
47
+ """Reject `--config` with a message that says what replaced it."""
48
+
49
+ def __call__(self, parser, namespace, values, option_string=None):
50
+ parser.error(
51
+ "--config was removed; pass --workspace <dir> "
52
+ "and put the agent's config.json in that directory"
53
+ )
54
+
55
+
56
+ def _report_failed_plugins(failures: dict[str, PluginImportFailure]) -> None:
57
+ """Say on stderr which plugins are unavailable, before anything uses them.
58
+
59
+ A plugin that could not be imported is tolerated (issue #39) but never
60
+ silent: if the run later succeeds, this line is the only evidence that the
61
+ fleet is running on an incomplete venv, and if it dies at build time the
62
+ line sits directly above the error that names the same plugin.
63
+
64
+ Keyed by `type:` name, so one module maps to several entries; report each
65
+ module once.
66
+ """
67
+ by_module = {failure.module: failure for failure in failures.values()}
68
+ for module in sorted(by_module):
69
+ failure = by_module[module]
70
+ types = ", ".join(failure.types)
71
+ print(
72
+ f"agent: warning: plugin module {module!r} unavailable "
73
+ f"(types: {types}): {failure.error}",
74
+ file=sys.stderr,
75
+ )
76
+
77
+
78
+ # The exceptions `main()` turns into a one-line message and its own exit code.
79
+ # `_cmd_run` lets these through untouched: they mean no run happened, so there
80
+ # is no run log for them to belong to.
81
+ _MAIN_FORMATS = (ConfigError, ListenerError, UnknownPluginError, PluginImportError)
82
+
83
+
84
+ def _cmd_run(args: argparse.Namespace) -> int:
85
+ """Timestamp the whole run's output, then run (issue #139).
86
+
87
+ The wrapper goes around everything, not just `run()`, because a plugin that
88
+ failed to import is a fact about this run and lands in the same log as the
89
+ summary line.
90
+
91
+ A traceback needs printing from in here rather than being left to the
92
+ interpreter. The interpreter prints it only once the exception has left this
93
+ function, which is after the wrapper put the real streams back, so an
94
+ escaping exception would write the one part of a failed run that explains it
95
+ as the only untimed lines in the file. Printing it inside and exiting with
96
+ `SystemExit` keeps it timestamped and stops the interpreter printing it a
97
+ second time.
98
+
99
+ `Exception`, not `BaseException`: a `KeyboardInterrupt` or a `SystemExit`
100
+ says the run was ended on purpose, and reporting that as a failed run with
101
+ a traceback and exit 1 would lose the interrupt's own exit status and could
102
+ have a scheduler retry something a person had just stopped. Those two keep
103
+ their normal semantics, and the timestamped-traceback guarantee is for the
104
+ unexpected failures it was written for.
105
+ """
106
+ with timestamped():
107
+ try:
108
+ retval = _run_workspace(args)
109
+ except _MAIN_FORMATS:
110
+ raise
111
+ except Exception:
112
+ traceback.print_exc()
113
+ raise SystemExit(1)
114
+ return retval
115
+
116
+
117
+ def _run_workspace(args: argparse.Namespace) -> int:
118
+ cfg = load_workspace(args.workspace)
119
+
120
+ _report_failed_plugins(load_plugins())
121
+ # A source that keeps its own state (github-releases' fetch window) keeps
122
+ # it beside the dedupe state, so configs need not name the directory. The
123
+ # registry hands a factory only its own block, hence the injection.
124
+ cfg.source.setdefault("state_dir", str(cfg.workspace / STATE_DIRNAME))
125
+ source = build_source(cfg.source)
126
+ # The registry hands a factory only its own block (docs/PLUGIN-CONTRACT.md),
127
+ # so run-level paths are injected here: the approval destination keeps its
128
+ # proposals store in the workspace, and anything built on `framework.llm`
129
+ # needs the workspace (parked-vendor state) and the workspaces root (the
130
+ # shared `_shared/llm.json` waterfall).
131
+ for block in (cfg.scorer, cfg.destination):
132
+ block["_workspace"] = str(cfg.workspace)
133
+ block["_root"] = str(cfg.root)
134
+ scorer = build_scorer(cfg.scorer)
135
+ destination = build_destination(cfg.destination)
136
+
137
+ state_path = Path(args.state) if args.state else cfg.default_state_path
138
+ seen = SeenStore(state_path)
139
+
140
+ retval = run(source, scorer, destination, seen, cfg.agent)
141
+ return retval
142
+
143
+
144
+ def _cmd_approvals(args: argparse.Namespace) -> int:
145
+ cfg = load_approvals_config(args.workspace)
146
+ _report_failed_plugins(load_plugins())
147
+ if args.listen:
148
+ retval = run_listener(cfg)
149
+ return retval
150
+ retval = run_approvals(cfg)
151
+ return retval
152
+
153
+
154
+ def _cmd_install_schedule(args: argparse.Namespace) -> int:
155
+ retval = install_schedule(args.workspace, args.label, args.venv, args.force, args.dry_run)
156
+ return retval
157
+
158
+
159
+ def _cmd_uninstall_schedule(args: argparse.Namespace) -> int:
160
+ retval = uninstall_schedule(args.workspace, args.label, args.force)
161
+ return retval
162
+
163
+
164
+ def build_parser() -> argparse.ArgumentParser:
165
+ parser = argparse.ArgumentParser(prog="agent", description="Run a single-purpose signal agent.")
166
+ sub = parser.add_subparsers(dest="command", required=True)
167
+
168
+ run_parser = sub.add_parser("run", help="Run one pass of an agent and exit.")
169
+ run_parser.add_argument(
170
+ "--workspace",
171
+ required=True,
172
+ help="The agent's workspace directory; <dir>/config.json is loaded.",
173
+ )
174
+ run_parser.add_argument("--config", action=_RemovedConfigOption, help=argparse.SUPPRESS)
175
+ run_parser.add_argument(
176
+ "--state",
177
+ default=None,
178
+ help="Path to the dedupe state file (default: <workspace>/state/seen.json).",
179
+ )
180
+ run_parser.set_defaults(func=_cmd_run)
181
+
182
+ approvals_parser = sub.add_parser(
183
+ "approvals",
184
+ help="Execute proposals a trusted user has replied 'do <id>' to, and exit.",
185
+ )
186
+ approvals_parser.add_argument(
187
+ "--workspace",
188
+ required=True,
189
+ help="The agent's workspace directory; <dir>/config.json and <dir>/state/proposals.json.",
190
+ )
191
+ approvals_parser.add_argument(
192
+ "--listen",
193
+ action="store_true",
194
+ help=(
195
+ "Hold a Socket Mode connection and act on approval button clicks until killed "
196
+ "(long-running; needs approvals.app_token_env). Without it, one polling pass."
197
+ ),
198
+ )
199
+ approvals_parser.set_defaults(func=_cmd_approvals)
200
+
201
+ install_parser = sub.add_parser(
202
+ "install-schedule",
203
+ help="Write and load the workspace's launchd plist(s) (macOS).",
204
+ )
205
+ install_parser.add_argument(
206
+ "--workspace",
207
+ required=True,
208
+ help="The agent's workspace directory; its config.json supplies 'agent' and 'schedule'.",
209
+ )
210
+ install_parser.add_argument(
211
+ "--label",
212
+ default=None,
213
+ help=(
214
+ "launchd label (default: com.agents.<agent>); the approvals job is "
215
+ "<label>.approvals and the button listener <label>.approvals.listen."
216
+ ),
217
+ )
218
+ install_parser.add_argument(
219
+ "--venv",
220
+ default=None,
221
+ help="Venv whose bin/agent the job runs (default: the venv running this command).",
222
+ )
223
+ install_parser.add_argument(
224
+ "--force",
225
+ action="store_true",
226
+ help="Replace a job at the label that this workspace's install-schedule did not write.",
227
+ )
228
+ install_parser.add_argument(
229
+ "--dry-run",
230
+ action="store_true",
231
+ help="Print the plist(s) and do nothing else.",
232
+ )
233
+ install_parser.set_defaults(func=_cmd_install_schedule)
234
+
235
+ uninstall_parser = sub.add_parser(
236
+ "uninstall-schedule",
237
+ help="Unload and delete the workspace's launchd plist(s) (macOS).",
238
+ )
239
+ uninstall_parser.add_argument(
240
+ "--workspace",
241
+ required=True,
242
+ help="The agent's workspace directory; config.json is read only for the default label.",
243
+ )
244
+ uninstall_parser.add_argument(
245
+ "--label",
246
+ default=None,
247
+ help="launchd label the install used (default: com.agents.<agent>).",
248
+ )
249
+ uninstall_parser.add_argument(
250
+ "--force",
251
+ action="store_true",
252
+ help="Remove a job at the label that this workspace's install-schedule did not write.",
253
+ )
254
+ uninstall_parser.set_defaults(func=_cmd_uninstall_schedule)
255
+ return parser
256
+
257
+
258
+ def main(argv: list[str] | None = None) -> int:
259
+ parser = build_parser()
260
+ args = parser.parse_args(argv)
261
+ try:
262
+ retval = args.func(args)
263
+ except _MAIN_FORMATS as exc:
264
+ print(f"agent: {exc}", file=sys.stderr)
265
+ return 2
266
+ except ScheduleError as exc:
267
+ print(f"agent: {exc}", file=sys.stderr)
268
+ retval = 1
269
+ return retval
270
+
271
+
272
+ if __name__ == "__main__":
273
+ sys.exit(main())