Merge branch 'simp/r3-29-D' into simp/integration3
This commit is contained in:
@@ -14,6 +14,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import contextlib
|
||||
import enum
|
||||
import hashlib
|
||||
import hmac
|
||||
@@ -27,7 +28,7 @@ import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
|
||||
from urllib.parse import quote as _urlquote
|
||||
@@ -46,7 +47,6 @@ LINE_PUSH_URL = "https://api.line.me/v2/bot/message/push"
|
||||
LINE_LOADING_URL = "https://api.line.me/v2/bot/chat/loading/start"
|
||||
LINE_CONTENT_URL_FMT = "https://api-data.line.me/v2/bot/message/{message_id}/content"
|
||||
LINE_BOT_INFO_URL = "https://api.line.me/v2/bot/info"
|
||||
|
||||
LINE_PER_BUBBLE_CHARS = 5000 # LINE hard limit
|
||||
LINE_SAFE_BUBBLE_CHARS = 4500 # conservative chunking limit
|
||||
LINE_MAX_MESSAGES_PER_CALL = 5
|
||||
@@ -55,38 +55,29 @@ WEBHOOK_BODY_MAX_BYTES = 1_048_576 # 1 MiB — webhooks are tiny JSON
|
||||
DEFAULT_WEBHOOK_PORT = 8646
|
||||
DEFAULT_WEBHOOK_PATH = "/line/webhook"
|
||||
DEFAULT_MEDIA_PATH_PREFIX = "/line/media"
|
||||
|
||||
# ``None`` → asyncio binds BOTH address families (mirrors gateway/platforms/webhook.py).
|
||||
# "0.0.0.0" is unreachable on IPv6-only networks (Fly.io 6PN → 502s); "::" breaks IPv4
|
||||
# loopback probes on IPV6_V6ONLY=1 hosts. Pin via ``LINE_HOST`` / ``extra.host``.
|
||||
DEFAULT_HOST = None
|
||||
|
||||
# Bind hosts LINE's servers could never fetch media from → public URL required.
|
||||
_WILDCARD_HOSTS = frozenset({"0.0.0.0", "::", ""})
|
||||
|
||||
_WILDCARD_HOSTS = frozenset({"0.0.0.0", "::", ""}) # LINE can't fetch media from these → public URL required
|
||||
DEFAULT_SLOW_RESPONSE_THRESHOLD = 45.0 # seconds; 0 disables the postback button
|
||||
DEFAULT_PENDING_REPLY_TEXT = "🤔 Still thinking. Tap below to fetch the answer when it's ready."
|
||||
DEFAULT_BUTTON_LABEL = "Get answer"
|
||||
DEFAULT_DELIVERED_TEXT = "Already replied ✅"
|
||||
DEFAULT_INTERRUPTED_TEXT = "Run was interrupted before completion."
|
||||
|
||||
MEDIA_TOKEN_TTL_SECONDS = 1800 # 30 minutes; LINE caches the URL aggressively
|
||||
LINE_IMAGE_MAX_BYTES = 10 * 1024 * 1024 # 10 MB per LINE docs
|
||||
LINE_AV_MAX_BYTES = 200 * 1024 * 1024 # 200 MB for voice/video
|
||||
|
||||
# LINE message type → normalized MessageType. LINE audio is recorded voice clips →
|
||||
# VOICE (STT path), like Telegram/WhatsApp. Unknown types fall back to TEXT.
|
||||
_LINE_MESSAGE_TYPES = {
|
||||
"text": MessageType.TEXT, "image": MessageType.PHOTO, "video": MessageType.VIDEO, "audio": MessageType.VOICE,
|
||||
"file": MessageType.DOCUMENT, "location": MessageType.LOCATION, "sticker": MessageType.STICKER}
|
||||
|
||||
# 1×1 transparent PNG: fallback video preview (LINE requires ``previewImageUrl``).
|
||||
_FALLBACK_PNG_PREVIEW = bytes.fromhex(
|
||||
"89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4"
|
||||
"890000000d49444154789c63000100000005000100377a7ff20000000049454e"
|
||||
"44ae426082")
|
||||
|
||||
|
||||
# Markdown LINE can't render, applied in order (code blocks first so their content survives).
|
||||
_MD_STRIP_RULES: Tuple[Tuple[re.Pattern, Any], ...] = (
|
||||
(re.compile(r"```[a-zA-Z0-9_+-]*\n?(.*?)```", re.DOTALL), lambda m: m.group(1).rstrip("\n")),
|
||||
@@ -110,10 +101,8 @@ def strip_markdown_preserving_urls(text: str) -> str:
|
||||
|
||||
def split_for_line(text: str, max_chars: int = LINE_SAFE_BUBBLE_CHARS) -> List[str]:
|
||||
"""Split into ≤5 LINE bubbles at paragraph/line/word breaks; overflow is ellipsised."""
|
||||
if not text:
|
||||
return []
|
||||
if len(text) <= max_chars:
|
||||
return [text]
|
||||
if not text or len(text) <= max_chars:
|
||||
return [text] if text else []
|
||||
chunks: List[str] = []
|
||||
remaining = text
|
||||
while remaining and len(chunks) < LINE_MAX_MESSAGES_PER_CALL:
|
||||
@@ -163,12 +152,6 @@ class State(enum.Enum):
|
||||
class _CacheEntry:
|
||||
state: State
|
||||
payload: Any = None
|
||||
chat_id: str = ""
|
||||
created_at: float = field(default_factory=time.time)
|
||||
updated_at: float = field(default_factory=time.time)
|
||||
|
||||
|
||||
_KEEP = object() # sentinel: leave entry.payload untouched
|
||||
|
||||
|
||||
class RequestCache:
|
||||
@@ -179,20 +162,17 @@ class RequestCache:
|
||||
|
||||
def register_pending(self, chat_id: str) -> str:
|
||||
rid = str(uuid.uuid4())
|
||||
self._entries[rid] = _CacheEntry(state=State.PENDING, chat_id=chat_id)
|
||||
self._entries[rid] = _CacheEntry(state=State.PENDING)
|
||||
return rid
|
||||
|
||||
def get(self, request_id: str) -> Optional[_CacheEntry]:
|
||||
return self._entries.get(request_id)
|
||||
|
||||
def _transition(self, request_id: str, allowed: Set[State], state: State, payload: Any = _KEEP) -> None:
|
||||
def _transition(self, request_id: str, allowed: Set[State], state: State, payload: Any = None) -> None:
|
||||
entry = self._entries.get(request_id)
|
||||
if entry is None or entry.state not in allowed:
|
||||
return
|
||||
entry.state = state
|
||||
if payload is not _KEEP:
|
||||
entry.payload = payload
|
||||
entry.updated_at = time.time()
|
||||
if entry is not None and entry.state in allowed:
|
||||
entry.state = state
|
||||
entry.payload = entry.payload if state is State.DELIVERED else payload
|
||||
|
||||
def set_ready(self, request_id: str, payload: Any) -> None:
|
||||
self._transition(request_id, {State.PENDING}, State.READY, payload)
|
||||
@@ -230,9 +210,7 @@ _SOURCE_KINDS = {"group": ("groupId", "group"), "room": ("roomId", "room"), "use
|
||||
def _resolve_chat(source: Dict[str, Any]) -> Tuple[str, str]:
|
||||
"""Return ``(chat_id, chat_type)`` from a LINE event ``source`` block (user/group/room)."""
|
||||
kind = _SOURCE_KINDS.get((source or {}).get("type", ""))
|
||||
if kind is None:
|
||||
return "", "dm"
|
||||
return source.get(kind[0], ""), kind[1]
|
||||
return ("", "dm") if kind is None else (source.get(kind[0], ""), kind[1])
|
||||
|
||||
|
||||
def _allowed_for_source(
|
||||
@@ -279,16 +257,14 @@ class _LineClient:
|
||||
clamped = max(5, min(60, (seconds // 5) * 5 or 5)) # LINE: 5-step increments, max 60
|
||||
try:
|
||||
async with self._session(5.0) as session:
|
||||
await session.post(
|
||||
LINE_LOADING_URL, headers=self._headers, json={"chatId": chat_id, "loadingSeconds": clamped}
|
||||
)
|
||||
await session.post(LINE_LOADING_URL, headers=self._headers, json={"chatId": chat_id, "loadingSeconds": clamped})
|
||||
except Exception as exc: # best-effort; never raise
|
||||
logger.debug("LINE loading indicator failed: %s", exc)
|
||||
|
||||
async def fetch_content(self, message_id: str) -> bytes:
|
||||
"""Download an inbound media message's binary content."""
|
||||
url = LINE_CONTENT_URL_FMT.format(message_id=message_id)
|
||||
async with self._session(30.0) as session:
|
||||
url = LINE_CONTENT_URL_FMT.format(message_id=message_id)
|
||||
async with session.get(url, headers={"Authorization": f"Bearer {self._token}"}) as resp:
|
||||
if resp.status >= 400:
|
||||
raise RuntimeError(f"LINE content {resp.status}")
|
||||
@@ -300,19 +276,14 @@ class _LineClient:
|
||||
try:
|
||||
async with self._session(10.0) as session:
|
||||
async with session.get(LINE_BOT_INFO_URL, headers=self._headers) as resp:
|
||||
if resp.status >= 400:
|
||||
return None
|
||||
data = await resp.json()
|
||||
return data.get("userId")
|
||||
return None if resp.status >= 400 else (await resp.json()).get("userId")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _text_message(text: str) -> Dict[str, Any]:
|
||||
"""Build a LINE text message object, capped to per-bubble max."""
|
||||
if len(text) > LINE_PER_BUBBLE_CHARS:
|
||||
text = text[: LINE_PER_BUBBLE_CHARS - 1] + "…"
|
||||
return {"type": "text", "text": text}
|
||||
return {"type": "text", "text": text if len(text) <= LINE_PER_BUBBLE_CHARS else text[: LINE_PER_BUBBLE_CHARS - 1] + "…"}
|
||||
|
||||
|
||||
def _text_messages(content: str) -> List[Dict[str, Any]]:
|
||||
@@ -387,7 +358,6 @@ class LineAdapter(BasePlatformAdapter):
|
||||
|
||||
def __init__(self, config, **kwargs):
|
||||
super().__init__(config=config, platform=Platform("line"))
|
||||
|
||||
extra = getattr(config, "extra", {}) or {}
|
||||
|
||||
def env_or(env: str, key: str, default: Any = "") -> Any:
|
||||
@@ -435,7 +405,6 @@ class LineAdapter(BasePlatformAdapter):
|
||||
async def connect(self, *, is_reconnect: bool = False) -> bool:
|
||||
if not self.channel_access_token or not self.channel_secret:
|
||||
return self._fail("config_missing", "LINE_CHANNEL_ACCESS_TOKEN and LINE_CHANNEL_SECRET must be set")
|
||||
|
||||
# One profile per channel token; lock on a hash so the secret never hits disk.
|
||||
try:
|
||||
from gateway.status import acquire_scoped_lock
|
||||
@@ -445,21 +414,16 @@ class LineAdapter(BasePlatformAdapter):
|
||||
self._lock_key = tok_hash
|
||||
except ImportError:
|
||||
self._lock_key = None
|
||||
|
||||
self._client = _LineClient(self.channel_access_token)
|
||||
|
||||
# Best-effort self-userId for self-echo filtering (LINE rarely echoes anyway).
|
||||
try:
|
||||
try: # best-effort self-userId for self-echo filtering (LINE rarely echoes anyway)
|
||||
self._bot_user_id = await self._client.get_bot_user_id()
|
||||
except Exception as exc:
|
||||
logger.debug("LINE: get_bot_user_id failed: %s", exc)
|
||||
self._bot_user_id = None
|
||||
|
||||
try:
|
||||
from aiohttp import web
|
||||
except ImportError:
|
||||
return self._fail("missing_dep", "aiohttp is required for the LINE adapter — install with `pip install aiohttp`")
|
||||
|
||||
self._app = web.Application(client_max_size=WEBHOOK_BODY_MAX_BYTES)
|
||||
self._app.router.add_post(self.webhook_path, self._handle_webhook)
|
||||
self._app.router.add_get(f"{self.webhook_path}/health", self._handle_health) # tunnel/proxy probe
|
||||
@@ -495,10 +459,8 @@ class LineAdapter(BasePlatformAdapter):
|
||||
for attr, method in (("_site", "stop"), ("_runner", "cleanup")):
|
||||
obj = getattr(self, attr)
|
||||
if obj is not None:
|
||||
try:
|
||||
with contextlib.suppress(Exception):
|
||||
await getattr(obj, method)()
|
||||
except Exception:
|
||||
pass
|
||||
setattr(self, attr, None)
|
||||
self._app = None
|
||||
for path in list(self._media_temp_paths):
|
||||
@@ -506,11 +468,9 @@ class LineAdapter(BasePlatformAdapter):
|
||||
self._media_temp_paths.clear()
|
||||
self._media_tokens.clear()
|
||||
if self._lock_key:
|
||||
try:
|
||||
with contextlib.suppress(Exception):
|
||||
from gateway.status import release_scoped_lock
|
||||
release_scoped_lock("line", self._lock_key)
|
||||
except Exception:
|
||||
pass
|
||||
self._lock_key = None
|
||||
|
||||
async def _handle_health(self, request) -> Any:
|
||||
@@ -621,17 +581,16 @@ class LineAdapter(BasePlatformAdapter):
|
||||
try:
|
||||
await self._client.reply(reply_token, messages)
|
||||
except Exception as exc:
|
||||
if state is State.READY:
|
||||
logger.warning("LINE: postback reply failed (%s); falling back to push", exc)
|
||||
try:
|
||||
await self._client.push(chat_id, messages)
|
||||
except Exception as exc2:
|
||||
logger.error("LINE: postback push fallback failed: %s", exc2)
|
||||
return
|
||||
else:
|
||||
if state is not State.READY:
|
||||
if state is State.ERROR:
|
||||
logger.warning("LINE: postback ERROR reply failed: %s", exc)
|
||||
return
|
||||
logger.warning("LINE: postback reply failed (%s); falling back to push", exc)
|
||||
try:
|
||||
await self._client.push(chat_id, messages)
|
||||
except Exception as exc2:
|
||||
logger.error("LINE: postback push fallback failed: %s", exc2)
|
||||
return
|
||||
if state in (State.READY, State.ERROR):
|
||||
self._cache.mark_delivered(request_id)
|
||||
self._pending_buttons.pop(chat_id, None)
|
||||
@@ -727,10 +686,8 @@ class LineAdapter(BasePlatformAdapter):
|
||||
finally:
|
||||
if not post_task.done():
|
||||
post_task.cancel()
|
||||
try:
|
||||
with contextlib.suppress(asyncio.CancelledError, Exception):
|
||||
await post_task
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
|
||||
async def interrupt_session_activity(self, session_key: str, chat_id: str) -> None:
|
||||
"""Resolve any orphan PENDING postback so the button doesn't loop."""
|
||||
@@ -892,10 +849,8 @@ class LineAdapter(BasePlatformAdapter):
|
||||
|
||||
|
||||
def _unlink_quietly(path: str) -> None:
|
||||
try:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _env_credentials_present() -> bool:
|
||||
@@ -996,24 +951,14 @@ def interactive_setup() -> None:
|
||||
def register(ctx) -> None:
|
||||
"""Plugin entry point — called by the Hermes plugin system at startup."""
|
||||
ctx.register_platform(
|
||||
name="line",
|
||||
label="LINE",
|
||||
adapter_factory=lambda cfg: LineAdapter(cfg),
|
||||
check_fn=check_requirements,
|
||||
validate_config=validate_config,
|
||||
is_connected=is_connected,
|
||||
required_env=["LINE_CHANNEL_ACCESS_TOKEN", "LINE_CHANNEL_SECRET"],
|
||||
install_hint="pip install aiohttp",
|
||||
setup_fn=interactive_setup,
|
||||
env_enablement_fn=_env_enablement,
|
||||
cron_deliver_env_var="LINE_HOME_CHANNEL",
|
||||
standalone_sender_fn=_standalone_send,
|
||||
allowed_users_env="LINE_ALLOWED_USERS",
|
||||
name="line", label="LINE", adapter_factory=lambda cfg: LineAdapter(cfg), check_fn=check_requirements,
|
||||
validate_config=validate_config, is_connected=is_connected,
|
||||
required_env=["LINE_CHANNEL_ACCESS_TOKEN", "LINE_CHANNEL_SECRET"], install_hint="pip install aiohttp",
|
||||
setup_fn=interactive_setup, env_enablement_fn=_env_enablement, cron_deliver_env_var="LINE_HOME_CHANNEL",
|
||||
standalone_sender_fn=_standalone_send, allowed_users_env="LINE_ALLOWED_USERS",
|
||||
allow_all_env="LINE_ALLOW_ALL_USERS",
|
||||
max_message_length=LINE_SAFE_BUBBLE_CHARS, # per-bubble cap is 5000; smart-chunker uses 4500
|
||||
emoji="💚",
|
||||
pii_safe=False,
|
||||
allow_update_command=True,
|
||||
emoji="💚", pii_safe=False, allow_update_command=True,
|
||||
platform_hint=(
|
||||
"You are chatting via LINE Messaging API. LINE does NOT render "
|
||||
"Markdown — text bubbles show ** and # literally. Bare URLs are "
|
||||
|
||||
@@ -34,13 +34,12 @@ WS_RETRY_DELAY_INITIAL = 2.0
|
||||
WS_RETRY_DELAY_MAX = 60.0
|
||||
HEALTH_CHECK_INTERVAL = 30.0
|
||||
HEALTH_CHECK_STALE_THRESHOLD = 300.0
|
||||
|
||||
# Correlation ID prefix for requests we send so we can ignore our own echoes.
|
||||
_CORR_PREFIX = "hermes-"
|
||||
|
||||
_CORR_PREFIX = "hermes-" # marks requests we sent so our own echoes can be ignored
|
||||
_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
|
||||
_AUDIO_EXTS = {".mp3", ".wav", ".ogg", ".m4a", ".aac", ".opus"}
|
||||
_VOICE_TAG_EXTS = {".ogg", ".mp3", ".wav", ".m4a", ".opus"} # MEDIA: tags sent as voice notes
|
||||
_TEXT_BEARING_TYPES = ("text", "file", "image", "voice", "link", "video")
|
||||
_MEDIA_KIND_PRECEDENCE = (("audio/", MessageType.VOICE), ("image/", MessageType.PHOTO)) # first match wins
|
||||
|
||||
|
||||
def _parse_comma_list(value: str) -> List[str]:
|
||||
@@ -64,6 +63,14 @@ def _is_audio_ext(ext: str) -> bool:
|
||||
return ext.lower() in _AUDIO_EXTS
|
||||
|
||||
|
||||
def _mime_for_ext(ext: str) -> str:
|
||||
if _is_image_ext(ext):
|
||||
return f"image/{ext.lstrip('.')}"
|
||||
if _is_audio_ext(ext):
|
||||
return f"audio/{ext.lstrip('.')}"
|
||||
return "application/octet-stream"
|
||||
|
||||
|
||||
def _display_name(obj: dict, profile_key: str, default: str = "") -> str:
|
||||
"""``localDisplayName`` falling back to the nested profile's ``displayName``."""
|
||||
return obj.get("localDisplayName", "") or (obj.get(profile_key, {}) or {}).get("displayName", default)
|
||||
@@ -92,7 +99,6 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
|
||||
def __init__(self, config: PlatformConfig, **kwargs):
|
||||
super().__init__(config=config, platform=Platform("simplex"))
|
||||
|
||||
extra = getattr(config, "extra", {}) or {}
|
||||
self.ws_url = extra.get("ws_url", "ws://127.0.0.1:5225").rstrip("/")
|
||||
# Auto-accept is on by default; env wins over the ``_env_enablement`` seed.
|
||||
@@ -104,7 +110,6 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
# Without SIMPLEX_GROUP_ALLOWED group messages are ignored (safer default); ``*`` = any group.
|
||||
group_allowed_str = _get_scoped_secret("SIMPLEX_GROUP_ALLOWED", "") or extra.get("group_allowed", "")
|
||||
self.group_allow_from = set(_parse_comma_list(group_allowed_str))
|
||||
|
||||
self._ws = None # websockets connection
|
||||
self._ws_task: Optional[asyncio.Task] = None
|
||||
self._health_task: Optional[asyncio.Task] = None
|
||||
@@ -130,7 +135,6 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
except ImportError:
|
||||
logger.error("SimpleX: 'websockets' package not installed. Run: pip install websockets")
|
||||
return False
|
||||
|
||||
if not self.ws_url:
|
||||
logger.error("SimpleX: SIMPLEX_WS_URL is required")
|
||||
return False
|
||||
@@ -174,7 +178,6 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
"""Maintain a persistent WebSocket connection to the daemon."""
|
||||
import websockets as _wsclient
|
||||
from websockets.exceptions import ConnectionClosed
|
||||
|
||||
backoff = WS_RETRY_DELAY_INITIAL
|
||||
while self._running:
|
||||
try:
|
||||
@@ -262,8 +265,7 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
for item in chat_items if isinstance(chat_items, list) else [chat_items]:
|
||||
await self._safe_handle_chat_item(item, "SimpleX: error processing chat item")
|
||||
|
||||
async def _on_new_chat_item(self, resp: dict) -> None:
|
||||
"""Singular variant emitted by some daemon versions."""
|
||||
async def _on_new_chat_item(self, resp: dict) -> None: # singular variant from some daemon versions
|
||||
await self._safe_handle_chat_item(resp, "SimpleX: error processing chat item")
|
||||
|
||||
async def _on_rcv_file_complete(self, resp: dict) -> None:
|
||||
@@ -308,13 +310,10 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
content_type = content.get("type", "") if isinstance(content, dict) else ""
|
||||
if content_type != "rcvMsgContent":
|
||||
return
|
||||
text = ""
|
||||
msg_type_str = msg_content.get("type", "") if isinstance(msg_content, dict) else ""
|
||||
if msg_type_str in ("text", "file", "image", "voice", "link", "video"):
|
||||
text = msg_content.get("text", "")
|
||||
text = msg_content.get("text", "") if msg_type_str in _TEXT_BEARING_TYPES else ""
|
||||
if not text and msg_type_str not in ("image", "file", "voice"):
|
||||
return
|
||||
|
||||
is_group = chat_type == "group"
|
||||
if chat_type == "direct":
|
||||
contact = chat_info.get("contact", {}) or {}
|
||||
@@ -340,7 +339,6 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
if not sender_id:
|
||||
logger.debug("SimpleX: ignoring message with no sender")
|
||||
return
|
||||
|
||||
# Attachment: chatItem.chatItem.file (sibling of meta/content/chatDir).
|
||||
media_urls: List[str] = []
|
||||
media_types: List[str] = []
|
||||
@@ -360,26 +358,16 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
await self._send_fire_and_forget(f"/freceive {file_id}")
|
||||
return
|
||||
if file_path:
|
||||
if _is_image_ext(ext):
|
||||
mime = f"image/{ext.lstrip('.')}"
|
||||
elif _is_audio_ext(ext):
|
||||
mime = f"audio/{ext.lstrip('.')}"
|
||||
else:
|
||||
mime = "application/octet-stream"
|
||||
media_urls.append(file_path)
|
||||
media_types.append(mime)
|
||||
|
||||
media_types.append(_mime_for_ext(ext))
|
||||
source = self.build_source(
|
||||
chat_id=chat_id, chat_name=chat_name, chat_type="group" if is_group else "dm",
|
||||
user_id=sender_id, user_name=sender_name or sender_id)
|
||||
# Non-image/non-audio files are DOCUMENT so run.py's document-context injection surfaces them.
|
||||
msg_type = MessageType.TEXT
|
||||
if media_types:
|
||||
if any(mt.startswith("audio/") for mt in media_types):
|
||||
msg_type = MessageType.VOICE
|
||||
elif any(mt.startswith("image/") for mt in media_types):
|
||||
msg_type = MessageType.PHOTO
|
||||
else: # other files are DOCUMENT so run.py's document-context injection surfaces them
|
||||
msg_type = MessageType.DOCUMENT
|
||||
msg_type = next((t for prefix, t in _MEDIA_KIND_PRECEDENCE if any(mt.startswith(prefix) for mt in media_types)),
|
||||
MessageType.DOCUMENT)
|
||||
ts_str = meta.get("itemTs") or meta.get("createdAt", "")
|
||||
try:
|
||||
timestamp = datetime.fromisoformat(ts_str.replace("Z", "+00:00")) if ts_str else datetime.now(tz=timezone.utc)
|
||||
@@ -405,10 +393,9 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
try:
|
||||
await asyncio.sleep(self._text_batch_delay)
|
||||
event = self._pending_text_batches.pop(key, None)
|
||||
if not event:
|
||||
return
|
||||
logger.info("[SimpleX] Flushing text batch %s (%d chars)", key, len(event.text or ""))
|
||||
await self.handle_message(event)
|
||||
if event:
|
||||
logger.info("[SimpleX] Flushing text batch %s (%d chars)", key, len(event.text or ""))
|
||||
await self.handle_message(event)
|
||||
finally:
|
||||
if self._pending_text_batch_tasks.get(key) is current_task:
|
||||
self._pending_text_batch_tasks.pop(key, None)
|
||||
@@ -425,12 +412,11 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
|
||||
async def _send_ws(self, payload: dict) -> None:
|
||||
"""Fire-and-forget JSON write; drops cleanly when the WS is missing/closed."""
|
||||
ws = self._ws
|
||||
if not ws:
|
||||
if not self._ws:
|
||||
logger.debug("SimpleX: WS send dropped (not connected)")
|
||||
return
|
||||
try:
|
||||
await ws.send(json.dumps(payload))
|
||||
await self._ws.send(json.dumps(payload))
|
||||
except Exception as e:
|
||||
logger.warning("SimpleX: WS send error: %s", e)
|
||||
|
||||
@@ -524,7 +510,6 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
the ``image`` field. Uses Pillow when available, else ImageMagick ``convert``."""
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
p = Path(file_path)
|
||||
png_path = file_path
|
||||
thumb_uri = ""
|
||||
@@ -532,7 +517,6 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
try:
|
||||
from PIL import Image
|
||||
import io
|
||||
|
||||
img = Image.open(file_path)
|
||||
if needs_png:
|
||||
png_path = str(p.with_suffix(".png"))
|
||||
@@ -557,11 +541,9 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
os.remove(tmp_path)
|
||||
except (FileNotFoundError, subprocess.SubprocessError) as exc:
|
||||
logger.warning("SimpleX: image conversion unavailable: %s", exc)
|
||||
|
||||
return png_path, thumb_uri
|
||||
|
||||
async def send_image(
|
||||
self, chat_id: str, image_url: str, caption: Optional[str] = None, **kwargs) -> SendResult:
|
||||
async def send_image(self, chat_id: str, image_url: str, caption: Optional[str] = None, **kwargs) -> SendResult:
|
||||
"""Send an image. Supports ``file://`` URLs and ``http(s)://`` URLs."""
|
||||
if image_url.startswith("file://"):
|
||||
file_path = unquote(image_url[7:])
|
||||
@@ -578,30 +560,24 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
item = {"filePath": png_path, "msgContent": {"type": "image", "image": thumb_uri, "text": caption or ""}}
|
||||
return await self._send_items(chat_id, [item], "Failed to send image")
|
||||
|
||||
async def send_image_file(
|
||||
self, chat_id: str, image_path: str, caption: Optional[str] = None,
|
||||
reply_to: Optional[str] = None, **kwargs) -> SendResult:
|
||||
"""Send a local image file via SimpleX."""
|
||||
async def send_image_file(self, chat_id: str, image_path: str, caption: Optional[str] = None,
|
||||
reply_to: Optional[str] = None, **kwargs) -> SendResult:
|
||||
return await self.send_image(chat_id, f"file://{image_path}", caption=caption, **kwargs)
|
||||
|
||||
async def send_video(
|
||||
self, chat_id: str, video_path: str, caption: Optional[str] = None,
|
||||
reply_to: Optional[str] = None, **kwargs) -> SendResult:
|
||||
"""Send a video file via SimpleX (as a file attachment)."""
|
||||
async def send_video(self, chat_id: str, video_path: str, caption: Optional[str] = None,
|
||||
reply_to: Optional[str] = None, **kwargs) -> SendResult:
|
||||
"""Videos go as file attachments."""
|
||||
return await self.send_document(chat_id, video_path, caption=caption)
|
||||
|
||||
async def send_document(
|
||||
self, chat_id: str, file_path: str, caption: Optional[str] = None,
|
||||
filename: Optional[str] = None, **kwargs) -> SendResult:
|
||||
"""Send a document/file attachment."""
|
||||
async def send_document(self, chat_id: str, file_path: str, caption: Optional[str] = None,
|
||||
filename: Optional[str] = None, **kwargs) -> SendResult:
|
||||
if not Path(file_path).exists():
|
||||
return SendResult(success=False, error="File not found")
|
||||
item = {"filePath": file_path, "msgContent": {"type": "file", "text": caption or ""}}
|
||||
return await self._send_items(chat_id, [item], "Failed to send document")
|
||||
|
||||
async def send_voice(
|
||||
self, chat_id: str, audio_path: str, caption: Optional[str] = None,
|
||||
reply_to: Optional[str] = None, duration: int = 0, **kwargs) -> SendResult:
|
||||
async def send_voice(self, chat_id: str, audio_path: str, caption: Optional[str] = None,
|
||||
reply_to: Optional[str] = None, duration: int = 0, **kwargs) -> SendResult:
|
||||
"""Send an audio file as an inline SimpleX voice note (``msgContent.type == "voice"``)."""
|
||||
if not Path(audio_path).exists():
|
||||
return SendResult(success=False, error="Voice file not found")
|
||||
@@ -613,10 +589,8 @@ class SimplexAdapter(BasePlatformAdapter):
|
||||
"""SimpleX has no typing-indicator API — no-op."""
|
||||
|
||||
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
|
||||
"""Return basic chat info."""
|
||||
if chat_id.startswith("group:"):
|
||||
return {"chat_id": chat_id, "type": "group", "name": chat_id[6:]}
|
||||
return {"chat_id": chat_id, "type": "dm", "name": chat_id}
|
||||
is_group = chat_id.startswith("group:")
|
||||
return {"chat_id": chat_id, "type": "group" if is_group else "dm", "name": chat_id[6:] if is_group else chat_id}
|
||||
|
||||
|
||||
def check_requirements() -> bool:
|
||||
@@ -625,19 +599,18 @@ def check_requirements() -> bool:
|
||||
return False
|
||||
try:
|
||||
import websockets # noqa: F401
|
||||
return True
|
||||
except ImportError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def validate_config(config) -> bool:
|
||||
"""Validate that the platform config has enough info to connect."""
|
||||
extra = getattr(config, "extra", {}) or {}
|
||||
return bool(_get_scoped_secret("SIMPLEX_WS_URL") or extra.get("ws_url", ""))
|
||||
|
||||
|
||||
def is_connected(config) -> bool:
|
||||
"""Check whether SimpleX is configured (env or config.yaml)."""
|
||||
"""Configured (env or config.yaml) ⇒ shown as connected in status."""
|
||||
return validate_config(config)
|
||||
|
||||
|
||||
@@ -723,24 +696,14 @@ def interactive_setup() -> None:
|
||||
def register(ctx) -> None:
|
||||
"""Plugin entry point — called by the Hermes plugin system at startup."""
|
||||
ctx.register_platform(
|
||||
name="simplex",
|
||||
label="SimpleX Chat",
|
||||
adapter_factory=lambda cfg: SimplexAdapter(cfg),
|
||||
check_fn=check_requirements,
|
||||
validate_config=validate_config,
|
||||
is_connected=is_connected,
|
||||
name="simplex", label="SimpleX Chat", adapter_factory=lambda cfg: SimplexAdapter(cfg),
|
||||
check_fn=check_requirements, validate_config=validate_config, is_connected=is_connected,
|
||||
required_env=["SIMPLEX_WS_URL"],
|
||||
install_hint=("pip install websockets # SimpleX adapter requires the websockets package"),
|
||||
setup_fn=interactive_setup,
|
||||
env_enablement_fn=_env_enablement,
|
||||
cron_deliver_env_var="SIMPLEX_HOME_CHANNEL",
|
||||
standalone_sender_fn=_standalone_send,
|
||||
allowed_users_env="SIMPLEX_ALLOWED_USERS",
|
||||
allow_all_env="SIMPLEX_ALLOW_ALL_USERS",
|
||||
max_message_length=MAX_MESSAGE_LENGTH,
|
||||
emoji="🔒",
|
||||
# SimpleX uses opaque contact IDs only — nothing to redact.
|
||||
pii_safe=True,
|
||||
setup_fn=interactive_setup, env_enablement_fn=_env_enablement, cron_deliver_env_var="SIMPLEX_HOME_CHANNEL",
|
||||
standalone_sender_fn=_standalone_send, allowed_users_env="SIMPLEX_ALLOWED_USERS",
|
||||
allow_all_env="SIMPLEX_ALLOW_ALL_USERS", max_message_length=MAX_MESSAGE_LENGTH, emoji="🔒",
|
||||
pii_safe=True, # SimpleX uses opaque contact IDs only — nothing to redact
|
||||
allow_update_command=True,
|
||||
platform_hint=(
|
||||
"You are chatting via SimpleX Chat, a private decentralised "
|
||||
|
||||
@@ -42,7 +42,7 @@ def _probe_teams_sdk_available() -> bool:
|
||||
|
||||
|
||||
TEAMS_SDK_AVAILABLE = _probe_teams_sdk_available()
|
||||
# SDK symbols stay None until check_teams_requirements() binds them.
|
||||
# SDK symbols stay None until check_teams_requirements() binds them (via _SDK_IMPORTS below).
|
||||
ClientOptions = App = ActivityContext = MessageActivity = ConversationReference = None # type: ignore[assignment,misc]
|
||||
TypingActivityInput = AdaptiveCardInvokeActivity = AdaptiveCardActionCardResponse = None # type: ignore[assignment,misc]
|
||||
AdaptiveCardActionMessageResponse = AdaptiveCardInvokeResponse = InvokeResponse = None # type: ignore[assignment,misc]
|
||||
@@ -195,22 +195,20 @@ async def _standalone_send(
|
||||
return {"error": "Teams standalone send: TEAMS_CLIENT_ID, TEAMS_CLIENT_SECRET, and TEAMS_TENANT_ID are all required"}
|
||||
raw_service_url = os.getenv("TEAMS_SERVICE_URL") or extra.get("service_url", "") or _DEFAULT_TEAMS_SERVICE_URL
|
||||
service_url = _validate_teams_service_url(raw_service_url)
|
||||
if service_url is None:
|
||||
return {"error": f"Teams standalone send: TEAMS_SERVICE_URL host is not on the Bot Framework allowlist; "
|
||||
f"expected one of {sorted(_ALLOWED_TEAMS_SERVICE_HOSTS)}"}
|
||||
if not chat_id:
|
||||
return {"error": "Teams standalone send: chat_id (conversation ID) is required"}
|
||||
if not _TEAMS_CONV_ID_RE.match(chat_id):
|
||||
return {"error": "Teams standalone send: chat_id contains characters outside the Bot Framework conversation ID set"}
|
||||
if not _TEAMS_CONV_ID_RE.match(tenant_id):
|
||||
return {"error": "Teams standalone send: TEAMS_TENANT_ID contains characters outside the expected set"}
|
||||
for failed, error in (
|
||||
(service_url is None, f"TEAMS_SERVICE_URL host is not on the Bot Framework allowlist; "
|
||||
f"expected one of {sorted(_ALLOWED_TEAMS_SERVICE_HOSTS)}"),
|
||||
(not chat_id, "chat_id (conversation ID) is required"),
|
||||
(not _TEAMS_CONV_ID_RE.match(chat_id or ""), "chat_id contains characters outside the Bot Framework conversation ID set"),
|
||||
(not _TEAMS_CONV_ID_RE.match(tenant_id), "TEAMS_TENANT_ID contains characters outside the expected set"),
|
||||
(not AIOHTTP_AVAILABLE, "aiohttp not installed"),
|
||||
):
|
||||
if failed:
|
||||
return {"error": f"Teams standalone send: {error}"}
|
||||
token_url, token_form = _bf_token_request(tenant_id, client_id, client_secret)
|
||||
activities_url = f"{service_url}v3/conversations/{chat_id}/activities"
|
||||
if not AIOHTTP_AVAILABLE:
|
||||
return {"error": "Teams standalone send: aiohttp not installed"}
|
||||
try:
|
||||
import aiohttp as _aiohttp
|
||||
|
||||
# Per-request timeouts so a slow STS endpoint cannot starve the activity POST.
|
||||
per_request_timeout = _aiohttp.ClientTimeout(total=15.0)
|
||||
async with _aiohttp.ClientSession(trust_env=gateway_trust_env()) as session:
|
||||
@@ -283,7 +281,6 @@ def check_teams_requirements() -> bool:
|
||||
|
||||
def _import() -> dict:
|
||||
from aiohttp import web as _web
|
||||
|
||||
bindings: dict = {"web": _web, "AIOHTTP_AVAILABLE": True}
|
||||
with _suppress_third_party_dotenv():
|
||||
for module_name, names in _SDK_IMPORTS.items():
|
||||
@@ -365,7 +362,6 @@ class TeamsAdapter(BasePlatformAdapter):
|
||||
if failed:
|
||||
self._set_fatal_error(code, message, retryable=False)
|
||||
return False
|
||||
|
||||
try:
|
||||
# aiohttp app first — the bridge adapter wires SDK routes into it.
|
||||
aiohttp_app = web.Application(client_max_size=_MAX_BODY_BYTES)
|
||||
@@ -407,8 +403,7 @@ class TeamsAdapter(BasePlatformAdapter):
|
||||
self._running = False
|
||||
if self._runner:
|
||||
await self._runner.cleanup()
|
||||
self._runner = None
|
||||
self._app = None
|
||||
self._runner = self._app = None
|
||||
self._mark_disconnected()
|
||||
logger.info("[teams] Disconnected")
|
||||
|
||||
@@ -418,7 +413,6 @@ class TeamsAdapter(BasePlatformAdapter):
|
||||
because ``asyncio.Lock()`` in __init__ may bind the wrong loop."""
|
||||
import time
|
||||
import httpx
|
||||
|
||||
if self._bf_token_lock is None:
|
||||
self._bf_token_lock = asyncio.Lock()
|
||||
async with self._bf_token_lock:
|
||||
@@ -432,17 +426,15 @@ class TeamsAdapter(BasePlatformAdapter):
|
||||
resp = await client.post(token_url, data=token_form)
|
||||
resp.raise_for_status()
|
||||
payload = resp.json()
|
||||
token = payload["access_token"]
|
||||
expires_in = float(payload.get("expires_in", 3600) or 3600)
|
||||
self._bf_token_cache = (token, time.monotonic() + expires_in)
|
||||
return token
|
||||
self._bf_token_cache = (payload["access_token"], time.monotonic() + expires_in)
|
||||
return self._bf_token_cache[0]
|
||||
|
||||
async def _fetch_attachment_bytes(self, url: str, timeout: float = 30.0) -> bytes:
|
||||
"""Download attachment bytes with SSRF protection. Connector URLs get the bot's bearer token;
|
||||
redirects and body size go through the shared guards (as the cache_*_from_url helpers)."""
|
||||
from tools.url_safety import create_ssrf_safe_async_client, is_safe_url
|
||||
from gateway.platforms.base import _ssrf_redirect_guard, _read_httpx_body_with_limit
|
||||
|
||||
if not is_safe_url(url):
|
||||
raise ValueError("Blocked unsafe attachment URL (SSRF protection)")
|
||||
headers = {"User-Agent": "Mozilla/5.0 (compatible; HermesAgent/1.0)"}
|
||||
@@ -452,8 +444,7 @@ class TeamsAdapter(BasePlatformAdapter):
|
||||
except Exception as e:
|
||||
logger.warning("[teams] Could not acquire Bot Framework token for attachment: %s", e)
|
||||
async with create_ssrf_safe_async_client(
|
||||
timeout=timeout, follow_redirects=True, event_hooks={"response": [_ssrf_redirect_guard]}
|
||||
) as client:
|
||||
timeout=timeout, follow_redirects=True, event_hooks={"response": [_ssrf_redirect_guard]}) as client:
|
||||
async with client.stream("GET", url, headers=headers) as response:
|
||||
response.raise_for_status()
|
||||
# Never buffer .content — a lying Content-Length must not OOM the gateway.
|
||||
@@ -573,10 +564,8 @@ class TeamsAdapter(BasePlatformAdapter):
|
||||
|
||||
@staticmethod
|
||||
def _invoke_card(body: list) -> "InvokeResponse[AdaptiveCardActionMessageResponse]":
|
||||
return InvokeResponse(
|
||||
status=200,
|
||||
body=AdaptiveCardActionCardResponse(value=AdaptiveCard().with_version("1.4").with_body(body)),
|
||||
)
|
||||
card = AdaptiveCard().with_version("1.4").with_body(body)
|
||||
return InvokeResponse(status=200, body=AdaptiveCardActionCardResponse(value=card))
|
||||
|
||||
async def _on_card_action(
|
||||
self, ctx: "ActivityContext[AdaptiveCardInvokeActivity]"
|
||||
@@ -589,23 +578,9 @@ class TeamsAdapter(BasePlatformAdapter):
|
||||
session_key = data.get("session_key", "")
|
||||
if not hermes_action or not session_key:
|
||||
return self._invoke_message("Unknown action.")
|
||||
# Default-deny: approval clicks require TEAMS_ALLOWED_USERS or an explicit
|
||||
# TEAMS_ALLOW_ALL_USERS=true opt-in, else anyone who can message the bot could approve.
|
||||
allowed_csv = os.getenv("TEAMS_ALLOWED_USERS", "").strip()
|
||||
allow_all = os.getenv("TEAMS_ALLOW_ALL_USERS", "").strip().lower() in {"1", "true", "yes"}
|
||||
if not allow_all:
|
||||
if not allowed_csv:
|
||||
logger.warning(
|
||||
"[teams] card action rejected: TEAMS_ALLOWED_USERS not configured "
|
||||
"and TEAMS_ALLOW_ALL_USERS not set — default deny")
|
||||
return self._invoke_message("⛔ Approval buttons require TEAMS_ALLOWED_USERS to be configured.")
|
||||
from_account = ctx.activity.from_
|
||||
clicker_id = getattr(from_account, "aad_object_id", None) or getattr(from_account, "id", "")
|
||||
allowed_ids = {uid.strip() for uid in allowed_csv.split(",") if uid.strip()}
|
||||
if "*" not in allowed_ids and clicker_id not in allowed_ids:
|
||||
logger.warning("[teams] Unauthorized card action by %s — ignoring", clicker_id)
|
||||
return self._invoke_message("⛔ Not authorized.")
|
||||
|
||||
denied = self._card_action_denied(ctx.activity.from_)
|
||||
if denied:
|
||||
return self._invoke_message(denied)
|
||||
choice = _APPROVAL_CHOICES.get(hermes_action)
|
||||
if not choice:
|
||||
return self._invoke_message("Unknown action.")
|
||||
@@ -616,6 +591,26 @@ class TeamsAdapter(BasePlatformAdapter):
|
||||
body.append(TextBlock(text=_APPROVAL_LABELS[choice], wrap=True, weight="Bolder"))
|
||||
return self._invoke_card(body)
|
||||
|
||||
@staticmethod
|
||||
def _card_action_denied(from_account: Any) -> Optional[str]:
|
||||
"""Default-deny gate for approval clicks: require TEAMS_ALLOWED_USERS or an explicit
|
||||
TEAMS_ALLOW_ALL_USERS=true opt-in, else anyone who can message the bot could approve.
|
||||
Returns the user-facing denial text, or ``None`` when allowed."""
|
||||
if os.getenv("TEAMS_ALLOW_ALL_USERS", "").strip().lower() in {"1", "true", "yes"}:
|
||||
return None
|
||||
allowed_csv = os.getenv("TEAMS_ALLOWED_USERS", "").strip()
|
||||
if not allowed_csv:
|
||||
logger.warning(
|
||||
"[teams] card action rejected: TEAMS_ALLOWED_USERS not configured "
|
||||
"and TEAMS_ALLOW_ALL_USERS not set — default deny")
|
||||
return "⛔ Approval buttons require TEAMS_ALLOWED_USERS to be configured."
|
||||
clicker_id = getattr(from_account, "aad_object_id", None) or getattr(from_account, "id", "")
|
||||
allowed_ids = {uid.strip() for uid in allowed_csv.split(",") if uid.strip()}
|
||||
if "*" not in allowed_ids and clicker_id not in allowed_ids:
|
||||
logger.warning("[teams] Unauthorized card action by %s — ignoring", clicker_id)
|
||||
return "⛔ Not authorized."
|
||||
return None
|
||||
|
||||
async def send_exec_approval(
|
||||
self, chat_id: str, command: str, session_key: str, description: str = "dangerous command",
|
||||
metadata: Optional[Dict[str, Any]] = None, allow_permanent: bool = True, allow_session: bool = True,
|
||||
@@ -628,8 +623,7 @@ class TeamsAdapter(BasePlatformAdapter):
|
||||
|
||||
def _action(title: str, hermes_action: str, **kw) -> "ExecuteAction":
|
||||
return ExecuteAction(
|
||||
title=title, verb="hermes_approve", data={**btn_data_base, "hermes_action": hermes_action}, **kw
|
||||
)
|
||||
title=title, verb="hermes_approve", data={**btn_data_base, "hermes_action": hermes_action}, **kw)
|
||||
|
||||
actions = [_action("Allow Once", "approve_once", style="positive")]
|
||||
if not smart_denied and allow_session:
|
||||
@@ -699,7 +693,6 @@ class TeamsAdapter(BasePlatformAdapter):
|
||||
mime_type = mimetypes.guess_type(path)[0] or default_mime
|
||||
with open(path, "rb") as f:
|
||||
content_url = f"data:{mime_type};base64,{base64.b64encode(f.read()).decode()}"
|
||||
|
||||
activity = MessageActivityInput().add_attachments(Attachment(content_type=mime_type, content_url=content_url))
|
||||
if caption:
|
||||
activity = activity.add_text(caption)
|
||||
@@ -709,30 +702,24 @@ class TeamsAdapter(BasePlatformAdapter):
|
||||
logger.error("[teams] send_%s failed: %s", media_label, e, exc_info=True)
|
||||
return SendResult(success=False, error=str(e), retryable=True)
|
||||
|
||||
async def send_image(
|
||||
self, chat_id: str, image_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
|
||||
metadata: Optional[Dict[str, Any]] = None) -> SendResult:
|
||||
async def send_image(self, chat_id: str, image_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
|
||||
metadata: Optional[Dict[str, Any]] = None) -> SendResult:
|
||||
return await self._send_media_attachment(chat_id, image_url, "image/png", caption=caption, media_label="image")
|
||||
|
||||
async def send_image_file(
|
||||
self, chat_id: str, image_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None, **kwargs
|
||||
) -> SendResult:
|
||||
async def send_image_file(self, chat_id: str, image_path: str, caption: Optional[str] = None,
|
||||
reply_to: Optional[str] = None, **kwargs) -> SendResult:
|
||||
return await self.send_image(chat_id=chat_id, image_url=image_path, caption=caption, reply_to=reply_to)
|
||||
|
||||
async def send_video(
|
||||
self, chat_id: str, video_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
|
||||
metadata: Optional[Dict[str, Any]] = None, **kwargs) -> SendResult:
|
||||
async def send_video(self, chat_id: str, video_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
|
||||
metadata: Optional[Dict[str, Any]] = None, **kwargs) -> SendResult:
|
||||
return await self._send_media_attachment(chat_id, video_path, "video/mp4", caption=caption, media_label="video")
|
||||
|
||||
async def send_voice(
|
||||
self, chat_id: str, audio_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
|
||||
metadata: Optional[Dict[str, Any]] = None, **kwargs) -> SendResult:
|
||||
async def send_voice(self, chat_id: str, audio_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
|
||||
metadata: Optional[Dict[str, Any]] = None, **kwargs) -> SendResult:
|
||||
return await self._send_media_attachment(chat_id, audio_path, "audio/mpeg", caption=caption, media_label="voice")
|
||||
|
||||
async def send_document(
|
||||
self, chat_id: str, file_path: str, caption: Optional[str] = None, file_name: Optional[str] = None,
|
||||
reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs,
|
||||
) -> SendResult:
|
||||
async def send_document(self, chat_id: str, file_path: str, caption: Optional[str] = None, file_name: Optional[str] = None,
|
||||
reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs) -> SendResult:
|
||||
return await self._send_media_attachment(
|
||||
chat_id, file_path, "application/octet-stream", caption=caption, media_label="document")
|
||||
|
||||
@@ -744,30 +731,22 @@ _SETUP_CREDENTIALS = (
|
||||
("Client ID", "TEAMS_CLIENT_ID", {}),
|
||||
("Client secret", "TEAMS_CLIENT_SECRET", {"password": True}),
|
||||
("Tenant ID", "TEAMS_TENANT_ID", {}))
|
||||
_SETUP_INTRO = (
|
||||
"You'll need the Teams CLI. If you haven't already:",
|
||||
" npm install -g @microsoft/teams.cli@preview",
|
||||
" teams login",
|
||||
"",
|
||||
"Then expose port 3978 publicly (devtunnel / ngrok / cloudflared),",
|
||||
"and create your bot:",
|
||||
' teams app create --name "Hermes" --endpoint "https://<tunnel>/api/messages"',
|
||||
"",
|
||||
"The CLI will print CLIENT_ID, CLIENT_SECRET, and TENANT_ID. Paste them below.",
|
||||
"")
|
||||
_SETUP_INTRO = ( # "" → blank line
|
||||
"You'll need the Teams CLI. If you haven't already:", " npm install -g @microsoft/teams.cli@preview",
|
||||
" teams login", "", "Then expose port 3978 publicly (devtunnel / ngrok / cloudflared),", "and create your bot:",
|
||||
' teams app create --name "Hermes" --endpoint "https://<tunnel>/api/messages"', "",
|
||||
"The CLI will print CLIENT_ID, CLIENT_SECRET, and TENANT_ID. Paste them below.", "")
|
||||
|
||||
|
||||
def interactive_setup() -> None:
|
||||
"""Guide the user through Teams setup using the Teams CLI."""
|
||||
from hermes_cli.config import get_env_value, save_env_value
|
||||
from hermes_cli.cli_output import prompt, prompt_yes_no, print_info, print_success, print_warning
|
||||
|
||||
existing_id = get_env_value("TEAMS_CLIENT_ID")
|
||||
if existing_id:
|
||||
print_info(f"Teams: already configured (app ID: {existing_id})")
|
||||
if not prompt_yes_no("Reconfigure Teams?", False):
|
||||
return
|
||||
|
||||
for line in _SETUP_INTRO:
|
||||
print_info(line) if line else print()
|
||||
for label, env_key, prompt_kwargs in _SETUP_CREDENTIALS:
|
||||
@@ -776,7 +755,6 @@ def interactive_setup() -> None:
|
||||
print_warning(f"{label} is required — skipping Teams setup")
|
||||
return
|
||||
save_env_value(env_key, value.strip())
|
||||
|
||||
print()
|
||||
print_info("To find your AAD object ID for the allowlist: teams status --verbose")
|
||||
if prompt_yes_no("Restrict access to specific users? (recommended)", True):
|
||||
@@ -789,7 +767,6 @@ def interactive_setup() -> None:
|
||||
else:
|
||||
save_env_value("TEAMS_ALLOW_ALL_USERS", "true")
|
||||
print_warning("⚠️ Open access — anyone who can message the bot can command it.")
|
||||
|
||||
print()
|
||||
print_success("Teams configuration saved to ~/.hermes/.env")
|
||||
print_info("Install the app in Teams: teams app install --id <teamsAppId>")
|
||||
@@ -812,24 +789,18 @@ def _install_hint() -> str:
|
||||
def register(ctx) -> None:
|
||||
"""Plugin entry point — called by the Hermes plugin system."""
|
||||
ctx.register_platform(
|
||||
name="teams",
|
||||
label="Microsoft Teams",
|
||||
adapter_factory=lambda cfg: TeamsAdapter(cfg),
|
||||
name="teams", label="Microsoft Teams", adapter_factory=lambda cfg: TeamsAdapter(cfg),
|
||||
check_fn=check_requirements, # PASSIVE probe — never installs
|
||||
ensure_deps_fn=check_teams_requirements, # ACTIVE lazy-installer, run by create_adapter()
|
||||
validate_config=validate_config,
|
||||
is_connected=is_connected,
|
||||
validate_config=validate_config, is_connected=is_connected,
|
||||
required_env=["TEAMS_CLIENT_ID", "TEAMS_CLIENT_SECRET", "TEAMS_TENANT_ID"],
|
||||
install_hint=_install_hint(),
|
||||
setup_fn=interactive_setup,
|
||||
install_hint=_install_hint(), setup_fn=interactive_setup,
|
||||
env_enablement_fn=_env_enablement, # env-only setups show up in gateway status
|
||||
cron_deliver_env_var="TEAMS_HOME_CHANNEL", # deliver=teams cron home-channel routing
|
||||
standalone_sender_fn=_standalone_send, # out-of-process cron delivery via Bot Framework REST
|
||||
allowed_users_env="TEAMS_ALLOWED_USERS",
|
||||
allow_all_env="TEAMS_ALLOW_ALL_USERS",
|
||||
allowed_users_env="TEAMS_ALLOWED_USERS", allow_all_env="TEAMS_ALLOW_ALL_USERS",
|
||||
max_message_length=28000, # Teams supports up to ~28 KB per message
|
||||
emoji="💼",
|
||||
allow_update_command=True,
|
||||
emoji="💼", allow_update_command=True,
|
||||
platform_hint=(
|
||||
"You are chatting via Microsoft Teams. Teams renders a subset of "
|
||||
"markdown — bold (**text**), italic (*text*), and inline code "
|
||||
|
||||
Reference in New Issue
Block a user