cli-watch-kit
A library for building a watch command into a CLI. The CLI says how to poll its API and how to diff two snapshots into events; the library does the rest:
- one JSON event per line on stdout (or a message into the Claude Code session that started the watch), with a status header on stderr;
--events/--exclude-eventsfilters with groups,--until,--timeout,--idle-after, and the app's own threshold events computed from time;- a changelog (
events.jsonl) and a baseline per watched resource, so a watcher resumes its numbering and never reports a change twice; - one shared daemon per user and app that polls each resource once for all its watchers, batches resources of one account into one API call, paces every account on a rate budget with several dimensions (requests and complexity points, for example), and survives the watcher that started it;
- a
daemon status|stop|logscommand group.
It was extracted from the glab-watch command of glab-cli-extras.
Installation
Requires Python 3.12+. The core depends only on click.
uv add cli-watch-kit # stdout only
uv add 'cli-watch-kit[claude-code]' # also messages into a Claude Code session, through cc-blackbox
Concepts
- A source (
cli_watch_kit.source.Source) polls targets (Target(kind, id, data)), such asissue ABC-123. Itspoll()gets a batch ofPollItems (target, previous snapshot, the event kinds anyone wants) and returns aPollOutcomeper target: the new snapshot, the events, an optional end, or a per-target error (NotFound,Unauthorized,RateLimited,Transient). The diff should be a pure function the CLI tests on its own. A poll without a previous snapshot is the baseline and reports nothing. - Keep the snapshot stable. The engine hashes
encode(snapshot)after every poll, and a new hash is what sends the snapshot to the watchers again (and rewrites theirbaseline.json); after a restart, an equal hash is what drops a repeatedwatch_started. So the snapshot holds only what the diff compares, and stays the same while nothing changed. Volatile values (fetch times, ETags, rate-limit readings, cursors, request counts) belong inPollItem.state. PollItem.stateis a dict private to one resource that lives as long as the resource: the place for an ETag, work held back for a later poll, or a stateful poller object. It starts empty after a daemon restart; only the snapshot survives one.- Source options are what a watcher asks of the source besides event kinds (glab's
--logs=failed|all|none, for example).run_watch(source_options=...)sends them with the subscription,Source.check_optionsvalidates them, andPollItem.optionsholds those of every subscriber and parent, each once, for the source to merge. A parent asks its children for kinds and options withWants(events, options). - An account (
Source.account(target, params)) is whose rate limit a poll spends. Targets of different accounts never share a call or a budget. - Targets of one account with the same batch key (
Source.batch_key) that are due withincoalesce_windowseconds go into onepoll()call; the first poll of a new target waits up to that window (baseline_wait), so watchers that start a few seconds apart share it, split so that no call costs more thanbatch_cost_cap.cost(batch)estimates a call's cost per budget dimension; the source reports what the API said throughctx.budget.observe(...)and, when it knows what each response really cost (an ETag 304, a complexity header), charges that withctx.spend(...); the engine then gives back its estimate for those dimensions. An API client shared by the polls of an account finds the poll it serves withPollContext.current(). A poll that handles a 429 itself, for a side request it tries again later, reports it withctx.rate_limited(retry_after), so the engine still blocks the account and does not count the poll as a success. - Params are what a watcher sends along with its subscription, such as an API key. They travel over the daemon's private socket (
0600in a0700dir), reach the source per account, and never appear in the status or the log. Before it sends any, the watcher checks that the state dir and the socket (or the TCP endpoint file) belong to the user and that nobody else can write them, and over TCP that a daemon still holds the lock, so a stale port gets no token. The daemon log is0600too. The latest params of an account win, soSource.account()must check the key it gets (and raiseUnauthorizedfor a bad one): otherwise one watcher with a wrong key would break the account's other watchers. - The catalog (
KindCatalog) names the event kinds per resource kind, the groups of the filter options, and the threshold kinds the watcher computes itself.watch_started,watch_degradedandwatch_endedare always reported.
A minimal source and CLI
# my_cli/watch.py
from collections.abc import Mapping, Sequence
from typing import Any
import click
from cli_watch_kit.app import WatchApp
from cli_watch_kit.budget import DimensionSpec
from cli_watch_kit.cli import WatchOptions, daemon_group, run_watch, watch_options
from cli_watch_kit.events import KindCatalog, RawEvent
from cli_watch_kit.source import NotFound, Params, PollContext, PollItem, PollOutcome, Source, Target
type Snapshot = dict[str, Any]
class IssueSource(Source[Snapshot]):
catalog = KindCatalog({"issue": ("state_changed",)}, groups={"status": ("state_changed",)})
dimensions = {
"requests": DimensionSpec(per_minute=40),
"complexity": DimensionSpec(per_minute=50_000, burst=10_000),
}
batch_cost_cap = {"complexity": 5_000}
async def account(self, target: Target, params: Params) -> str:
return await whoami(params["api_key"]) # the user the key belongs to
def batch_key(self, target: Target) -> str:
return "issues" # every issue of an account in one request
def interval(self, target: Target, snapshot: Snapshot | None) -> float:
return 30.0
def cost(self, batch: Sequence[PollItem[Snapshot]]) -> Mapping[str, float]:
return {"requests": 1, "complexity": 20 * len(batch)}
async def poll(self, batch: Sequence[PollItem[Snapshot]], ctx: PollContext) -> Mapping[str, PollOutcome[Snapshot]]:
found = await fetch_issues(ctx.params["api_key"], [item.target.id for item in batch]) # raise RateLimited etc.
outcomes = {}
for item in batch:
issue = found.get(item.target.id)
if issue is None:
outcomes[item.key] = PollOutcome(error=NotFound(f"no issue {item.target.id}"))
continue
events = diff(item.snapshot, issue) if item.snapshot is not None else [] # list[RawEvent]
ended = "completed" if issue["state"] == "Done" else None
outcomes[item.key] = PollOutcome(issue, events, ended=ended)
return outcomes
APP = WatchApp(
name="my-cli-watch",
source=IssueSource, # or an instance; a callable is called once, when needed
daemon_module="my_cli.watch_daemon",
app_protocol=1,
version="1.0.0",
status_prefix="my-cli watch: ",
envelope_tag="my-cli-watcher",
command="my-cli watch",
files_dir_name="my-cli", # <scratchpad>/my-cli/issue/ABC-123/events.jsonl; default: the name
)
@click.group()
def watch() -> None:
"""Watch issues."""
@watch.command()
@click.argument("issue_id")
@watch_options
def issue(issue_id: str, options: WatchOptions) -> None:
raise SystemExit(run_watch(APP, Target("issue", issue_id), options, params={"api_key": api_key()}))
watch.add_command(daemon_group(APP))
# my_cli/watch_daemon.py: what `python -m my_cli.watch_daemon` runs
from cli_watch_kit.daemon import main
from my_cli.watch import APP
if __name__ == "__main__":
main(APP)
run_watch also takes enabled_thresholds and timers (the app's ClientTimers for threshold kinds), also_subscribe (kinds the daemon should track for a timer without the watcher reporting them), a writer factory for the app's own files in the resource dir (it gets a WriterContext with the base and resource dirs, the target, the backend for extra ops and the status output), resource_dir, readme, sender_name, restart and extra header lines. Only one watcher at a time writes a resource dir: a second watcher of the same target into the same base dir waits up to 5 s for the first one to finish, then exits with 1 and says so, and runs with its own --base-dir. Watchers of one target in different base dirs, such as two Claude Code sessions with their own scratchpads, always work: they share one resource of the daemon, and each gets every event into its own files and stream, also across a daemon restart or drain, one of them ending first, or one starting later. A CLI on another framework fills a WatchOptions itself, or uses cli_watch_kit.client.Watcher directly; that one takes no lock, so the CLI must keep two watchers of one resource out of the same dir itself.
An app with requests the daemon should serve within the budget (fetching a log for a watcher, for example) puts them in Source.ops; a watcher calls them with backend.call(op, payload, params). A source whose targets relay other targets (an MR and its head pipeline) returns them from Source.children.
The daemon
- The first watcher starts the daemon with
python -m <daemon_module>under a spawn lock. The daemon forks once more, so a tool that kills the watcher's whole process tree does not kill it, and holds a lock for its lifetime; a second one exits at once. - IPC is one NDJSON request and response per connection over a Unix socket under
$XDG_RUNTIME_DIR/<name>/(or$TMPDIR, or the temp dir). Windows, or<PREFIX>TRANSPORT=tcp, uses loopback TCP with a token in a private file. The socket name carries the library's and the app's protocol versions (daemon-l1-a1.sock), so incompatible daemons never meet. - Each watcher polls the daemon every 5 s, which renews its lease; a subscription not renewed for 20 s is dropped. Watchers of one target in one account share one resource, which keeps its last 500 events. The daemon exits 30 s after its last subscription.
- Each account has a token bucket per budget dimension, refilled at half of
remaining / (reset - now)once the source reports readings. A 429 (RateLimited) blocks the account for itsRetry-Afterand backs off exponentially. When the watched resources would exceed any dimension, all their intervals stretch by the same factor. Errors are reported once per kind aswatch_degraded, with exponential backoff per resource. - After a daemon crash, the watcher starts a new daemon and resubscribes with its baseline, so the new daemon reports only what changed meanwhile, and the watcher drops a repeated
watch_started. When another watcher already brought the resource back, the engine diffs the baseline against the current snapshot withSource.diff, so every resubscriber gets the gap; the same holds for a watcher whose lease expired. A resubscribe that fails for a reason that may pass (the API unreachable after a suspend) is retried with a backoff. Leases run on a monotonic clock. - Upgrades:
helloreturns the library and app versions and a stamp of the installed code (a fingerprint and the newest file time of both packages). A watcher with newer code asks an older daemon todrain(stop) and starts a current one; the old daemon's watchers resubscribe from their baselines. A watcher with older code uses a newer daemon as it is. This also covers editable installs, where the code changes without a version. --no-daemonruns the same engine and request handler in a thread of the watcher, with a private budget.--no-daemonand the daemon build their engine the same way (Engine.for_app), fromWatchApp.client_poll_msandlease_timeoutand the environment. For tests,APP.with_overrides(source=..., client_poll_ms=..., lease_timeout=...)returns a copy of the app with another source and settings, to run withWatchOptions(no_daemon=True).- A hung daemon (it holds its lock but answers nothing) is replaced: a watcher whose polls time out 3 times in a row, or that gets no answer to two hellos when it starts, kills it and starts a new one, and
daemon stopkills one that does not stop withinSTOP_TIMEOUT. It is killed only when its pid is verified: the daemon writes it into its lock file, the lock is held, and the process runs the app's daemon module. Otherwise the watcher exits with an error that says how to stop it.daemon statusreports such a daemon as running but not answering. On Windows a hung daemon is reported but never killed. - Environment variables, with the app's prefix (default: the name in upper case,
-as_, plus_):STATE_DIR,BASE_DIR,TRANSPORT,IDLE_TIMEOUT,LEASE_TIMEOUT,CLIENT_POLL_MS,REQUEST_TIMEOUT(10 s),STOP_TIMEOUT(10 s),DEBUG.
Claude Code
With the claude-code extra, --events-stream=auto (the default) sends the events into the Claude Code session that started the watcher, when that session accepts messages, as <envelope_tag resource="issue ABC-123" seq="1-2"> blocks. cc-blackbox does the delivery: session lookup, the protocol check, burst batching, the 64 KB cap, the receiver's rate limit, and the end of the watch when the session is gone. The resource dir then lives in the session's scratchpad. Without the extra, auto uses stdout, and under Claude Code the header says which extra to install; claude-message fails with the same hint. Nothing imports cc-blackbox until a stream needs it.
Only the message with watch_started names the resource dir and the changelog; its watch_started drops the summary's dir, and WatchApp.announced can rewrite it further (glab-watch makes its threads dir relative there). A message's sender id is <WatchApp.sender>:<pid> (default: the app's name), and its sender name is what run_watch(sender_name=...) says (default: <command> <target key>).
Developing
uv sync
uv run ruff check . && uv run ruff format --check . && uv run mypy --strict src tests && uv run pytest
The tests run the engine on a fake clock against a fake source (tests/fakeapp), and start real daemon processes in short temp dirs over both transports. CI runs the same checks on Python 3.12 to 3.15.
To develop a CLI against a local checkout, add it as an editable path dependency of the CLI:
[tool.uv.sources]
cli-watch-kit = { path = "../cli-watch-kit", editable = true }
Commit hooks
Fixtures and captured output can carry private identifiers such as workspace, account or issue names, API keys or paths. scripts/hooks holds a pre-commit and a commit-msg hook that refuse a commit when a staged line or the commit message matches a private identifier. The identifiers live in a file outside the repository, because listing them here would publish the very strings the hooks exist to keep out. Set it up once per clone:
git config core.hooksPath scripts/hooks
git config hooks.forbiddenPatternsFile ~/.config/git/forbidden-patterns.txt # any path outside the repo
The file holds one extended regex per line, matched case-insensitively; blank lines and # comments are ignored. Until hooks.forbiddenPatternsFile points at a file with at least one pattern, both hooks refuse every commit and print how to fix it.
Releasing
The version comes from the git tag through hatch-vcs. Pushing a vX.Y.Z tag runs .github/workflows/publish.yml, which builds the package and publishes it to PyPI through trusted publishing (the pypi environment of the GitHub repository must be registered as a trusted publisher on PyPI first).
License
MIT
Metadata
Release files for cli-watch-kit 0.1.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| cli_watch_kit-0.1.1.tar.gz | 126.8 kB | With provenance | Details for cli_watch_kit-0.1.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| cli_watch_kit-0.1.1-py3-none-any.whl | Python 3 | none | any | Details for cli_watch_kit-0.1.1-py3-none-any.whl |
Total release size: 201.7 kB
Release files / cli_watch_kit-0.1.1.tar.gz
| Download URL | cli_watch_kit-0.1.1.tar.gz |
|---|---|
| Size | 126.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9fd4609a6284ce37c9e09f397971dfa26dc7460d2e532898569e4b824487d181
|
|
BLAKE2b-256 checksum How to use checksums |
07efdfdfffe3a77a4b9c26d79e1e52d35996c6b3e0ba12a7ea0f2acfb1282b32
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.
Transparency logRelease files / cli_watch_kit-0.1.1-py3-none-any.whl
| Download URL | cli_watch_kit-0.1.1-py3-none-any.whl |
|---|---|
| Size | 74.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
80d6ea793c38d4286087a0676d2476d891a15575363ff4ec39e6ccdbb5b17508
|
|
BLAKE2b-256 checksum How to use checksums |
ac58d40f8c410885dc64d7e39f3c98c991a09a861db8f6129d145ce01a458f8e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.
Transparency logSecurity for cli-watch-kit 0.1.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for cli_watch_kit-0.1.1.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.