Skip to content

gerodp/hermes-productivity-skills / calendar/calendar

calendar

Verified

Check your Google Calendar (read-only): today's / this week's / upcoming events as an agenda.

FileKindSize
SKILL.mdskill md6.2 KB
scripts/calendar_agenda.pyscript16.7 KB
scripts/test_calendar_agenda.pyscript8.5 KB

scripts/calendar_agenda.py

View on GitHub
#!/usr/bin/env python3
"""calendar-agenda — check your Google Calendar (read-only) from the terminal.

A thin, stdlib-only wrapper over the builtin **google-workspace** skill: it
delegates the actual API call (and Hermes-managed OAuth) to that skill's
``google_api.py calendar list`` and adds the conveniences the other tap skills
share — local-time **Monday-start windows** (today / this-week / next N days /
explicit range), an agenda grouped by day, ``--json``, and a ``check`` that
verifies setup and otherwise prints the exact steps.

Read-only by design: it lists events, it never creates or deletes them.

No new configuration — OAuth/token are owned by the google-workspace skill
(``~/.hermes/google_token.json``). Python standard library only; the heavy
lifting (Google API client) lives in the builtin.
"""
from __future__ import annotations

import argparse
import json
import os
import re
import shutil
import subprocess
import sys
from datetime import date, datetime, timedelta

# Event titles/locations come from calendar invites — anyone can send one — so
# strip control chars (terminal escapes) before rendering. JSON output is safe.
CONTROL_CHARS_RE = re.compile(r"[\x00-\x1f\x7f]")


def sanitize_text(s):
    return CONTROL_CHARS_RE.sub(" ", s).strip()

CHILD_TIMEOUT = 60  # seconds per builtin invocation


class CalendarError(Exception):
    """User-facing error — message is safe to print (never contains secrets)."""


# --------------------------------------------------------------------------- #
# Locating the builtin google-workspace skill
# --------------------------------------------------------------------------- #
def hermes_home():
    return os.environ.get("HERMES_HOME") or os.path.expanduser("~/.hermes")


def _gws_dir():
    return os.path.join(hermes_home(), "skills", "productivity",
                        "google-workspace", "scripts")


def gws_script(override=None):
    return os.path.expanduser(override) if override else \
        os.path.join(_gws_dir(), "google_api.py")


def setup_script(override=None):
    return os.path.expanduser(override) if override else \
        os.path.join(_gws_dir(), "setup.py")


# --------------------------------------------------------------------------- #
# Choosing an interpreter that can drive the builtin (google libs + ssl)
# --------------------------------------------------------------------------- #
_ABS_PYTHONS = ("/opt/homebrew/bin/python3", "/usr/local/bin/python3",
                "/usr/bin/python3")

_PROBE = ("import googleapiclient, google.auth, ssl")

_GCAL_PY = None


def _can_drive(py):
    try:
        r = subprocess.run([py, "-c", _PROBE], capture_output=True, timeout=20)
        return r.returncode == 0
    except (OSError, subprocess.TimeoutExpired):
        return False


def _venv_python():
    """The dedicated uv venv that holds the Google client libs (preferred)."""
    return os.path.join(hermes_home(), ".venvs", "google", "bin", "python3")


def gcal_python():
    """First interpreter that can import the Google client libs **and** ssl.

    Same hard-won lesson as weekly-report: under Hermes the PATH ``python3`` may
    be a pyenv shim with broken ssl, and ``sys.executable`` may be a venv without
    the google libs. We therefore prefer an explicit interpreter — ``$HERMES_GCAL_PYTHON``
    or the dedicated ``~/.hermes/.venvs/google`` venv created at setup — then fall
    back to probing PATH and absolute pythons. Pick the first that actually
    imports the libs + ssl. Returns None if none qualify (deps not installed)."""
    global _GCAL_PY
    if _GCAL_PY:
        return _GCAL_PY
    candidates = []
    for p in (os.environ.get("HERMES_GCAL_PYTHON"), _venv_python()):
        if p and p not in candidates:
            candidates.append(os.path.expanduser(p))
    for name in ("python3", "python"):
        p = shutil.which(name)
        if p and p not in candidates:
            candidates.append(p)
    for p in _ABS_PYTHONS:
        if os.path.exists(p) and p not in candidates:
            candidates.append(p)
    if sys.executable and sys.executable not in candidates:
        candidates.append(sys.executable)
    for p in candidates:
        if _can_drive(p):
            _GCAL_PY = p
            return p
    return None


# --------------------------------------------------------------------------- #
# Running the builtin
# --------------------------------------------------------------------------- #
def run_gws_json(args, *, gws=None):
    """Run ``<py> google_api.py <args>`` and return parsed JSON, or
    ``{"error": ...}`` on any failure (never raises)."""
    script = gws or gws_script()
    if not os.path.exists(script):
        return {"error": f"google-workspace skill not found at {script}"}
    py = gcal_python()
    if not py:
        return {"error": "google API libraries not installed — run "
                "`calendar check` for setup steps"}
    try:
        proc = subprocess.run([py, script] + list(args),
                              capture_output=True, text=True, timeout=CHILD_TIMEOUT)
    except subprocess.TimeoutExpired:
        return {"error": f"timed out after {CHILD_TIMEOUT}s"}
    except OSError as e:
        return {"error": f"could not run google_api.py: {e.strerror or e}"}
    if proc.returncode != 0:
        return {"error": _first_line(proc.stderr) or f"exit code {proc.returncode}"}
    try:
        return {"data": json.loads(proc.stdout)}
    except json.JSONDecodeError:
        return {"error": _first_line(proc.stderr) or "google_api.py: non-JSON output"}


def _first_line(text):
    for line in (text or "").splitlines():
        line = line.strip()
        if line:
            return line[7:] if line.lower().startswith("error: ") else line
    return ""


def is_authenticated(setup=None):
    """True if the builtin reports AUTHENTICATED (setup.py --check, exit 0)."""
    script = setup or setup_script()
    if not os.path.exists(script):
        return False
    py = gcal_python() or sys.executable
    try:
        proc = subprocess.run([py, script, "--check"],
                              capture_output=True, text=True, timeout=CHILD_TIMEOUT)
    except (OSError, subprocess.TimeoutExpired):
        return False
    return proc.returncode == 0


# --------------------------------------------------------------------------- #
# Date windows (local time, Monday-start weeks) — shared vocabulary.
# --------------------------------------------------------------------------- #
PERIODS = ("today", "tomorrow", "this-week", "next-week", "this-month",
           "next-month")


def _monday(d):
    return d - timedelta(days=d.weekday())


def _first_of_month(d):
    return d.replace(day=1)


def _last_of_month(d):
    nxt = (d.replace(day=28) + timedelta(days=4)).replace(day=1)
    return nxt - timedelta(days=1)


def _parse_date(s):
    try:
        return datetime.strptime(s, "%Y-%m-%d").date()
    except ValueError:
        raise CalendarError(f"invalid date (use YYYY-MM-DD): {s}")


# NOTE: intentional variant of the shared window vocabulary — this one is
# FORWARD-looking (see docstring), so it is deliberately excluded from the
# repo-level sync check in test_shared_window_vocab.py. Don't "align" it.
def compute_range(today, *, period=None, days=None, nxt=None, start=None, end=None):
    """Return (start_date, end_date) inclusive for the requested window.

    Precedence: start/end > next > days > period. Default: today. Unlike the
    backward-looking report skills, calendar windows look **forward** (today and
    upcoming), so `--days N` / `--next N` span from today forward."""
    if start or end:
        if not (start and end):
            raise CalendarError("--start and --end must be given together")
        s, e = _parse_date(start), _parse_date(end)
        if e < s:
            raise CalendarError("--end is before --start")
        return s, e
    if nxt is not None:
        if nxt < 1:
            raise CalendarError("--next must be >= 1")
        return today, today + timedelta(days=nxt - 1)
    if days is not None:
        if days < 1:
            raise CalendarError("--days must be >= 1")
        return today, today + timedelta(days=days - 1)

    period = period or "today"
    if period == "today":
        s, e = today, today
    elif period == "tomorrow":
        s, e = today + timedelta(days=1), today + timedelta(days=1)
    elif period == "this-week":
        s, e = _monday(today), _monday(today) + timedelta(days=6)
    elif period == "next-week":
        s = _monday(today) + timedelta(days=7)
        e = s + timedelta(days=6)
    elif period == "this-month":
        s, e = _first_of_month(today), _last_of_month(today)
    elif period == "next-month":
        first_next = _last_of_month(today) + timedelta(days=1)
        s, e = first_next, _last_of_month(first_next)
    else:
        raise CalendarError(f"unknown period: {period}")
    return s, e


def _local_tz():
    return datetime.now().astimezone().tzinfo


def iso_bounds(start, end):
    """(timeMin, timeMax) ISO 8601 strings: local-midnight(start) →
    local-midnight(end + 1 day), so the whole end day is included."""
    tz = _local_tz()
    lo = datetime(start.year, start.month, start.day, tzinfo=tz)
    hi = datetime(end.year, end.month, end.day, tzinfo=tz) + timedelta(days=1)
    return lo.isoformat(), hi.isoformat()


# --------------------------------------------------------------------------- #
# Event normalisation + agenda rendering
# --------------------------------------------------------------------------- #
def _parse_event_dt(s):
    """Parse a Google start/end value (RFC3339 datetime, or all-day 'YYYY-MM-DD').

    Returns (date_obj, time_str_or_None). time_str is local 'HH:MM' for timed
    events, None for all-day."""
    if not s:
        return None, None
    if len(s) == 10 and s[4] == "-" and s[7] == "-":   # all-day date
        try:
            return datetime.strptime(s, "%Y-%m-%d").date(), None
        except ValueError:
            return None, None
    try:
        dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
    except ValueError:
        return None, None
    if dt.tzinfo is not None:
        dt = dt.astimezone(_local_tz())
    return dt.date(), dt.strftime("%H:%M")


def normalize_events(raw):
    """Add day/start_local/end_local/all_day to each event; sort chronologically."""
    out = []
    for e in raw:
        sd, st = _parse_event_dt(e.get("start", ""))
        ed, et = _parse_event_dt(e.get("end", ""))
        out.append({
            **e,
            "day": sd.isoformat() if sd else "",
            "start_local": st,
            "end_local": et,
            "all_day": st is None,
        })
    out.sort(key=lambda x: (x["day"], x["start_local"] or ""))
    return out


def render_agenda(events, start, end):
    title = (f"Calendar  {start.isoformat()}"
             if start == end else
             f"Calendar  {start.isoformat()} → {end.isoformat()}")
    out = [title, ""]
    if not events:
        out.append("(no events)")
        return "\n".join(out)
    current = None
    for e in events:
        if e["day"] != current:
            current = e["day"]
            label = _day_label(current)
            out.append(label)
        when = "all-day" if e["all_day"] else \
            f"{e['start_local']}–{e['end_local']}" if e["end_local"] else e["start_local"]
        loc = f"  @ {sanitize_text(e['location'])}" if e.get("location") else ""
        summary = sanitize_text(e.get("summary") or "(no title)")
        out.append(f"  {when:>11}  {summary}{loc}")
    return "\n".join(out)


def _day_label(iso):
    try:
        d = datetime.strptime(iso, "%Y-%m-%d")
        return d.strftime("%a %Y-%m-%d")
    except ValueError:
        return iso or "(undated)"


# --------------------------------------------------------------------------- #
# Subcommands
# --------------------------------------------------------------------------- #
def _today():
    return date.today()


def do_check(args):
    setup = setup_script(args.setup_script)
    gws = gws_script(args.gws_script)
    if not os.path.exists(gws):
        print(f"✗ google-workspace skill not found ({gws}).")
        print(_setup_steps())
        return 1
    if gcal_python() is None:
        print("✗ Google API libraries are not installed.")
        print(_setup_steps())
        return 1
    if is_authenticated(setup):
        print("✓ ready — google-workspace is authenticated; calendar is reachable.")
        print(f"  (using interpreter: {gcal_python()})")
        return 0
    print("✗ not authenticated with Google yet.")
    print(_setup_steps())
    return 1


def _setup_steps():
    setup = setup_script()
    venv = os.path.join(hermes_home(), ".venvs", "google")
    py = gcal_python() or os.path.join(venv, "bin", "python3")
    return (
        "\nOne-time setup (read-only calendar):\n"
        "  1. Install the Google API libs into a uv venv (Homebrew/system pythons\n"
        "     are externally-managed, so a venv is the clean path):\n"
        f"       uv venv {venv} --python 3.12\n"
        f"       uv pip install --python {venv}/bin/python \\\n"
        "           google-api-python-client google-auth-oauthlib google-auth-httplib2\n"
        "     (The skill auto-detects this venv. To use a different interpreter,\n"
        "      set HERMES_GCAL_PYTHON to its path.)\n"
        "  2. Create a Desktop OAuth client in Google Cloud Console, enable the\n"
        "     Google Calendar API, and download client_secret.json.\n"
        f"  3. {py} {setup} --client-secret <path-to-client_secret.json>\n"
        f"  4. {py} {setup} --auth-url --services calendar   # open the URL, authorize\n"
        f"  5. {py} {setup} --auth-code <CODE-from-redirect>\n"
        f"  6. {py} {setup} --check                          # expect AUTHENTICATED"
    )


def do_agenda(args):
    start, end = compute_range(
        _today(), period=args.period, days=args.days, nxt=args.next,
        start=args.start, end=args.end)
    time_min, time_max = iso_bounds(start, end)
    res = run_gws_json(["calendar", "list", "--start", time_min, "--end", time_max,
                        "--max", str(args.max), "--calendar", args.calendar],
                       gws=gws_script(args.gws_script))
    if "error" in res:
        msg = res["error"]
        if args.json:
            print(json.dumps({"range": {"start": start.isoformat(), "end": end.isoformat()},
                              "error": msg}, indent=2))
        else:
            print(f"calendar unavailable: {msg}", file=sys.stderr)
            print("Run `calendar check` for setup steps.", file=sys.stderr)
        return 1
    events = normalize_events(res.get("data") or [])
    if args.json:
        print(json.dumps({
            "range": {"start": start.isoformat(), "end": end.isoformat()},
            "count": len(events),
            "events": events,
        }, indent=2, ensure_ascii=False))
    else:
        print(render_agenda(events, start, end))
    return 0


def build_parser():
    p = argparse.ArgumentParser(
        prog="calendar_agenda",
        description="Check your Google Calendar (read-only) via the "
                    "google-workspace skill.")
    sub = p.add_subparsers(dest="cmd")

    def add_common(sp):
        sp.add_argument("--gws-script", help="override path to google_api.py")
        sp.add_argument("--setup-script", help="override path to setup.py")

    chk = sub.add_parser("check", help="verify Google auth + deps (else print setup)")
    add_common(chk)

    g = sub.add_parser("agenda", help="list calendar events for a window (default)")
    win = g.add_mutually_exclusive_group()
    win.add_argument("--period", choices=PERIODS, help="named window (default today)")
    win.add_argument("--days", type=int, help="next N days incl. today")
    win.add_argument("--next", type=int, help="next N days incl. today (alias of --days)")
    g.add_argument("--start", help="explicit start date YYYY-MM-DD (with --end)")
    g.add_argument("--end", help="explicit end date YYYY-MM-DD (with --start)")
    g.add_argument("--calendar", default="primary", help="calendar id (default primary)")
    g.add_argument("--max", type=int, default=50, help="max events (default 50)")
    g.add_argument("--json", action="store_true", help="machine-readable output")
    add_common(g)
    return p


def main(argv=None):
    parser = build_parser()
    args = parser.parse_args(argv)
    try:
        if args.cmd == "check":
            return do_check(args)
        if args.cmd in (None, "agenda"):
            if args.cmd is None:  # default subcommand: agenda, today
                args = parser.parse_args(["agenda"])
            return do_agenda(args)
        parser.error(f"unknown command {args.cmd}")
    except CalendarError as e:
        print(f"error: {e}", file=sys.stderr)
        return 1
    except KeyboardInterrupt:
        return 130


if __name__ == "__main__":
    sys.exit(main())
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall