Skip to content
Open
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
13 changes: 8 additions & 5 deletions forks/hermes-agent/gateway/run_turn_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -713,7 +713,8 @@ def _text_fallback():
except Exception:
logger.debug("request_reopen_seed after clarify answer failed", exc_info=True)
try:
ctx._status_adapter.resume_typing_for_chat(ctx._status_chat_id)
(self._runner._delivery_adapter_for(ctx.source) if getattr(ctx, "source", None) is not None
else ctx._status_adapter).resume_typing_for_chat(ctx._status_chat_id)
except Exception:
logger.debug("resume_typing_for_chat after clarify answer failed", exc_info=True)
return response, answered
Expand All @@ -736,7 +737,9 @@ def _render_approval_sync(self, approval_data: dict) -> None:
from gateway.run_turn_runner_approval_settle import register_timeout_notice
from gateway.run_turn_runner_approval_text import approval_text_prompt
ctx = self._ctx
adapter = ctx._status_adapter
adapter = self._runner._delivery_adapter_for(ctx.source) if getattr(ctx, "source", None) is not None else ctx._status_adapter
if adapter is None:
raise RuntimeError("exec approval undeliverable: no live delivery adapter")
# Slack's assistant_threads_setStatus disables the compose box, so the user can't type
# /approve while "is thinking..." shows. Pausing stops _keep_typing re-setting it; resumed
# in approve/deny.
Expand Down Expand Up @@ -773,7 +776,7 @@ def _render_approval_sync(self, approval_data: dict) -> None:
# learns the command did NOT run (only the TUI registered a settle hook).
register_timeout_notice(
self, approval_data, command=cmd,
card_message_id=getattr(fut.result(timeout=0), "message_id", None))
card_message_id=getattr(fut.result(timeout=0), "message_id", None), adapter=adapter)
return
if outcome == "ambiguous":
# Timeout ≠ failure: the card may have posted with a late ack. The prompt
Expand All @@ -790,7 +793,7 @@ def _render_approval_sync(self, approval_data: dict) -> None:
raw = getattr(fut.result(timeout=0), "raw_response", None) if fut.exception(timeout=0) is None else None
if outcome == "failed" and isinstance(raw, dict) and raw.get("approval_text_fallback_posted"):
# The adapter already posted the text prompt in the approval's thread and owns its deadline.
register_timeout_notice(self, approval_data, command=cmd, card_message_id=None)
register_timeout_notice(self, approval_data, command=cmd, card_message_id=None, adapter=adapter)
return
if outcome == "declined":
# P5(b): the connector AUTHORIZED this destination and
Expand Down Expand Up @@ -845,7 +848,7 @@ def _render_approval_sync(self, approval_data: dict) -> None:
approval_data.get("request_id"), ctx.session_key)
# No card to edit on the text path: the prompt has no buttons to drop and carries
# the /approve instructions, so the timeout notice is posted as a new message.
register_timeout_notice(self, approval_data, command=cmd, card_message_id=None)
register_timeout_notice(self, approval_data, command=cmd, card_message_id=None, adapter=adapter)
except Exception as e:
logger.error("Failed to send approval request: %s", e)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@


def register_timeout_notice(
runner, approval_data: dict, *, command: str, card_message_id: Optional[str]) -> None:
runner, approval_data: dict, *, command: str, card_message_id: Optional[str], adapter=None) -> None:
"""Arm a settle hook that posts the timed-out notice for ``approval_data['request_id']``.

``runner`` is the ``TurnRunner`` (for ``_ctx`` and ``_schedule``); ``card_message_id`` is the
Expand Down Expand Up @@ -54,7 +54,7 @@ def settle(reason: str) -> None:
if callable(still_current) and not still_current():
return
runner._schedule(
_post_timeout_notice(runner._ctx, command, card_message_id, timeout_s, flagged),
_post_timeout_notice(runner._ctx, command, card_message_id, timeout_s, flagged, adapter=adapter),
"Approval timeout notice scheduling error")

register_gateway_settle(session_key, request_id, settle)
Expand All @@ -78,12 +78,12 @@ def settle(choice: str) -> None:


async def _post_timeout_notice(
ctx, command: str, card_message_id: Optional[str], timeout_s: int, reason: str = "") -> None:
ctx, command: str, card_message_id: Optional[str], timeout_s: int, reason: str = "", *, adapter=None) -> None:
from gateway.run import _interim_metadata

from gateway.bot_peer_notices import automatic_notices_allowed

adapter = ctx._status_adapter
adapter = adapter if adapter is not None else ctx._status_adapter
if not automatic_notices_allowed(getattr(ctx, "source", None)):
return
notice = format_approval_timed_out_notice(timeout_s)
Expand Down
52 changes: 36 additions & 16 deletions forks/hermes-agent/plugins/platforms/discord/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3361,16 +3361,25 @@ async def send(
chunk_reference = reference
else: # "first" (default) or "off"
chunk_reference = reference if i == 0 else None
send_kwargs = {"content": chunk, "reference": chunk_reference}
if metadata and metadata.get("_approval_mentions"):
allowed_mentions_cls = getattr(discord, "AllowedMentions", None)
if allowed_mentions_cls is not None:
send_kwargs["allowed_mentions"] = allowed_mentions_cls(
users=[discord.Object(id=int(metadata["_approval_mentions"]))],
roles=False, everyone=False, replied_user=False,
)
try:
msg = await channel.send(content=chunk, reference=chunk_reference)
msg = await channel.send(**send_kwargs)
except Exception as e:
if chunk_reference is not None and self._is_reply_reference_rejected(e):
logger.warning(
"[%s] Reply target %s rejected the reply reference; retrying send without reply reference",
self.name, reply_to,
)
reference = None
msg = await channel.send(content=chunk, reference=None)
retry_kwargs = {**send_kwargs, "reference": None}
msg = await channel.send(**retry_kwargs)
else:
raise
message_ids.append(str(msg.id))
Expand Down Expand Up @@ -5733,7 +5742,7 @@ async def _send_prompt(
"""Shared tail for interactive prompts: resolve target channel, call ``build(channel) ->
(send_kwargs, view)``, send, remember the message on the view. ``fail_log`` labels failures."""
if not self._client or not DISCORD_AVAILABLE:
return SendResult(success=False, error="Not connected")
return SendResult(success=False, error="Not connected", retryable=DISCORD_AVAILABLE)
try:
client = self._client
channel = await self._resolve_channel(_prompt_target_id(chat_id, metadata))
Expand All @@ -5747,9 +5756,10 @@ async def _send_prompt(
view.bound_client = client
return SendResult(success=True, message_id=str(msg.id))
except Exception as e:
retryable = _is_discord_transport_error(e)
if fail_log:
logger.warning("[%s] %s failed: %s", self.name, fail_log, e)
return SendResult(success=False, error=str(e))
return SendResult(success=False, error=str(e), retryable=retryable)

# Payload lives in plain content: embeds can be invisible/detached on web/mobile. Properties, not
# class constants: the wording comes from the catalog for the language active at send time.
Expand Down Expand Up @@ -5965,48 +5975,58 @@ async def _reply_unanswered_approval_press(self, interaction, custom_id: str, te
custom_id, exc_info=True)

async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult:
"""Send an approval card. A card that fails or does not confirm within ``approval_card_confirm_timeout``
keeps its request pending: the plain-text prompt goes to the approval's thread, and the request is
withdrawn if nobody answers it within the same window."""
"""Send the card, then fall back to text before withdrawing."""
view = self._new_exec_approval_view(prompt)
window = _read_approval_card_confirm_timeout(getattr(self.config, "extra", None))
try:
result = await asyncio.wait_for(self._send_exec_approval_card(prompt, view), window)
except TimeoutError:
result = SendResult(success=False, error=_CARD_CONFIRM_TIMEOUT_ERROR)
except Exception as exc:
result = SendResult(success=False, error=str(exc), retryable=_is_discord_transport_error(exc))
from gateway.relay.egress import declined_send
if result.success or not view.request_id or declined_send(result):
return result
logger.warning("[%s] approval card not delivered (request_id=%s): %s; posting the text prompt",
self.name, view.request_id, result.error)
view.undelivered = True
# The withdrawal starts before the fallback send, so a hung send cannot hold the request past the window.
view.undelivered_withdrawal = task = asyncio.get_running_loop().create_task(
self._withdraw_undelivered_approval(prompt.session_key, view.request_id, window))
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
task.add_done_callback(_consume_background_task_result)
text_failure = await self._send_exec_approval_text_fallback(prompt)
if text_failure is not None and result.error != _CARD_CONFIRM_TIMEOUT_ERROR:
# Card and text fallback both failed: no surface shows the prompt, so a /stop must say so. A reconnect
# repost that already showed the card wins: its request is not marked, even if this fallback fails later.
from tools.approval import mark_gateway_approval_undelivered
mark_gateway_approval_undelivered(prompt.session_key, view.request_id, f"{result.error}, then {text_failure}")
return SendResult(success=False, error=result.error, raw_response={"approval_text_fallback_posted": True})
reason = f"{result.error}, then {text_failure}"
if mark_gateway_approval_undelivered(prompt.session_key, view.request_id, reason):
logger.error("[%s] approval prompt was never delivered (request_id=%s): %s",
self.name, view.request_id, reason)
return SendResult(success=False, error=result.error,
raw_response={"approval_text_fallback_posted": True})

async def _send_exec_approval_text_fallback(self, prompt: ExecApprovalPrompt) -> str | None:
"""Post the plain-text approval prompt in the approval's own thread. Never raises. Returns ``None`` when the
text prompt was delivered, else the failure reason. The request is withdrawn after approval_card_confirm_timeout,
so the prompt states that window, not approvals.timeout."""
"""Post the text fallback in the approval thread with the card's opt-in owner mention."""
from gateway.run_turn_runner_approval_text import approval_text_prompt
actions = set(prompt.choices)
window = _read_approval_card_confirm_timeout(getattr(self.config, "extra", None))
text = approval_text_prompt(self, prompt.chat_id, prompt.session_key, prompt.request_id, prompt.command,
prompt.description, getattr(self, "typed_command_prefix", "/"),
allow_permanent="always" in actions, allow_session="session" in actions,
smart_denied=prompt.smart_denied, deadline_s=math.ceil(window))
from tools.approval import list_gateway_approval_authority
authority = next((a for a in list_gateway_approval_authority(prompt.session_key)
if a.get("request_id") == prompt.request_id), {})
requester = str(authority.get("requester_id") or "")
mention = (requester.isdigit() and self._approval_mention_content()
and self._approval_mentions_target() == "session")
if mention:
text = f"<@{requester}>\n{text}"
try:
metadata = {**(prompt.metadata or {}), "is_approval_prompt": True}
thread_id = _prompt_target_id(prompt.chat_id, prompt.metadata)
metadata = {**(prompt.metadata or {}), "thread_id": thread_id, "is_approval_prompt": True}
if mention:
metadata["_approval_mentions"] = requester
result = await self.send(prompt.chat_id, text, metadata=metadata)
if not getattr(result, "success", False):
return getattr(result, "error", None) or "text prompt send failed"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def _runner(adapter: _Adapter):
session_key="sk1",
source=SimpleNamespace(chat_id="C1", platform="discord", session_key="sk1"),
)
runner = TurnRunner(SimpleNamespace(), ctx)
runner = TurnRunner(SimpleNamespace(_delivery_adapter_for=lambda _source: adapter), ctx)

class _Fut:
def __init__(self, result): self._r = result
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ def __init__(self, *, everyone=True, roles=True, users=True, replied_user=True):
self.users = users
self.replied_user = replied_user

@classmethod
def none(cls):
return cls(everyone=False, roles=False, users=False, replied_user=False)

def __repr__(self) -> str: # pragma: no cover - debug helper
return (
f"AllowedMentions(everyone={self.everyone}, roles={self.roles}, "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -877,7 +877,7 @@ async def test_runner_to_discord_redacts_credential_from_prompt_and_index(tmp_pa
session_key="discord:555", source=SimpleNamespace(platform=SimpleNamespace(value="discord")),
_loop_for_step=asyncio.get_running_loop(), stream_consumer_holder=[None],
)
runner = TurnRunner(SimpleNamespace(), ctx)
runner = TurnRunner(SimpleNamespace(_delivery_adapter_for=lambda _source: adapter), ctx)
loop = asyncio.get_running_loop()
runner._schedule = lambda coro, _label: _LoopFuture(asyncio.run_coroutine_threadsafe(coro, loop))
runner._close_native_stream_boundary = lambda _why: None
Expand Down
Loading
Loading