Files

560 lines
26 KiB
Python

"""`ai-agent tags` — a tag's colour, icon, description and auto-tag triggers.
Tags are derived by the app (projects and services on disk, skills, agents…);
what can be said about one lives in the hub's tag store (backend ``tags/``,
``/api/tag-meta``) — the same overrides Settings → Tags edits, live in every
open tab.
ai-agent tags [ls] [WORDS…] [--kind K] [--custom]
ai-agent tags show TAG
ai-agent tags set TAG [--color C|auto|none] [--icon KEY] [--icon-file PATH|URL]
[--selfhst REF] [--real-icon] [--tint] [--keep-color]
[--description TEXT] [--source TEXT]
ai-agent tags find-icon TAG where its real icon is, best first
ai-agent tags triggers TAG [--add W]… [--remove W]… [--mute W]… [--unmute W]…
ai-agent tags reset TAG [--field F]…
ai-agent tags icons [--rm ID]
TAG is ``<kind>:<slug>`` (``project:ballance``, ``service:git``,
``skill:screenshot``, ``agent:radar``) or a bare name when only one kind has it.
**Real icons.** ``find-icon`` looks where a project keeps its own: the
``<link rel=icon>`` of its ``index.html``, its web manifest, the favicon / logo
/ app-icon files of ``public/``, ``static/``, ``assets/``, an Android launcher
icon — skipping the template's placeholder favicon and Vite's — and, for a
self-hosted app, its selfh.st logo (the homepage tile's, or the shipped
default). ``set --real-icon`` takes the best one. An icon file is drawn in its
own colours (``--tint`` to draw it in the tag's colour instead) and gives the
tag its colour (its most used saturated one) unless ``--keep-color`` or
``--color`` says otherwise.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import os
import re
import sys
import urllib.error
import urllib.request
from pathlib import Path
HOME = Path.home()
PROJECTS_DIR = Path(os.environ.get("PROJECTS_DIR") or HOME / "projects")
HOMELAB_DIR = Path(os.environ.get("HOMELAB_DIR") or HOME / "homelab")
KINDS = ("project", "service", "skill", "agent", "stack", "account", "linear")
SELFHST = "https://cdn.jsdelivr.net/gh/selfhst/icons/{fmt}/{ref}.{fmt}"
ICON_EXT = (".svg", ".png", ".ico", ".webp", ".jpg", ".jpeg", ".gif")
SKIP_DIRS = {"node_modules", ".git", "dist", "build", ".next", "target", ".venv", "venv",
"__pycache__", "ai-history", ".ai", "coverage", "storybook-static", ".expo",
"test", "tests", "__tests__", "fixtures", "e2e", "vendor", "third_party",
"data", "uploads", "posts", "email", "screenshots"}
NAME_RE = re.compile(r"^(favicon|icon|logo|apple-touch-icon|app-icon|android-chrome|pwa|mask-icon|"
r"adaptive-icon|ic_launcher|brand)[-_.\w]*\.(svg|png|ico|webp)$", re.I)
# Scaffolds' default icons: Vite's, and Astro's flame logo.
PLACEHOLDER_MARKERS = ("vitejs", "IconifyId", "#41D1FF", "#BD34FE", "#FF5D01; }")
def _err(msg: str) -> None:
print(msg, file=sys.stderr, flush=True)
# ── the tags the app derives (the CLI's view of lib/tags.ts) ─────────────────
def _services(hub) -> list[dict]:
"""The homelab services, from the services plugin's catalogue
(``provides: services.index``); none when the plugin is off or the hub
predates the route — a service tag is the plugin's since 2026-11-28."""
try:
return [s for s in hub.get("/api/plugins/services-index").get("services") or []
if isinstance(s, dict) and s.get("dir")]
except Exception: # noqa: BLE001 — HubError, an old hub's 404
return []
def catalog(hub) -> dict[str, dict]:
"""Every tag the composer offers, keyed by id: its kind, slug, path and the
triggers it is derived with (a location's name, a skill's trigger_words)."""
out: dict[str, dict] = {}
for p in hub.get("/api/projects").get("projects") or []:
out["project:" + p["dir"]] = {"kind": "project", "slug": p["dir"], "derived": [p["dir"]],
"isRoot": bool(p.get("isRoot")),
"path": str(PROJECTS_DIR / p["dir"]) if not p.get("isRoot") else str(HOMELAB_DIR),
"description": p.get("description") or ""}
for s in _services(hub):
out["service:" + s["dir"]] = {"kind": "service", "slug": s["dir"], "derived": [s["dir"]],
"path": str(HOMELAB_DIR / "services" / s["dir"]),
"description": s.get("description") or "", "homepageIcon": s.get("icon")}
for s in hub.get("/api/skills").get("skills") or []:
if s.get("sourceKind") == "builtin":
continue
e = out.setdefault("skill:" + s["name"], {"kind": "skill", "slug": s["name"], "derived": [],
"path": s.get("dir") or "", "description": s.get("description") or ""})
e["derived"] = list(dict.fromkeys(e["derived"] + (s.get("triggerWords") or [])))
for g in hub.get("/api/agents").get("agents") or []:
out.setdefault("agent:" + g["name"], {"kind": "agent", "slug": g["name"], "derived": [],
"path": g.get("path") or "", "description": g.get("description") or ""})
return out
def resolve(tag: str, cat: dict[str, dict]) -> str:
"""``kind:slug`` as given, or the one tag a bare name names."""
if ":" in tag and tag.split(":", 1)[0] in KINDS:
return tag
hits = [tid for tid, t in cat.items() if t["slug"].lower() == tag.lower()]
if len(hits) == 1:
return hits[0]
if not hits:
raise ValueError(f"no tag named {tag!r} — say <kind>:<slug> (kinds: {', '.join(KINDS)})")
raise ValueError(f"{tag!r} is several tags: {', '.join(sorted(hits))} — say which")
def effective(derived: list[str], meta: dict) -> list[str]:
muted = {m.lower() for m in meta.get("mutedTriggers") or []}
out, seen = [], set()
for w in [d for d in derived if d.lower() not in muted] + (meta.get("triggers") or []):
if w.lower() not in seen:
seen.add(w.lower())
out.append(w)
return out
# ── real-icon discovery ──────────────────────────────────────────────────────
def _placeholder_hashes() -> set[str]:
"""The template favicons every new project starts with — not its icon."""
out = set()
tdir = PROJECTS_DIR / "templates"
if tdir.is_dir():
for f in tdir.glob("*/public/*"):
if f.is_file() and f.suffix.lower() in ICON_EXT:
out.add(hashlib.sha1(f.read_bytes()).hexdigest())
return out
def _is_placeholder(f: Path, hashes: set[str]) -> bool:
try:
data = f.read_bytes()
except OSError:
return True
if hashlib.sha1(data).hexdigest() in hashes:
return True
return f.suffix.lower() == ".svg" and any(m.encode() in data for m in PLACEHOLDER_MARKERS)
def _walk(root: Path, depth: int):
try:
entries = list(root.iterdir())
except OSError:
return
for p in entries:
if p.name in SKIP_DIRS or (p.name.startswith(".") and p.name != ".well-known") or p.name.startswith("dist"):
continue
if p.is_dir():
if depth > 0:
yield from _walk(p, depth - 1)
elif p.is_file():
yield p
def _png_size(data: bytes) -> int:
if data[:8] == b"\x89PNG\r\n\x1a\n" and len(data) > 24:
return int.from_bytes(data[16:20], "big")
return 0
def _html_links(root: Path) -> list[Path]:
"""Icons a page links, resolved the Vite way (``/x`` → ``public/x``)."""
out = []
# The project's own pages (root, `frontend/`, `apps/web/`) — not every
# demo or plugin page a vendored upstream ships deeper down.
pages = [f for f in _walk(root, 2) if f.name == "index.html"]
for idx in pages:
try:
html = idx.read_text(errors="ignore")
except OSError:
continue
for m in re.finditer(r"<link\b[^>]*>", html, re.I):
tag = m.group(0)
if not re.search(r'rel=["\'][^"\']*(icon|apple-touch-icon|mask-icon)', tag, re.I):
continue
h = re.search(r'href=["\']([^"\']+)["\']', tag)
if not h or h.group(1).startswith(("http", "data:", "%")):
continue
href = h.group(1).split("?")[0].lstrip("./")
for base in (idx.parent / "public", idx.parent, idx.parent / "static"):
f = base / href.lstrip("/")
if f.is_file():
out.append(f)
break
return out
def _manifest_icons(root: Path) -> list[Path]:
out = []
for mf in list(root.glob("public/*manifest*.json")) + list(root.glob("public/*.webmanifest")) + \
list(root.glob("*/public/*manifest*.json")) + list(root.glob("*/public/*.webmanifest")):
try:
data = json.loads(mf.read_text())
except (OSError, ValueError):
continue
if not isinstance(data, dict):
continue
for ic in data.get("icons") or []:
if not isinstance(ic, dict):
continue
src = str(ic.get("src") or "").lstrip("./").lstrip("/")
f = mf.parent / src
if src and f.is_file():
out.append(f)
return out
def _default_selfhst() -> dict[str, str]:
"""The frontend's shipped `sh:` defaults (lib/tagDefaults.ts)."""
for base in (Path(__file__).resolve().parent.parent, PROJECTS_DIR / "ai-agent"):
f = base / "frontend/src/lib/tagDefaults.ts"
if f.is_file():
return dict(re.findall(r'"((?:project|service):[^"]+)":\s*"sh:([^"]+)"', f.read_text()))
return {}
def _selfhst_ref(homepage_icon: str | None) -> str | None:
m = re.search(r"selfhst/icons/(?:webp|png|svg)/([\w.-]+)\.(?:webp|png|svg)", homepage_icon or "")
return m.group(1) if m else None
def find_icons(tag_id: str, info: dict) -> list[dict]:
"""Candidate real icons for a project / service, best first."""
kind = info["kind"]
if kind not in ("project", "service"):
return []
root = Path(info["path"])
cands: dict[str, dict] = {}
hashes = _placeholder_hashes()
def add(f: Path, why: str, bonus: int) -> None:
key = str(f.resolve())
if f.suffix.lower() not in ICON_EXT or _is_placeholder(f, hashes):
return
try:
data = f.read_bytes()
except OSError:
return
if len(data) > 1_500_000:
return
ext = f.suffix.lower().lstrip(".")
px = _png_size(data) if ext == "png" else 0
score = bonus + {"svg": 40, "png": 20, "webp": 15, "ico": 10}.get(ext, 0)
score += min(px, 512) // 32
name = f.name.lower()
score += 10 if name.startswith(("favicon", "icon", "logo", "app-icon", "adaptive-icon")) else 0
score -= 25 if "maskable" in name or "mask-icon" in name else 0
score -= 8 if "-16x16" in name or "-32x32" in name else 0
try:
score -= 3 * max(0, len(f.relative_to(root).parts) - 3)
except ValueError:
pass
rel = str(f).replace(str(HOME), "~", 1)
if key in cands:
cands[key]["score"] = max(cands[key]["score"], score)
cands[key]["why"] = sorted(set(cands[key]["why"] + [why]))
return
cands[key] = {"source": rel, "file": str(f), "format": ext, "bytes": len(data),
**({"px": px} if px else {}), "score": score, "why": [why]}
if info.get("isRoot"):
root = Path("/nonexistent") # the homelab repo itself: its apps' icons aren't its own
if root.is_dir():
for f in _html_links(root):
add(f, "linked by index.html", 30)
for f in _manifest_icons(root):
add(f, "web manifest", 20)
for f in _walk(root, 4):
if NAME_RE.match(f.name):
where = "android launcher" if "mipmap" in str(f) else "icon file"
add(f, where, 5 if "mipmap-xxxhdpi" in str(f) else 0)
ref = _selfhst_ref(info.get("homepageIcon")) or _default_selfhst().get(tag_id)
if ref:
# A self-hosted app's logo: what a service dir (config, not the app's
# source) is best shown by, unless it ships a page of its own; for a
# project only a stand-in, behind any icon the project links itself.
cands["selfh.st:" + ref] = {
"source": f"selfh.st:{ref}", "url": SELFHST.format(fmt="svg", ref=ref), "format": "svg",
"score": 60 if kind == "service" else 55,
"why": ["homepage tile" if _selfhst_ref(info.get("homepageIcon")) else "shipped default"]}
return sorted(cands.values(), key=lambda c: -c["score"])
def _fetch(url: str) -> bytes:
req = urllib.request.Request(url, headers={"User-Agent": "ai-agent-cli"})
with urllib.request.urlopen(req, timeout=20) as r:
return r.read()
def load_icon_bytes(src: str) -> tuple[bytes, str]:
"""(bytes, name) for a path, a URL or ``selfh.st:<ref>``."""
if src.startswith("selfh.st:"):
ref = src.split(":", 1)[1]
last: Exception | None = None
for fmt in ("svg", "png", "webp"): # not every logo has every format
try:
return _fetch(SELFHST.format(fmt=fmt, ref=ref)), ref
except urllib.error.URLError as exc:
last = exc
raise ValueError(f"selfh.st has no {ref!r} logo ({last})")
if re.match(r"^https?://", src):
return _fetch(src), Path(src.split("?")[0]).stem
p = Path(os.path.expanduser(src))
if not p.is_file():
raise ValueError(f"no such file: {src}")
return p.read_bytes(), p.stem
# ── commands ─────────────────────────────────────────────────────────────────
def _row(tid: str, info: dict, meta: dict) -> dict:
return {"id": tid, "kind": info.get("kind") or tid.split(":", 1)[0], "slug": info.get("slug") or tid.split(":", 1)[1],
"color": meta.get("color"), "icon": meta.get("icon"), "iconSource": meta.get("iconSource"),
"description": meta.get("description"), "derivedTriggers": info.get("derived") or [],
"triggers": meta.get("triggers") or [], "mutedTriggers": meta.get("mutedTriggers") or [],
"effectiveTriggers": effective(info.get("derived") or [], meta), "updatedAt": meta.get("updatedAt")}
def cmd(hub, a: argparse.Namespace) -> int:
action = a.action or "ls"
snap = hub.get("/api/tag-meta")
tags_meta, icons = snap.get("tags") or {}, snap.get("icons") or {}
if action == "icons":
return _icons(hub, a, icons)
cat = catalog(hub)
for tid in tags_meta:
cat.setdefault(tid, {"kind": tid.split(":", 1)[0], "slug": tid.split(":", 1)[1], "derived": []})
if action == "ls":
words = [w.casefold() for w in (getattr(a, "query", None) or [])]
kind, custom = getattr(a, "kind", None), getattr(a, "custom", False)
rows = [_row(t, i, tags_meta.get(t) or {}) for t, i in sorted(cat.items())]
rows = [r for r in rows if (not kind or r["kind"] == kind)
and (not custom or any(r[k] for k in ("color", "icon", "description", "triggers", "mutedTriggers")))
and all(w in json.dumps(r).casefold() for w in words)]
if a.json:
print(json.dumps(rows, ensure_ascii=False))
return 0
for r in rows:
look = " ".join(x for x in (r["color"], r["icon"]) if x) or "·"
trig = ", ".join(r["effectiveTriggers"][:5])
print(f"{r['id']:<36} {look[:28]:<28} {trig[:70]}")
if not rows:
_err("ai-agent: nothing matches")
return 0
tid = resolve(a.tag, cat)
info = cat.get(tid) or {"kind": tid.split(":", 1)[0], "slug": tid.split(":", 1)[1], "derived": []}
meta = tags_meta.get(tid) or {}
if action == "show":
row = _row(tid, info, meta)
if row["icon"] and row["icon"].startswith("svg:"):
ic = icons.get(row["icon"][4:]) or {}
row["iconFile"] = {"id": ic.get("id"), "name": ic.get("name"),
"type": "image" if ic.get("image") else "svg", "tint": ic.get("tint")}
print(json.dumps(row, ensure_ascii=False, indent=None if a.json else 1))
return 0
if action == "find-icon":
cands = find_icons(tid, info)
if a.json:
print(json.dumps(cands, ensure_ascii=False))
return 0
if not cands:
_err(f"ai-agent: no icon found for {tid}")
return 1
for c in cands:
size = f"{c.get('px', '')}px " if c.get("px") else ""
print(f"{c['score']:>4} {c['format']:<4} {size:<7}{c['source']} ({', '.join(c['why'])})")
return 0
if action == "reset":
if a.field:
hub.call("PATCH", "/api/tag-meta/tag", {"id": tid, "patch": {f: None for f in a.field}})
else:
hub.call("DELETE", "/api/tag-meta/tag", query={"id": tid})
print(f"{tid}: reset{' ' + ', '.join(a.field) if a.field else ''}")
return 0
if action == "triggers":
added = list(meta.get("triggers") or [])
muted = list(meta.get("mutedTriggers") or [])
low = lambda xs: {x.lower() for x in xs} # noqa: E731
if a.clear:
added = []
for w in a.add or []:
if w.lower() not in low(added) and w.lower() not in low(effective(info.get("derived") or [], meta)):
added.append(w)
muted = [m for m in muted if m.lower() != w.lower()]
for w in a.remove or []:
added = [x for x in added if x.lower() != w.lower()]
for w in a.mute or []:
if w.lower() not in low(info.get("derived") or []):
# Only a derived trigger can be muted; an added one is removed.
added = [x for x in added if x.lower() != w.lower()]
continue
if w.lower() not in low(muted):
muted.append(w)
for w in a.unmute or []:
muted = [m for m in muted if m.lower() != w.lower()]
res = hub.call("PATCH", "/api/tag-meta/tag", {"id": tid, "patch": {"triggers": added or None,
"mutedTriggers": muted or None}})
new = res.get("meta") or {}
if a.json:
print(json.dumps(_row(tid, info, new), ensure_ascii=False))
else:
print(f"{tid}: watches {', '.join(effective(info.get('derived') or [], new)) or '— nothing'}"
+ (f" (muted: {', '.join(new.get('mutedTriggers') or [])})" if new.get("mutedTriggers") else ""))
return 0
if action == "set":
return _set(hub, a, tid, info)
raise ValueError(f"unknown action {action}")
def _set(hub, a, tid: str, info: dict) -> int:
patch: dict = {}
color_from_icon = None
src = a.icon_file or (f"selfh.st:{a.selfhst}" if a.selfhst else None)
if a.real_icon:
cands = find_icons(tid, info)
if not cands:
raise ValueError(f"no real icon found for {tid} (try `ai-agent tags find-icon {tid}`)")
src = cands[0].get("file") or cands[0]["source"]
_err(f"{tid}: using {cands[0]['source']}")
if src:
data, name = load_icon_bytes(src)
if not a.tint and not a.own_colors and b"currentColor" in data and data.lstrip()[:1] == b"<":
# A glyph drawn in `currentColor` (a lucide icon as favicon) has no
# colours of its own: as a picture it is black. Draw it tinted.
a.tint = True
_err(f"{tid}: the icon is drawn in currentColor — tinting it with the tag's colour")
res = hub.post("/api/tag-meta/icons", {"name": name or info.get("slug") or "icon",
"data": base64.b64encode(data).decode(),
"tint": bool(a.tint)})
icon = res["icon"]
color_from_icon = res.get("color")
if src.startswith("selfh.st:") and not color_from_icon and not a.tint:
# A black-and-white logo in its own colours vanishes on one theme or
# the other: the selfh.st mono glyph (`sh:`) is drawn in the tag's
# colour instead, like the shipped defaults.
if not any(k.get("icon") == "svg:" + icon["id"] for k in hub.get("/api/tag-meta")["tags"].values()):
hub.call("DELETE", f"/api/tag-meta/icons/{icon['id']}")
patch["icon"] = "sh:" + src.split(":", 1)[1]
_err(f"{tid}: {src} has no colour of its own — using the tinted selfh.st glyph")
else:
if bool(icon.get("tint", not icon.get("image"))) != bool(a.tint):
icon = hub.call("PATCH", f"/api/tag-meta/icons/{icon['id']}", {"tint": bool(a.tint)})["icon"]
patch["icon"] = "svg:" + icon["id"]
if not color_from_icon and not a.tint:
_err(f"{tid}: the icon has no colour of its own — if it's a dark glyph on a transparent "
f"background it disappears in dark mode; `--tint` draws it in the tag's colour")
patch["iconSource"] = a.source or (src.replace(str(HOME), "~", 1) if not src.startswith("selfh.st:") else src)
elif a.icon:
patch["icon"] = a.icon
if a.source:
patch["iconSource"] = a.source
if a.color == "none":
patch["color"] = None
elif a.color and a.color != "auto":
patch["color"] = a.color
elif (a.color == "auto" or (src and not a.keep_color)) and color_from_icon:
patch["color"] = color_from_icon
elif a.color == "auto" and not src:
raise ValueError("--color auto needs an icon file (--icon-file / --selfhst / --real-icon)")
if a.description is not None:
patch["description"] = a.description or None
if not patch:
raise ValueError("nothing to set — pass --color, --icon, --icon-file, --selfhst, --real-icon or --description")
res = hub.call("PATCH", "/api/tag-meta/tag", {"id": tid, "patch": patch})
meta = res.get("meta") or {}
if a.json:
print(json.dumps(_row(tid, info, meta), ensure_ascii=False))
else:
bits = [f"{k}={v}" for k, v in patch.items() if k != "description"]
if "description" in patch:
bits.append("description")
print(f"{tid}: {' '.join(bits)}")
return 0
def _icons(hub, a, icons: dict) -> int:
if a.rm:
hub.call("DELETE", f"/api/tag-meta/icons/{a.rm}")
print(f"icon {a.rm}: removed")
return 0
rows = [{"id": i["id"], "name": i.get("name"), "type": "image" if i.get("image") else "svg",
"tint": i.get("tint"), "bytes": len(i.get("image") or i.get("svg") or "")} for i in icons.values()]
if a.json:
print(json.dumps(rows))
return 0
for r in rows:
print(f"svg:{r['id']:<10} {r['type']:<5} {r['bytes']:>6}B {r['name']}")
return 0
def add_parser(sub) -> argparse.ArgumentParser:
tg = sub.add_parser(
"tags", help="a tag's colour / icon / description / auto-tag triggers (Settings → Tags)",
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
tg.add_argument("--json", action="store_true")
ts = tg.add_subparsers(dest="action")
# `ai-agent tags --json show x` and `ai-agent tags show x --json` alike: a
# subparser's own default must not reset the flag given before it.
J = {"action": "store_true", "default": argparse.SUPPRESS}
ls = ts.add_parser("ls", help="every tag with its look and triggers")
ls.add_argument("query", nargs="*", help="filter words")
ls.add_argument("--kind", choices=KINDS)
ls.add_argument("--custom", action="store_true", help="only the ones with overrides")
ls.add_argument("--json", **J)
for name, hlp in (("show", "one tag: look, triggers (derived / added / muted), icon"),
("find-icon", "where a project's / service's real icon is, best first")):
p = ts.add_parser(name, help=hlp)
p.add_argument("tag")
p.add_argument("--json", **J)
st = ts.add_parser("set", help="colour, icon, description")
st.add_argument("tag")
st.add_argument("--color", help="palette key (sky, orange…), #rrggbb, auto (from the icon) or none")
st.add_argument("--icon", help="a glyph key: lucide name, sh:<selfh.st ref> (mono), svg:<id>")
st.add_argument("--icon-file", metavar="PATH|URL", help="an SVG / PNG / ICO / WebP — the real icon")
st.add_argument("--selfhst", metavar="REF", help="a selfh.st logo, in its own colours (gitea, jellyfin…)")
st.add_argument("--real-icon", action="store_true", help="the best `find-icon` candidate")
st.add_argument("--tint", action="store_true",
help="draw the icon in the tag's colour, as a mask of its shape (default: its own colours)")
st.add_argument("--own-colors", action="store_true",
help="never tint (by default a currentColor SVG is tinted, having no colours of its own)")
st.add_argument("--keep-color", action="store_true", help="don't take the tag's colour from the icon")
st.add_argument("--description", help="what a spawned prompt's location bullet says ('' = derived)")
st.add_argument("--source", help="where the icon came from (recorded as iconSource)")
st.add_argument("--json", **J)
tr = ts.add_parser("triggers", help="auto-tag words: add / remove yours, mute / unmute derived ones")
tr.add_argument("tag")
tr.add_argument("--add", action="append", metavar="WORD")
tr.add_argument("--remove", action="append", metavar="WORD")
tr.add_argument("--mute", action="append", metavar="WORD", help="a derived trigger (its name, a SKILL.md word)")
tr.add_argument("--unmute", action="append", metavar="WORD")
tr.add_argument("--clear", action="store_true", help="drop every added trigger first")
tr.add_argument("--json", **J)
rs = ts.add_parser("reset", help="back to the derived look (or just --field …)")
rs.add_argument("tag")
rs.add_argument("--field", action="append",
choices=("color", "icon", "description", "triggers", "mutedTriggers", "iconSource"))
rs.add_argument("--json", **J)
ic = ts.add_parser("icons", help="the uploaded icons (--rm ID to delete one)")
ic.add_argument("--rm", metavar="ID")
ic.add_argument("--json", **J)
return tg