Files
ai-agent/cli/notify.py
gabrielvidalandClaude Opus 5.5 acda5ecc30 refactor: retire core leftovers the plugins replaced
- frontend: drop the dead Conversations dashboard code (costAnalysis,
  DashboardFilters, ConversationsDashboard), the unused analytics /
  footprint / pricing helpers, the orphan api.ts comment and the dead
  mocks (perf dashboard, storage dashboard, telemetry hub/usage,
  usage daily/history/calibration); their French strings
- backend: drop look.parse_action (the conversation-labels plugin has its
  own) and UsersStore.emails() (no caller)
- routes: drop GET /api/usage/daily|history|calibration,
  GET /api/telemetry/usage, GET /api/goals, POST /api/goal-work — the
  plugin bridges call daily_usage, calibrate.history, views.usage,
  goals_list and goal_work directly; authz table + golden matrix updated;
  openapi.json re-dumped, src/generated regenerated
- FALLBACK_ACCOUNTS: one neutral Claude seat instead of a stale copy of
  the providers' profiles (the full list moves to mock/accounts.ts)
- notify CLI: no local PRICES estimate — the line is
  "Claude Code · 78k tokens · 8m" and the hub's restate_cost puts the
  run's exact list price in (an older CLI's $ line is still restated)
- CLAUDE.md / docs / docstrings: scheduled/, templates/, sidecar
  *_usage.py, the clarifier (now the plugin's agents[] + prefs),
  runs/extras.py, sidecar/routes_chrome.py

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 11:53:15 +01:00

868 lines
37 KiB
Python
Executable File

#!/usr/bin/env python3
"""notify — the one CLI an agent session uses to reach Gabriel through the
ai-agent hub: a push notification or a 2-3-button choice. (Forms are the
standalone ask-form tool's — `ask-form create`, github.com/GabrielVidal1/ask-form.)
notify send [TITLE] MESSAGE [--type T] [--url U] [--image I] [--say S]
[--action-cmd "Title::cmd"] [--final] [--no-cost] [--dry-run]
notify ask "QUESTION" "Opt 1" "Opt 2" ["Opt 3"] [--background|-b]
[--timeout N] [--type T] [--url U] [--image I] [--dry-run]
notify wait ID [--timeout N] ask_… → chosen label; ntf_… → action title
notify cost the "<harness> · Nk tokens · 8m" line
notify conv add <url|key> [--kind K] [--title T] [--label L] [--state S]
[--primary] [--repo owner/repo] record what this conversation
is about (a link, a branch, or a resource
plugin's kind: an issue key, a PR) — alias
`conv`; the hub reads keys and links
notify conv title "…" rename this conversation (a rename by the
owner always wins)
notify conv rm <url|key> drop a resource (hides the parsed one too)
notify conv look [ACTION] [--color C] [--icon I] [--clear]
what the conversation does (its card's
badge), its colour, its project icon
notify conv show what the conversation has (hub only)
Two transports, picked by the environment the session was launched with:
* **hub** (the lab) — talks to the ai-agent backend at ``AI_AGENT_URL``
(default ``http://127.0.0.1:8096``), the notification source of truth.
* **outbox** (a remote worker) — the sidecar that launched this run exported
``AI_AGENT_OUTBOX_URL``: the request is dropped into *that sidecar's* outbox
and the hub, which polls every worker it has paired with, picks it up,
records it, forwards it to the phone and pushes any answer back into the
outbox. The worker never calls the hub (see sidecar/outbox.py).
Ids are minted **here** (``ntf_`` / ``ask_`` + 12 hex) so they are
the same on the worker, in the hub and in the viewer whichever transport
carried them. ``wait`` then works on either side.
Deliberately stdlib-only (urllib, argparse): a worker has whatever python3 the
Mac has and nothing installed for us. The notify-done / notify-ask skill
scripts are thin shims onto this file.
The compat aliases map 1:1: notify-done → send, notify-ask → ask, conv → conv.
`notify form` (the hub's own forms for agents) went on 2026-10-28: agents ask
with the standalone ask-form tool, whose forms the hub mirrors (backend askform/).
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
HERE = Path(__file__).resolve().parent
# One long-poll cycle. The hub (and the outbox) cap the in-request wait at 55 s,
# so a backgrounded wait is one request a minute that still returns the instant
# an answer lands.
POLL_WAIT_S = 55
NOTIFY_TYPES = ("deploy", "code", "config", "build", "git", "commit", "service",
"container", "ai", "mcp", "music", "download", "media",
"jellyfin", "research", "logs", "metrics", "dns", "auth",
"security", "mail", "success", "done", "backup", "error",
"fail", "warn", "warning", "notify", "default", "")
_ID_RE = re.compile(r"^(ntf|ask|frm)_[0-9a-f]{12}$")
# The core's kinds; a resource plugin's (`pr`, `linear`, `slack`…) are the
# hub's to read — `--kind` takes any slug and the hub checks it.
CONV_KINDS = ("branch", "url")
_KIND_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,47}$")
# `conv look` — keep in step with backend/conversations/look.py (the hub
# re-validates; these just make `--help` and a typo useful on a worker).
CONV_ACTIONS = ("feature", "fix", "investigate", "review", "refactor", "perf",
"research", "design", "docs", "test", "data", "deploy", "ops",
"question", "plan", "chore")
CONV_COLORS = ("sky", "blue", "emerald", "amber", "violet", "rose", "cyan",
"orange", "lime", "fuchsia", "teal")
def _err(msg: str) -> None:
print(msg, file=sys.stderr, flush=True)
def _mint(prefix: str) -> str:
return f"{prefix}_{uuid.uuid4().hex[:12]}"
# ── .env.claude (private defaults, gitignored) ───────────────────────────────
def load_env_claude(start: Path = HERE) -> None:
"""Source the first ``.env.claude`` found walking up from ``start`` (bash
``set -a; . file`` semantics: file values override the environment)."""
cur = start.resolve()
while True:
f = cur / ".env.claude"
if f.is_file():
try:
text = f.read_text(encoding="utf-8", errors="replace")
except OSError:
return
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[7:].lstrip()
m = re.match(r"^([A-Za-z_][A-Za-z0-9_]*)=(.*)$", line)
if not m:
continue
k, v = m.group(1), m.group(2)
if len(v) >= 2 and v[0] == v[-1] and v[0] in "'\"":
v = v[1:-1]
os.environ[k] = v
return
if cur == cur.parent:
return
cur = cur.parent
# ── session / transcript ─────────────────────────────────────────────────────
def config_dirs() -> list[Path]:
"""Every Claude config dir a transcript may live under, most relevant
first: $CLAUDE_CONFIG_DIR (the run's own account), ~/.claude, then any
extra in $CLAUDE_CONFIG_DIRS (colon-separated)."""
raw = [os.environ.get("CLAUDE_CONFIG_DIR", ""), str(Path.home() / ".claude"),
str(Path.home() / ".claude-work")]
raw += [p for p in os.environ.get("CLAUDE_CONFIG_DIRS", "").split(":") if p]
out: list[Path] = []
for p in raw:
if p:
d = Path(os.path.expanduser(p))
if d not in out:
out.append(d)
return out
def opencode_roots() -> list[Path]:
"""The opencode harness's mirrored transcripts (the sidecar writes one dir
per opencode account under ``~/.opencode-runner/transcripts``)."""
base = Path(os.path.expanduser(os.environ.get("SIDECAR_OPENCODE_DIR", "~/.opencode-runner")))
root = base / "transcripts"
try:
return sorted(p for p in root.iterdir() if p.is_dir())
except OSError:
return []
def find_transcript(sid: str) -> Path | None:
roots = [d / "projects" for d in config_dirs()] + opencode_roots()
for root in roots:
if root.is_dir():
hits = sorted(root.glob(f"*/{sid}.jsonl"))
if hits:
return hits[0]
return None
def newest_transcript_for_cwd() -> Path | None:
enc = os.getcwd().replace("/", "-")
best, best_m = None, -1.0
for d in config_dirs():
for f in (d / "projects" / enc).glob("*.jsonl"):
try:
m = f.stat().st_mtime
except OSError:
continue
if m > best_m:
best, best_m = f, m
return best
def resolve_session_id(*, guess: bool = True) -> str:
"""The calling Claude Code session: $CLAUDE_SESSION_ID (the sidecar exports
it for every run it launches), else an external resolver the lab's shims
point at ($NOTIFY_SESSION_RESOLVER — conv-meta's PID-ancestry match),
else (``guess``) the newest transcript written for this cwd — a guess, ""
without it."""
sid = os.environ.get("CLAUDE_SESSION_ID", "").strip()
if sid:
return sid
resolver = os.environ.get("NOTIFY_SESSION_RESOLVER", "")
if resolver and os.path.isfile(resolver):
try:
out = subprocess.run(["bash", resolver], capture_output=True,
text=True, timeout=30).stdout.strip()
if out:
return out
except (OSError, subprocess.TimeoutExpired):
pass
if not guess:
return ""
t = newest_transcript_for_cwd()
return t.name[:-6] if t else ""
# ── cost line ────────────────────────────────────────────────────────────────
def transcript_cost(path: Path) -> dict:
"""Sum a transcript's per-turn tokens (deduped by requestId). No price:
the hub owns pricing and puts the run's exact list price in the line
(``usage/calibrate.py`` ``restate_cost``)."""
seen: set[str] = set()
tokens = 0
first = last = None
harness = "Claude Code"
with open(path, encoding="utf-8", errors="replace") as fh:
for line in fh:
try:
o = json.loads(line)
except ValueError:
continue
if o.get("entrypoint") == "opencode":
harness = "OpenCode"
if o.get("type") != "assistant":
continue
msg = o.get("message") or {}
u = msg.get("usage") or {}
# The opencode mirror writes a step's content before its usage,
# under the same requestId: only a usage-bearing record counts.
if not u:
continue
req = o.get("requestId")
if req:
if req in seen:
continue
seen.add(req)
i = int(u.get("input_tokens") or 0)
out = int(u.get("output_tokens") or 0)
cw = int(u.get("cache_creation_input_tokens") or 0)
cr = int(u.get("cache_read_input_tokens") or 0)
if not (i or out or cw or cr):
continue
tokens += i + out + cw + cr
ts = o.get("timestamp")
if ts:
first = ts if first is None else min(first, ts)
last = ts if last is None else max(last, ts)
duration = ""
if first and last and last > first:
from datetime import datetime
try:
secs = int((datetime.fromisoformat(last.replace("Z", "+00:00"))
- datetime.fromisoformat(first.replace("Z", "+00:00")))
.total_seconds())
m, s = divmod(secs, 60)
h, m = divmod(m, 60)
duration = f"{h}h {m}m {s}s" if h else (f"{m}m {s}s" if m else f"{s}s")
except ValueError:
pass
return {"tokens": tokens, "duration": duration, "harness": harness}
def cost_line(sid: str) -> str:
"""``Claude Code · 78k tokens · 8m 38s`` for the session (the hub adds the
price), or '' when no transcript resolves (never fatal)."""
try:
# A known session that has no transcript yet (an opencode run's mirror
# lags a couple of seconds) must not borrow another session's.
t = find_transcript(sid) if sid else newest_transcript_for_cwd()
if not t:
return ""
c = transcript_cost(t)
except Exception:
return ""
n = c["tokens"]
tok = (f"{n / 1e6:.1f}M tokens" if n >= 1_000_000
else f"{n // 1000}k tokens" if n >= 1000 else f"{n} tokens")
line = f"{c['harness']} · {tok}"
if c["duration"]:
line += f" · {c['duration']}"
return line
# ── transport ────────────────────────────────────────────────────────────────
# The host token (the hub's INTERNAL_API_TOKEN): what a host caller presents
# so loopback alone stops being its credential (docs/permissions.md). Env
# first, else a 0600 file the deploy writes; none ⇒ the call goes out bare and
# the hub logs it (Security → Access) until loopback is refused.
HOST_TOKEN_FILE = Path(os.environ.get("AI_AGENT_TOKEN_FILE")
or Path.home() / ".config" / "ai-agent" / "token")
def host_token() -> str:
tok = os.environ.get("AI_AGENT_TOKEN", "").strip()
if tok:
return tok
try:
return HOST_TOKEN_FILE.read_text().strip()
except OSError:
return ""
class Transport:
"""``hub`` POSTs straight to the backend; ``outbox`` drops the same payload
into the local sidecar for the hub to collect."""
def __init__(self) -> None:
self.outbox = os.environ.get("AI_AGENT_OUTBOX_URL", "").rstrip("/")
self.outbox_token = os.environ.get("AI_AGENT_OUTBOX_TOKEN", "")
self.hub = (os.environ.get("AI_AGENT_URL") or "http://127.0.0.1:8096").rstrip("/")
self.mode = "outbox" if self.outbox else "hub"
def _call(self, url: str, data: dict | None = None, *, method: str = "POST",
timeout: float = 15, token: str = "") -> tuple[int, dict]:
body = json.dumps(data).encode() if data is not None else None
headers = {"Content-Type": "application/json"}
if token:
headers["Authorization"] = f"Bearer {token}"
elif url.startswith(self.hub + "/") and host_token():
headers["X-Internal-Auth"] = host_token()
req = urllib.request.Request(url, data=body, method=method, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, _json(r.read().decode(errors="replace"))
except urllib.error.HTTPError as e:
return e.code, _json(e.read().decode(errors="replace"))
except (urllib.error.URLError, OSError, ValueError) as e:
return 0, {"error": str(e)}
# create
def submit(self, kind: str, payload: dict) -> tuple[int, dict]:
if self.mode == "outbox":
return self._call(f"{self.outbox}/outbox",
{"kind": kind, "payload": payload},
token=self.outbox_token)
path = {"notify": "/api/notify", "ask": "/api/ask"}[kind]
return self._call(f"{self.hub}{path}", payload)
# read / long-poll
def status(self, rid: str, wait_s: int = 0) -> tuple[int, dict]:
q = f"?waitSecs={wait_s}" if wait_s > 0 else ""
if self.mode == "outbox":
return self._call(f"{self.outbox}/outbox/{rid}{q}", method="GET",
timeout=wait_s + 15, token=self.outbox_token)
path = {"ntf": "/api/notify/", "ask": "/api/ask/"}[rid[:3]]
return self._call(f"{self.hub}{path}{rid}{q}", method="GET",
timeout=wait_s + 15)
def record(self, sid: str, patch: dict) -> tuple[int, dict]:
"""Set what this conversation is about (``conv``): straight onto the
hub's metadata, or a ``meta`` outbox item the hub applies."""
if self.mode == "outbox":
return self._call(f"{self.outbox}/outbox", {"kind": "meta", "payload": {
"id": _mint("met"), "sessionId": sid, "patch": patch}},
token=self.outbox_token)
return self._call(f"{self.hub}/api/conversation-meta", {"id": sid, **patch})
def describe(self) -> str:
return f"outbox {self.outbox}" if self.mode == "outbox" else f"hub {self.hub}"
def _json(text: str) -> dict:
try:
d = json.loads(text or "{}")
return d if isinstance(d, dict) else {"value": d}
except ValueError:
return {"raw": text[:300]}
def _accepted(code: int, resp: dict) -> bool:
"""A create is accepted when the hub recorded it (partial webhook delivery
still counts — the record is answerable from the viewer) or the outbox
queued it."""
if code == 202 or resp.get("queued"):
return True
if code != 200:
return False
return bool(resp.get("id")) and (
resp.get("ok") is True
or any(d.get("ok") for d in (resp.get("delivered") or []))
or "delivered" not in resp)
def _delivery_warning(resp: dict) -> str:
"""A channel that failed (Home Assistant down…), or none at all: the push
is in the app all the same."""
rows = [d for d in (resp.get("delivered") or []) if d.get("user") in (None, "owner")]
failed = [f"{d.get('channel') or d.get('webhook') or d.get('target')}"
+ (f" ({d['error']})" if d.get("error") else "")
for d in rows if not d.get("ok")]
if failed:
return f"warn: channel(s) failed: {', '.join(failed)}"
if rows and not any(d.get("channel") or d.get("webhook") for d in rows):
return "note: no notification channel set up — in the app only"
return ""
# ── og:image (deploy pushes preview the site's social card) ──────────────────
def og_image_for(url: str) -> str:
"""``<origin>/og-image.png`` when it answers 200 — publicly trusted hosts
only (the phone can't validate the lab's certs)."""
if os.environ.get("HA_NOTIFY_NO_OG"):
return ""
try:
u = urllib.parse.urlsplit(url.strip())
except ValueError:
return ""
host = u.hostname or ""
if not u.scheme.startswith("http") or not host or host.endswith(".lab.gabvdl.xyz"):
return ""
name = os.environ.get("HA_NOTIFY_OG_NAME", "og-image.png").lstrip("/")
og = f"{u.scheme}://{u.netloc}/{name}"
try:
req = urllib.request.Request(og, method="HEAD")
with urllib.request.urlopen(req, timeout=5) as r:
code = r.status
except urllib.error.HTTPError as e:
code = e.code
except (urllib.error.URLError, OSError, ValueError):
code = 0
if code == 200:
_err(f"attaching og:image {og}")
return og
_err(f"warn: og:image not attached ({og} → HTTP {code})")
return ""
# ── wait loops ───────────────────────────────────────────────────────────────
def wait_for(t: Transport, rid: str, timeout: int, *, quiet: bool = False) -> int:
"""Long-poll until the record reaches a terminal state.
ask_: prints the chosen label (exit 0); expired → 3.
ntf_: prints the tapped action title (0); expired → 3.
An unknown id is 1. ``timeout`` 0 = no local deadline."""
deadline = time.time() + timeout if timeout > 0 else 0
kind = rid[:3]
while True:
code, r = t.status(rid, POLL_WAIT_S)
if code == 404:
_err(f"error: unknown {rid}")
return 1
st = r.get("status") or ""
if code == 0 or not st:
_err("warn: backend unreachable (retrying in 10s)")
time.sleep(10)
elif kind == "ask" and st == "answered":
label = (r.get("answer") or "").replace("\n", " ")
_err(f"chosen: {r.get('answerIndex')} {label}")
print(label, flush=True)
return 0
elif kind == "ntf" and st == "acted":
print(r.get("actionTitle") or str(r.get("actionIndex")), flush=True)
return 0
elif st in ("expired", "cancelled"):
if not quiet:
_err(f"{st}: {rid} ended without an answer")
return 3
if deadline and time.time() >= deadline:
if not quiet:
_err(f"timeout: no answer within {timeout}s ({rid} still pending)")
return 3
def _spawn_detached(argv: list[str]) -> None:
try:
subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, start_new_session=True)
except OSError:
pass
# ── commands ─────────────────────────────────────────────────────────────────
def cmd_send(a: argparse.Namespace) -> int:
if not a.args:
_err("usage: notify send [TITLE] MESSAGE [--type T] [--url U] …")
return 2
title, message = ("Claude Code", a.args[0]) if len(a.args) == 1 else (a.args[0], a.args[1])
ntype = (a.type if a.type is not None else os.environ.get("HA_NOTIFY_TYPE", "")).strip()
if ntype not in NOTIFY_TYPES:
_err(f"error: unknown --type {ntype!r} (one of: "
f"{', '.join(t for t in NOTIFY_TYPES if t)})")
return 2
url = (a.url if a.url is not None else os.environ.get("HA_NOTIFY_URL", "")).strip()
image = (a.image if a.image is not None else os.environ.get("HA_NOTIFY_IMAGE", "")).strip()
spoken = (a.spoken if a.spoken is not None else os.environ.get("HA_NOTIFY_SPOKEN", "")).strip()
if not image and ntype == "deploy" and url:
image = og_image_for(url)
sid = resolve_session_id()
if not a.no_cost and not os.environ.get("HA_NOTIFY_NO_COST"):
line = cost_line(sid)
if line:
message = f"{message}\n{line}"
nid = _mint("ntf")
payload: dict = {"id": nid, "title": title, "message": message}
for k, v in (("type", ntype), ("url", url), ("image", image), ("spoken", spoken),
("channel", a.channel), ("importance", a.importance),
("vibrationPattern", a.vibration), ("sessionId", sid)):
if (v or "").strip():
payload[k] = v.strip()
if a.final:
payload["final"] = True
action_cmd = ""
if a.action_cmd:
if "::" not in a.action_cmd:
_err("error: --action-cmd must be '<title>::<command>'")
return 2
action_title, action_cmd = a.action_cmd.split("::", 1)
payload["actions"] = [{"action": f"{nid}__0", "title": action_title.strip()}]
t = Transport()
if a.dry_run:
print(f"DRY RUN — {t.describe()} notify payload:")
print(json.dumps(payload, ensure_ascii=False))
return 0
if not url:
_err("no --url given: the hub links this conversation in the viewer")
code, resp = t.submit("notify", payload)
if not _accepted(code, resp):
_err(f"error: notification not sent via {t.describe()} "
f"(HTTP {code}: {json.dumps(resp)[:300]})")
return 1
w = _delivery_warning(resp)
if w:
_err(w)
print(f"notification sent via {t.describe()} ({nid})", flush=True)
if action_cmd:
# Detached waiter: runs the command when the button is tapped (6 h —
# a "Merge to main" tap may come much later). Survives this call.
_spawn_detached([sys.executable, str(Path(__file__).resolve()), "_on-action",
nid, os.environ.get("HA_ACTION_TIMEOUT", "21600"), action_cmd])
return 0
def cmd_on_action(a: argparse.Namespace) -> int:
"""Hidden: wait for a notify's action button, then run its command."""
rc = wait_for(Transport(), a.id, int(a.timeout), quiet=True)
if rc != 0:
return 0
return subprocess.run(["bash", "-c", a.command]).returncode
def cmd_ask(a: argparse.Namespace) -> int:
if a.args and a.args[0] == "wait": # `notify-ask wait <id>` compat
a.id = next((x for x in a.args[1:] if x.startswith("ask_")), "")
return cmd_wait(a)
question, options = (a.args[0] if a.args else ""), [o for o in a.args[1:] if o.strip()]
if not question.strip() or len(options) < 2:
_err('usage: notify ask "<question>" "Label1" "Label2" [Label3] [--background]')
return 2
if len(options) > 3:
_err("error: Android shows at most 3 action buttons; pass 2 or 3 options")
return 2
ntype = (a.type if a.type is not None else os.environ.get("HA_NOTIFY_TYPE", "")).strip()
if ntype not in NOTIFY_TYPES:
_err(f"error: unknown --type {ntype!r}")
return 2
timeout = int(a.timeout if a.timeout is not None else os.environ.get("HA_ASK_TIMEOUT", "180"))
sid = resolve_session_id()
aid = _mint("ask")
payload: dict = {"id": aid, "question": question.strip(), "options": options,
"timeoutSecs": timeout}
url = (a.url if a.url is not None else os.environ.get("HA_NOTIFY_URL", "")).strip()
image = (a.image if a.image is not None else os.environ.get("HA_NOTIFY_IMAGE", "")).strip()
for k, v in (("type", ntype), ("url", url), ("image", image), ("sessionId", sid)):
if v:
payload[k] = v
t = Transport()
if a.dry_run:
print(f"DRY RUN — {t.describe()} ask payload:")
print(json.dumps(payload, ensure_ascii=False))
return 0
code, resp = t.submit("ask", payload)
if not _accepted(code, resp):
_err(f"error: ask not sent via {t.describe()} (HTTP {code}: {json.dumps(resp)[:300]})")
return 1
w = _delivery_warning(resp)
if w:
_err(w)
if a.background:
_err(f"asked via {t.describe()} (not waiting): {question}")
print(f"ASK_ID={aid}", flush=True)
_err(f"next: run `notify wait {aid}` under a Monitor (or in a background "
f"shell) — do NOT block the turn on it")
return 0
_err(f"asked via {t.describe()} (waiting up to {timeout}s for a tap): {question}")
return wait_for(t, aid, timeout + 5 if timeout > 0 else 0)
_ASSET_MAX = 20 * 1024 * 1024
_ASSET_RE = re.compile(r"\{\{\s*asset:\s*([^}\s]+)\s*\}\}")
# ── conv: what this conversation is about ────────────────────────────────────
def _resource_urls():
sys.path.insert(0, str(HERE))
import resource_urls # cli/resource_urls.py — the backend parses with it too
return resource_urls
def _conv_ref(a: argparse.Namespace) -> dict | None:
"""What ``conv add`` / ``rm`` was handed: a core record (a link, a
branch), or ``{ref, kind?}`` — a key or an id (``INS-2229``, ``#13722``)
the hub reads with its active resource plugins."""
ru = _resource_urls()
kind = getattr(a, "kind", None)
raw = (a.ref or "").strip()
if kind and not _KIND_RE.match(kind):
_err(f"error: --kind must be a resource kind slug ({', '.join(CONV_KINDS)}, "
"or a resource plugin's: pr, linear, slack…)")
return None
repo = getattr(a, "repo", None)
if repo and re.fullmatch(r"#?\d{1,7}", raw):
raw = f"{repo}#{raw.lstrip('#')}" # a bare PR number in that repo
r = ru.parse(raw, kind=kind) if kind in (None, *CONV_KINDS) else None
if r:
return r
if not raw or (kind is None and " " in raw) or (kind in CONV_KINDS):
_err(f"error: not a resource: {a.ref!r} — a URL, an issue key (INS-2229), "
"a PR (#13722) or --kind branch <name>")
return None
return {"ref": raw, **({"kind": kind} if kind else {})}
def _ref_label(r: dict) -> str:
return f"{r['kind']}:{r['id']}" if r.get("id") else str(r.get("ref"))
def _record(sid: str, patch: dict, what: str, dry_run: bool) -> int:
t = Transport()
if dry_run:
print(f"DRY RUN — {t.describe()} conv patch for {sid}:")
print(json.dumps(patch, ensure_ascii=False))
return 0
code, resp = t.record(sid, patch)
if code not in (200, 202):
detail = resp.get("detail")
msg = detail.get("message") if isinstance(detail, dict) else detail
_err(f"error: {msg or json.dumps(resp)[:300]} (HTTP {code} via {t.describe()})")
return 1
print(what, flush=True)
return 0
def _sid_or_fail() -> str:
sid = resolve_session_id()
if not sid:
_err("error: no session id ($CLAUDE_SESSION_ID unset and none resolved)")
return sid
def cmd_conv_add(a: argparse.Namespace) -> int:
r = _conv_ref(a)
sid = _sid_or_fail() if r else ""
if not r or not sid:
return 2 if not r else 1
for f in ("title", "label", "state"):
v = (getattr(a, f, None) or "").strip()
if v:
r[f] = v.lower() if f == "state" else v
r["source"] = "agent"
r["firstSeen"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
keep = ("kind", "id", "ref", "url", "label", "title", "state", "primary", "source",
"firstSeen")
rec = {k: r[k] for k in keep if r.get(k) not in (None, "")}
if a.primary:
rec["primary"] = True # omitted otherwise: re-adding never demotes
what = f"recorded {_ref_label(r)}" + (" (primary)" if a.primary else "")
return _record(sid, {"resources": [rec]}, what, a.dry_run)
def cmd_conv_title(a: argparse.Namespace) -> int:
title = " ".join(a.title or []).strip()
if not title:
_err('usage: conv title "<title>"')
return 2
sid = _sid_or_fail()
if not sid:
return 1
return _record(sid, {"title": title[:200], "titleSource": "agent"},
f"titled: {title[:200]}", a.dry_run)
def cmd_conv_look(a: argparse.Namespace) -> int:
look = {"action": a.action, "color": a.color, "icon": a.icon}
look = {k: v for k, v in look.items() if v is not None}
if a.clear: # back to the derived look
look = {"action": "", "color": "", "icon": ""}
if not look:
_err("usage: conv look [ACTION] [--color C] [--icon I] [--clear]\n"
f" actions: {', '.join(CONV_ACTIONS)}\n colours: {', '.join(CONV_COLORS)}")
return 2
sid = _sid_or_fail()
if not sid:
return 1
what = "look: " + (", ".join(f"{k}={v or '∅'}" for k, v in look.items()))
return _record(sid, {"look": look}, what, a.dry_run)
def cmd_conv_rm(a: argparse.Namespace) -> int:
r = _conv_ref(a)
sid = _sid_or_fail() if r else ""
if not r or not sid:
return 2 if not r else 1
# A link goes as itself: the hub drops the plugin kind it reads (and the
# plain link) — `url:<hash>` alone would miss a PR pill.
k = r["url"] if r.get("kind") == "url" and r.get("url") else (
f"{r['kind']}:{r['id']}" if r.get("id") else r["ref"])
return _record(sid, {"resourcesRemove": [k]}, f"removed {_ref_label(r)}", a.dry_run)
def cmd_conv_show(a: argparse.Namespace) -> int:
t = Transport()
if t.mode == "outbox":
_err("conv show reads the hub — from a worker, what you recorded is "
"applied there (see the conversation's pills in the viewer)")
return 0
sid = _sid_or_fail()
if not sid:
return 1
code, resp = t._call(f"{t.hub}/api/conversations?sessions={urllib.parse.quote(sid)}",
method="GET")
convs = resp.get("conversations") or []
if code != 200 or not convs:
_err(f"error: conversation not found (HTTP {code})")
return 1
c = convs[0]
m = c.get("meta") or {}
print(f"title: {c.get('title')}" + (f" [{m['titleSource']}]" if m.get("titleSource") else ""))
for r in m.get("resources") or []:
bits = [r.get("label") or r.get("id"), r.get("title") or "", r.get("state") or ""]
flag = "*" if r.get("primary") else " "
print(f"{flag} {r['kind']:<6} " + " · ".join(b for b in bits if b)
+ f" ({r.get('source')}) {r.get('url') or ''}".rstrip())
if not m.get("resources"):
print("(no resources — no resource plugin's scope may cover this conversation)")
return 0
def cmd_wait(a: argparse.Namespace) -> int:
rid = (a.id or "").strip()
if not _ID_RE.match(rid) or rid.startswith("frm_"):
_err("usage: notify wait <ask_…|ntf_…> [--timeout N]")
return 2
return wait_for(Transport(), rid, int(a.timeout or 0))
def cmd_cost(a: argparse.Namespace) -> int:
line = cost_line(resolve_session_id())
if not line:
_err("error: no transcript resolves for this session")
return 1
print(line)
return 0
# ── argv ─────────────────────────────────────────────────────────────────────
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(prog="notify", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = p.add_subparsers(dest="cmd", metavar="COMMAND")
s = sub.add_parser("send", help="push a notification (alias: notify-done)")
s.add_argument("args", nargs="*", metavar="[TITLE] MESSAGE")
s.add_argument("--url", "-u")
s.add_argument("--type", "-t")
s.add_argument("--image", "-i")
s.add_argument("--spoken", "--say", dest="spoken",
help="one short French sentence the desk phone reads aloud")
s.add_argument("--channel")
s.add_argument("--importance")
s.add_argument("--vibration", "--vibrate", dest="vibration")
s.add_argument("--action-cmd", dest="action_cmd",
help="extra button '<title>::<shell command>' run on tap")
s.add_argument("--final", action="store_true",
help="this is the task's closing notification: the hub marks "
"the session finished")
s.add_argument("--no-cost", action="store_true")
s.add_argument("--dry-run", action="store_true")
s.set_defaults(fn=cmd_send)
k = sub.add_parser("ask", help="2-3-button choice (alias: notify-ask)")
k.add_argument("args", nargs="*", metavar='"QUESTION" OPTION…')
k.add_argument("--timeout")
k.add_argument("--type", "-t")
k.add_argument("--url", "-u")
k.add_argument("--image", "-i")
k.add_argument("--target", help=argparse.SUPPRESS) # legacy, ignored
k.add_argument("--background", "--no-wait", "-b", action="store_true")
k.add_argument("--dry-run", action="store_true")
k.set_defaults(fn=cmd_ask, id="")
w = sub.add_parser("wait", help="collect an ask's answer")
w.add_argument("id")
w.add_argument("--timeout", default="0")
w.set_defaults(fn=cmd_wait)
sub.add_parser("cost", help="print this session's cost line").set_defaults(fn=cmd_cost)
cv = sub.add_parser("conv", help="record what this conversation is about (alias: conv)")
cvs = cv.add_subparsers(dest="conv_cmd", metavar="COMMAND")
ca = cvs.add_parser("add", help="add a link / branch / issue / PR / thread")
ca.add_argument("ref", help="a URL, an issue key (INS-2229), #13722, or a branch "
"with --kind branch")
ca.add_argument("--kind", help="branch | url, or a resource plugin's kind "
"(pr, linear, slack…) — read by the hub")
ca.add_argument("--title", help="the issue / PR / page title")
ca.add_argument("--label", help="pill text — a Slack thread's '#channel'")
ca.add_argument("--state", help="open | draft | merged | closed, or an issue status")
ca.add_argument("--primary", action="store_true",
help="what the conversation is mainly about (names it, once)")
ca.add_argument("--repo", help="owner/repo for a bare PR number")
ca.add_argument("--dry-run", action="store_true")
ca.set_defaults(fn=cmd_conv_add)
ct = cvs.add_parser("title", help="rename this conversation")
ct.add_argument("title", nargs="+")
ct.add_argument("--dry-run", action="store_true")
ct.set_defaults(fn=cmd_conv_title)
cl = cvs.add_parser("look", help="what this conversation does (the card's "
"action badge), its colour, its icon")
cl.add_argument("action", nargs="?", choices=CONV_ACTIONS,
help="feature | fix | investigate | review | …")
cl.add_argument("--color", choices=CONV_COLORS,
help="pin the card colour (default: from its issue / project)")
cl.add_argument("--icon", help="project-icon override: a glyph key or sh:<selfh.st ref>")
cl.add_argument("--clear", action="store_true", help="back to the derived look")
cl.add_argument("--dry-run", action="store_true")
cl.set_defaults(fn=cmd_conv_look)
cr = cvs.add_parser("rm", help="drop a resource")
cr.add_argument("ref")
cr.add_argument("--kind")
cr.add_argument("--repo")
cr.add_argument("--dry-run", action="store_true")
cr.set_defaults(fn=cmd_conv_rm)
cvs.add_parser("show", help="what this conversation has (hub only)").set_defaults(
fn=cmd_conv_show)
h = sub.add_parser("_on-action")
h.add_argument("id")
h.add_argument("timeout")
h.add_argument("command")
h.set_defaults(fn=cmd_on_action)
return p
def main(argv: list[str] | None = None) -> int:
load_env_claude()
argv = list(sys.argv[1:] if argv is None else argv)
# Compat entry points set NOTIFY_AS=send|ask|form (the shims) so the old
# argv shapes keep working: `notify-done "msg" --url …`.
alias = os.environ.get("NOTIFY_AS", "")
if alias in ("send", "ask") and (not argv or argv[0] not in
("send", "ask", "wait",
"cancel", "secret", "cost",
"_on-action")):
argv = [alias, *argv]
elif alias == "conv":
argv = ["conv", *argv]
p = build_parser()
a = p.parse_args(argv)
if not getattr(a, "fn", None):
p.print_help()
return 2
return a.fn(a)
if __name__ == "__main__":
sys.exit(main())