Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ Many features span both repos. The app's side of each route lives in the app rep
| `loopdy_plugin/agent_guide.py`, `skills/bighelp/` | What agents are told about bighelp: the chat brief and the `bighelp` skill |
| `loopdy_plugin/agent_board.py`, `provider_usage.py`, `secure_input.py`, `agent_templates.py`, `reactions.py` | Feature modules |
| `loopdy_plugin/live_voice_*.py`, `native_voice.py` | Live voice |
| `loopdy_plugin/managed_notifications*.py`, `sealed_alerts.py`, `notification_crypto.py` | Notifications and Live Activities |
| `loopdy_plugin/managed_notifications*.py`, `sealed_alerts.py`, `card_detail.py`, `notification_crypto.py` | Notifications and Live Activities (`card_detail.py`: what a card shows beyond its phase, sealed for the phone) |
| `loopdy_plugin/plugin_update*.py`, `host_restart.py` | Self-update and the in-place restart |
| `loopdy_plugin/store.py` | The local store for card templates, form answers, approvals and events (`get_service()` in `adapter.py`) |
| `loopdy_plugin/adapter.py`, `service.py`, `provider.py`, `providers/` | The `loopdy` gateway platform and the legacy push provider, kept only for older setups |
Expand Down
31 changes: 29 additions & 2 deletions docs/NOTIFICATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -371,8 +371,35 @@ older plugin is marked failed and never sent.

The app starts the Live Activity itself. The host then sends updates for the current turn through the same
grant (`PUT/DELETE /notifications/enrollments/<grantId>/live-activities/<activityId>`). Updates carry only a
phase, a fixed label such as "Your agent is working" or "Your agent finished", and counts. They never include
message text.
phase, a fixed label such as "Your agent is working" or "Your agent finished", and counts. The notification
service and Apple can read these. They never include message text.

### Sealed card detail

An app that shows more on the card gives the host a key for that chat's row
(`PUT /notifications/enrollments/<grantId>/live-activities/<activityId>/card-key`, body
`{"version": 1, "key": "<32 bytes, base64url>"}`). The key comes over the app's own connection to this host,
never through the notification service. `capabilities` lists `sealedCardDetail: {"version": 1}`.

From then on each update for that card also carries `sealed`: the step in progress and what it works on, the
last three steps, the model's latest words between steps, a question or command that waits for the person, the
reply's first lines when the turn ends, helper goals, context use and the model's name. It is AES-256-GCM under
the row key, bound to the update's timestamp, and at most 1,200 characters. The service keeps and forwards the
bytes and cannot read them. A note that could hold a credential is left out. The format is in
[`card_detail.py`](../loopdy_plugin/card_detail.py), and `fixtures/contracts/sealed-card-v1-vector.json` is
shared with the app's tests.

A card with detail gets an update for each new step, at most one every 8 seconds. A new step alone is sent
with `quiet: true`, which the service sends at low priority, except that one update in every 30 seconds is not
quiet. A question, a command that waits for approval and the end of the turn go at once. A chat without a key
gets the updates it always got, 30 seconds apart. If the service refuses an update that has `sealed`, the host
drops that card's key and sends plain updates.

While the agent asks a question with `clarify`, or a command waits for approval, the card's phase is `waiting`.

A card goes stale on the phone 120 seconds after its last update. While a turn runs and no hook fires (a question
that waits, one long tool call), each Hermes process sends that turn's state again once a minute. It stops 30
minutes after the turn's last hook, unless the turn waits for the person.

## Host storage

Expand Down
9 changes: 6 additions & 3 deletions docs/SECURITY_AND_PRIVACY.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,12 @@ The host never sends an alert it can't seal: until the phone has registered its
builds do right after turning notifications on, no alert is queued or sent. App builds before bighelp 2.3.0 (20)
never register a key, so they get no alerts.

Live Activity updates contain only a phase, a fixed label and counts, never message text. The Lock Screen can
still show the agent and chat name the app put on the activity; turn off Live Activities or notification
previews in iOS settings if that matters to you.
Live Activity updates contain a phase, a fixed label and counts that the notification service and Apple can
read, never message text. For an app that asks for it, an update also carries detail (the step in progress, a
question that waits, the reply's first lines) encrypted with a key that only that phone and this host hold; the
service and Apple forward bytes they cannot read (see [Notifications](NOTIFICATIONS.md#sealed-card-detail)). The
Lock Screen shows what the app draws from it, with the agent and chat name; choose how much in the app's
Settings › Notifications, or turn off Live Activities in iOS settings if that matters to you.

## Cards

Expand Down
35 changes: 35 additions & 0 deletions fixtures/contracts/sealed-card-v1-vector.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"comment": "sealed-card-v1: AES-256-GCM, blob = nonce(12)+ciphertext+tag(16) in unpadded base64url, AAD = 'bighelp-card-v1|' + timestamp. Shared by the plugin's card_detail.py and the app's BighelpActivityDetail. Made-up data.",
"key": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8",
"nonce": "ZGVmZ2hpamtsbW5v",
"timestamp": 1800000123,
"detail": {
"v": 1,
"b": 1800000000,
"s": 9,
"t": "execute_code",
"n": "price per lb",
"tr": [
{
"t": "web_extract",
"c": 6,
"n": "example.com"
},
{
"t": "web_search",
"c": 3,
"n": "protein powder prices"
}
],
"say": "Comparing four brands now.",
"h": [
"Check shipping costs"
],
"cu": 30300,
"cm": 272000,
"m": "sample-model-1",
"q": "Send the order for $47.00?",
"p": "Cheapest per lb is Northfield Whey at $9.40 — “four” brands compared."
},
"sealed": "ZGVmZ2hpamtsbW5vMzm8REPYbq4OUm_Y6lVa0WChayixXsRAl-GcZNnA0Gqu2nDzfCK3JpXRQmTfAaKqeDC4lEgjMViTn8v2jO7W_nuuhiL0Jhk_qRyMLmHmVMsJF3tRy-i85PPTWOZBMT4j5xL3Xhsoyl7fmPzpgH2a0gBo6HqgCdxHxlnj1KiUZKUS9uuIJ10wX6EvP2Dl5HzV_qKEZjE_prYIv0p9wPMlbrDTp8D2s5SSidg8144GwqDygu3KWN4irgpkdWbgrD2_6BUkuc17ECE2Fw5DKkiWbTJo8G31eCiJxTYy5NPHPck9BZjCjqdYX2OOZvPrOu2hMaRuxZTki6SygjoJUF-U_wRT5O8KB7b6n3z0vtrDZnXL_jlP-lwfAbxhanAbCGZJiI83CFpfi8RC9nSm0ZKuymphN4xnZiG1OPVMbvTqTl7FM7KUY3xjjeGsIUi2AkVGldI4E6dsz-KWptnpW9OnePr0uekMckrYwePdhj92y1QkvYZtvbGK1VlkmtlKqYrJAEJjaMKx-gPuzr8rT9W-IvFxGhvqvwrnjg"
}
176 changes: 176 additions & 0 deletions loopdy_plugin/card_detail.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
"""What a Live Activity row shows beyond its phase, sealed for the phone (sealed-card-v1).

The notification service and Apple read a row's phase, time and helper count. Everything
else (the step in progress, the last steps, a question, the reply's first lines) goes in
`sealed`, which only the phone opens. The phone gives this host one key per chat row over
its own connection, never through the notification service.

Format: unpadded base64url of nonce(12) + AES-256-GCM(JSON) + tag(16).
AAD: "bighelp-card-v1|" + the update's timestamp, which is the row's timestamp on the phone,
so a blob cannot be shown with another update's time.
The JSON's keys are short because five rows share one 4 KB push:
v 1 · b turn start · s steps so far · t tool in progress · n its note
tr last finished steps, newest first: {t tool, c how many in a row, n note}
say the model's latest words between steps · q the question that waits
p the reply's first lines · h helper goals · cu/cm context tokens used/window · m model
The phone words the steps itself from the tool names (it has the translations).
`fixtures/contracts/sealed-card-v1-vector.json` is shared with the app's opener.
"""
from __future__ import annotations

import hashlib
import json
import os
from typing import Any
from urllib.parse import urlsplit

from cryptography.hazmat.primitives.ciphers.aead import AESGCM

from .notification_crypto import b64url_decode, b64url_encode
from .sensitive import contains_sensitive_credential

VERSION = 1
KEY_BYTES = 32
# What the notification service takes for one row.
MAX_SEALED_CHARS = 1_200
# (840 + 28) bytes are 1,158 base64url characters.
_MAX_PLAINTEXT_BYTES = 840
_AAD_LABEL = "bighelp-card-v1|"
_TRAIL = 3


def key_from(value: Any) -> bytes | None:
"""The row key a phone sent, or None when it is not 32 bytes of base64url."""
if not isinstance(value, str) or len(value) != 43: return None
try:
key = b64url_decode(value)
except ValueError:
return None
return key if len(key) == KEY_BYTES else None


def new_detail(started: int) -> dict[str, Any]:
return {"started": int(started), "steps": 0, "tool": "", "note": "", "trail": [], "say": "",
"question": "", "preview": "", "goals": {}, "used": None, "window": None, "model": ""}


def _line(value: Any, limit: int) -> str:
"""One bounded line of text, or nothing when it could carry a credential."""
if not isinstance(value, str): return ""
text = " ".join(value.split())
if not text or contains_sensitive_credential(text): return ""
return text if len(text) <= limit else text[:limit - 1].rstrip() + "…"


def _site(value: Any) -> str:
if isinstance(value, list): value = value[0] if value else ""
if not isinstance(value, str): return ""
try:
host = urlsplit(value if "//" in value else "//" + value).hostname or ""
except ValueError:
return ""
return _line(host.removeprefix("www."), 60)


def _note(tool: str, args: Any) -> str:
"""A few words on what this step works on. Never a whole argument list."""
if not isinstance(args, dict): return ""
name = tool.lower()
if "search" in name: return _line(args.get("query") or args.get("pattern"), 80)
if "web_extract" in name or "browser" in name or "fetch" in name:
return _site(args.get("url") or args.get("urls"))
if "terminal" in name: return _line((args.get("command") or "").split("\n")[0] if isinstance(args.get("command"), str) else "", 60)
if "file" in name or name == "patch":
path = args.get("path") or args.get("file_path")
return _line(os.path.basename(path), 60) if isinstance(path, str) else ""
if "delegate" in name: return _line(args.get("goal"), 80)
if "image" in name: return _line(args.get("prompt"), 80)
if "skill" in name: return _line(args.get("name"), 60)
return ""


def tool_started(detail: dict[str, Any], tool: Any, args: Any) -> None:
if not isinstance(tool, str) or not tool: return
detail["steps"] = min(detail["steps"] + 1, 9_999)
detail["tool"], detail["note"] = tool[:48], _note(tool, args)


def tool_finished(detail: dict[str, Any], tool: Any, args: Any) -> None:
if not isinstance(tool, str) or not tool: return
tool, trail = tool[:48], detail["trail"]
note = detail["note"] if detail["tool"] == tool else _note(tool, args)
if trail and trail[0]["t"] == tool:
trail[0]["c"] = min(trail[0]["c"] + 1, 999)
if note: trail[0]["n"] = note
else:
trail.insert(0, {"t": tool, "c": 1, **({"n": note} if note else {})})
del trail[_TRAIL:]
if detail["tool"] == tool: detail["tool"], detail["note"] = "", ""


def model_answered(detail: dict[str, Any], payload: dict[str, Any]) -> None:
"""One model request ended (Hermes' post_api_request): its words, the context it used, its model."""
message = payload.get("assistant_message")
content = getattr(message, "content", None)
if isinstance(message, dict): content = message.get("content")
if isinstance(content, list):
content = " ".join(str(part.get("text", "")) for part in content if isinstance(part, dict))
said = _line(content, 160)
if said: detail["say"] = said
usage, window = payload.get("usage"), payload.get("context_length")
used = usage.get("prompt_tokens") if isinstance(usage, dict) else None
if type(used) is int and used > 0: detail["used"] = used
if type(window) is int and window > 0: detail["window"] = window
model = payload.get("response_model") or payload.get("model")
if isinstance(model, str) and model: detail["model"] = _line(model.rsplit("/", 1)[-1], 48)


def plaintext(detail: dict[str, Any], phase: str) -> bytes:
"""The row's JSON, cut down until it fits one row's share of a push."""
body: dict[str, Any] = {"v": VERSION, "b": detail["started"], "s": detail["steps"]}
terminal = phase in ("completed", "failed")
if detail["tool"] and not terminal:
body["t"] = detail["tool"]
if detail["note"]: body["n"] = detail["note"]
if detail["trail"]: body["tr"] = [dict(step) for step in detail["trail"]]
if detail["say"] and not terminal: body["say"] = detail["say"]
if phase == "waiting" and detail["question"]: body["q"] = _line(detail["question"], 200)
if terminal and detail["preview"]: body["p"] = _line(detail["preview"], 280)
goals = [goal for goal in detail["goals"].values() if goal][:2]
if goals and not terminal: body["h"] = goals
if detail["used"] and detail["window"]: body["cu"], body["cm"] = detail["used"], detail["window"]
if detail["model"]: body["m"] = detail["model"]

def encoded() -> bytes:
return json.dumps(body, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode()
# Drop what matters least first; the question and the reply's lines go last, and shorter.
for cut in ("h", "say", "m", "n"):
if len(encoded()) <= _MAX_PLAINTEXT_BYTES: break
body.pop(cut, None)
if len(encoded()) > _MAX_PLAINTEXT_BYTES:
for step in body.get("tr", []): step.pop("n", None)
for key in ("p", "q"):
while len(encoded()) > _MAX_PLAINTEXT_BYTES and len(body.get(key, "")) > 40:
body[key] = body[key][:len(body[key]) // 2].rstrip() + "…"
if len(encoded()) > _MAX_PLAINTEXT_BYTES:
# Tool names or what is left in a script that takes many bytes a character: the timer and count alone.
body = {"v": VERSION, "b": detail["started"], "s": detail["steps"]}
return encoded()


def digest(plain: bytes) -> str:
"""Stands for the detail in an update's signature, so a new step counts as a change."""
return hashlib.sha256(plain).hexdigest()[:16]


def seal(key: bytes, timestamp: int, plain: bytes, *, nonce: bytes | None = None) -> str:
nonce = nonce or os.urandom(12)
sealed = b64url_encode(nonce + AESGCM(key).encrypt(nonce, plain, (_AAD_LABEL + str(int(timestamp))).encode()))
if len(sealed) > MAX_SEALED_CHARS: raise ValueError("sealed card detail is too large")
return sealed


def open_sealed(key: bytes, timestamp: int, sealed: str) -> dict[str, Any]:
"""What the phone does. Here for tests and the shared vector."""
raw = b64url_decode(sealed)
return json.loads(AESGCM(key).decrypt(raw[:12], raw[12:], (_AAD_LABEL + str(int(timestamp))).encode()))
Loading
Loading