Skip to main content

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-events filters 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|logs command 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 as issue ABC-123. Its poll() gets a batch of PollItems (target, previous snapshot, the event kinds anyone wants) and returns a PollOutcome per 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 their baseline.json); after a restart, an equal hash is what drops a repeated watch_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 in PollItem.state.
  • PollItem.state is 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_options validates them, and PollItem.options holds those of every subscriber and parent, each once, for the source to merge. A parent asks its children for kinds and options with Wants(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 within coalesce_window seconds go into one poll() 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 than batch_cost_cap. cost(batch) estimates a call's cost per budget dimension; the source reports what the API said through ctx.budget.observe(...) and, when it knows what each response really cost (an ETag 304, a complexity header), charges that with ctx.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 with PollContext.current().
  • Params are what a watcher sends along with its subscription, such as an API key. They travel over the daemon's private socket (0600 in a 0700 dir), 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 is 0600 too. The latest params of an account win, so Source.account() must check the key it gets (and raise Unauthorized for 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_degraded and watch_ended are 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 exits with 1 and says so, and runs with its own --base-dir. 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 its Retry-After and 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 as watch_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 with Source.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: hello returns 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 to drain (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-daemon runs the same engine and request handler in a thread of the watcher, with a private budget.
  • --no-daemon and the daemon build their engine the same way (Engine.for_app), from WatchApp.client_poll_ms and lease_timeout and 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 with WatchOptions(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 stop kills one that does not stop within STOP_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 status reports 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.

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.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cli-watch-kit 0.1.0
File Size Uploaded Provenance Actions
cli_watch_kit-0.1.0.tar.gz 123.1 kB With provenance Details for cli_watch_kit-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cli-watch-kit 0.1.0
File Interpreter ABI Platform Actions
cli_watch_kit-0.1.0-py3-none-any.whl Python 3 none any Details for cli_watch_kit-0.1.0-py3-none-any.whl

Total release size: 197.0 kB

Release files / cli_watch_kit-0.1.0.tar.gz

Download URL cli_watch_kit-0.1.0.tar.gz
Size 123.1 kB
Tags Source
SHA-256 checksum
How to use checksums
cd77ee7a62c635eaffebf7fa109cde9d0acc9ceb64d78a40891d39df7eb4489b
BLAKE2b-256 checksum
How to use checksums
2dcb0e38d10a406a9e108afef0a2bf33dd2636c54d058857aec37ae056999a7a
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 log

Release files / cli_watch_kit-0.1.0-py3-none-any.whl

Download URL cli_watch_kit-0.1.0-py3-none-any.whl
Size 73.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a154d6a1555672a95c66bd917541db53320e8f420a503213a10cfbe1a07721f0
BLAKE2b-256 checksum
How to use checksums
d9a29ad32faef043505aea36d1031105877a8179d9da901dc809b978d1a50800
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 log

Security for cli-watch-kit 0.1.0

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.

Select from 2 files

Attestation for cli_watch_kit-0.1.0.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 log

A 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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page