cli-watch-kit 0.1.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.
@@ -0,0 +1,195 @@
1
+ """Choosing the events stream: stdout, or messages into the Claude Code session that started the watcher.
2
+
3
+ The `claude-message` stream needs cc-blackbox, which this module imports only when it is used, from the
4
+ `claude-code` extra (`pip install 'cli-watch-kit[claude-code]'`). cc-blackbox finds the session, checks that its
5
+ messaging protocol is one it speaks, batches the events that arrive within 3 s into one message, caps a message at
6
+ 64 KB, keeps below the session's rate limit, notices when the session is gone, and moves the events to stdout when
7
+ messaging stops working. Without the extra, `auto` falls back to stdout and says which extra to install.
8
+
9
+ Each message is a `<{envelope_tag} resource="..." seq="...">` block for one resource, sent as `<app>:<pid>` under a
10
+ sender name the app chooses. Only the message with `watch_started` names the resource dir and the changelog.
11
+ Delivery is best effort: the receiver may rate-limit a message, or hold it until its user approves it. The changelog
12
+ always has every event.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import importlib.util
18
+ import os
19
+ import time
20
+ from collections.abc import Callable, Mapping
21
+ from dataclasses import dataclass
22
+ from importlib import metadata
23
+ from pathlib import Path
24
+ from typing import TYPE_CHECKING, Any, cast
25
+
26
+ from cli_watch_kit.events import WATCH_ENDED, WATCH_STARTED, Event
27
+ from cli_watch_kit.sinks import Sink, StatusOutput, StdoutSink
28
+
29
+ if TYPE_CHECKING:
30
+ from cc_blackbox import ActiveSession, EventEnvelope, RateLimitedSender
31
+
32
+ from cli_watch_kit.app import WatchApp
33
+
34
+ EXTRA = "claude-code"
35
+ REQUIRED = "cc-blackbox>=0.11,<0.13"
36
+ INSTALL_HINT = "install the claude-code extra of cli-watch-kit (cc-blackbox) to message the session"
37
+ STREAM_MODES: tuple[str, ...] = ("auto", "stdout", "claude-message")
38
+ MESSAGE_PRIORITIES: tuple[str, ...] = ("now", "next", "later")
39
+
40
+
41
+ class StreamError(RuntimeError):
42
+ pass
43
+
44
+
45
+ def claude_code_problem() -> str | None:
46
+ """Why the `claude-code` extra cannot be used, or `None` when it can: cc-blackbox is missing, or another
47
+ version than the extra pins is installed and lacks what this module imports."""
48
+ try:
49
+ missing = importlib.util.find_spec("cc_blackbox") is None
50
+ except ValueError: # imported already, without a spec
51
+ missing = False
52
+ if missing:
53
+ return INSTALL_HINT
54
+ try:
55
+ from cc_blackbox import ( # noqa: F401
56
+ EventEnvelope,
57
+ EventStreamMode,
58
+ MessageEventSink,
59
+ MessagingUnavailable,
60
+ choose_event_stream,
61
+ current_session_or_none,
62
+ )
63
+ except ImportError:
64
+ try:
65
+ found = metadata.version("cc-blackbox")
66
+ except metadata.PackageNotFoundError:
67
+ found = "of an unknown version"
68
+ return (
69
+ f"the installed cc-blackbox {found} does not fit; the claude-code extra of cli-watch-kit needs {REQUIRED}"
70
+ )
71
+ return None
72
+
73
+
74
+ def claude_code_available() -> bool:
75
+ """Whether the `claude-code` extra is installed and fits."""
76
+ return claude_code_problem() is None
77
+
78
+
79
+ def find_session() -> ActiveSession | None:
80
+ """The Claude Code session this process runs under, or `None`, also when the extra is not usable."""
81
+ if not claude_code_available():
82
+ return None
83
+ from cc_blackbox import current_session_or_none
84
+
85
+ return current_session_or_none()
86
+
87
+
88
+ def _under_claude_code() -> bool:
89
+ return bool(os.environ.get("CLAUDE_CODE_MESSAGING_SOCKET") or os.environ.get("CLAUDECODE"))
90
+
91
+
92
+ @dataclass
93
+ class Stream:
94
+ sink: Sink
95
+ fallback: str | None = None
96
+ """Why `auto` picked stdout although the watcher runs under a Claude Code session; printed in the header."""
97
+
98
+
99
+ def open_stream(
100
+ app: WatchApp,
101
+ mode: str,
102
+ *,
103
+ session: ActiveSession | None,
104
+ resource: str,
105
+ sender_name: str,
106
+ changelog: Path,
107
+ priority: str,
108
+ status: StatusOutput,
109
+ ) -> Stream:
110
+ """The sink for `mode`. `session` is :func:`find_session`'s answer; `changelog` the watcher's events file."""
111
+ if mode not in STREAM_MODES:
112
+ raise StreamError(f"--events-stream must be one of {', '.join(STREAM_MODES)}")
113
+ if priority not in MESSAGE_PRIORITIES:
114
+ raise StreamError(f"--message-priority must be one of {', '.join(MESSAGE_PRIORITIES)}")
115
+ if mode == "stdout":
116
+ return Stream(StdoutSink())
117
+ problem = claude_code_problem()
118
+ if problem is not None:
119
+ if mode == "claude-message":
120
+ raise StreamError(f"--events-stream=claude-message is not possible: {problem}")
121
+ return Stream(StdoutSink(), problem if _under_claude_code() else None)
122
+ from cc_blackbox import EventStreamMode, MessagingUnavailable, choose_event_stream
123
+
124
+ try:
125
+ choice = choose_event_stream(cast(EventStreamMode, mode), session)
126
+ except MessagingUnavailable as exc:
127
+ raise StreamError(f"--events-stream=claude-message is not possible: {exc}; use --events-stream=stdout") from exc
128
+ if choice.mode == "claude-message" and choice.session is not None:
129
+ sink = claude_message_sink(app, choice.session, resource, sender_name, changelog, priority, status)
130
+ return Stream(sink)
131
+ return Stream(StdoutSink(), choice.fallback)
132
+
133
+
134
+ def _event_payload(event: Event) -> Mapping[str, Any]:
135
+ """An event as a message line: the envelope already names the resource, and the time is of no use there."""
136
+ payload: dict[str, object] = {"kind": event.kind, "seq": event.seq, "data": event.data}
137
+ if event.artifacts:
138
+ payload["artifacts"] = list(event.artifacts)
139
+ return payload
140
+
141
+
142
+ def _without_announced_dir(event: Event, directory: Path) -> Event:
143
+ """`watch_started` as the announcing message shows it: the head names the dir, so the summary does not repeat it."""
144
+ summary = event.data.get("summary")
145
+ if event.kind != WATCH_STARTED or not isinstance(summary, dict):
146
+ return event
147
+ summary = {k: v for k, v in summary.items() if not (k == "dir" and v == str(directory))}
148
+ return Event(event.kind, event.resource, event.seq, event.observed_at, {**event.data, "summary": summary})
149
+
150
+
151
+ def message_envelope(app: WatchApp, resource: str, changelog: Path) -> EventEnvelope[Event]:
152
+ """`<tag resource="…" seq="…">`. The message with `watch_started` also names the resource dir and the changelog.
153
+ Above 64 KB the body becomes a count per kind that points at the changelog."""
154
+ from cc_blackbox import EventEnvelope
155
+
156
+ return EventEnvelope(
157
+ app.envelope_tag,
158
+ {"resource": resource},
159
+ payload=_event_payload,
160
+ announce_on=WATCH_STARTED,
161
+ announce_attributes={"dir": str(changelog.parent), "changelog": str(changelog)},
162
+ announced=lambda event: _without_announced_dir(event, changelog.parent),
163
+ record=str(changelog),
164
+ )
165
+
166
+
167
+ def claude_message_sink(
168
+ app: WatchApp,
169
+ session: ActiveSession,
170
+ resource: str,
171
+ sender_name: str,
172
+ changelog: Path,
173
+ priority: str,
174
+ status: StatusOutput,
175
+ *,
176
+ rate_limiter: RateLimitedSender | None = None,
177
+ clock: Callable[[], float] = time.monotonic,
178
+ session_alive: Callable[[], bool] | None = None,
179
+ ) -> Sink:
180
+ """The sink for one watched resource. `watch_ended` goes out at once, so the session learns the end without the
181
+ 3 s burst wait."""
182
+ from cc_blackbox import MessageEventSink, Priority
183
+
184
+ return MessageEventSink(
185
+ session,
186
+ message_envelope(app, resource, changelog),
187
+ sender=f"{app.name}:{os.getpid()}",
188
+ sender_name=sender_name,
189
+ status=status.line,
190
+ priority=cast(Priority, priority),
191
+ flush_on={WATCH_ENDED},
192
+ rate_limiter=rate_limiter,
193
+ clock=clock,
194
+ session_alive=session_alive,
195
+ )
cli_watch_kit/cli.py ADDED
@@ -0,0 +1,410 @@
1
+ """click helpers: the common options of a watch command, the run of one watch, and the `daemon` command group.
2
+
3
+ A CLI declares its own watch commands (what to watch, its arguments) and hands the rest to :func:`run_watch`:
4
+
5
+ ```python
6
+ @watch.command()
7
+ @click.argument("issue_id")
8
+ @watch_options
9
+ def issue(issue_id: str, options: WatchOptions) -> None:
10
+ raise SystemExit(run_watch(APP, Target("issue", issue_id), options, params={"api_key": key()}))
11
+
12
+ watch.add_command(daemon_group(APP))
13
+ ```
14
+
15
+ The core takes a plain :class:`WatchOptions`, so a CLI on another framework fills it from its own options.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import functools
21
+ import json
22
+ import sys
23
+ from collections.abc import Callable, Iterable, Mapping, Sequence
24
+ from dataclasses import dataclass, fields
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ import click
29
+
30
+ from cli_watch_kit.app import WatchApp
31
+ from cli_watch_kit.changelog import Changelog
32
+ from cli_watch_kit.claude import MESSAGE_PRIORITIES, STREAM_MODES, StreamError, find_session, open_stream
33
+ from cli_watch_kit.client import Backend, Watcher, WatchSettings, Writer, WriterContext, default_backend
34
+ from cli_watch_kit.daemon.lifecycle import daemon_running, stop_daemon
35
+ from cli_watch_kit.daemon.transport import DaemonFiles, DaemonTimeout, DaemonUnavailable, request
36
+ from cli_watch_kit.durations import format_duration, parse_duration
37
+ from cli_watch_kit.events import LIFECYCLE_KINDS, FilterError
38
+ from cli_watch_kit.locks import FileLock
39
+ from cli_watch_kit.paths import sanitize_part
40
+ from cli_watch_kit.sinks import Sink, StatusOutput
41
+ from cli_watch_kit.source import Target
42
+ from cli_watch_kit.timers import ClientTimer
43
+
44
+ EXIT_USAGE = 2
45
+ DIR_LOCK = ".watcher.lock"
46
+ """The lock file in a resource dir that keeps a second watcher of the same resource out of it."""
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class WatchOptions:
51
+ """The options every watch command shares."""
52
+
53
+ events: tuple[str, ...] = ()
54
+ exclude_events: tuple[str, ...] = ()
55
+ until: str | None = None
56
+ timeout: str | None = None
57
+ idle_after: str | None = None
58
+ events_stream: str = "auto"
59
+ message_priority: str = "next"
60
+ base_dir: Path | None = None
61
+ no_daemon: bool = False
62
+
63
+
64
+ _OPTION_NAMES = [f.name for f in fields(WatchOptions)]
65
+
66
+ _OPTIONS: list[Callable[[Any], Any]] = [
67
+ click.option(
68
+ "--events",
69
+ "events",
70
+ multiple=True,
71
+ help="Report only these event kinds or groups, comma-separated or repeated.",
72
+ ),
73
+ click.option(
74
+ "--exclude-events",
75
+ "exclude_events",
76
+ multiple=True,
77
+ help="Do not report these event kinds or groups, comma-separated or repeated.",
78
+ ),
79
+ click.option("--until", help="Stop after the first event of this kind."),
80
+ click.option("--timeout", help="Stop after this long, for example 90s, 30m, 2h, 1h30m."),
81
+ click.option(
82
+ "--idle-after",
83
+ help="Stop when nothing was reported for this long, for example 3h. Every reported event starts the count "
84
+ "again; threshold events do not.",
85
+ ),
86
+ click.option(
87
+ "--events-stream",
88
+ type=click.Choice(STREAM_MODES),
89
+ default="auto",
90
+ show_default=True,
91
+ help="auto picks claude-message inside a Claude Code session that accepts messages, else stdout.",
92
+ ),
93
+ click.option(
94
+ "--message-priority",
95
+ type=click.Choice(MESSAGE_PRIORITIES),
96
+ default="next",
97
+ show_default=True,
98
+ help="claude-message only: now or next deliver into the running turn, later waits until the session is idle.",
99
+ ),
100
+ click.option(
101
+ "--base-dir",
102
+ type=click.Path(file_okay=False, path_type=Path),
103
+ help="Where the resource dirs go (events.jsonl, baseline.json). Default: <session scratchpad>/<app> under "
104
+ "Claude Code, else <temp dir>/<app>-<uid>.",
105
+ ),
106
+ click.option(
107
+ "--no-daemon", is_flag=True, help="Poll inside this process with a private budget, without the daemon."
108
+ ),
109
+ ]
110
+
111
+
112
+ def watch_options[F: Callable[..., Any]](func: F) -> F:
113
+ """Add the common options to a click command; the command gets them as one `options: WatchOptions` argument."""
114
+
115
+ @functools.wraps(func)
116
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
117
+ values = {name: kwargs.pop(name) for name in _OPTION_NAMES if name in kwargs}
118
+ values["events"] = tuple(values.get("events") or ())
119
+ values["exclude_events"] = tuple(values.get("exclude_events") or ())
120
+ return func(*args, options=WatchOptions(**values), **kwargs)
121
+
122
+ decorated: Any = wrapper
123
+ for option in reversed(_OPTIONS):
124
+ decorated = option(decorated)
125
+ return decorated # type: ignore[no-any-return]
126
+
127
+
128
+ class _Usage(Exception):
129
+ def __init__(self, message: str, code: int = EXIT_USAGE) -> None:
130
+ super().__init__(message)
131
+ self.code = code
132
+
133
+
134
+ def _duration(option: str, value: str | None) -> float | None:
135
+ if value is None:
136
+ return None
137
+ try:
138
+ seconds = parse_duration(value)
139
+ except ValueError as exc:
140
+ raise _Usage(f"{option}: {exc}") from exc
141
+ if seconds <= 0:
142
+ raise _Usage(f"{option}: the duration must be longer than zero")
143
+ return seconds
144
+
145
+
146
+ def default_resource_dir(base: Path, target: Target) -> Path:
147
+ """`<base>/<kind>/<id>`, each part made safe for a path."""
148
+ return base / sanitize_part(target.kind) / sanitize_part(target.id)
149
+
150
+
151
+ def run_watch(
152
+ app: WatchApp,
153
+ target: Target,
154
+ options: WatchOptions,
155
+ *,
156
+ params: Mapping[str, Any] | None = None,
157
+ source_options: Mapping[str, Any] | None = None,
158
+ enabled_thresholds: Iterable[str] = (),
159
+ also_subscribe: Iterable[str] = (),
160
+ timers: Sequence[ClientTimer] = (),
161
+ writer: Callable[[WriterContext], Writer] | None = None,
162
+ resource_dir: Callable[[Path, Target], Path] = default_resource_dir,
163
+ readme: str | None = None,
164
+ sender_name: str | None = None,
165
+ restart: str | None = None,
166
+ header: Sequence[str] = (),
167
+ status: StatusOutput | None = None,
168
+ ) -> int:
169
+ """Run one watch of `target` to its end and return the exit code: 0, 1 for an error, 2 for a usage error.
170
+
171
+ - `params` go with the subscription to the daemon (an API key, for example), and so do `source_options`, which
172
+ the source checks with `Source.check_options` and gets in `PollItem.options` (glab's `--logs` mode).
173
+ - `enabled_thresholds` are the threshold kinds whose option was given; `timers` compute them. `also_subscribe`
174
+ names kinds the daemon should track although the watcher does not report them, because a timer reads what
175
+ they put into the snapshot (glab's `quiet` reads the head pipeline's status).
176
+ - `writer` makes the app's writer of the resource dir from a :class:`WriterContext`.
177
+ - Only one watcher at a time writes a resource dir. A second watcher of the same target into the same base dir
178
+ exits with 1 and says so; give it its own `--base-dir` to run both.
179
+ - `sender_name` is what Claude Code shows as the sender (default: `<command> <target key>`), `restart` the
180
+ command line that watches the same target again (default: `<command> <kind> <id>`), `header` extra header lines.
181
+ """
182
+ status = status or StatusOutput(app.status_prefix)
183
+ source = app.make_source()
184
+ catalog = source.catalog
185
+ try:
186
+ selected = catalog.resolve(target.kind, options.events, options.exclude_events, enabled_thresholds)
187
+ if options.until is not None and options.until not in catalog.produced(target.kind):
188
+ raise _Usage(f"--until: a {target.kind} watch never produces {options.until!r}")
189
+ if options.until is not None and options.until not in selected:
190
+ raise _Usage(f"--until={options.until} is filtered out by --events/--exclude-events")
191
+ extra = frozenset(also_subscribe)
192
+ if extra - set(catalog.produced(target.kind)):
193
+ unknown = ", ".join(sorted(extra - set(catalog.produced(target.kind))))
194
+ raise _Usage(f"a {target.kind} watch never produces {unknown}, so it cannot also subscribe to it")
195
+ timeout = _duration("--timeout", options.timeout)
196
+ idle_after = _duration("--idle-after", options.idle_after)
197
+ session = find_session() if options.events_stream != "stdout" else None
198
+ scratchpad = getattr(session, "scratchpad_dir", None) if session is not None else None
199
+ base = app.paths.base_dir(options.base_dir, scratchpad)
200
+ changelog = Changelog(resource_dir(base, target), target.key, readme)
201
+ stream = open_stream(
202
+ app,
203
+ options.events_stream,
204
+ session=session,
205
+ resource=target.key,
206
+ sender_name=sender_name or f"{app.command} {target.key}",
207
+ changelog=changelog.events_path,
208
+ priority=options.message_priority,
209
+ status=status,
210
+ )
211
+ except (FilterError, StreamError, _Usage) as exc:
212
+ status.line(f"error: {exc}")
213
+ return exc.code if isinstance(exc, _Usage) else EXIT_USAGE
214
+ # One watcher per resource dir: two would interleave their seq numbers in one events.jsonl and overwrite each
215
+ # other's baseline. The OS releases the lock when the watcher dies.
216
+ changelog.dir.mkdir(parents=True, exist_ok=True)
217
+ dir_lock = FileLock(changelog.dir / DIR_LOCK)
218
+ if not dir_lock.try_acquire():
219
+ status.line(
220
+ f"error: another watcher already watches {target.key} into {changelog.dir}; stop that one first, or give"
221
+ " this one its own --base-dir"
222
+ )
223
+ return 1
224
+ try:
225
+ try:
226
+ backend = default_backend(app, options.no_daemon)
227
+ except (DaemonUnavailable, TimeoutError) as exc:
228
+ status.line(f"error: cannot start the daemon: {exc}; retry with --no-daemon to poll without it")
229
+ return 1
230
+ thresholds = [d for t in timers if (d := t.describe())]
231
+ print_header(
232
+ status,
233
+ app,
234
+ target,
235
+ stream.sink,
236
+ changelog,
237
+ selected,
238
+ backend,
239
+ until=options.until,
240
+ timeout=options.timeout,
241
+ idle_after=idle_after,
242
+ fallback=stream.fallback,
243
+ thresholds=thresholds,
244
+ restart=restart or f"{app.command} {target.kind} {target.id}",
245
+ extra=header,
246
+ )
247
+ settings = WatchSettings(
248
+ target,
249
+ selected,
250
+ until=options.until,
251
+ timeout=timeout,
252
+ idle_after=idle_after,
253
+ params=dict(params or {}),
254
+ source_options=dict(source_options or {}),
255
+ threshold_kinds=frozenset(catalog.thresholds),
256
+ subscribed=catalog.daemon_kinds(selected) | catalog.daemon_kinds(extra),
257
+ )
258
+ watcher = Watcher(
259
+ settings,
260
+ backend,
261
+ stream.sink,
262
+ changelog,
263
+ status,
264
+ writer=writer(WriterContext(base, changelog.dir, target, backend, status)) if writer is not None else None,
265
+ timers=timers,
266
+ )
267
+ try:
268
+ return watcher.run()
269
+ finally:
270
+ backend.close()
271
+ finally:
272
+ dir_lock.release()
273
+
274
+
275
+ def print_header(
276
+ status: StatusOutput,
277
+ app: WatchApp,
278
+ target: Target,
279
+ sink: Sink,
280
+ changelog: Changelog,
281
+ events: frozenset[str],
282
+ backend: Backend,
283
+ *,
284
+ until: str | None = None,
285
+ timeout: str | None = None,
286
+ idle_after: float | None = None,
287
+ fallback: str | None = None,
288
+ thresholds: Sequence[str] = (),
289
+ restart: str | None = None,
290
+ extra: Sequence[str] = (),
291
+ ) -> None:
292
+ """The startup header: what is watched, how events are delivered, and how to restart with other options."""
293
+ catalog = app.make_source().catalog
294
+ # A threshold kind without its option is not tracked at all, rather than ignored.
295
+ tracked = [k for k in catalog.produced(target.kind) if k not in catalog.thresholds or k in events]
296
+ subscribed = [k for k in tracked if k in events]
297
+ ignored = [k for k in tracked if k not in events]
298
+ status.line(f"resource: {target.key}")
299
+ status.line(f"stream: {sink.describe()}")
300
+ if fallback:
301
+ status.line(f"stream fallback: not messaging the Claude Code session: {fallback}")
302
+ status.line(f"dir: {changelog.dir}")
303
+ status.line(f"changelog: {changelog.events_path}")
304
+ for line in extra:
305
+ status.line(line)
306
+ status.line(f"events: {','.join(subscribed) or '(none)'} (always: {','.join(LIFECYCLE_KINDS)})")
307
+ status.line(f"ignored: {','.join(ignored) or '(none)'}")
308
+ if thresholds:
309
+ status.line(f"thresholds: {'; '.join(thresholds)}")
310
+ ends = [f"on {until}"] if until else []
311
+ ends += [f"after {timeout}"] if timeout else []
312
+ ends += [f"after {format_duration(idle_after)} without an event"] if idle_after else []
313
+ if ends:
314
+ status.line(f"ends: {' or '.join(ends)}")
315
+ status.line(f"daemon: {backend.describe()}")
316
+ groups = ", ".join(catalog.groups_for(target.kind))
317
+ if restart:
318
+ options = "--events=<kinds|groups> --exclude-events=<kinds|groups>"
319
+ status.line(f"restart with: {restart} {options} (groups: {groups or 'none'})")
320
+
321
+
322
+ def daemon_group(app: WatchApp, name: str = "daemon") -> click.Group:
323
+ """`daemon status|stop|logs` for the app's daemon."""
324
+
325
+ @click.group(name, help="Inspect or stop the shared polling daemon.")
326
+ def group() -> None:
327
+ pass
328
+
329
+ @group.command("status")
330
+ @click.option("--json", "as_json", is_flag=True, help="Print the raw status object.")
331
+ def status(as_json: bool) -> None:
332
+ """Show the daemon's subscriptions, resources, accounts and budgets."""
333
+ files = DaemonFiles.for_app(app)
334
+ try:
335
+ response = request(files, {"op": "status"}, timeout=5)
336
+ except (DaemonUnavailable, DaemonTimeout):
337
+ if not daemon_running(files):
338
+ click.echo("daemon: not running")
339
+ sys.exit(0)
340
+ pid = files.owner_pid()
341
+ click.echo(
342
+ f"daemon: running (pid {pid if pid is not None else 'unknown'}) but not answering; see"
343
+ f" `{app.command} daemon logs`, and `{app.command} daemon stop` ends it"
344
+ )
345
+ sys.exit(1)
346
+ if as_json:
347
+ click.echo(json.dumps(response, indent=2))
348
+ return
349
+ for line in format_status(response, files):
350
+ click.echo(line)
351
+
352
+ @group.command("stop")
353
+ def stop() -> None:
354
+ """Stop the daemon. Running watchers start a new one on their next poll."""
355
+ files = DaemonFiles.for_app(app)
356
+ try:
357
+ # A daemon that does not stop by itself (a hung one) is killed, once its pid is verified.
358
+ stopped = stop_daemon(files, app.env_float("STOP_TIMEOUT", 10.0), kill=app)
359
+ except DaemonUnavailable as exc:
360
+ StatusOutput(app.status_prefix).line(f"error: {exc}")
361
+ sys.exit(1)
362
+ click.echo("daemon: stopped" if stopped else "daemon: not running")
363
+
364
+ @group.command("logs")
365
+ @click.option("--lines", "-n", default=50, show_default=True, help="How many lines from the end.")
366
+ def logs(lines: int) -> None:
367
+ """Print the end of the daemon's log file."""
368
+ files = DaemonFiles.for_app(app)
369
+ try:
370
+ content = files.log.read_text(encoding="utf-8", errors="replace").splitlines()
371
+ except FileNotFoundError:
372
+ click.echo(f"no daemon log at {files.log}")
373
+ return
374
+ click.echo(f"==> {files.log}")
375
+ for line in content[-lines:]:
376
+ click.echo(line)
377
+
378
+ return group
379
+
380
+
381
+ def format_status(status: Mapping[str, Any], files: DaemonFiles) -> list[str]:
382
+ """The daemon status as text lines."""
383
+ lines = [
384
+ f"daemon: pid {status.get('pid')}, {status.get('app')} {status.get('app_version')}, cli-watch-kit"
385
+ f" {status.get('lib_version')}, protocols {status.get('lib_protocol')}/{status.get('app_protocol')},"
386
+ f" up {status.get('uptime_s')} s, endpoint {files.describe_endpoint()}"
387
+ ]
388
+ for sub in status.get("subscriptions", []):
389
+ lines.append(
390
+ f"subscription {sub['id'][:8]} client {sub['client_id'][:8]} {sub['resource']}"
391
+ f" (account {sub['account'] or '-'}, lease idle {sub['idle_s']} s)"
392
+ )
393
+ for res in status.get("resources", []):
394
+ state = "ended" if res["ended"] else (f"degraded: {res['degraded']}" if res["degraded"] else "active")
395
+ lines.append(
396
+ f"resource {res['resource']}: {state}, {res['polls']} polls, seq {res['seq']},"
397
+ f" next poll in {res['next_poll_in_s']} s"
398
+ )
399
+ for name, account in status.get("accounts", {}).items():
400
+ dims = ", ".join(
401
+ f"{dim} {info['rate_per_minute']}/min (remaining {info['remaining']})"
402
+ for dim, info in account["budget"]["dimensions"].items()
403
+ )
404
+ lines.append(
405
+ f"account {name or '-'}: {account['calls']} calls for {account['items']} items,"
406
+ f" stretch {account['stretch']}, {dims}"
407
+ )
408
+ if status.get("source"):
409
+ lines.append(f"source: {json.dumps(status['source'], separators=(',', ':'))}")
410
+ return lines