Skip to content

gerodp/hermes-productivity-skills / travel/trip-planner

trip-planner

Verified

Plan a trip step by step: an itinerary plus a running budget that converts every currency into your preferred one, printed as two tables after each change — and a final summary with the budget broken down by category, the average spend per day, and checks for accommodation gaps and missing daily food/misc estimates.

FileKindSize
SKILL.mdskill md18.0 KB
scripts/render_trip.pyscript18.0 KB
scripts/test_render_trip.pyscript8.6 KB
scripts/test_trip_planner.pyscript31.4 KB
scripts/trip_planner.pyscript81.9 KB

scripts/render_trip.py

View on GitHub
#!/usr/bin/env python3
"""render_trip — deterministic HTML / Markdown / iCalendar output for a trip.

Input is the bundle printed by ``trip_planner.py show --json``: it already
carries pre-formatted display strings (dates, amounts, concepts) and the
translated labels, so this module is pure presentation — no date maths, no
currency logic, no LLM. That keeps the two renderers impossible to drift apart.

    python3 trip_planner.py show --json > bundle.json
    python3 render_trip.py --html < bundle.json

Everything here escapes its input: itinerary titles, notes and links are free
text that can carry HTML, Markdown link syntax or calendar control characters.

Python standard library only.
"""
from __future__ import annotations

import argparse
import html
import json
import re
import sys
from datetime import date, datetime, timedelta, timezone

CONTROL_CHARS_RE = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]")
# Item types that become calendar events with a real duration.
STAY_TYPES = ("stay", "lodging", "car")


def _clean(s):
    return CONTROL_CHARS_RE.sub("", str(s or ""))


def safe_url(url):
    """Only http(s) survives — a stored link could be hand-edited into the file."""
    url = _clean(url).strip()
    return url if url.lower().startswith(("http://", "https://")) else ""


# --------------------------------------------------------------------------- #
# Markdown
# --------------------------------------------------------------------------- #
def md_cell(s):
    """Escape a Markdown table cell: pipes break the table, brackets fake links."""
    return (_clean(s).replace("\\", "\\\\").replace("|", "\\|")
            .replace("[", "\\[").replace("]", "\\]")
            .replace("\n", " ").strip())


def md_link(url):
    url = _clean(url).strip()
    if not url.lower().startswith(("http://", "https://")):
        return ""
    return f"<{url}>"  # autolink: never renders attacker-chosen link text


def _md_breakdown(bundle):
    """The end-of-planning category table + the readiness checks."""
    L, t, c = bundle["labels"], bundle["totals"], bundle.get("checks") or {}
    cur = bundle["trip"]["currency"]
    out = [f'## {L["breakdown"]}', "",
           f'| {L["category"]} | {L["amount"]} {cur} | {L["share"]} | '
           f'{L["per_day_col"]} | {L["per_person_col"]} |',
           "| --- | ---: | ---: | ---: | ---: |"]
    for r in t.get("breakdown", []):
        out.append(f'| {md_cell(r["emoji"])} {md_cell(r["label"])} | '
                   f'{md_cell(r["display"]["amount"])} | {r["pct"]:.1f}% | '
                   f'{md_cell(r["display"]["per_day"])} | '
                   f'{md_cell(r["display"]["per_person"])} |')
    out.append(f'| **{L["total_all"]}** | **{md_cell(t["display"]["spent"])}** | '
               f'100.0% | {md_cell(t["display"]["per_day"])} | '
               f'{md_cell(t["display"]["per_person"])} |')
    out += ["", f'{L["avg_per_day"]}: **{t["display"]["per_day"]}** · '
                f'{L["avg_per_person_day"]}: '
                f'**{t["display"].get("avg_per_person_day", "—")}**', ""]
    if c:
        out += [f'## {L["checks"]}', ""]
        if c.get("nights_total"):
            out.append(f'- {"✓" if c["lodging_ok"] else "✗"} '
                       f'{c["nights_covered"]}/{c["nights_total"]} '
                       + md_cell(c.get("nights_gaps") or ""))
        out.append(f'- {"✓" if c.get("has_food") else "✗"} '
                   f'{md_cell(L["cat_food"])}')
        out.append(f'- {"✓" if c.get("has_misc") else "✗"} '
                   f'{md_cell(L["cat_other"])}')
        if c.get("questions"):
            out += ["", f'### {L["questions"]}', ""]
            out += [f'- {md_cell(q["text"])}' for q in c["questions"]]
        out.append("")
    return out


def itinerary_rows(bundle):
    """Itinerary rows — each leg of a return flight is its own row. Older
    bundles (before the split) carry no `itinerary` key: fall back to items."""
    return bundle.get("itinerary") or bundle["items"]


def render_markdown(bundle, what="both"):
    L, tr, t = bundle["labels"], bundle["trip"], bundle["totals"]
    cur = tr["currency"]
    if what == "summary":
        head = [f'# {md_cell(tr.get("name") or tr["slug"])} — {L["summary"]}', "",
                " · ".join(x for x in [md_cell(tr.get("destination") or ""),
                                       f'{tr.get("start")} → {tr.get("end")}',
                                       f'{tr.get("travelers") or 1} '
                                       f'{L["travelers"].lower()}'] if x), ""]
        return "\n".join(head + _md_breakdown(bundle)).rstrip() + "\n"
    out = [f'# {md_cell(tr.get("name") or tr["slug"])}', ""]
    meta = [md_cell(tr.get("destination") or ""),
            f'{tr.get("start")} → {tr.get("end")}',
            f'{tr.get("travelers") or 1} {L["travelers"].lower()}']
    out.append(" · ".join(x for x in meta if x))
    out.append("")

    if what in ("both", "itinerary"):
        out.append(f'## {L["itinerary"]}')
        out.append("")
        out.append(f'| {L["date"]} | {L["place"]} | {L["activity"]} | '
                   f'{L["notes"]} | {L["link"]} |')
        out.append("| --- | --- | --- | --- | --- |")
        for it in itinerary_rows(bundle):
            d = it["display"]
            out.append(f'| {md_cell(d["dates"])} | {md_cell(d["place"])} | '
                       f'{md_cell(d["activity"])} | {md_cell(d["notes"])} | '
                       f'{md_link(d["link"])} |')
        if not itinerary_rows(bundle):
            out.append(f'| {L["empty"]} |  |  |  |  |')
        out.append("")
        if bundle["warnings"]:
            for w in bundle["warnings"]:
                out.append(f"- ⚠ {md_cell(w)}")
            out.append("")

    if what in ("both", "budget"):
        out.append(f'## 💰 {L["budget"]}')
        out.append("")
        out.append(f'| {L["concept"]} | {L["dates"]} | {L["amount"]} {cur} | '
                   f'{L["original"]} | {L["notes"]} |')
        out.append("| --- | --- | ---: | ---: | --- |")
        for it in bundle["items"]:
            d = it["display"]
            out.append(f'| {md_cell(d["concept"])} | {md_cell(d["dates"])} | '
                       f'{md_cell(d["amount"])} | {md_cell(d["original"])} | '
                       f'{md_cell(d["budget_notes"])} |')
        out.append(f'| **{L["total"]}** |  | **{md_cell(t["display"]["spent"])}** '
                   f'|  |  |')
        out.append("")
        if t.get("budget"):
            out.append(f'**{L["budget_line"]}** {t["display"]["budget"]} · '
                       f'**{L["spent"]}** {t["display"]["spent"]} ({t["pct"]}%) · '
                       f'**{L["remaining"]}** {t["display"]["remaining"]}')
        out.append(f'{L["per_person"]} {t["display"]["per_person"]} · '
                   f'{L["per_day"]} {t["display"]["per_day"]}')
    return "\n".join(out).rstrip() + "\n"


# --------------------------------------------------------------------------- #
# HTML
# --------------------------------------------------------------------------- #
CSS = """
:root { color-scheme: light dark; --fg:#1c1c1e; --muted:#6b7280; --bg:#fff;
        --card:#f7f7f8; --line:#e5e7eb; --accent:#0f766e; --warn:#b45309; }
@media (prefers-color-scheme: dark) {
  :root { --fg:#e8e8ea; --muted:#9ca3af; --bg:#131316; --card:#1c1c20;
          --line:#2c2c33; --accent:#5eead4; --warn:#fbbf24; } }
* { box-sizing:border-box; }
body { margin:0 auto; padding:2rem 1.25rem 4rem; max-width:64rem; background:var(--bg);
       color:var(--fg); font:16px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",
       Roboto,Helvetica,Arial,sans-serif; }
h1 { margin:0 0 .25rem; font-size:1.9rem; letter-spacing:-.02em; }
h2 { margin:2.5rem 0 .75rem; font-size:1.15rem; text-transform:uppercase;
     letter-spacing:.08em; color:var(--muted); }
.sub { color:var(--muted); margin-bottom:1.5rem; }
.cards { display:flex; flex-wrap:wrap; gap:.75rem; margin:1.5rem 0; }
.card { flex:1 1 9rem; background:var(--card); border:1px solid var(--line);
        border-radius:.75rem; padding:.85rem 1rem; }
.card .k { color:var(--muted); font-size:.78rem; text-transform:uppercase;
           letter-spacing:.06em; }
.card .v { font-size:1.35rem; font-weight:600; margin-top:.15rem; }
.wrap { overflow-x:auto; -webkit-overflow-scrolling:touch; }
table { border-collapse:collapse; width:100%; font-size:.94rem; min-width:34rem; }
th,td { text-align:left; padding:.55rem .6rem; border-bottom:1px solid var(--line);
        vertical-align:top; }
th { font-size:.76rem; text-transform:uppercase; letter-spacing:.06em;
     color:var(--muted); white-space:nowrap; }
td.num, th.num { text-align:right; white-space:nowrap; }
tr.total td { font-weight:700; border-top:2px solid var(--line); border-bottom:none; }
.warn { background:var(--card); border-left:3px solid var(--warn);
        border-radius:.4rem; padding:.6rem .9rem; margin:.4rem 0; color:var(--warn); }
a { color:var(--accent); }
.bar { height:.5rem; background:var(--line); border-radius:99px; overflow:hidden;
       margin:.6rem 0 0; }
.bar span { display:block; height:100%; background:var(--accent); }
details { margin-top:1rem; } summary { cursor:pointer; color:var(--muted); }
footer { margin-top:3rem; color:var(--muted); font-size:.8rem; }
@media print { body { padding:0; max-width:none; } .card { break-inside:avoid; } }
"""


def h(s):
    return html.escape(_clean(s), quote=True)


def h_link(url, max_len=48):
    url = _clean(url).strip()
    if not url.lower().startswith(("http://", "https://")):
        return ""
    label = url if len(url) <= max_len else url[:max_len - 1] + "…"
    return (f'<a href="{html.escape(url, quote=True)}" rel="noopener noreferrer" '
            f'target="_blank">{html.escape(label, quote=True)}</a>')


def render_html(bundle):
    L, tr, t = bundle["labels"], bundle["trip"], bundle["totals"]
    cur = tr["currency"]
    title = h(tr.get("name") or tr["slug"])
    sub = " · ".join(x for x in [
        h(tr.get("destination") or ""),
        f'{h(tr.get("start"))} → {h(tr.get("end"))}',
        f'{tr.get("travelers") or 1} {h(L["travelers"].lower())}'] if x)

    cards = [(L["spent"], t["display"]["spent"])]
    if t.get("budget"):
        cards += [(L["budget_line"], t["display"]["budget"]),
                  (L["remaining"], t["display"]["remaining"])]
    cards += [(L["per_person"], t["display"]["per_person"]),
              (L["per_day"], t["display"]["per_day"])]
    card_html = "".join(
        f'<div class="card"><div class="k">{h(k)}</div>'
        f'<div class="v">{h(v)}</div></div>' for k, v in cards if v)

    bar = ""
    if t.get("pct") is not None:
        pct = max(0, min(100, int(t["pct"])))  # int-coerced before raw HTML
        bar = f'<div class="bar"><span style="width:{pct}%"></span></div>'

    itin_rows = "".join(
        "<tr>"
        f'<td>{h(i["display"]["dates"])}</td>'
        f'<td>{h(i["display"]["place"])}</td>'
        f'<td>{h(i["display"]["activity"])}</td>'
        f'<td>{h(i["display"]["notes"])}</td>'
        f'<td>{h_link(i["display"]["link"])}</td>'
        "</tr>" for i in itinerary_rows(bundle))
    budget_rows = "".join(
        "<tr>"
        f'<td>{h(i["display"]["concept"])}</td>'
        f'<td>{h(i["display"]["dates"])}</td>'
        f'<td class="num">{h(i["display"]["amount"])}</td>'
        f'<td class="num">{h(i["display"]["original"])}</td>'
        f'<td>{h(i["display"]["budget_notes"])}</td>'
        "</tr>" for i in bundle["items"])
    warn_html = "".join(f'<div class="warn">⚠ {h(w)}</div>'
                        for w in bundle["warnings"])
    breakdown_rows = "".join(
        "<tr>"
        f'<td>{h(r["emoji"])} {h(r["label"])}</td>'
        f'<td class="num">{h(r["display"]["amount"])}</td>'
        f'<td class="num">{r["pct"]:.1f}%</td>'
        f'<td class="num">{h(r["display"]["per_day"])}</td>'
        f'<td class="num">{h(r["display"]["per_person"])}</td>'
        "</tr>" for r in t.get("breakdown", []))
    checks = bundle.get("checks") or {}
    check_rows = ""
    if checks:
        bits = []
        if checks.get("nights_total"):
            bits.append(
                f'{"✓" if checks["lodging_ok"] else "✗"} {h(L["cat_lodging"])}: '
                f'{checks["nights_covered"]}/{checks["nights_total"]} '
                f'{h(checks.get("nights_gaps") or "")}')
        bits.append(f'{"✓" if checks.get("has_food") else "✗"} {h(L["cat_food"])}')
        bits.append(f'{"✓" if checks.get("has_misc") else "✗"} {h(L["cat_other"])}')
        bits += [f'? {h(q["text"])}' for q in checks.get("questions", [])]
        check_rows = "".join(f"<li>{b}</li>" for b in bits)

    return f"""<!doctype html>
<html lang="{h(bundle.get('lang') or 'es')}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
<style>{CSS}</style>
</head>
<body>
<h1>{title}</h1>
<div class="sub">{sub}</div>
<div class="cards">{card_html}</div>
{bar}
<h2>{h(L["itinerary"])}</h2>
<div class="wrap"><table>
<thead><tr><th>{h(L["date"])}</th><th>{h(L["place"])}</th>
<th>{h(L["activity"])}</th><th>{h(L["notes"])}</th><th>{h(L["link"])}</th></tr></thead>
<tbody>{itin_rows or f'<tr><td colspan="5">{h(L["empty"])}</td></tr>'}</tbody>
</table></div>
{warn_html}
<h2>💰 {h(L["budget"])}</h2>
<div class="wrap"><table>
<thead><tr><th>{h(L["concept"])}</th><th>{h(L["dates"])}</th>
<th class="num">{h(L["amount"])} {h(cur)}</th>
<th class="num">{h(L["original"])}</th><th>{h(L["notes"])}</th></tr></thead>
<tbody>{budget_rows or f'<tr><td colspan="5">{h(L["empty"])}</td></tr>'}
<tr class="total"><td>{h(L["total"])}</td><td></td>
<td class="num">{h(t["display"]["spent"])}</td><td></td><td></td></tr></tbody>
</table></div>
<h2>{h(L["breakdown"])}</h2>
<div class="wrap"><table>
<thead><tr><th>{h(L["category"])}</th>
<th class="num">{h(L["amount"])} {h(cur)}</th><th class="num">{h(L["share"])}</th>
<th class="num">{h(L["per_day_col"])}</th>
<th class="num">{h(L["per_person_col"])}</th></tr></thead>
<tbody>{breakdown_rows}
<tr class="total"><td>{h(L["total_all"])}</td>
<td class="num">{h(t["display"]["spent"])}</td><td class="num">100.0%</td>
<td class="num">{h(t["display"]["per_day"])}</td>
<td class="num">{h(t["display"]["per_person"])}</td></tr></tbody>
</table></div>
<details open><summary>{h(L["checks"])}</summary>
<ul>{check_rows}</ul></details>
<footer>{h(L["generated"])}: {h(bundle.get("generated"))} · trip-planner</footer>
</body>
</html>
"""


# --------------------------------------------------------------------------- #
# iCalendar
# --------------------------------------------------------------------------- #
def ics_escape(s):
    return (_clean(s).replace("\\", "\\\\").replace(";", "\\;")
            .replace(",", "\\,").replace("\n", "\\n"))


def fold(line):
    """RFC 5545 line folding at 75 octets, continuation lines start with a space."""
    raw = line.encode("utf-8")
    if len(raw) <= 75:
        return line
    out, chunk, size = [], [], 0
    for ch in line:
        n = len(ch.encode("utf-8"))
        if size + n > (73 if out else 74):
            out.append("".join(chunk))
            chunk, size = [ch], n
        else:
            chunk.append(ch)
            size += n
    out.append("".join(chunk))
    return "\r\n ".join(out)


def _date_only(s):
    return str(s).replace("-", "")


def render_ics(bundle, now=None):
    tr = bundle["trip"]
    stamp = (now or datetime.now(timezone.utc)).strftime("%Y%m%dT%H%M%SZ")
    lines = ["BEGIN:VCALENDAR", "VERSION:2.0",
             "PRODID:-//hermes//trip-planner//EN", "CALSCALE:GREGORIAN",
             f'X-WR-CALNAME:{ics_escape(tr.get("name") or tr["slug"])}']
    for it in itinerary_rows(bundle):
        if not it.get("start"):
            continue
        start = date.fromisoformat(it["start"])
        end = date.fromisoformat(it.get("end") or it["start"])
        # All-day events: DTEND is exclusive. A stay 13→16 occupies 13,14,15 and
        # ends on the 16th; a same-day item lasts exactly one day.
        if it.get("type") in STAY_TYPES and end > start:
            dtend = end
        else:
            dtend = end + timedelta(days=1)
        link = safe_url(it.get("link"))
        desc = " · ".join(x for x in [
            it["display"].get("budget_notes"),
            it["display"].get("amount") if it.get("converted") is not None else "",
            link] if x)
        lines += [
            "BEGIN:VEVENT",
            f'UID:{ics_escape(tr["slug"])}-{it.get("id")}'
            f'{"-" + ics_escape(it["leg"]) if it.get("leg") else ""}'
            "@hermes-trip-planner",
            f"DTSTAMP:{stamp}",
            f"DTSTART;VALUE=DATE:{_date_only(start.isoformat())}",
            f"DTEND;VALUE=DATE:{_date_only(dtend.isoformat())}",
            f'SUMMARY:{ics_escape(it["display"]["concept"])}',
        ]
        if it.get("place"):
            lines.append(f'LOCATION:{ics_escape(it["place"])}')
        if desc:
            lines.append(f"DESCRIPTION:{ics_escape(desc)}")
        if link:
            lines.append(f"URL:{ics_escape(link)}")
        if it.get("status") == "pending":
            lines.append("STATUS:TENTATIVE")
        lines.append("END:VEVENT")
    lines.append("END:VCALENDAR")
    return "\r\n".join(fold(x) for x in lines) + "\r\n"


def main(argv=None):
    p = argparse.ArgumentParser(
        prog="render_trip",
        description="Render a trip bundle (from `trip_planner.py show --json`).")
    g = p.add_mutually_exclusive_group()
    g.add_argument("--html", action="store_true")
    g.add_argument("--markdown", action="store_true")
    g.add_argument("--ics", action="store_true")
    p.add_argument("-i", "--input", help="bundle JSON file (default: stdin)")
    args = p.parse_args(argv)
    try:
        raw = (open(args.input, encoding="utf-8").read() if args.input
               else sys.stdin.read())
        bundle = json.loads(raw)
    except (OSError, ValueError) as e:
        print(f"error: cannot read the bundle JSON ({e})", file=sys.stderr)
        return 1
    if args.ics:
        sys.stdout.write(render_ics(bundle))
    elif args.markdown:
        sys.stdout.write(render_markdown(bundle))
    else:
        sys.stdout.write(render_html(bundle))
    return 0


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