From c8881b008c5a07709507c9584f7d860fb3b5ab4e Mon Sep 17 00:00:00 2001 From: "Prompt. Click. Run." <59135406+promptclickrun@users.noreply.github.com> Date: Sun, 27 Sep 2026 00:35:39 -0500 Subject: [PATCH 1/4] fix(notifications): alert as soon as the reply is saved (2.16.1) Reply alerts were queued at on_session_end, which Hermes fires only after post-turn work such as external memory sync and background reviews, adding seconds to every alert. post_llm_call fires once per finished, uninterrupted turn right after the reply is saved (0.21.1 through 0.21.5), so the alert is queued there; the later turn end sends nothing more for that turn. The sender now checks every second, since an alert queued by another Hermes process doesn't wake it. Co-Authored-By: Claude Opus 5.5 --- loopdy_plugin/link_contracts.py | 2 +- loopdy_plugin/managed_notifications.py | 36 ++++++++++++++++++++++++-- plugin.yaml | 2 +- tests/test_managed_notifications.py | 20 ++++++++++++++ 4 files changed, 56 insertions(+), 4 deletions(-) diff --git a/loopdy_plugin/link_contracts.py b/loopdy_plugin/link_contracts.py index 6932b4a..51060b2 100644 --- a/loopdy_plugin/link_contracts.py +++ b/loopdy_plugin/link_contracts.py @@ -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.16.1" AVAILABLE_WIKI_OPERATIONS = available_wiki_operations() GROUPS_OPERATIONS = frozenset( { diff --git a/loopdy_plugin/managed_notifications.py b/loopdy_plugin/managed_notifications.py index 2024c91..b7e6a75 100644 --- a/loopdy_plugin/managed_notifications.py +++ b/loopdy_plugin/managed_notifications.py @@ -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, @@ -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() @@ -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") @@ -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) @@ -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: @@ -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. @@ -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()} diff --git a/plugin.yaml b/plugin.yaml index fb72460..726b623 100644 --- a/plugin.yaml +++ b/plugin.yaml @@ -2,7 +2,7 @@ manifest_version: 1 name: loopdy label: Loopdy kind: platform -version: "2.16.0" +version: "2.16.1" license: Apache-2.0 description: > Native authenticated Hermes workspace controls, media voice, approvals, and diff --git a/tests/test_managed_notifications.py b/tests/test_managed_notifications.py index 843c374..2bc4290 100644 --- a/tests/test_managed_notifications.py +++ b/tests/test_managed_notifications.py @@ -183,6 +183,26 @@ def test_one_native_terminal_event_persists_and_retries_identical_rich_payload(s with sqlite3.connect(self.service.db_path) as db: self.assertEqual(db.execute("SELECT state FROM pending").fetchone()[0],"accepted") + def test_reply_alert_is_queued_when_the_reply_is_saved_not_after_post_turn_work(self): + # Hermes fires on_session_end only after external memory sync and reviews, + # which can take seconds; the alert must not wait for it. + self.service.observe("post_llm_call",profile="default",session_id="native-session",turn_id="turn-a",assistant_response="Here is your answer.") + with sqlite3.connect(self.service.db_path) as db: + self.assertEqual(db.execute("SELECT COUNT(*) FROM pending WHERE state='pending'").fetchone()[0],1) + self.service.drain_pending() + self.assertEqual([e["eventType"] for e in self.events_sent()],["session.completed"]) + # The later turn end, completed or failed, sends nothing more. + self.service.observe("on_session_end",profile="default",session_id="native-session",turn_id="turn-a",completed=True,platform="desktop") + self.service.observe("post_llm_call",profile="default",session_id="native-session",turn_id="turn-b",assistant_response="I couldn't finish: the provider failed.") + self.service.observe("on_session_end",profile="default",session_id="native-session",turn_id="turn-b",failed=True,error="provider failed",platform="desktop") + self.service.drain_pending() + self.assertEqual([e["eventType"] for e in self.events_sent()],["session.completed","session.completed"]) + + def test_failed_turn_without_a_reply_still_alerts_at_turn_end(self): + self.service.observe("on_session_end",profile="default",session_id="native-session",turn_id="turn-a",failed=True,error="provider failed",platform="desktop") + self.service.drain_pending() + self.assertEqual([e["eventType"] for e in self.events_sent()],["session.failed"]) + def test_unsubscribed_other_profile_children_and_cancellation_do_not_alert(self): for change in [dict(profile="other"),dict(platform="subagent"),dict(interrupted=True)]: payload=dict(profile="default",session_id="native-session",turn_id="turn-a",completed=True,platform="desktop")|change From 4dadd19b6fa39e9acf8ecc0c4886b02c50c9603f Mon Sep 17 00:00:00 2001 From: "Prompt. Click. Run." <59135406+promptclickrun@users.noreply.github.com> Date: Sun, 27 Sep 2026 00:39:56 -0500 Subject: [PATCH 2/4] feat: restart the serving Hermes process in place after an app-driven update POST /native/host/restart (native-host-restart-v1, POSIX only) re-executes the process with its original command line after the response is written. The PID is unchanged, so supervisors keep working. The bighelp app uses it after updating the plugin so the new version actually loads, then verifies the running version. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +++ loopdy_plugin/host_restart.py | 64 +++++++++++++++++++++++++++++++++ loopdy_plugin/native_api.py | 21 +++++++++++ loopdy_plugin/native_context.py | 5 +++ tests/test_host_restart.py | 54 ++++++++++++++++++++++++++++ tests/test_native_api.py | 3 ++ 6 files changed, 152 insertions(+) create mode 100644 loopdy_plugin/host_restart.py create mode 100644 tests/test_host_restart.py diff --git a/README.md b/README.md index 5e3ec0f..6989aa9 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/loopdy_plugin/host_restart.py b/loopdy_plugin/host_restart.py new file mode 100644 index 0000000..74f5080 --- /dev/null +++ b/loopdy_plugin/host_restart.py @@ -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} diff --git a/loopdy_plugin/native_api.py b/loopdy_plugin/native_api.py index 2856922..211eaeb 100644 --- a/loopdy_plugin/native_api.py +++ b/loopdy_plugin/native_api.py @@ -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 diff --git a/loopdy_plugin/native_context.py b/loopdy_plugin/native_context.py index 56a5e95..660e37d 100644 --- a/loopdy_plugin/native_context.py +++ b/loopdy_plugin/native_context.py @@ -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) diff --git a/tests/test_host_restart.py b/tests/test_host_restart.py new file mode 100644 index 0000000..04a7d5d --- /dev/null +++ b/tests/test_host_restart.py @@ -0,0 +1,54 @@ +"""In-place restart used by the bighelp app after it updates the plugin.""" +import sys +import unittest +from unittest import mock + +from loopdy_plugin import host_restart + + +class HostRestartTests(unittest.TestCase): + def setUp(self): + host_restart._scheduled = False + + def test_restart_reuses_the_exact_command_line(self): + calls, timers = [], [] + + class Timer: + def __init__(self, delay, function): + self.delay, self.function, self.daemon = delay, function, False + timers.append(self) + def start(self): + pass + + with mock.patch.object(sys, "orig_argv", ["python3", "-m", "hermes_cli.main", "serve", "--isolated", "--port", "9121"]), \ + mock.patch.object(host_restart.os, "name", "posix"): + result = host_restart.schedule(execv=lambda path, argv: calls.append((path, argv)), timer=Timer) + self.assertEqual(result, {"restarting": True, "alreadyScheduled": False}) + # A second request while one is pending doesn't restart twice. + self.assertEqual(host_restart.schedule(execv=lambda *_: None, timer=Timer)["alreadyScheduled"], True) + self.assertEqual(len(timers), 1) + self.assertTrue(timers[0].daemon) + timers[0].function() + self.assertEqual(calls, [(sys.executable, [sys.executable, "-m", "hermes_cli.main", "serve", "--isolated", "--port", "9121"])]) + + def test_failed_exec_keeps_running_and_allows_another_try(self): + class Timer: + def __init__(self, delay, function): self.function, self.daemon = function, False + def start(self): self.function() + + def fail(path, argv): + raise OSError("exec failed") + + with mock.patch.object(host_restart.os, "name", "posix"): + host_restart.schedule(execv=fail, timer=Timer) + self.assertFalse(host_restart._scheduled) + + def test_unavailable_without_posix_exec(self): + with mock.patch.object(host_restart.os, "name", "nt"): + self.assertFalse(host_restart.available()) + with self.assertRaises(RuntimeError): + host_restart.schedule(execv=lambda *_: None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_native_api.py b/tests/test_native_api.py index d69001a..f74c274 100644 --- a/tests/test_native_api.py +++ b/tests/test_native_api.py @@ -148,6 +148,9 @@ def test_context_exact_safe_identity_cookie_and_no_unimplemented_features(self): from loopdy_plugin.native_attachments import available as attachments_available if attachments_available(): expected.extend(("native-agent-attachments-v1", "native-agent-media-v1")) + from loopdy_plugin.host_restart import available as restart_available + if restart_available(): + expected.append("native-host-restart-v1") self.assertEqual(value["features"], expected) self.assertEqual(value["servingProfileId"], "default") self.assertEqual(result.headers["cache-control"], "no-store") From 8da61b2506130fe933050715c13874b3d6941bed Mon Sep 17 00:00:00 2001 From: GordieBox Date: Sun, 27 Sep 2026 00:57:58 -0500 Subject: [PATCH 3/4] Test a real in-place restart: same PID, same flags, serving again Co-Authored-By: Claude Opus 5.5 --- tests/test_host_restart.py | 79 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/tests/test_host_restart.py b/tests/test_host_restart.py index 04a7d5d..03613fd 100644 --- a/tests/test_host_restart.py +++ b/tests/test_host_restart.py @@ -1,6 +1,13 @@ """In-place restart used by the bighelp app after it updates the plugin.""" +import json +import os +import subprocess import sys +import textwrap +import time import unittest +import urllib.request +from pathlib import Path from unittest import mock from loopdy_plugin import host_restart @@ -50,5 +57,77 @@ def test_unavailable_without_posix_exec(self): host_restart.schedule(execv=lambda *_: None) +# A tiny server that restarts itself exactly like a Hermes process does when the +# app asks: same PID, same command line, listening socket released and bound again. +_SERVER = textwrap.dedent(""" + import json, os, sys, uuid + from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + sys.path.insert(0, sys.argv[1]) + from loopdy_plugin import host_restart + RUNTIME = uuid.uuid4().hex + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): pass + def reply(self, value): + body = json.dumps(value).encode() + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + def do_GET(self): + self.reply({"pid": os.getpid(), "runtime": RUNTIME, "argv": sys.orig_argv[1:]}) + def do_POST(self): + self.reply(host_restart.schedule(delay=0.2)) + server = ThreadingHTTPServer(("127.0.0.1", int(sys.argv[2])), Handler) + print(server.server_address[1], flush=True) + server.serve_forever() +""") + + +@unittest.skipUnless(host_restart.available(), "in-place restart needs a POSIX host") +class RealRestartTests(unittest.TestCase): + def test_process_restarts_in_place_and_serves_again(self): + import socket + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + port = probe.getsockname()[1] + root = str(Path(__file__).resolve().parents[1]) + script = Path(self.id().replace(".", "_") + ".py") + tmp = Path(os.environ.get("TMPDIR", "/tmp")) / script + tmp.write_text(_SERVER) + self.addCleanup(tmp.unlink, missing_ok=True) + child = subprocess.Popen([sys.executable, str(tmp), root, str(port)], stdout=subprocess.PIPE, text=True) + + def stop(): + child.kill() + child.wait(timeout=5) + child.stdout.close() + self.addCleanup(stop) + self.assertEqual(int(child.stdout.readline()), port) + + def get(method="GET"): + request = urllib.request.Request(f"http://127.0.0.1:{port}/", method=method, data=b"" if method == "POST" else None) + with urllib.request.urlopen(request, timeout=2) as response: + return json.load(response) + + before = get() + self.assertEqual(get("POST"), {"restarting": True, "alreadyScheduled": False}) + after = None + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + time.sleep(0.2) + try: + value = get() + except OSError: + continue + if value["runtime"] != before["runtime"]: + after = value + break + self.assertIsNotNone(after, "the process never came back") + # Same process for launchd/systemd, same flags, fresh code. + self.assertEqual(after["pid"], before["pid"]) + self.assertEqual(after["argv"], before["argv"]) + self.assertIsNone(child.poll()) + + if __name__ == "__main__": unittest.main() From 27b7c2f5174f7605bc511982ee9990dbbb94eb3d Mon Sep 17 00:00:00 2001 From: GordieBox Date: Sun, 27 Sep 2026 01:49:16 -0500 Subject: [PATCH 4/4] Secure input tool for agents (2.17.0) bighelp_request_secure_input asks the person for a password or key through Hermes' own secret-capture pathway (the app's masked pop-up). Hermes saves it to the profile's .env; the agent may use it only as $NAME in commands. The value never reaches the model. System names and Hermes provider keys are refused. Startup-logging tests now expect native-host-restart-v1. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + loopdy_plugin/link_contracts.py | 2 +- loopdy_plugin/secure_input.py | 177 +++++++++++++++++++++++++++ loopdy_plugin/tools.py | 2 + plugin.yaml | 3 +- tests/test_generative_ui_actions.py | 2 +- tests/test_loopdy_card_tool.py | 2 +- tests/test_native_startup_logging.py | 7 +- tests/test_secure_input.py | 67 ++++++++++ tests/test_tools_registration.py | 5 + 10 files changed, 262 insertions(+), 6 deletions(-) create mode 100644 loopdy_plugin/secure_input.py create mode 100644 tests/test_secure_input.py diff --git a/README.md b/README.md index 6989aa9..95277af 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,7 @@ systemd and Hermes Desktop keep supervising it; chats running on that process st | 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) | diff --git a/loopdy_plugin/link_contracts.py b/loopdy_plugin/link_contracts.py index 51060b2..fb450a3 100644 --- a/loopdy_plugin/link_contracts.py +++ b/loopdy_plugin/link_contracts.py @@ -112,7 +112,7 @@ def parse_direct_enrollment(payload: dict[str, Any]) -> dict[str, Any]: "body_fat_percentage", "workout", ) -PLUGIN_VERSION = "2.16.1" +PLUGIN_VERSION = "2.17.0" AVAILABLE_WIKI_OPERATIONS = available_wiki_operations() GROUPS_OPERATIONS = frozenset( { diff --git a/loopdy_plugin/secure_input.py b/loopdy_plugin/secure_input.py new file mode 100644 index 0000000..37c05ea --- /dev/null +++ b/loopdy_plugin/secure_input.py @@ -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 diff --git a/loopdy_plugin/tools.py b/loopdy_plugin/tools.py index 0520924..f635a93 100644 --- a/loopdy_plugin/tools.py +++ b/loopdy_plugin/tools.py @@ -634,6 +634,7 @@ def register( request_id_factory: Callable[[], str] | None = None, ): from .reactions import register as register_reactions + from .secure_input import register as register_secure_input selected_profile = str(profile or getattr(ctx, "profile_name", "default") or "default") clock = now or (lambda: datetime.now(timezone.utc)) @@ -793,3 +794,4 @@ def register( ) # Unsupported hosts omit the capability instead of registering a no-op. register_reactions(ctx) + register_secure_input(ctx) diff --git a/plugin.yaml b/plugin.yaml index 726b623..c7c0164 100644 --- a/plugin.yaml +++ b/plugin.yaml @@ -2,7 +2,7 @@ manifest_version: 1 name: loopdy label: Loopdy kind: platform -version: "2.16.1" +version: "2.17.0" license: Apache-2.0 description: > Native authenticated Hermes workspace controls, media voice, approvals, and @@ -72,6 +72,7 @@ provides_tools: - loopdy_render_card_template - loopdy_marketplace_prepare_upload - loopdy_react_to_message + - bighelp_request_secure_input - bighelp_board platforms: - linux diff --git a/tests/test_generative_ui_actions.py b/tests/test_generative_ui_actions.py index c1c7552..dc67c63 100644 --- a/tests/test_generative_ui_actions.py +++ b/tests/test_generative_ui_actions.py @@ -83,7 +83,7 @@ def test_catalog_registers_exact_legacy_and_card_tools_with_strict_schemas(self) "loopdy_render_checklist", "loopdy_render_selection", "loopdy_render_automation", "loopdy_search_card_templates", "loopdy_get_card_template", "loopdy_render_card_template", "loopdy_await_form_response", "loopdy_marketplace_prepare_upload", - "loopdy_react_to_message", + "loopdy_react_to_message", "bighelp_request_secure_input", }, ) for name, schema in self.context.schemas.items(): diff --git a/tests/test_loopdy_card_tool.py b/tests/test_loopdy_card_tool.py index 8ae7862..8c9892c 100644 --- a/tests/test_loopdy_card_tool.py +++ b/tests/test_loopdy_card_tool.py @@ -53,7 +53,7 @@ def test_exactly_one_generic_renderer_is_registered_in_the_stable_order(self) -> self.assertEqual(1, context.names.count("loopdy_render_card")) self.assertEqual( - [*LEGACY_RENDERERS, "loopdy_render_checklist", "loopdy_render_selection", "loopdy_render_automation", "loopdy_render_card", "loopdy_await_form_response", "loopdy_marketplace_prepare_upload", "loopdy_react_to_message"], + [*LEGACY_RENDERERS, "loopdy_render_checklist", "loopdy_render_selection", "loopdy_render_automation", "loopdy_render_card", "loopdy_await_form_response", "loopdy_marketplace_prepare_upload", "loopdy_react_to_message", "bighelp_request_secure_input"], context.names, ) diff --git a/tests/test_native_startup_logging.py b/tests/test_native_startup_logging.py index 13dcc34..5041f4b 100644 --- a/tests/test_native_startup_logging.py +++ b/tests/test_native_startup_logging.py @@ -20,7 +20,7 @@ "native-context-v1", "serving-profile-v1", "native-card-templates-v1", "native-voice-v1", "native-device-tools-v1", "native-room-activity-v1", "native-project-git-read-v1", "native-agent-templates-v1", - "native-workspace-files-v1", "native-workspace-recent-v1", + "native-workspace-files-v1", "native-workspace-recent-v1", "native-host-restart-v1", ) WIKI_FEATURES = ("native-wiki-v1", "native-wiki-disconnect-v1") @@ -58,8 +58,10 @@ def setUp(self): self.files = module("loopdy_plugin.workspace_artifacts", CAPABILITY=PROCESS_FEATURES[8], RECENT_CAPABILITY=PROCESS_FEATURES[9], available=Mock(return_value=True)) self.wiki = module("loopdy_plugin.wiki_contract", available_wiki_operations=Mock(return_value=True)) + self.restart = module("loopdy_plugin.host_restart", CAPABILITY=PROCESS_FEATURES[10], + available=Mock(return_value=True)) modules = [self.constants, self.profiles, self.device, self.room, self.git, - self.templates, self.files, self.wiki, + self.templates, self.files, self.wiki, self.restart, module("hermes_cli.dashboard_auth.base", Session=Session)] self.stack.enter_context(patch.dict(sys.modules, {value.__name__: value for value in modules})) self.stack.enter_context(patch.object(native_context, "_startup_advertisement_logged", False)) @@ -100,6 +102,7 @@ def test_unavailable_capabilities_are_omitted_and_each_is_warned(self): self.git.supported.return_value = False self.templates.available.return_value = False self.files.available.return_value = False + self.restart.available.return_value = False with self.assertLogs(LOG, level="INFO") as logs: native_context.log_native_feature_startup("research") expected = PROCESS_FEATURES[:2] diff --git a/tests/test_secure_input.py b/tests/test_secure_input.py new file mode 100644 index 0000000..657accd --- /dev/null +++ b/tests/test_secure_input.py @@ -0,0 +1,67 @@ +"""Agent-requested secure input via Hermes' secret-capture pathway.""" +import json +import unittest + +from loopdy_plugin import secure_input + + +class SecureInputTests(unittest.TestCase): + def call(self, args, *, callback=None, interactive=True, saved=False, provider=False): + self.allowed = [] + self.asked = [] + + def capture(name, prompt, metadata): + self.asked.append((name, prompt, metadata)) + return callback(name) if callback else {"success": True, "stored_as": name, "skipped": False} + + raw = secure_input.request( + args, callback=capture, interactive=lambda: interactive, saved=lambda _: saved, + allow=self.allowed.append, provider_credential=lambda _: provider) + self.assertNotIn("hunter2", raw) + return json.loads(raw) + + def test_saves_through_the_pop_up_and_never_returns_the_value(self): + result = self.call({"name": "BANK_PASSWORD", "prompt": "Enter your bank\npassword.", "label": "Bank password"}, + callback=lambda name: {"success": True, "stored_as": name, "skipped": False, "value": "hunter2"}) + self.assertEqual(result["success"], True) + self.assertEqual(result["stored_as"], "BANK_PASSWORD") + self.assertEqual(self.asked, [("BANK_PASSWORD", "Enter your bank password.", + {"source": "agent", "label": "Bank password"})]) + self.assertEqual(self.allowed, ["BANK_PASSWORD"]) + + def test_cancelled_pop_up_is_reported_and_nothing_is_allowed(self): + result = self.call({"name": "GITHUB_TOKEN", "prompt": "Paste a token."}, + callback=lambda name: {"success": True, "stored_as": name, "skipped": True}) + self.assertEqual((result["success"], result["skipped"]), (False, True)) + self.assertEqual(self.allowed, []) + + def test_saved_value_is_reused_unless_replaced(self): + result = self.call({"name": "GITHUB_TOKEN", "prompt": "Paste a token."}, saved=True) + self.assertEqual(result["already_saved"], True) + self.assertEqual(self.asked, []) + self.call({"name": "GITHUB_TOKEN", "prompt": "Paste a new token.", "replace": True}, saved=True) + self.assertEqual(len(self.asked), 1) + + def test_messaging_chats_cannot_show_the_pop_up(self): + result = self.call({"name": "GITHUB_TOKEN", "prompt": "Paste a token."}, interactive=False) + self.assertEqual(result["error"], "secure_input_unavailable") + self.assertEqual(self.asked, []) + + def test_system_names_and_provider_keys_are_refused(self): + for name in ["PATH", "HERMES_HOME", "LD_PRELOAD", "DYLD_INSERT_LIBRARIES", "PYTHONPATH", "lower_case", "X", + "A" * 65, 42, None]: + self.assertEqual(self.call({"name": name, "prompt": "x"})["error"], "invalid_name", name) + self.assertEqual(self.call({"name": "OPENAI_API_KEY", "prompt": "x"}, provider=True)["error"], + "provider_credential") + self.assertEqual(self.call({"name": "GITHUB_TOKEN", "prompt": " "})["error"], "missing_prompt") + self.assertEqual(self.asked, []) + + def test_a_failing_pop_up_is_an_error_not_a_crash(self): + def broken(name): + raise RuntimeError("socket closed") + self.assertEqual(self.call({"name": "GITHUB_TOKEN", "prompt": "x"}, callback=broken)["error"], + "secure_input_failed") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_tools_registration.py b/tests/test_tools_registration.py index 122296b..50cad09 100644 --- a/tests/test_tools_registration.py +++ b/tests/test_tools_registration.py @@ -116,6 +116,11 @@ def test_root_entrypoint_registers_model_schema_and_json_result(self): self.assertNotIn("calendarID", renderer_schema["parameters"]["properties"]) self.assertNotIn("occurrenceStart", renderer_schema["parameters"]["properties"]) continue + if tool_name == "bighelp_request_secure_input": + from loopdy_plugin.secure_input import PARAMETERS as SECURE_INPUT_PARAMETERS + self.assertEqual(renderer_schema["parameters"], SECURE_INPUT_PARAMETERS) + self.assertIn("never see it", description) + continue if tool_name == "loopdy_react_to_message": from loopdy_plugin.reactions import PARAMETERS self.assertEqual(renderer_schema["parameters"], PARAMETERS)