Files
gabrielvidalandClaude Fable 5.2 1f616161ac feat(plugins): notify.respond bridge and webhooks that answer, for a phone app channel
- notify.respond (plugins/hubnotify.py, handler token only, any user may
  approve it): pairing addresses, read one push back, answer an ask, run a
  push's button, mark pushes dismissed — as the handler's user, for their own
  pushes only; an ask no longer pending answers 409, a swipe clears the
  person's other channels but the one it came from.
- webhooks[].respond: "result" answers the action's own JSON (or a file of
  the plugin's shared / data dir); webhooks[].methods lets one answer GET.
- The ask / action / dismissed routes share their work with the bridge.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 20:13:33 +01:00

178 lines
7.2 KiB
Python

"""Notification channels a plugin contributes (``provides: notify.channel``).
The hub records every push, ask and form in its own log and reaches each
person in the app (the feed, SSE) and on their browsers (web push). Anything
past that — a phone through Home Assistant, ntfy, Telegram — is a **channel**:
a live plugin whose manifest says ``"provides": {"notify.channel": "<action>"}``.
For each event the host runs that action of **every enabled, approved install
of the person it is for** (a channel is per person: the owner's Home
Assistant, a guest's own ntfy), with on stdin::
{"event": "notify" | "ask" | "clear", "push": {…}}
``push`` is the payload the Home Assistant webhook always got — ``id``,
``title``, ``message`` (an ask: ``question`` + ``options``), ``url``,
``image``, ``type``, ``spoken``, ``importance``, ``channel``, ``actions``
(``[{action: "<id>__<i>", title}]``), ``tag``, ``account``…; a clear is
``{"tags": [...]}``. The action answers ``{"ok": bool, "status"?: int,
"error"?: str}``.
A tapped button comes back the way it always did — ``POST /api/ask/{id}/answer``
or ``/api/notify/{id}/action`` on the hub, from whichever channel it was
tapped on; the first answer wins and the hub clears the rest.
A notify / ask is delivered on the request thread (the CLI reads the
result) and tried once — a failure is recorded on the push, not retried
(Gabriel's call, 2026-11-25). Clears go off the request thread. With no
channel at all a push still lands in the app and on the browsers, and counts
as delivered.
"""
from __future__ import annotations
import logging
import threading
from typing import Any
log = logging.getLogger("ai-agent.channels")
PROVIDES = "notify.channel"
EVENTS = ("notify", "ask", "clear")
_DEFAULT_TIMEOUT_S = 12
def channels_for(deps, uid: str) -> list[dict[str, Any]]:
"""``uid``'s installs that deliver pushes (enabled, approved, declaring
``provides.notify.channel`` on an existing action)."""
store = getattr(deps, "plugin_store", None)
if store is None:
return []
out = []
try:
recs = [r for u, r in store.all_installed() if u == store.norm_uid(uid)]
except Exception:
return []
for rec in recs:
if not rec.get("enabled") or rec.get("needsApproval"):
continue
mf = rec.get("manifest") or {}
act = (mf.get("provides") or {}).get(PROVIDES)
if act and act in (mf.get("actions") or {}):
out.append(rec)
return out
def _run(deps, uid: str, rec: dict, event: str, push: dict) -> dict:
"""One delivery through one channel → a delivery record."""
from plugins.runner import run_script
mf = rec["manifest"]
act = mf["actions"][mf["provides"][PROVIDES]]
rec_out: dict[str, Any] = {"channel": mf["id"], "ok": False}
try:
raw = run_script(deps, deps.plugin_store, uid, rec, act["script"],
payload={"event": event, "push": push},
timeout_sec=min(int(act.get("timeoutSec") or _DEFAULT_TIMEOUT_S), 30))
except Exception as e: # a broken channel never breaks the push
msg = getattr(e, "message", None) or str(e)
log.warning("channel %s (%s): %s", mf["id"], event, msg)
return {**rec_out, "status": getattr(e, "status", 0) or 0,
"error": str(msg)[:300]}
ok = bool(raw.get("ok"))
rec_out["ok"] = ok
if isinstance(raw.get("status"), int):
rec_out["status"] = raw["status"]
if not ok:
rec_out["error"] = str(raw.get("error") or "failed")[:300]
return rec_out
def deliver(deps, uid: str, event: str, push: dict) -> list[dict]:
"""Send ``push`` through every channel of ``uid``, now; returns one
record per channel (``{channel, ok, status?, error?}``)."""
return [_run(deps, uid, rec, event, push) for rec in channels_for(deps, uid)]
def clear_async(deps, uid: str, tags: list[str], exclude: str | None = None) -> None:
"""Take ``tags`` off ``uid``'s channels, off the request thread —
``exclude``: but the channel (a plugin id) they were dismissed on."""
tags = [t for t in tags if t]
recs = [r for r in (channels_for(deps, uid) if tags else [])
if not exclude or (r.get("manifest") or {}).get("id") != exclude]
if not recs:
return
def run():
for rec in recs:
_run(deps, uid, rec, "clear", {"event": "clear", "tags": tags})
threading.Thread(target=run, daemon=True, name="channel-clear").start()
# ── notify.audio: a push's sound, from a plugin ─────────────────────────────
#
# The notification card's ▶ button (``POST /api/notifications/audio``) replays
# what the desk phone played for a push: the type's jingle, then its spoken
# line. Core only routes the request: the owner's plugin declaring
# ``"provides": {"notify.audio": "<action>"}`` (``desk-phone``) gets
# ``{spoken, type, title, message, audio}`` on stdin and answers
# ``{"ok": true, "wavBase64", "contentType": "audio/wav"}``. With no provider
# the button is hidden (``usePluginProvides("notify.audio")``) and the route
# answers 503.
AUDIO_PROVIDES = "notify.audio"
_AUDIO_TIMEOUT_S = 30
_AUDIO_FIELDS = ("spoken", "type", "title", "message", "audio")
class AudioUnavailable(Exception):
"""No ``notify.audio`` provider, or it could not render this push."""
def audio_provider(deps) -> tuple[dict[str, Any], str] | None:
"""The owner's active plugin providing ``notify.audio`` → (rec, action)."""
from plugins.store import OWNER_UID
from plugins.waiting import _providers_for
try:
found = _providers_for(deps, OWNER_UID, AUDIO_PROVIDES)
except Exception: # noqa: BLE001 — no plugin store (tests, early boot)
return None
for rec, _grant in found:
act = ((rec.get("manifest") or {}).get("provides") or {}).get(AUDIO_PROVIDES)
if act:
return rec, act
return None
def render_audio(deps, push: dict[str, Any]) -> bytes:
"""A push's sound as WAV bytes, from the owner's ``notify.audio``
plugin; :class:`AudioUnavailable` when there is none or it fails."""
import base64
import binascii
from plugins.runner import ActionError, run_script
hit = audio_provider(deps)
if hit is None:
raise AudioUnavailable("no notify.audio plugin is installed")
rec, action = hit
from plugins.store import OWNER_UID
act = rec["manifest"]["actions"][action]
payload = {k: str(push.get(k) or "") for k in _AUDIO_FIELDS}
try:
res = run_script(deps, deps.plugin_store, OWNER_UID, rec, act["script"], payload=payload,
timeout_sec=min(int(act.get("timeoutSec") or _AUDIO_TIMEOUT_S), _AUDIO_TIMEOUT_S))
except ActionError as e:
raise AudioUnavailable(e.message) from None
except Exception as e: # noqa: BLE001 — a broken plugin never breaks the hub
log.warning("notify.audio via %s failed: %s", rec.get("id"), e)
raise AudioUnavailable(str(e)[:300]) from None
try:
wav = base64.b64decode(str((res or {}).get("wavBase64") or ""), validate=True)
except (binascii.Error, ValueError):
wav = b""
if not wav.startswith(b"RIFF"):
raise AudioUnavailable(str((res or {}).get("error") or "the audio plugin returned no WAV")[:300])
return wav