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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ The updater pins `main` to an exact commit, validates it, backs up the current c
own installer. Your settings stay in place. It refuses to overwrite a modified install. Self-update needs macOS
launchd or Linux user systemd.

The bighelp app shows when a host's plugin is out of date (Settings › Hosts) and can update it, restart the
messaging gateway, and restart the Hermes process it's connected to so the new version loads. It then checks that
the new version is running. The in-place restart (`native-host-restart-v1`) keeps the same process, so launchd,
systemd and Hermes Desktop keep supervising it; chats running on that process stop.

## What it adds

| Feature | What you get in bighelp | Details |
Expand All @@ -53,6 +58,7 @@ launchd or Linux user systemd.
| Apps tab | Files the agent recently made or changed, and the pictures and videos it delivered. | [Artifacts and media](docs/APPS_ARTIFACTS_AND_MEDIA.md) |
| Cards | Native cards in chat: summaries, metrics, lists, timelines, charts, forms, checklists, weather, scores, stock quotes and more, via the `loopdy_render_*` tools. Card templates can be saved and reused. | [Cards guide](docs/CARDS.md) |
| Reactions | Agents can react to your messages with an emoji (`loopdy_react_to_message`). | |
| Secure input | An agent can ask for a password, API key or other secret with `bighelp_request_secure_input`. bighelp shows a masked pop-up; Hermes saves what you type to the agent's `.env` and the agent can use it only as `$NAME` in commands. The AI never sees the value. Hermes' own AI provider keys are excluded. | |
| Agent templates | Save an agent's setup as a template and start new agents from it. | |
| iPhone tools | `iphone_health` (read-only), `iphone_calendar` and `iphone_reminders`. Each is off until you allow it for a host on your phone. They only work while bighelp is open and in the foreground. | [iPhone tools](docs/IPHONE_DEVICE_TOOLS.md) |
| Live voice | Talk with your agent in real time. It uses the Codex subscription signed in on the host (or an API key); the work itself runs as a normal Hermes chat. | [Live voice](docs/LIVE_VOICE.md) |
Expand Down
64 changes: 64 additions & 0 deletions loopdy_plugin/host_restart.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""Restart the Hermes process serving the bighelp app, in place.

After the app updates this plugin, new code only runs once the process that
serves the native API restarts. Hermes has no API for restarting that process,
so this re-executes it with the exact command line and environment it started
with. The PID stays the same, so launchd, systemd and Hermes Desktop keep
supervising it. Running chats on this process stop.
"""
from __future__ import annotations

import logging
import os
import sys
import threading
from typing import Any

CAPABILITY = "native-host-restart-v1"
_DELAY_SECONDS = 0.75

logger = logging.getLogger("hermes.plugins.loopdy")
_lock = threading.Lock()
_scheduled = False


def available() -> bool:
"""POSIX only: Windows has no in-place exec."""
return os.name == "posix" and bool(getattr(sys, "orig_argv", None)) and bool(sys.executable)


def restart_command() -> list[str]:
# orig_argv keeps "-m hermes_cli.main" and every flag (--isolated, --port, ...).
return [sys.executable, *sys.orig_argv[1:]]


def schedule(*, execv=os.execv, delay: float = _DELAY_SECONDS, timer=threading.Timer) -> dict[str, Any]:
"""Re-exec shortly after the HTTP response is written. One restart at a time."""
global _scheduled
if not available():
raise RuntimeError("host_restart_unavailable")
with _lock:
if _scheduled:
return {"restarting": True, "alreadyScheduled": True}
_scheduled = True
command = restart_command()

def restart() -> None:
global _scheduled
logger.warning("bighelp: restarting this Hermes process to load an updated plugin")
for stream in (sys.stdout, sys.stderr):
try:
stream.flush()
except (OSError, ValueError):
pass
try:
execv(command[0], command)
except OSError:
logger.exception("bighelp: in-place restart failed; the process keeps running")
with _lock:
_scheduled = False

worker = timer(delay, restart)
worker.daemon = True
worker.start()
return {"restarting": True, "alreadyScheduled": False}
2 changes: 1 addition & 1 deletion loopdy_plugin/link_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def parse_direct_enrollment(payload: dict[str, Any]) -> dict[str, Any]:
"body_fat_percentage",
"workout",
)
PLUGIN_VERSION = "2.16.0"
PLUGIN_VERSION = "2.17.0"
AVAILABLE_WIKI_OPERATIONS = available_wiki_operations()
GROUPS_OPERATIONS = frozenset(
{
Expand Down
36 changes: 34 additions & 2 deletions loopdy_plugin/managed_notifications.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ def _private_file(path: Path) -> None:
raise ManagedNotificationError("notification_private_storage_required", 503)


class _AlreadyAlerted(Exception):
"""The turn's reply alert already went out from post_llm_call."""


class ManagedNotifications:
"""One process-owned observer/worker; SQLite serializes other API processes."""
def __init__(self, directory: Path, *, transport: Callable = _https_request,
Expand All @@ -149,6 +153,9 @@ def __init__(self, directory: Path, *, transport: Callable = _https_request,
self._approval_owner = str(uuid.uuid4())
self._work: OrderedDict[tuple[str, str, str], dict[str, Any]] = state["work"]
self._responses: OrderedDict[tuple[str, str, str], str] = state["responses"]
# Turns whose reply alert already went out from post_llm_call (setdefault: a
# state dict made by an older copy of this module in the same process).
self._alerted: OrderedDict[tuple[str, str, str], bool] = state.setdefault("alerted", OrderedDict())
self._child_owners: dict[tuple[str, str, str], str] = state["child_owners"]
self._child_goals: dict[tuple[str, str, str], str] = state["child_goals"]
self._key = self._identity()
Expand Down Expand Up @@ -743,6 +750,22 @@ def _observe(self, hook: str, *, profile: str, **payload: Any):
self._responses.move_to_end(coordinate)
while len(self._responses) > 256:
self._responses.popitem(last=False)
# Hermes fires post_llm_call once per finished, uninterrupted turn, right after the
# reply is saved. on_session_end comes only after post-turn work (external memory
# sync, reviews) that can take several seconds, so the reply alert goes out now.
if response_text and not child_hook:
scheduled = payload.get("platform") == "cron" or _CRON_SESSION.fullmatch(session_id) is not None
try:
self._queue_event(profile, session_id, turn,
"scheduled.completed" if scheduled else "session.completed",
content_text=response_text)
except (ValueError, OSError):
logger.warning("Notification presentation unavailable; work state remains authoritative")
else:
with self._lock:
self._alerted[coordinate] = True
while len(self._alerted) > 256:
self._alerted.popitem(last=False)
if not child_hook and isinstance(turn, str) and _ID.fullmatch(turn):
if hook == "on_session_end":
self._retire_approval_scope(profile, session_id, turn, "", "turn_end")
Expand All @@ -754,9 +777,13 @@ def _observe(self, hook: str, *, profile: str, **payload: Any):
and payload.get("interrupted") is not True):
with self._lock:
content = self._responses.pop((profile, session_id, turn), "")
alerted = self._alerted.pop((profile, session_id, turn), False)
# Alert presentation must not prevent the authoritative work/Activity
# terminal below, including turns with no text or unavailable avatars.
# A turn already alerted from post_llm_call gets no second alert, not even
# "failed": that alert already carried the reply Hermes wrote about it.
try:
if alerted: raise _AlreadyAlerted()
scheduled = payload.get("platform") == "cron" or _CRON_SESSION.fullmatch(session_id) is not None
if payload.get("failed") is True:
content = self._rich_text(payload.get("error") or content)
Expand All @@ -767,6 +794,8 @@ def _observe(self, hook: str, *, profile: str, **payload: Any):
self._queue_event(profile, session_id, turn,
"scheduled.completed" if scheduled else "session.completed",
content_text=content)
except _AlreadyAlerted:
pass
except (ValueError, OSError):
logger.warning("Notification presentation unavailable; work state remains authoritative")
with self._lock:
Expand Down Expand Up @@ -916,7 +945,9 @@ def _run(self):
while not self._stop.is_set():
try: self.drain_pending()
except (ValueError, OSError, sqlite3.Error): logger.warning("Managed notification journal unavailable")
self._wake.wait(5); self._wake.clear()
# Short wait: another Hermes process may have queued the alert (this process
# owns the sender), and its wake-up doesn't reach this thread.
self._wake.wait(1); self._wake.clear()

def _approval_transport_ready(self, row) -> bool:
"""Last local fence after signing, immediately before the HTTPS call.
Expand Down Expand Up @@ -1002,7 +1033,8 @@ def drain_pending(self):

def _new_observations() -> dict[str, Any]:
return {"lock": threading.RLock(), "wake": threading.Event(),
"work": OrderedDict(), "responses": OrderedDict(), "child_owners": {}, "child_goals": {},
"work": OrderedDict(), "responses": OrderedDict(), "alerted": OrderedDict(),
"child_owners": {}, "child_goals": {},
"loaded_profiles": set(), "approval_profiles": set(), "clarification_profiles": set()}


Expand Down
21 changes: 21 additions & 0 deletions loopdy_plugin/native_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,27 @@ async def device_tools(operation: str, request: Request) -> Response:
return await native_device_tools.request(operation, request)


class _HostRestart(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
confirm: Literal[True]


@router.post("/host/restart")
async def host_restart(request: Request) -> Response:
"""Restart this Hermes process in place so an updated plugin loads (bighelp app Update)."""
from .host_restart import CAPABILITY, schedule
owner = native_context(request)
request_id = _precondition(request, owner)
if CAPABILITY not in owner.features:
raise NativeAPIError(503, "host_restart_unavailable", "This host can't restart from the app.")
await _body(request, _HostRestart)
try:
value = schedule()
except RuntimeError:
raise NativeAPIError(503, "host_restart_unavailable", "This host can't restart from the app.") from None
return _response({**value, "runtimeId": owner.runtime_id}, owner, request_id)


@router.post("/attachments/{operation}")
async def agent_attachments(operation: str, request: Request) -> Response:
from .native_attachments import request as attachments_request
Expand Down
5 changes: 5 additions & 0 deletions loopdy_plugin/native_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,4 +256,9 @@ def skip(feature: str, reason: str) -> None:
except ImportError:
skip("native-agent-attachments-v1", "native attachment support is unimportable.")
skip("native-agent-media-v1", "native attachment support is unimportable.")
from .host_restart import CAPABILITY as restart_capability, available as restart_available
if restart_available():
features.append(restart_capability)
else:
skip(restart_capability, "in-place restart needs a POSIX host.")
return profile, tuple(features)
177 changes: 177 additions & 0 deletions loopdy_plugin/secure_input.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
"""Secure input the agent can ask for, using Hermes' own secret-capture pathway.

The bighelp app (and the Hermes TUI) answer Hermes' ``secret`` server request with a
masked field. Hermes saves the answer to this profile's ``.env`` through its credential
lifecycle; this tool then lets the agent's terminal and code tools read it as ``$NAME``.
The value never enters the conversation, the tool result or any log: the model only
learns whether it was saved.
"""
from __future__ import annotations

import json
import os
import re
from typing import Any, Callable

SCHEMA = "bighelp.secure-input"
TOOL_NAME = "bighelp_request_secure_input"
_NAME = re.compile(r"^[A-Z][A-Z0-9_]{1,63}$")
# Names that steer processes rather than hold a secret for a task.
_RESERVED = {"PATH", "HOME", "SHELL", "USER", "LOGNAME", "PWD", "TMPDIR", "TERM", "LANG", "NODE_OPTIONS"}
_RESERVED_PREFIXES = ("HERMES_", "LOOPDY_", "BIGHELP_", "PYTHON", "LD_", "DYLD_", "GIT_", "SSH_", "LC_")

PARAMETERS = {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Variable name to save it under, UPPER_SNAKE_CASE, e.g. GITHUB_TOKEN or BANK_PASSWORD.",
},
"prompt": {
"type": "string",
"description": "One or two plain sentences telling the person what to enter and why.",
},
"label": {
"type": "string",
"description": "Short field label shown above the input, e.g. \"GitHub token\".",
},
"replace": {
"type": "boolean",
"description": "Ask again even when a value is already saved (e.g. it stopped working).",
},
},
"required": ["name", "prompt"],
"additionalProperties": False,
}

DESCRIPTION = (
"Ask the person to type a password, API key, token or other sensitive value into a secure "
"pop-up on their device. Never ask for secrets in chat. What they type is saved privately on "
"this computer and you never see it: afterwards use it only as the environment variable "
"$NAME in terminal commands or code (for example curl -H \"Authorization: Bearer $GITHUB_TOKEN\"). "
"Never print, echo or log it. If a value is already saved you get already_saved without a "
"pop-up; pass replace=true only when the saved one is wrong or expired. Hermes' own AI "
"provider keys can't be set this way; point the person to Settings for those."
)


def _result(**fields: Any) -> str:
return json.dumps({"schema": SCHEMA, "version": 1, **fields}, separators=(",", ":"), sort_keys=True)


def _clean(value: Any, limit: int) -> str:
if not isinstance(value, str):
return ""
text = " ".join(value.split())
return text[:limit]


def valid_name(name: Any) -> bool:
if not isinstance(name, str) or not _NAME.fullmatch(name) or name in _RESERVED:
return False
return not name.startswith(_RESERVED_PREFIXES)


def _is_provider_credential(name: str) -> bool:
"""Hermes-managed AI provider keys stay in Settings (fails closed)."""
try:
from tools.environments.local_env_policy import _is_hermes_internal_secret, _is_provider_env_blocklisted
except Exception:
return True
return bool(_is_hermes_internal_secret(name) or _is_provider_env_blocklisted(name))


def _already_saved(name: str) -> bool:
try:
from agent.secret_scope import get_secret
return bool(get_secret(name))
except Exception:
return bool(os.environ.get(name))


def _capture_callback() -> Callable[..., Any] | None:
try:
from tools import skills_tool
except Exception:
return None
return getattr(skills_tool, "_secret_capture_callback", None)


def _has_interactive_session() -> bool:
"""Only an app or TUI session can show the pop-up; messaging chats can't."""
try:
from gateway.session_context import get_session_env
except Exception:
return False
return bool(get_session_env("HERMES_UI_SESSION_ID"))


def _allow_in_commands(name: str) -> None:
from tools.env_passthrough import register_env_passthrough
register_env_passthrough([name])


def request(
args: dict,
*,
callback: Callable[..., Any] | None = None,
interactive: Callable[[], bool] = _has_interactive_session,
saved: Callable[[str], bool] = _already_saved,
allow: Callable[[str], None] = _allow_in_commands,
provider_credential: Callable[[str], bool] = _is_provider_credential,
) -> str:
name = args.get("name")
if not valid_name(name):
return _result(success=False, error="invalid_name",
message="Use an UPPER_SNAKE_CASE name like GITHUB_TOKEN (not a system variable).")
if provider_credential(name):
return _result(success=False, error="provider_credential", stored_as=name,
message="AI provider keys are set in the bighelp app under Settings, not here.")
prompt = _clean(args.get("prompt"), 400)
if not prompt:
return _result(success=False, error="missing_prompt", message="Say what to enter and why.")
if saved(name) and args.get("replace") is not True:
allow(name)
return _result(success=True, already_saved=True, stored_as=name,
message=f"Already saved. Use ${name} in commands or code; never print it.")
capture = callback if callback is not None else _capture_callback()
if capture is None or not interactive():
return _result(success=False, error="secure_input_unavailable", stored_as=name,
message=f"Secure input needs the bighelp app or the Hermes TUI. Ask the person to add {name} "
"to this agent's .env file on the computer instead. Never ask for it in chat.")
metadata = {"source": "agent"}
if label := _clean(args.get("label"), 60):
metadata["label"] = label
try:
outcome = capture(name, prompt, metadata)
except Exception:
return _result(success=False, error="secure_input_failed", stored_as=name,
message="The secure pop-up couldn't be shown. Try again in a moment.")
if not isinstance(outcome, dict) or not outcome.get("success") or outcome.get("skipped"):
return _result(success=False, skipped=True, stored_as=name,
message="The person didn't enter it. Don't ask for it in chat; continue without it or ask later.")
allow(name)
return _result(success=True, stored_as=name,
message=f"Saved. Use ${name} in terminal commands or code; never print, echo or log it.")


def supported() -> bool:
try:
from tools.env_passthrough import register_env_passthrough # noqa: F401
from tools import skills_tool # noqa: F401
except Exception:
return False
return hasattr(skills_tool, "set_secret_capture_callback")


def register(ctx: Any) -> bool:
if not supported():
return False
ctx.register_tool(
name=TOOL_NAME,
toolset="loopdy",
schema={"name": TOOL_NAME, "description": DESCRIPTION, "parameters": PARAMETERS},
handler=lambda args, **_: request(args or {}),
emoji="🔐",
)
return True
Loading
Loading