The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway,cli): a skill's missing env var opens main's masked secret panel; the gateway saves it
Tekniumee9f9c82a06f
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 590f494629e..9f4f7c63637 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -1242,8 +1242,9 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):persist_msg, persist_ts = self._prepare_turn_message(agent_history)compressions = getattr(getattr(agent, "context_compressor", None), "compression_count", None)from gateway.session_cli_turn import run_classic_cli_turn+ from gateway.session_secret_prompt import secret_prompt_scopefrom gateway.session_sudo_prompt import sudo_prompt_scope- with sudo_prompt_scope(self, agent):+ with sudo_prompt_scope(self, agent), secret_prompt_scope(self, agent):result = run_classic_cli_turn(self, lambda: self._run_conversation_with_approval(agent, agent_history, observed_group_context, persist_msg, persist_ts))finally:diff --git a/gateway/session_secret_prompt.py b/gateway/session_secret_prompt.pynew file mode 100644index 00000000000..c413f8475cf--- /dev/null+++ b/gateway/session_secret_prompt.py@@ -0,0 +1,52 @@+"""The masked skill-secret prompt for a local viewer's turn.++Main's classic CLI registered ``set_secret_capture_callback`` in process: a skill whose+``required_environment_variables`` are missing opened the masked "Skill Setup Required" panel and the+value was saved to the profile ``.env`` (``save_env_value_secure``) without ever reaching the model.+On the session authority the skill runs in the gateway, where a gateway surface only got the+"secret entry is not available" hint. For a local viewer's turn the owner now sends main's ``secret``+server→client request (``tui_gateway/contracts/server_requests.py``: ``SecretRequestParams`` →+``ValueResult``) to the attached viewers, saves a non-empty answer in this profile's ``.env`` here,+and returns main's callback result. The value travels only in the viewer's response frame.+"""+from __future__ import annotations++import contextlib+import logging++logger = logging.getLogger(__name__)++SECRET_TIMEOUT_S = 120 # main's CLI secret panel deadline (hermes_cli/callbacks.py)+++def _skipped(var_name, reason, message):+ return {"success": True, "reason": reason, "stored_as": var_name, "validated": False,+ "skipped": True, "message": message}+++def secret_prompt_scope(turn, agent):+ """Bind this turn's secret-capture callback (a ContextVar, so parallel tool workers inherit it)."""+ from gateway.run_turn_progress import local_viewer_turn+ if not local_viewer_turn(turn):+ yield+ return+ from tools.skills_tool import bind_turn_secret_capture+ authority, session_id, _generation = turn._approval_owner++ def callback(var_name, prompt, metadata=None):+ from gateway.session_sudo_prompt import ask_viewer+ live = authority.sessions.get(session_id)+ if live is None:+ return _skipped(var_name, "cancelled", "Secret setup was skipped.")+ params = {"env_var": var_name, "prompt": prompt, **({"metadata": metadata} if metadata else {})}+ value = ask_viewer(live.event_stream, session_id, "secret", params, timeout=SECRET_TIMEOUT_S,+ cancelled=lambda: bool(getattr(agent, "_interrupt_requested", False)))+ if not value:+ return _skipped(var_name, "cancelled", "Secret setup was skipped.")+ from hermes_cli.config import save_env_value_secure+ return {**save_env_value_secure(var_name, value), "skipped": False,+ "message": "Secret stored securely. The secret value was not exposed to the model."}++ with bind_turn_secret_capture(callback):+ yielddiff --git a/gateway/session_sudo_prompt.py b/gateway/session_sudo_prompt.pyindex 4791c2aa734..48872431666 100644--- a/gateway/session_sudo_prompt.py+++ b/gateway/session_sudo_prompt.py@@ -58,14 +58,20 @@ def resolve(frame, *, session_ok=lambda session_id: True) -> bool:def ask_sudo(events, session_id, command, *, cancelled=lambda: False, timeout=SUDO_TIMEOUT_S) -> str:"""Send one ``sudo`` request to the session's attached viewers and wait for its ``value``."" when nobody is attached, the viewer skipped, the turn was interrupted, or it timed out."""+ return ask_viewer(events, session_id, "sudo", {"command": command}, cancelled=cancelled, timeout=timeout)+++def ask_viewer(events, session_id, method, params, *, cancelled=lambda: False, timeout=SUDO_TIMEOUT_S) -> str:+ """Send one one-string server→client request (``sudo``, ``secret``: ``ValueResult``) to the+ session's attached viewers and wait for its ``value``; "" on skip, interrupt, timeout or no viewer."""if not events.fanout.transports():return ""request_id = f"srq-{uuid.uuid4().hex[:12]}"pending = _Pending(session_id)with _lock:_open[request_id] = pending- events.fanout.write({"jsonrpc": "2.0", "id": request_id, "method": "sudo",- "params": {"session_id": session_id, "command": command}})+ events.fanout.write({"jsonrpc": "2.0", "id": request_id, "method": method,+ "params": {"session_id": session_id, **params}})waited = 0.0reason = "timeout"while not pending.event.wait(_POLL_S):@@ -81,7 +87,7 @@ def ask_sudo(events, session_id, command, *, cancelled=lambda: False, timeout=SU# The same teardown main's renderers key on (``request.cancel``): the card closes and a# timed-out password prompt says so.with contextlib.suppress(Exception):- events.publish(session_id, {"id": request_id, "method": "sudo", "reason": reason},+ events.publish(session_id, {"id": request_id, "method": method, "reason": reason},event_type="request.cancel")return ""return pending.valuediff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.pyindex 236b1f1980e..587afc307a0 100644--- a/hermes_cli/gateway_agent.py+++ b/hermes_cli/gateway_agent.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport loggingimport queue+import threadingimport timeimport uuid@@ -598,6 +599,28 @@ class GatewayAgent:callback = _get_sudo_password_callback()return (callback() or "") if callback is not None else ""+ def _ask_secret(self, params):+ """Main's masked "Skill Setup Required" panel (the CLI's registered secret-capture callback,+ ``hermes_cli.callbacks.prompt_for_secret``) collects the value and prints main's lines; the+ gateway, not this process, saves it in the profile ``.env``, so the panel's save is captured."""+ from tools import skills_tool+ callback = skills_tool._secret_capture_callback+ if callback is None:+ return ""+ from hermes_cli import callbacks+ captured = []++ def capture(key, value):+ captured.append(value)+ return {"success": True, "stored_as": key, "validated": False}+ with _SECRET_LOCK:+ saver, callbacks.save_env_value_secure = callbacks.save_env_value_secure, capture+ try:+ callback(params.get("env_var") or "", params.get("prompt") or "", params.get("metadata"))+ finally:+ callbacks.save_env_value_secure = saver+ return captured[0] if captured else ""+# -- result --------------------------------------------------------------------------------def _user_row(self, user_message):staged = self._pending_cli_user_message@@ -732,8 +755,10 @@ def _moa_handler(kind):return handler+_SECRET_LOCK = threading.Lock()_SERVER_REQUESTS = {"sudo": GatewayAgent._ask_sudo,+ "secret": GatewayAgent._ask_secret,}_HANDLERS = {diff --git a/tests/gateway/test_local_viewer_secret_prompt.py b/tests/gateway/test_local_viewer_secret_prompt.pynew file mode 100644index 00000000000..ccbe52c3b2f--- /dev/null+++ b/tests/gateway/test_local_viewer_secret_prompt.py@@ -0,0 +1,104 @@+"""A local viewer's turn asks for a skill's missing env var through main's masked secret panel+(``secret`` server→client request), and the gateway saves the answer in the profile ``.env``. Before,+a gateway surface only returned the "secure secret entry is not available" hint."""+import threading+import time+from types import SimpleNamespace++import pytest++from gateway.config import Platform+++class _Peer:+ def __init__(self):+ self.frames = []++ def write(self, frame):+ self.frames.append(frame)+ return True++ def close(self):+ pass+++def _turn(platform):+ from gateway.session_events import SessionEvents+ events, peer = SessionEvents(), _Peer()+ events.fanout.attach(peer)+ authority = SimpleNamespace(sessions={'s1': SimpleNamespace(event_stream=events)})+ turn = SimpleNamespace(_approval_owner=(authority, 's1', 1),+ _ctx=SimpleNamespace(source=SimpleNamespace(platform=platform)))+ return turn, peer+++def _wait_for(predicate, timeout=5.0):+ deadline = time.monotonic() + timeout+ while not predicate():+ assert time.monotonic() < deadline+ time.sleep(0.01)+++def _answer_when_asked(peer, value):+ from gateway.session_sudo_prompt import resolve+ _wait_for(lambda: any(f.get('method') == 'secret' for f in peer.frames))+ request = next(f for f in peer.frames if f.get('method') == 'secret')+ resolve({'jsonrpc': '2.0', 'id': request['id'], 'result': {'value': value}})+ return request+++def test_local_viewer_turn_prompts_and_saves_the_secret(monkeypatch):+ from gateway.session_secret_prompt import secret_prompt_scope+ from tools.skills_tool_setup import _capture_required_environment_variables+ saved = []+ from hermes_cli import config+ monkeypatch.setattr(config, 'save_env_value_secure',+ lambda key, value: saved.append((key, value)) or {'success': True, 'stored_as': key,+ 'validated': False})+ monkeypatch.setenv('HERMES_GATEWAY_SESSION', '1') # a gateway surface: the hint path before this fix+ monkeypatch.delenv('HERMES_INTERACTIVE', raising=False)+ turn, peer = _turn(Platform.LOCAL)+ out = {}+ with secret_prompt_scope(turn, SimpleNamespace()):+ # A tool worker thread, started the way the agent starts them (context propagated).+ from tools.thread_context import propagate_context_to_thread+ worker = threading.Thread(target=propagate_context_to_thread(lambda: out.update(+ _capture_required_environment_variables('hab-skill', [{'name': 'HAB_KEY', 'prompt': 'Enter the key'}]))))+ worker.start()+ request = _answer_when_asked(peer, 'sekrit')+ worker.join(5)+ assert request['params'] == {'session_id': 's1', 'env_var': 'HAB_KEY', 'prompt': 'Enter the key',+ 'metadata': {'skill_name': 'hab-skill'}}+ from tui_gateway.contracts.registry import SERVER_REQUESTS, validate_params+ assert validate_params(SERVER_REQUESTS['secret'], request['params'])[1] is None+ assert saved == [('HAB_KEY', 'sekrit')]+ assert out['missing_names'] == [] and out['gateway_setup_hint'] is None+ assert not any('sekrit' in repr(f) for f in peer.frames)+++def test_skipped_secret_stays_missing(monkeypatch):+ from gateway.session_secret_prompt import secret_prompt_scope+ from tools.skills_tool_setup import _capture_required_environment_variables+ turn, peer = _turn(Platform.LOCAL)+ out = {}+ with secret_prompt_scope(turn, SimpleNamespace()):+ # A tool worker thread, started the way the agent starts them (context propagated).+ from tools.thread_context import propagate_context_to_thread+ worker = threading.Thread(target=propagate_context_to_thread(lambda: out.update(+ _capture_required_environment_variables('hab-skill', [{'name': 'HAB_KEY', 'prompt': 'Enter the key'}]))))+ worker.start()+ _answer_when_asked(peer, '')+ worker.join(5)+ assert out['missing_names'] == ['HAB_KEY'] and out['setup_skipped'] is True++[email protected]('platform', [Platform.TELEGRAM])+def test_messaging_turn_keeps_the_unsupported_hint(monkeypatch, platform):+ from gateway.session_secret_prompt import secret_prompt_scope+ from tools.skills_tool_setup import _capture_required_environment_variables+ monkeypatch.setenv('HERMES_GATEWAY_SESSION', '1')+ monkeypatch.delenv('HERMES_INTERACTIVE', raising=False)+ turn, peer = _turn(platform)+ with secret_prompt_scope(turn, SimpleNamespace()):+ out = _capture_required_environment_variables('hab-skill', [{'name': 'HAB_KEY', 'prompt': 'p'}])+ assert out['gateway_setup_hint'] and peer.frames == []diff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.pyindex f424917ea34..7a787b25bce 100644--- a/tests/hermes_cli/test_gateway_agent.py+++ b/tests/hermes_cli/test_gateway_agent.py@@ -400,3 +400,30 @@ def test_connection_reply_sends_a_jsonrpc_response_frame():conn.close()import jsonassert [json.loads(raw) for raw in sent] == [{"jsonrpc": "2.0", "id": "srq-1", "result": {"value": ""}}]+++def test_gateway_secret_request_opens_mains_secret_panel_and_the_gateway_saves(make_agent, monkeypatch):+ """``secret`` (skill env var): main's panel collects the value and prints its lines, but the CLI+ process never writes ``.env`` — the value goes back to the gateway, which saves it."""+ from hermes_cli import callbacks+ from tools import skills_tool+ request = {"jsonrpc": "2.0", "id": "srq-sec", "method": "secret",+ "params": {"session_id": SID, "env_var": "HAB_KEY", "prompt": "Enter it",+ "metadata": {"skill_name": "hab"}}}+ agent, _ = make_agent([request, frame("message.complete", {"text": "ok", "outcome": "completed"})])+ replies = []+ agent.connection.reply = lambda rid, result: replies.append((rid, result)) or True+ local_writes = []+ monkeypatch.setattr(callbacks, "save_env_value_secure", lambda k, v: local_writes.append((k, v)))+ monkeypatch.setattr(callbacks, "cprint", lambda *a, **k: None)+ seen = []++ class Cli: # no prompt_toolkit app: main's prompt_for_secret reads the masked prompt+ pass+ monkeypatch.setattr(callbacks, "masked_secret_prompt", lambda prompt: seen.append(prompt) or "sekrit")+ monkeypatch.setattr(skills_tool, "_secret_capture_callback",+ lambda var, prompt, metadata=None: callbacks.prompt_for_secret(Cli(), var, prompt, metadata))+ agent.run_conversation("view the skill")+ assert seen and seen[0].startswith("Enter it")+ assert replies == [("srq-sec", {"value": "sekrit"})]+ assert local_writes == [] # the gateway saves; this process never writes .envdiff --git a/tools/skills_tool.py b/tools/skills_tool.pyindex 267194b950e..58eda3fd6e2 100644--- a/tools/skills_tool.py+++ b/tools/skills_tool.py@@ -4,11 +4,12 @@ holding SKILL.md (YAML frontmatter + instructions) plus optional references/, tescripts/. `skills_list` returns name/description only; `skill_view` returns full content andlinked files. Sibling modules (skills_tool_setup / _plugin / _dedup) re-export here."""+import contextvarsimport jsonimport loggingimport osimport time-from contextlib import suppress+from contextlib import contextmanager, suppressfrom pathlib import Path, PurePosixPath, PureWindowsPathfrom typing import Any, Dict, List, Optional, Tuple@@ -111,6 +112,21 @@ def set_secret_capture_callback(callback) -> None:_secret_capture_callback = callback+# A turn-scoped capture callback (the session owner binds one per local-viewer turn): it wins over the+# process-global slot and over the gateway-surface "unsupported" hint, because that turn's viewer can+# answer. A ContextVar, so tool worker threads started with ``propagate_context_to_thread`` inherit it.+_turn_secret_capture = contextvars.ContextVar("turn_secret_capture", default=None)+++@contextmanager+def bind_turn_secret_capture(callback):+ token = _turn_secret_capture.set(callback)+ try:+ yield+ finally:+ _turn_secret_capture.reset(token)++def _skill_utils_delegate(attr: str):"""Lazy call-time delegate to ``agent.skill_utils.<attr>`` (re-export; patches honored)."""def _delegate(*args):diff --git a/tools/skills_tool_setup.py b/tools/skills_tool_setup.pyindex 58c2017590c..8008c3dc1f3 100644--- a/tools/skills_tool_setup.py+++ b/tools/skills_tool_setup.py@@ -91,17 +91,18 @@ def _capture_required_environment_variables(if not missing_entries:return _capture_result([])missing_names = [entry["name"] for entry in missing_entries]+ callback = _st._turn_secret_capture.get()# Messaging-platform gateway surfaces can't prompt for a secret, so they get the "unsupported"# hint. Interactive gateway surfaces (desktop app / TUI) set HERMES_INTERACTIVE (same flag# tools/approval.py uses) and register a callback routing to a secure secret.request overlay.- if _is_gateway_surface() and not env_var_enabled("HERMES_INTERACTIVE"):+ if callback is None and _is_gateway_surface() and not env_var_enabled("HERMES_INTERACTIVE"):try:from gateway.platforms.base import GATEWAY_SECRET_CAPTURE_UNSUPPORTED_MESSAGE as hintexcept Exception:hint = (f"Secure secret entry is not available. Load this skill in the local CLI to be "f"prompted, or add the key to {display_hermes_home()}/.env manually.")return _capture_result(missing_names, gateway_setup_hint=hint)- if (callback := _st._secret_capture_callback) is None:+ if callback is None and (callback := _st._secret_capture_callback) is None:return _capture_result(missing_names)remaining_names: list[str] = []for entry in missing_entries: