Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
feat(email-cos): Telegram inline-button approvals + message-listener callback tee (#390)
Aurora Capitald12c3bcf3997
diff --git a/claude-ops/email-cos/README.md b/claude-ops/email-cos/README.mdindex fa9e7d3d..8768feb5 100644--- a/claude-ops/email-cos/README.md+++ b/claude-ops/email-cos/README.md@@ -93,6 +93,50 @@ Common auth issues:Known limit: Telegram approval requires a live MTProto session. If the session is expired, only Gmail and Slack approval paths are active.+#### Telegram inline-button approvals++An alternative approval path that requires no text replies — each digest item is posted as a Telegram message with tappable ✅ / ❌ buttons (or a) / b) / c) for multi-option items). Tapping a button immediately promotes the decision to `tasks.jsonl`.++**How it works:**++```+pocket digest → email-cos-tg-approve.py send+ posts one button message per open ASK to Telegram+ writes tg-callmap.json (short_id → full item)+ │+user taps ✅/❌/a/b/c in Telegram+ │+ops-message-listener (getUpdates owner)+ tees callback_query → $POCKET_STATE_DIR/tg-callbacks.jsonl+ advances offset via tg-maxoffset (so callbacks are not re-fetched)+ │+email-cos-tg-process.timer (~60s)+ email-cos-tg-approve.py process+ drains tg-callbacks.jsonl+ promotes APPROVE → tasks.jsonl / REJECT → approval-resolved.jsonl+ answers the callback (toast notification in Telegram)+ edits the message to show the result (freezes buttons)+```++**Dependency on the message-listener tee:** The listener script (`scripts/ops-message-listener.sh`) owns the bot's `getUpdates` long-poll. A second `getUpdates` poller for the same token would conflict and cause updates to be delivered to only one. The listener tees `callback_query` updates to `tg-callbacks.jsonl` so `email-cos-tg-approve.py process` can drain them without competing. This means the button system only works when `ops-message-listener` is running as the sole `getUpdates` consumer for the bot.++**Setup:**++```sh+EMAIL_COS_TG_ENABLE="true"+EMAIL_COS_TG_CHAT_ID="123456789" # numeric ID — find via @userinfobot+# EMAIL_COS_APPROVAL_BOT_TOKEN="" # defaults to TELEGRAM_BOT_TOKEN+# EMAIL_COS_APPROVALS_PY="" # defaults to scripts/ops-pocket-approvals.py+```++After configuring, re-run `install.sh` — it will enable `email-cos-tg-process.timer` automatically when `EMAIL_COS_TG_ENABLE=true` and `EMAIL_COS_TG_CHAT_ID` are both set.++To post button messages manually: `~/.local/share/email-cos/email-cos-tg-approve.py send`++To drain callbacks manually: `~/.local/share/email-cos/email-cos-tg-process.sh`++**Same-bot caveat:** Buttons are sent by the same bot token that the message-listener uses for `getUpdates`. Using a different bot token for button messages would require that bot to also own `getUpdates`, creating a conflict. Keep `EMAIL_COS_APPROVAL_BOT_TOKEN` unset (inherits `TELEGRAM_BOT_TOKEN`) unless you have explicitly set up the listener to use a different token for its polling.+Outbound confirmation only (no inbound approval reads — WhatsApp self-chat reply-read is not supported).@@ -173,6 +217,7 @@ The `"fallback": true` category catches everything not matched by prior rules.| email-cos-compact | weekly Sun 04:30 | EMAIL_COS_ACCOUNT set || email-cos-approve | every 3 min | any channel + account || email-cos-status | daily 08:00 | TG or Slack enabled |+| email-cos-tg-process | every ~60s | EMAIL_COS_TG_ENABLE=true + TG_CHAT_ID set |Check timer health: `systemctl --user list-timers 'email-cos*'`diff --git a/claude-ops/email-cos/email-cos-tg-approve.py b/claude-ops/email-cos/email-cos-tg-approve.pynew file mode 100644index 00000000..53a87b4a--- /dev/null+++ b/claude-ops/email-cos/email-cos-tg-approve.py@@ -0,0 +1,246 @@+#!/usr/bin/env python3+"""Telegram inline-button approvals for the pocket digest.++ send post each open ASK to Telegram as a message with tappable buttons+ (✅ Approve / ❌ Reject, or a)/b)/c) for choice items) + write a+ callmap (short_id -> full ASK entry) for the processor.+ process drain callbacks the listener tee'd to tg-callbacks.jsonl: promote the+ tapped decision (same logic as ops-pocket-approvals cmd_replies),+ answer the callback (toast), and edit the message to show the result.++Same bot as the message-listener, so we never poll getUpdates here — the listener+tees callback_query events to tg-callbacks.jsonl and we act on the file.++Configuration (env vars or ~/.config/email-cos/config.sh):+ EMAIL_COS_APPROVAL_BOT_TOKEN Bot token (falls back to TELEGRAM_BOT_TOKEN).+ EMAIL_COS_TG_CHAT_ID Numeric chat/user ID to send button messages to.+ Required — script exits cleanly if unset.+ EMAIL_COS_APPROVALS_PY Path to ops-pocket-approvals.py.+ Default: path relative to this script's location+ (../../scripts/ops-pocket-approvals.py).+ POCKET_STATE_DIR Pipeline state dir (default: /var/lib/pocket-pipeline).+ COS_TG_SEND_CAP Max button messages per send run (default: 8).+"""++import json, os, hashlib, subprocess, importlib.util, pathlib, urllib.parse, urllib.request, sys, time++STATE = pathlib.Path(os.environ.get("POCKET_STATE_DIR", "/var/lib/pocket-pipeline"))+CALLMAP = STATE / "tg-callmap.json"+CALLBACKS = STATE / "tg-callbacks.jsonl"+CB_SEEN = STATE / "tg-callbacks.seen"+TASKS = STATE / "tasks.jsonl"+RESOLVED = STATE / "approval-resolved.jsonl"++TOKEN = os.environ.get("EMAIL_COS_APPROVAL_BOT_TOKEN") or os.environ.get(+ "TELEGRAM_BOT_TOKEN", ""+)++CHAT = os.environ.get("EMAIL_COS_TG_CHAT_ID", "")+if not CHAT:+ print("EMAIL_COS_TG_CHAT_ID is not set — exiting.", file=sys.stderr)+ sys.exit(0)++# Path to ops-pocket-approvals.py. Configurable via EMAIL_COS_APPROVALS_PY.+# Default resolves relative to this script: email-cos/ → scripts/ops-pocket-approvals.py+_default_approvals_py = str(+ pathlib.Path(__file__).resolve().parent.parent+ / "scripts"+ / "ops-pocket-approvals.py"+)+APPROVALS_PY = os.path.expanduser(+ os.environ.get("EMAIL_COS_APPROVALS_PY", _default_approvals_py)+)+++def _api(method, payload):+ url = f"https://api.telegram.org/bot{TOKEN}/{method}"+ data = urllib.parse.urlencode(+ {+ k: (json.dumps(v) if isinstance(v, (dict, list)) else v)+ for k, v in payload.items()+ }+ ).encode()+ try:+ with urllib.request.urlopen(+ urllib.request.Request(url, data=data), timeout=15+ ) as r:+ return json.loads(r.read().decode())+ except Exception as e:+ return {"ok": False, "error": str(e)}+++def _load_approvals():+ spec = importlib.util.spec_from_file_location("appr", APPROVALS_PY)+ m = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(m)+ return m+++def _sid(item_id):+ return "i" + hashlib.sha1(item_id.encode()).hexdigest()[:10]+++def cmd_send():+ m = _load_approvals()+ items = m.open_items()+ if not items:+ print("no open items")+ return+ resolved = m._resolved_ids() if hasattr(m, "_resolved_ids") else set()+ cap = int(os.environ.get("COS_TG_SEND_CAP", "8"))+ # Idempotent: keep prior button messages, only send items not already sent.+ callmap = json.loads(CALLMAP.read_text()) if CALLMAP.exists() else {}+ already = {v.get("id") for v in callmap.values()}+ sent = 0+ for it in items:+ if sent >= cap:+ break+ iid = it["id"]+ if iid in resolved or iid in already:+ continue+ sid = _sid(iid)+ opts = []+ ap = ""+ # reuse the option extractor added in #387 if present+ if hasattr(m, "_extract_option_fields"):+ try:+ ap, dq, opts = m._extract_option_fields(it.get("raw", {}))+ except Exception:+ opts = []+ title = it.get("title", "")[:120]+ ctx = it.get("ctx") or ""+ ctx = (+ m._truncate_words(ctx, 500) if hasattr(m, "_truncate_words") else ctx[:500]+ )+ text = f"*{title}*\n{ctx}"+ if ap:+ text += f"\n\n→ *Approve =* {ap}"+ if opts:+ rows = [+ [+ {+ "text": f"{o['key']}) {o['label'][:40]}",+ "callback_data": f"po:{sid}:{o['key']}",+ }+ ]+ for o in opts+ ]+ rows.append([{"text": "❌ Reject", "callback_data": f"pr:{sid}"}])+ else:+ rows = [+ [+ {"text": "✅ Approve", "callback_data": f"pa:{sid}"},+ {"text": "❌ Reject", "callback_data": f"pr:{sid}"},+ ]+ ]+ r = _api(+ "sendMessage",+ {+ "chat_id": CHAT,+ "text": text[:3800],+ "parse_mode": "Markdown",+ "reply_markup": {"inline_keyboard": rows},+ },+ )+ mid = (r.get("result") or {}).get("message_id")+ callmap[sid] = {+ "id": iid,+ "kind": it.get("kind"),+ "bucket": it.get("bucket"),+ "raw": it.get("raw"),+ "options": opts,+ "message_id": mid,+ "title": title,+ }+ if r.get("ok"):+ sent += 1+ CALLMAP.write_text(json.dumps(callmap, indent=0))+ print(f"sent {sent} button message(s); callmap={len(callmap)}")+++def cmd_process():+ if not CALLBACKS.exists():+ print("no callbacks")+ return+ m = _load_approvals()+ callmap = json.loads(CALLMAP.read_text()) if CALLMAP.exists() else {}+ seen = set(CB_SEEN.read_text().split()) if CB_SEEN.exists() else set()+ resolved = m._resolved_ids() if hasattr(m, "_resolved_ids") else set()+ acted = 0+ for line in CALLBACKS.read_text().splitlines():+ line = line.strip()+ if not line:+ continue+ try:+ cb = json.loads(line)+ except Exception:+ continue+ cbid = str(cb.get("id"))+ if cbid in seen:+ continue+ seen.add(cbid)+ data = cb.get("data", "")+ parts = data.split(":")+ verb, sid = (parts[0], parts[1]) if len(parts) >= 2 else ("", "")+ ent = callmap.get(sid)+ toast = "Unknown / expired item."+ if ent and ent["id"] not in resolved:+ raw = ent.get("raw") or {}+ if verb == "pr":+ open(RESOLVED, "a").write(+ json.dumps(+ {"id": ent["id"], "decision": "REJECT", "ts": time.time()}+ )+ + "\n"+ )+ toast = "❌ Rejected."+ elif verb in ("pa", "po"):+ task = raw.get("task", raw) if isinstance(raw, dict) else {}+ task = dict(task)+ task["id"] = ent["id"]+ task.setdefault("kind", "action_item")+ task["approved_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())+ if verb == "po" and len(parts) >= 3:+ task["chosen_option"] = parts[2]+ lbl = next(+ (+ o["label"]+ for o in ent.get("options", [])+ if o["key"] == parts[2]+ ),+ "",+ )+ task["chosen_option_label"] = lbl+ toast = f"✅ Chose {parts[2]}) {lbl[:40]}"+ else:+ toast = "✅ Approved — running."+ open(TASKS, "a").write(json.dumps(task) + "\n")+ open(RESOLVED, "a").write(+ json.dumps(+ {"id": ent["id"], "decision": "APPROVE", "ts": time.time()}+ )+ + "\n"+ )+ resolved.add(ent["id"])+ acted += 1+ # tap feedback + freeze the message+ _api("answerCallbackQuery", {"callback_query_id": cbid, "text": toast})+ if ent.get("message_id"):+ _api(+ "editMessageText",+ {+ "chat_id": CHAT,+ "message_id": ent["message_id"],+ "text": f"*{ent.get('title', '')}*\n{toast}",+ "parse_mode": "Markdown",+ },+ )+ else:+ _api("answerCallbackQuery", {"callback_query_id": cbid, "text": toast})+ CB_SEEN.write_text("\n".join(sorted(seen)) + "\n")+ print(f"processed callbacks; acted={acted}")+++if __name__ == "__main__":+ mode = sys.argv[1] if len(sys.argv) > 1 else "send"+ {"send": cmd_send, "process": cmd_process}.get(mode, cmd_send)()diff --git a/claude-ops/email-cos/email-cos-tg-process.sh b/claude-ops/email-cos/email-cos-tg-process.shnew file mode 100644index 00000000..d6fbf2d7--- /dev/null+++ b/claude-ops/email-cos/email-cos-tg-process.sh@@ -0,0 +1,22 @@+#!/usr/bin/env bash+# email-cos-tg-process.sh — drain Telegram approval callbacks.+# Invoked by email-cos-tg-process.timer (oneshot, ~every 60s).+# Sources the email-cos config (for EMAIL_COS_TG_CHAT_ID etc.) then delegates+# to email-cos-tg-approve.py process.+set -euo pipefail++# Source config if available.+CONFIG="${EMAIL_COS_CONFIG:-$HOME/.config/email-cos/config.sh}"+if [[ -f "$CONFIG" ]]; then+ set -a; . "$CONFIG"; set +a+fi++# Also load secrets env if present (TELEGRAM_BOT_TOKEN lives here on most installs).+if [[ -f "$HOME/.mcp-secrets.env" ]]; then+ set -a; . "$HOME/.mcp-secrets.env"; set +a+fi++export POCKET_STATE_DIR="${POCKET_STATE_DIR:-/var/lib/pocket-pipeline}"++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+exec python3 "$SCRIPT_DIR/email-cos-tg-approve.py" processdiff --git a/claude-ops/email-cos/email-cos.config.example.sh b/claude-ops/email-cos/email-cos.config.example.shindex 2792bfb1..8630715e 100755--- a/claude-ops/email-cos/email-cos.config.example.sh+++ b/claude-ops/email-cos/email-cos.config.example.sh@@ -52,12 +52,25 @@ EMAIL_COS_REMIND_CAP_RUN="12"EMAIL_COS_TG_ENABLE="false"-# Numeric Telegram chat ID to receive notifications (your user ID or a group/channel).+# Numeric Telegram chat ID to receive notifications AND inline-button approvals.+# Find yours: message @userinfobot in Telegram; it replies with your numeric ID.+# Required for inline-button approvals — if unset, email-cos-tg-approve.py exits cleanly.EMAIL_COS_TG_CHAT_ID="YOUR_TELEGRAM_CHAT_ID"# @username of the Telegram bot used for outbound notifications.EMAIL_COS_TG_BOT_USERNAME="YourTelegramBotUsername"+# Bot token for sending inline-button approval messages.+# Usually the same bot as TELEGRAM_BOT_TOKEN (already set in ~/.mcp-secrets.env or Doppler).+# Set here only if you need a different bot for approvals.+# EMAIL_COS_APPROVAL_BOT_TOKEN=""++# Path to ops-pocket-approvals.py — the script that reads open ASK items and+# promotes decisions to tasks.jsonl. The default resolves relative to the+# email-cos package directory (../../scripts/ops-pocket-approvals.py), which is+# correct after install. Override if your pocket pipeline lives elsewhere.+# EMAIL_COS_APPROVALS_PY="/path/to/scripts/ops-pocket-approvals.py"+# ── Channel: WhatsApp ────────────────────────────────────────────────────────# Requires a running whatsapp-bridge (default: http://localhost:8080).# Leave ENABLE unset or set to "false" to skip WhatsApp entirely.diff --git a/claude-ops/email-cos/install.sh b/claude-ops/email-cos/install.shindex d9b76f92..3bdd1b74 100755--- a/claude-ops/email-cos/install.sh+++ b/claude-ops/email-cos/install.sh@@ -37,6 +37,8 @@ for f in \email-cos-slack.sh \email-cos-status.sh \email-cos-compact.sh \+ email-cos-tg-approve.py \+ email-cos-tg-process.sh \icloud-reminder.sh \pocket-telegram-read; docp "$SCRIPT_DIR/$f" "$INSTALL_DIR/$f"@@ -103,6 +105,12 @@ else# Approve-agent — Gmail reply channel is available whenever account is set.systemctl --user enable --now email-cos-approve.timer && echo " enabled: email-cos-approve.timer" || true++ # Telegram inline-button approval processor — enable when TG chat is configured.+ if [ "${EMAIL_COS_TG_ENABLE:-false}" = "true" ] \+ && [ -n "${EMAIL_COS_TG_CHAT_ID:-}" ]; then+ systemctl --user enable --now email-cos-tg-process.timer && echo " enabled: email-cos-tg-process.timer" || true+ fifi# ── 6. Reload ─────────────────────────────────────────────────────────────────diff --git a/claude-ops/email-cos/systemd/email-cos-tg-process.service b/claude-ops/email-cos/systemd/email-cos-tg-process.servicenew file mode 100644index 00000000..dbd9b920--- /dev/null+++ b/claude-ops/email-cos/systemd/email-cos-tg-process.service@@ -0,0 +1,6 @@+[Unit]+Description=email-cos Telegram approval-callback processor+[Service]+Type=oneshot+ExecStart=%h/.local/share/email-cos/email-cos-tg-process.sh+TimeoutStartSec=120diff --git a/claude-ops/email-cos/systemd/email-cos-tg-process.timer b/claude-ops/email-cos/systemd/email-cos-tg-process.timernew file mode 100644index 00000000..d9595f39--- /dev/null+++ b/claude-ops/email-cos/systemd/email-cos-tg-process.timer@@ -0,0 +1,8 @@+[Unit]+Description=Drain Telegram approval button taps ~every 60s+[Timer]+OnBootSec=2min+OnUnitInactiveSec=60s+AccuracySec=15s+[Install]+WantedBy=timers.targetdiff --git a/claude-ops/scripts/ops-message-listener.sh b/claude-ops/scripts/ops-message-listener.shindex 28483147..d34d28ff 100755--- a/claude-ops/scripts/ops-message-listener.sh+++ b/claude-ops/scripts/ops-message-listener.sh@@ -182,8 +182,31 @@ data = json.load(sys.stdin)if not data.get('ok'):print('[]')sys.exit(0)+import os as _os+_sd = _os.environ.get('POCKET_STATE_DIR', '/var/lib/pocket-pipeline')filtered = []+_maxuid = 0for upd in data.get('result', []):+ _uid = upd.get('update_id', 0)+ if _uid > _maxuid:+ _maxuid = _uid+ # Tee inline-button taps (callback_query) to a handoff file for the pocket+ # approval processor, then skip — this bot's getUpdates is owned here.+ cb = upd.get('callback_query')+ if cb:+ try:+ _cbm = cb.get('message') or {}+ with open(_os.path.join(_sd, 'tg-callbacks.jsonl'), 'a') as _f:+ _f.write(json.dumps({+ 'id': cb.get('id'),+ 'data': cb.get('data', ''),+ 'message_id': _cbm.get('message_id'),+ 'chat_id': (_cbm.get('chat') or {}).get('id'),+ 'update_id': _uid,+ }) + '\n')+ except Exception:+ pass+ continuemsg = upd.get('message', {})sender = msg.get('from', {})# Skip owner's own messages (add TELEGRAM_OWNER_ID to env to filter by user_id)@@ -200,6 +223,14 @@ for upd in data.get('result', []):'update_id': upd.get('update_id', 0),'raw': msg})+# Persist the max update_id seen (incl. callbacks) so the offset advances past+# callback-only polls — otherwise the listener re-fetches them forever.+try:+ if _maxuid:+ with open(_os.path.join(_sd, 'tg-maxoffset'), 'w') as _f:+ _f.write(str(_maxuid))+except Exception:+ passprint(json.dumps(filtered))" 2>/dev/null || echo "[]"}@@ -262,6 +293,13 @@ print(max(ids) if ids else $TG_LAST_UPDATE_ID)" 2>/dev/null || echo "$TG_LAST_UPDATE_ID")fi+ # Advance the offset past callback_query updates tee'd to the handoff file,+ # so callback-only polls don't get re-fetched forever.+ _CBMAX=$(cat "${POCKET_STATE_DIR:-/var/lib/pocket-pipeline}/tg-maxoffset" 2>/dev/null || echo 0)+ if [[ "${_CBMAX:-0}" =~ ^[0-9]+$ ]] && [[ "$_CBMAX" -gt "${TG_LAST_UPDATE_ID:-0}" ]]; then+ TG_LAST_UPDATE_ID="$_CBMAX"+ fi+# ── Save state ──────────────────────────────────────────────────────────save_state "$TG_LAST_UPDATE_ID"