Skip to content
Closed
Show file tree
Hide file tree
Changes from 11 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
122 changes: 118 additions & 4 deletions cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2467,8 +2467,118 @@ def _resolve_attachment_path(raw_path: str) -> Path | None:
return resolved


def _normalize_background_notifications_mode(raw: object) -> str:
if raw is False:
mode = "off"
else:
mode = str(raw or "").strip().lower()
if not mode:
return "all"
valid = {"all", "result", "error", "off"}
if mode not in valid:
logger.warning(
"Unknown background_process_notifications '%s', defaulting to 'all'",
mode,
)
return "all"
return mode


def _load_background_notifications_mode(config: "dict | None" = None) -> str:
"""Load CLI background process notification mode from env/config."""
mode = os.getenv("HERMES_BACKGROUND_NOTIFICATIONS", "")
if not mode:
cfg = config if isinstance(config, dict) else CLI_CONFIG
display = cfg.get("display", {}) if isinstance(cfg, dict) else {}
if isinstance(display, dict):
raw = display.get("background_process_notifications")
if raw not in (None, ""):
mode = raw
return _normalize_background_notifications_mode(mode)


def _is_deliberate_process_termination(evt: dict) -> bool:
return (
evt.get("completion_reason") == "killed"
and evt.get("termination_source") in {"process.kill", "kill_all"}
)


def _should_queue_process_notification(evt: dict, notification_mode: str) -> bool:
"""Return whether a drained process event should wake the CLI agent."""
mode = _normalize_background_notifications_mode(notification_mode)
if mode == "off":
return False
evt_type = evt.get("type", "completion")
if evt_type == "completion":
exit_code = evt.get("exit_code")
return mode in ("all", "result") or (
mode == "error"
and exit_code not in (0, None)
and not _is_deliberate_process_termination(evt)
)
if evt_type in {"watch_match", "watch_disabled", "watch_overflow_released", "watch_overflow_tripped"}:
return mode == "all"
return False


def _drain_process_notifications_to_pending_input(
process_registry,
pending_input,
notification_mode: "str | None" = None,
) -> int:
"""Drain background process notifications and enqueue allowed observations.

Formatting lives in ``tools.process_registry`` so CLI/TUI paths share the
same non-authoritative, ANSI-stripped text. Mode ``off`` still drains but
queues nothing, preventing stale completions from waking a future turn.
"""
mode = _load_background_notifications_mode() if notification_mode is None else notification_mode
mode = _normalize_background_notifications_mode(mode)

if mode == "off" and hasattr(process_registry, "completion_queue"):
drained = 0
completion_queue = process_registry.completion_queue
while not completion_queue.empty():
try:
completion_queue.get_nowait()
except queue.Empty:
break
drained += 1
return drained

drain_notifications = getattr(process_registry, "drain_notifications", None)
if callable(drain_notifications):
drained = 0
for _evt, _synth in drain_notifications(notification_mode=mode):
drained += 1
if _synth:
pending_input.put(_synth)
return drained

# Compatibility path for lightweight test doubles that expose only the
# queue/consumption API.
from tools.process_registry import format_process_notification

drained = 0
completion_queue = process_registry.completion_queue
while not completion_queue.empty():
try:
evt = completion_queue.get_nowait()
except queue.Empty:
break
drained += 1
_evt_sid = evt.get("session_id", "")
is_consumed = getattr(process_registry, "is_completion_consumed", lambda _sid: False)
if evt.get("type", "completion") == "completion" and is_consumed(_evt_sid):
continue
if not _should_queue_process_notification(evt, mode):
continue
_synth = format_process_notification(evt)
if _synth:
pending_input.put(_synth)
return drained


def _detect_file_drop(user_input: str) -> "dict | None":
"""Detect if *user_input* starts with a real local file path.
Expand Down Expand Up @@ -12949,8 +13059,10 @@ def process_loop():
# and watch pattern matches) while agent is idle.
try:
from tools.process_registry import process_registry
for _evt, _synth in process_registry.drain_notifications():
self._pending_input.put(_synth)
_drain_process_notifications_to_pending_input(
process_registry,
self._pending_input,
)
except Exception:
pass
continue
Expand Down Expand Up @@ -13087,8 +13199,10 @@ def _restart_recording():
# that arrived while the agent was running.
try:
from tools.process_registry import process_registry
for _evt, _synth in process_registry.drain_notifications():
self._pending_input.put(_synth)
_drain_process_notifications_to_pending_input(
process_registry,
self._pending_input,
)
except Exception:
pass # Non-fatal β€” don't break the main loop

Expand Down
52 changes: 49 additions & 3 deletions gateway/platforms/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1419,6 +1419,36 @@ class ProcessingOutcome(Enum):
CANCELLED = "cancelled"


class InternalEventKind(Enum):
"""Trusted gateway-internal event categories.

These values identify system-generated observations/control messages. The
plain ``MessageEvent.internal`` boolean is intentionally not sufficient for
trust decisions because it is mutable and can be set on arbitrary events.
"""

BACKGROUND_COMPLETION = "background_completion"
BACKGROUND_WATCH = "background_watch"
AUTO_RESUME = "auto_resume"
CLI_HANDOFF = "cli_handoff"
MESSAGE_RECALL = "message_recall"
WEBHOOK_NOTIFICATION = "webhook_notification"


_TRUSTED_INTERNAL_EVENT_SOURCES = frozenset({"gateway", "platform_adapter"})
_TRUSTED_INTERNAL_EVENT_KINDS = frozenset(kind.value for kind in InternalEventKind)


def normalize_internal_event_kind(kind: Any) -> Optional[str]:
"""Return a canonical internal-event kind string, or None if unknown."""
if isinstance(kind, InternalEventKind):
return kind.value
value = str(kind or "").strip()
if value in _TRUSTED_INTERNAL_EVENT_KINDS:
return value
return None


@dataclass
class MessageEvent:
"""
Expand Down Expand Up @@ -1469,13 +1499,29 @@ class MessageEvent:
# trigger message alone, then prepend this context afterward.
channel_context: Optional[str] = None

# Internal flag β€” set for synthetic events (e.g. background process
# completion notifications) that must bypass user authorization checks.
# Legacy internal marker. Bypass decisions must use
# ``is_trusted_internal()``, not this mutable boolean alone.
internal: bool = False
internal_event_kind: Optional[str] = None
internal_event_source: Optional[str] = None

# Timestamps
timestamp: datetime = field(default_factory=datetime.now)


def __post_init__(self) -> None:
self.internal_event_kind = normalize_internal_event_kind(self.internal_event_kind)
if self.internal_event_source is not None:
self.internal_event_source = str(self.internal_event_source).strip()

def is_trusted_internal(self) -> bool:
"""Return True only for typed, trusted, system-created internal events."""
if not self.internal:
return False
if normalize_internal_event_kind(self.internal_event_kind) is None:
return False
source = str(self.internal_event_source or "").strip()
return source in _TRUSTED_INTERNAL_EVENT_SOURCES

def is_command(self) -> bool:
"""Check if this is a command message (e.g., /new, /reset)."""
return self.text.startswith("/")
Expand Down
3 changes: 3 additions & 0 deletions gateway/platforms/msgraph_webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import (
BasePlatformAdapter,
InternalEventKind,
MessageEvent,
MessageType,
SendResult,
Expand Down Expand Up @@ -370,6 +371,8 @@ def _build_message_event(
raw_message=notification,
message_id=message_id,
internal=True,
internal_event_kind=InternalEventKind.WEBHOOK_NOTIFICATION.value,
internal_event_source="platform_adapter",
)

def _render_prompt(self, notification: Dict[str, Any]) -> str:
Expand Down
3 changes: 3 additions & 0 deletions gateway/platforms/yuanbao.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import (
BasePlatformAdapter,
InternalEventKind,
MessageEvent,
MessageType,
SendResult,
Expand Down Expand Up @@ -1373,6 +1374,8 @@ def _interrupt_for_recall(cls, adapter, session_key: str, recalled_id: str,
message_type=MessageType.TEXT,
source=cls._build_source(adapter, group_code, from_account),
internal=True,
internal_event_kind=InternalEventKind.MESSAGE_RECALL.value,
internal_event_source="platform_adapter",
)
# Set pending + signal directly (bypass handle_message to avoid busy-ack).
# May overwrite a user message pending in the same ~200ms window β€” acceptable.
Expand Down
Loading
Loading