adapter.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. """LINE Messaging API adapter: aiohttp webhook (signature-verified) → BasePlatformAdapter.
  2. * Reply token preferred (free, single-use, ~60s TTL), metered Push as fallback.
  3. * Slow-LLM postback button past ``slow_response_threshold`` (45s; 0 disables): the reply
  4. token is burned on a Template Buttons bubble; the tap yields a fresh free token that
  5. delivers the cached answer (PENDING → READY → DELIVERED, ERROR on cancel). Mid-turn
  6. progress/status sends (``_interim_send`` metadata / busy-ack prefixes) bypass the cache;
  7. a stale or vanished mapping falls through to a live wire send (#106446).
  8. * Three allowlists (users U…, groups C…, rooms R…); ``LINE_ALLOW_ALL_USERS`` is dev-only.
  9. * Media via public HTTPS only: local files served under ``/line/media/<token>/<name>``
  10. (allowed-roots guard); ``LINE_PUBLIC_URL`` overrides host:port behind tunnels/wildcards.
  11. * ≤5 message objects per call; text chunked at 4500 chars (bubble hard limit 5000).
  12. """
  13. from __future__ import annotations
  14. import asyncio
  15. import base64
  16. import contextlib
  17. import enum
  18. import hashlib
  19. import hmac
  20. import json
  21. import logging
  22. import mimetypes
  23. import os
  24. import re
  25. import secrets
  26. import sys
  27. import tempfile
  28. import time
  29. import uuid
  30. from dataclasses import dataclass
  31. from pathlib import Path
  32. from typing import Any, Callable, Dict, List, Optional, Set, Tuple
  33. from urllib.parse import quote as _urlquote
  34. from agent.i18n import t
  35. from gateway.platforms._shared import (
  36. get_scoped_secret as _get_scoped_secret, seed_extra_from_env as _seed_extra_from_env, send_error
  37. )
  38. from gateway.platforms.base import (
  39. gateway_trust_env, BasePlatformAdapter, SendResult,
  40. cache_audio_from_bytes_async, cache_document_from_bytes_async, cache_image_from_bytes_async,
  41. cache_video_from_bytes_async,
  42. )
  43. from gateway.platforms.helpers import MessageDeduplicator, cancel_task
  44. from gateway.platforms.event import MessageEvent, MessageType
  45. from gateway.config import Platform
  46. logger = logging.getLogger(__name__)
  47. LINE_REPLY_URL = "https://api.line.me/v2/bot/message/reply"
  48. LINE_PUSH_URL = "https://api.line.me/v2/bot/message/push"
  49. LINE_LOADING_URL = "https://api.line.me/v2/bot/chat/loading/start"
  50. LINE_CONTENT_URL_FMT = "https://api-data.line.me/v2/bot/message/{message_id}/content"
  51. LINE_BOT_INFO_URL = "https://api.line.me/v2/bot/info"
  52. LINE_PER_BUBBLE_CHARS = 5000 # LINE hard limit
  53. LINE_SAFE_BUBBLE_CHARS = 4500 # conservative chunking limit
  54. LINE_MAX_MESSAGES_PER_CALL = 5
  55. LINE_REPLY_TOKEN_TTL_SECONDS = 50 # below LINE's ~60s
  56. WEBHOOK_BODY_MAX_BYTES = 1_048_576 # 1 MiB — webhooks are tiny JSON
  57. DEFAULT_WEBHOOK_PORT = 8646
  58. DEFAULT_WEBHOOK_PATH = "/line/webhook"
  59. DEFAULT_MEDIA_PATH_PREFIX = "/line/media"
  60. # ``None`` → asyncio binds BOTH address families (mirrors gateway/platforms/webhook.py).
  61. # "0.0.0.0" is unreachable on IPv6-only networks (Fly.io 6PN → 502s); "::" breaks IPv4
  62. # loopback probes on IPV6_V6ONLY=1 hosts. Pin via ``LINE_HOST`` / ``extra.host``.
  63. DEFAULT_HOST = None
  64. _WILDCARD_HOSTS = frozenset({"0.0.0.0", "::", ""}) # LINE can't fetch media from these → public URL required
  65. DEFAULT_SLOW_RESPONSE_THRESHOLD = 45.0 # seconds; 0 disables the postback button
  66. # Catalog keys of the default copy (operators override per key via LINE_*_TEXT / extra.*);
  67. # resolved through ``t()`` in ``__init__``/at send time, never at import.
  68. DEFAULT_PENDING_REPLY_TEXT_KEY = "platform.line.pending.still_thinking"
  69. DEFAULT_BUTTON_LABEL_KEY = "platform.line.pending.button_label" # LINE caps postback labels at 20 chars
  70. DEFAULT_DELIVERED_TEXT_KEY = "platform.line.pending.delivered"
  71. DEFAULT_INTERRUPTED_TEXT_KEY = "platform.line.pending.interrupted"
  72. DEFAULT_EXPIRED_TEXT_KEY = "platform.line.pending.expired"
  73. MEDIA_TOKEN_TTL_SECONDS = 1800 # 30 minutes; LINE caches the URL aggressively
  74. LINE_IMAGE_MAX_BYTES = 10 * 1024 * 1024 # 10 MB per LINE docs
  75. LINE_AV_MAX_BYTES = 200 * 1024 * 1024 # 200 MB for voice/video
  76. # LINE message type → normalized MessageType. LINE audio is recorded voice clips →
  77. # VOICE (STT path), like Telegram/WhatsApp. Unknown types fall back to TEXT.
  78. _LINE_MESSAGE_TYPES = {
  79. "text": MessageType.TEXT, "image": MessageType.PHOTO, "video": MessageType.VIDEO, "audio": MessageType.VOICE,
  80. "file": MessageType.DOCUMENT, "location": MessageType.LOCATION, "sticker": MessageType.STICKER}
  81. # 1×1 transparent PNG: fallback video preview (LINE requires ``previewImageUrl``).
  82. _FALLBACK_PNG_PREVIEW = bytes.fromhex(
  83. "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4"
  84. "890000000d49444154789c63000100000005000100377a7ff20000000049454e"
  85. "44ae426082")
  86. # Markdown LINE can't render, applied in order (code blocks first so their content survives).
  87. _MD_STRIP_RULES: tuple[tuple[re.Pattern, Any], ...] = (
  88. (re.compile(r"```[a-zA-Z0-9_+-]*\n?(.*?)```", re.DOTALL), lambda m: m.group(1).rstrip("\n")),
  89. (re.compile(r"`([^`]+)`"), r"\1"),
  90. (re.compile(r"\[([^\]]+)\]\((https?://[^\s)]+)\)"), lambda m: f"{m.group(1)} ({m.group(2)})"),
  91. (re.compile(r"\*\*(.+?)\*\*"), r"\1"),
  92. (re.compile(r"(?<!\*)\*(?!\s)(.+?)(?<!\s)\*(?!\*)"), r"\1"),
  93. (re.compile(r"^#{1,6}\s+", re.MULTILINE), ""),
  94. (re.compile(r"^[\s]*[-*+]\s+", re.MULTILINE), "• "))
  95. def strip_markdown_preserving_urls(text: str) -> str:
  96. """Strip Markdown LINE can't render; ``[label](url)`` → ``label (url)`` keeps URLs
  97. tappable (LINE auto-links bare URLs only). Code-block content is kept.
  98. Source: PR #18153 (leepoweii) — adapted to keep code-block content visible (LINE users frequently want
  99. command snippets to land as plain text, not be eaten by the fence).
  100. """
  101. if not text:
  102. return text
  103. for pattern, repl in _MD_STRIP_RULES:
  104. text = pattern.sub(repl, text)
  105. return text
  106. def split_for_line(text: str, max_chars: int = LINE_SAFE_BUBBLE_CHARS) -> list[str]:
  107. """Split into ≤5 LINE bubbles at paragraph/line/word breaks; overflow is ellipsised."""
  108. if not text or len(text) <= max_chars:
  109. return [text] if text else []
  110. chunks: list[str] = []
  111. remaining = text
  112. while remaining and len(chunks) < LINE_MAX_MESSAGES_PER_CALL and len(remaining) > max_chars:
  113. # Prefer paragraph, then line, then word breaks past the half-way mark; else a hard cut.
  114. cuts = [remaining.rfind(sep, 0, max_chars) for sep in ("\n\n", "\n", " ")]
  115. cut = next((c for c in cuts if c >= int(max_chars * 0.5)), cuts[-1])
  116. if cut <= 0:
  117. cut = max_chars
  118. chunks.append(remaining[:cut].rstrip())
  119. remaining = remaining[cut:].lstrip()
  120. if remaining and len(chunks) < LINE_MAX_MESSAGES_PER_CALL:
  121. chunks.append(remaining)
  122. elif remaining: # budget exhausted → ellipsis on the last bubble
  123. chunks[-1] = chunks[-1][: max_chars - 1].rstrip() + "…"
  124. return chunks
  125. def verify_line_signature(body: bytes, signature: str, channel_secret: str) -> bool:
  126. """Verify ``X-Line-Signature``: base64(HMAC-SHA256(secret, raw body)), constant-time."""
  127. if not signature or not channel_secret or body is None:
  128. return False
  129. try:
  130. digest = hmac.new(channel_secret.encode("utf-8"), body, hashlib.sha256).digest()
  131. expected = base64.b64encode(digest).decode("utf-8")
  132. except Exception:
  133. return False
  134. # Bytes: compare_digest raises TypeError on non-ASCII str, and the header is raw.
  135. return hmac.compare_digest(expected.encode(), signature.encode())
  136. class State(enum.Enum):
  137. """Slow-LLM postback cache states."""
  138. PENDING = "pending" # button sent, LLM still running
  139. READY = "ready" # response cached, waiting for postback tap
  140. DELIVERED = "delivered"
  141. ERROR = "error" # LLM raised / interrupted; error text cached
  142. @dataclass
  143. class _CacheEntry:
  144. state: State
  145. payload: Any = None
  146. class RequestCache:
  147. """In-memory cache for slow-LLM postback retrieval (PENDING → READY|ERROR → DELIVERED).
  148. We keep the same model here. See #18153.
  149. """
  150. def __init__(self) -> None:
  151. self._entries: dict[str, _CacheEntry] = {}
  152. def register_pending(self, chat_id: str) -> str:
  153. rid = str(uuid.uuid4())
  154. self._entries[rid] = _CacheEntry(state=State.PENDING)
  155. return rid
  156. def get(self, request_id: str) -> Optional[_CacheEntry]:
  157. return self._entries.get(request_id)
  158. def _transition(self, request_id: str, allowed: set[State], state: State, payload: Any = None) -> None:
  159. entry = self._entries.get(request_id)
  160. if entry is not None and entry.state in allowed:
  161. entry.state = state
  162. entry.payload = entry.payload if state is State.DELIVERED else payload
  163. def set_ready(self, request_id: str, payload: Any) -> None:
  164. self._transition(request_id, {State.PENDING}, State.READY, payload)
  165. def set_error(self, request_id: str, message: str) -> None:
  166. self._transition(request_id, {State.PENDING}, State.ERROR, message)
  167. def mark_delivered(self, request_id: str) -> None:
  168. self._transition(request_id, {State.READY, State.ERROR}, State.DELIVERED)
  169. # LINE source type → (id key, normalized chat_type)
  170. _SOURCE_KINDS = {"group": ("groupId", "group"), "room": ("roomId", "room"), "user": ("userId", "dm")}
  171. def _resolve_chat(source: dict[str, Any]) -> tuple[str, str]:
  172. """Return ``(chat_id, chat_type)`` from a LINE event ``source`` block (user/group/room).
  173. Source: PR #21023 (perng), unchanged.
  174. """
  175. kind = _SOURCE_KINDS.get((source or {}).get("type", ""))
  176. return ("", "dm") if kind is None else (source.get(kind[0], ""), kind[1])
  177. def _allowed_for_source(
  178. source: dict[str, Any], *, allow_all: bool, user_ids: set[str], group_ids: set[str], room_ids: set[str]) -> bool:
  179. """Three-list gate: users, groups, rooms.
  180. See #18153.
  181. """
  182. if allow_all:
  183. return True
  184. sid, chat_type = _resolve_chat(source)
  185. return bool(sid) and sid in {"dm": user_ids, "group": group_ids, "room": room_ids}[chat_type]
  186. class _LineClient:
  187. """Thin aiohttp wrapper around the LINE Messaging API (no ``line-bot-sdk`` dependency)."""
  188. def __init__(self, channel_access_token: str, *, timeout: float = 15.0) -> None:
  189. self._token = channel_access_token
  190. self._timeout = timeout
  191. self._headers = {"Authorization": f"Bearer {channel_access_token}", "Content-Type": "application/json"}
  192. @staticmethod
  193. def _session(timeout: float):
  194. import aiohttp
  195. return aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout), trust_env=gateway_trust_env())
  196. async def _post_messages(self, url: str, label: str, payload: dict[str, Any]) -> None:
  197. async with self._session(self._timeout) as session:
  198. async with session.post(url, headers=self._headers, json=payload) as resp:
  199. if resp.status >= 400:
  200. body = await resp.text()
  201. raise RuntimeError(f"LINE {label} {resp.status}: {body[:200]}")
  202. async def reply(self, reply_token: str, messages: list[dict[str, Any]]) -> None:
  203. await self._post_messages(LINE_REPLY_URL, "reply", {"replyToken": reply_token, "messages": messages})
  204. async def push(self, chat_id: str, messages: list[dict[str, Any]]) -> None:
  205. await self._post_messages(LINE_PUSH_URL, "push", {"to": chat_id, "messages": messages})
  206. async def loading(self, chat_id: str, seconds: int = 60) -> None:
  207. """Loading indicator (DM only). LINE rejects this for groups/rooms."""
  208. if not chat_id or not chat_id.startswith("U"):
  209. return
  210. import aiohttp
  211. clamped = max(5, min(60, (seconds // 5) * 5 or 5)) # LINE: 5-step increments, max 60
  212. try:
  213. async with self._session(5.0) as session:
  214. await session.post(LINE_LOADING_URL, headers=self._headers, json={"chatId": chat_id, "loadingSeconds": clamped})
  215. except Exception as exc: # best-effort; never raise
  216. logger.debug("LINE loading indicator failed: %s", exc)
  217. async def fetch_content(self, message_id: str) -> bytes:
  218. async with self._session(30.0) as session:
  219. url = LINE_CONTENT_URL_FMT.format(message_id=message_id)
  220. async with session.get(url, headers={"Authorization": f"Bearer {self._token}"}) as resp:
  221. if resp.status >= 400:
  222. raise RuntimeError(f"LINE content {resp.status}")
  223. return await resp.read()
  224. async def get_bot_user_id(self) -> Optional[str]:
  225. """Fetch this channel's own userId so we can filter self-messages."""
  226. import aiohttp
  227. try:
  228. async with self._session(10.0) as session:
  229. async with session.get(LINE_BOT_INFO_URL, headers=self._headers) as resp:
  230. return None if resp.status >= 400 else (await resp.json()).get("userId")
  231. except Exception:
  232. return None
  233. def _text_message(text: str) -> dict[str, Any]:
  234. """Build a LINE text message object, capped to per-bubble max."""
  235. return {"type": "text", "text": text if len(text) <= LINE_PER_BUBBLE_CHARS else text[: LINE_PER_BUBBLE_CHARS - 1] + "…"}
  236. def _text_messages(content: str) -> list[dict[str, Any]]:
  237. """Markdown-strip, chunk and cap ``content`` into ≤5 LINE text messages."""
  238. chunks = split_for_line(strip_markdown_preserving_urls(content))
  239. return [_text_message(c) for c in chunks][:LINE_MAX_MESSAGES_PER_CALL]
  240. def build_postback_button_message(text: str, button_label: str, request_id: str) -> dict[str, Any]:
  241. """Slow-LLM postback bubble. Template Buttons stay tappable from history (Quick
  242. Reply chips vanish on the next message). LINE limits: text ≤160, altText ≤400.
  243. See #18153.
  244. """
  245. truncated = text if len(text) <= 160 else text[:157] + "..."
  246. alt = text if len(text) <= 400 else text[:397] + "..."
  247. action = {
  248. "type": "postback",
  249. "label": button_label[:20] or t(DEFAULT_BUTTON_LABEL_KEY)[:20],
  250. "data": json.dumps({"action": "show_response", "request_id": request_id}),
  251. "displayText": button_label[:300] or t(DEFAULT_BUTTON_LABEL_KEY)[:300]}
  252. return {"type": "template", "altText": alt, "template": {"type": "buttons", "text": truncated, "actions": [action]}}
  253. # Gateway busy-ack prefixes (interrupting / queued / steered / background review / working
  254. # heartbeat); these bypass a PENDING postback cache so they land as visible bubbles. Matched on
  255. # the leading emoji marker only: the words behind it are localized (``gateway.busy.*``) and every
  256. # translation keeps the marker, so the fallback keeps firing in any language.
  257. _SYSTEM_BYPASS_PREFIXES: tuple[str, ...] = ("⚡", "⏳", "⏩", "💾")
  258. def _is_system_bypass(content: str) -> bool:
  259. return bool(content) and any(content.startswith(p) for p in _SYSTEM_BYPASS_PREFIXES)
  260. def _is_interim_send(content: str, metadata: Optional[dict[str, Any]] = None) -> bool:
  261. """True for mid-turn progress/status sends that must not become the cached answer.
  262. Purpose-first: the gateway stamps every mid-turn send with ``_interim_send`` metadata
  263. (``gateway.run._interim_metadata``), which survives to the adapter and is stripped
  264. before the wire. The text prefixes remain a fallback for callers that pass no
  265. metadata. See #106446.
  266. """
  267. if (metadata or {}).get("_interim_send"):
  268. return True
  269. return _is_system_bypass(content)
  270. def _csv_set(value: str) -> set[str]:
  271. return {x.strip() for x in (value or "").split(",") if x.strip()}
  272. def _truthy_env(name: str, default: bool = False) -> bool:
  273. # Scoped read: under multiplex os.environ is the DEFAULT profile's allow-all flag.
  274. v = _get_scoped_secret(name)
  275. return default if v is None else v.strip().lower() in {"1", "true", "yes", "on"}
  276. def _credentials(config) -> tuple[str, str]:
  277. """Return ``(channel_access_token, channel_secret)`` from scoped secrets, then ``extra``."""
  278. extra = getattr(config, "extra", {}) or {}
  279. def read(env: str, key: str) -> str:
  280. # A whitespace-only or non-string value (YAML ``true``/``0``/null) reads as unset: it must
  281. # not key the HMAC with blanks or a guessable str() form such as "True".
  282. value = _get_scoped_secret(env) or extra.get(key)
  283. return value.strip() if isinstance(value, str) else ""
  284. return read("LINE_CHANNEL_ACCESS_TOKEN", "channel_access_token"), read("LINE_CHANNEL_SECRET", "channel_secret")
  285. def _coerce(cast: Callable[[Any], Any], value: Any, default: Any) -> Any:
  286. try:
  287. return cast(value)
  288. except (TypeError, ValueError):
  289. return default
  290. # Outbound media kinds → (size cap, size error, missing-public-URL error).
  291. _OUTBOUND_MEDIA = {
  292. "image": (
  293. LINE_IMAGE_MAX_BYTES, "image exceeds 10 MB LINE limit",
  294. "LINE_PUBLIC_URL must be set to send images (LINE only accepts publicly reachable HTTPS URLs)"),
  295. "audio": (LINE_AV_MAX_BYTES, "audio exceeds 200 MB LINE limit", "LINE_PUBLIC_URL must be set to send audio"),
  296. "video": (LINE_AV_MAX_BYTES, "video exceeds 200 MB LINE limit", "LINE_PUBLIC_URL must be set to send video"),
  297. }
  298. # Inbound media kinds → cached file extension.
  299. _INBOUND_MEDIA_EXT = {"image": ".jpg", "audio": ".m4a", "video": ".mp4", "file": ".bin"}
  300. _INBOUND_AV_CACHERS = {"audio": cache_audio_from_bytes_async, "video": cache_video_from_bytes_async}
  301. _LIFECYCLE_EVENTS = frozenset({"follow", "unfollow", "join", "leave"})
  302. _ENV_SEED_KEYS = (("LINE_PORT", "port", int), ("LINE_HOST", "host", None), ("LINE_PUBLIC_URL", "public_url", None))
  303. class LineAdapter(BasePlatformAdapter):
  304. """LINE Messaging API gateway adapter (no message editing → REQUIRES_EDIT_FINALIZE stays False)."""
  305. # Answers /p/<profile>/... on the default listener for a served secondary (shared_ingress).
  306. serves_profile_prefix: bool = True
  307. def __init__(self, config, **kwargs):
  308. super().__init__(config=config, platform=Platform("line"))
  309. extra = getattr(config, "extra", {}) or {}
  310. def env_or(env: str, key: str, default: Any = "") -> Any:
  311. return _get_scoped_secret(env) or extra.get(key, default)
  312. def allowlist(env: str, key: str) -> set[str]:
  313. # Scoped read: under multiplex os.environ is the DEFAULT profile's allowlist.
  314. return _csv_set(_get_scoped_secret(env, "")) | set(extra.get(key, []))
  315. self.channel_access_token, self.channel_secret = _credentials(config)
  316. # Host ``None`` → dual-stack bind (see DEFAULT_HOST); empty string collapses to None.
  317. self.webhook_host = env_or("LINE_HOST", "host", DEFAULT_HOST) or DEFAULT_HOST
  318. self.webhook_port = _coerce(int, env_or("LINE_PORT", "port", DEFAULT_WEBHOOK_PORT), DEFAULT_WEBHOOK_PORT)
  319. self.webhook_path = extra.get("webhook_path", DEFAULT_WEBHOOK_PATH)
  320. # Required for media when the bind isn't publicly reachable.
  321. self.public_base_url = (env_or("LINE_PUBLIC_URL", "public_url") or "").rstrip("/")
  322. self.allow_all = _truthy_env("LINE_ALLOW_ALL_USERS", bool(extra.get("allow_all_users", False)))
  323. self.allowed_users = allowlist("LINE_ALLOWED_USERS", "allowed_users")
  324. self.allowed_groups = allowlist("LINE_ALLOWED_GROUPS", "allowed_groups")
  325. self.allowed_rooms = allowlist("LINE_ALLOWED_ROOMS", "allowed_rooms")
  326. # Slow-LLM postback button threshold + user-overridable copy
  327. threshold = env_or("LINE_SLOW_RESPONSE_THRESHOLD", "slow_response_threshold", DEFAULT_SLOW_RESPONSE_THRESHOLD)
  328. self.slow_response_threshold = _coerce(float, threshold, DEFAULT_SLOW_RESPONSE_THRESHOLD)
  329. for attr, env, default_key in (
  330. ("pending_text", "LINE_PENDING_TEXT", DEFAULT_PENDING_REPLY_TEXT_KEY),
  331. ("button_label", "LINE_BUTTON_LABEL", DEFAULT_BUTTON_LABEL_KEY),
  332. ("delivered_text", "LINE_DELIVERED_TEXT", DEFAULT_DELIVERED_TEXT_KEY),
  333. ("interrupted_text", "LINE_INTERRUPTED_TEXT", DEFAULT_INTERRUPTED_TEXT_KEY),
  334. ("expired_text", "LINE_EXPIRED_TEXT", DEFAULT_EXPIRED_TEXT_KEY)):
  335. setattr(self, attr, env_or(env, attr, t(default_key)))
  336. # Runtime state
  337. self._client: Optional[_LineClient] = None
  338. self._app = self._runner = self._site = None # aiohttp web.Application / AppRunner / TCPSite
  339. self._reply_tokens: dict[str, tuple[str, float]] = {} # chat_id → (token, expiry)
  340. self._cache = RequestCache()
  341. # LINE redelivers webhooks for up to a day on non-2xx; no TTL, just a size bound.
  342. self._dedup = MessageDeduplicator(max_size=1000, ttl_seconds=float("inf"))
  343. self._bot_user_id: Optional[str] = None
  344. self._media_tokens: dict[str, tuple[str, float]] = {} # token → (path, expiry)
  345. self._media_temp_paths: set[str] = set()
  346. self._media_ttl = MEDIA_TOKEN_TTL_SECONDS
  347. self._pending_buttons: dict[str, str] = {} # one outstanding button per chat: chat_id → request_id
  348. def _fail(self, code: str, detail: str, *, retryable: bool = False) -> bool: # fatal connect error → False
  349. self._set_fatal_error(code, detail, retryable=retryable)
  350. return False
  351. async def connect(self, *, is_reconnect: bool = False) -> bool:
  352. if not self.channel_access_token or not self.channel_secret:
  353. return self._fail("config_missing", "LINE_CHANNEL_ACCESS_TOKEN and LINE_CHANNEL_SECRET must be set")
  354. # One profile per channel token; lock on a hash so the secret never hits disk.
  355. tok_hash = hashlib.sha256(self.channel_access_token.encode()).hexdigest()[:16]
  356. if not self._acquire_platform_lock("line", tok_hash, "LINE channel"):
  357. return False
  358. self._client = _LineClient(self.channel_access_token)
  359. try: # best-effort self-userId for self-echo filtering (LINE rarely echoes anyway)
  360. self._bot_user_id = await self._client.get_bot_user_id()
  361. except Exception as exc:
  362. logger.debug("LINE: get_bot_user_id failed: %s", exc)
  363. self._bot_user_id = None
  364. try:
  365. from aiohttp import web
  366. except ImportError:
  367. return self._fail("missing_dep", "aiohttp is required for the LINE adapter — install with `pip install aiohttp`")
  368. self._app = web.Application(client_max_size=WEBHOOK_BODY_MAX_BYTES)
  369. self._app.router.add_post(self.webhook_path, self._handle_webhook)
  370. self._app.router.add_get(f"{self.webhook_path}/health", self._handle_health) # tunnel/proxy probe
  371. self._app.router.add_get(f"{DEFAULT_MEDIA_PATH_PREFIX}/{{token}}/{{filename}}", self._handle_media)
  372. # Plugin-registered routes must be wired before AppRunner.setup() freezes the router.
  373. self._wire_plugin_handlers(self._app)
  374. from gateway.platforms.shared_ingress import bind_listener
  375. try:
  376. # SO_REUSEADDR: on macOS/BSD two sockets with it can silently split traffic →
  377. # disable; on Linux it only allows rebinding past TIME_WAIT → keep default.
  378. # Shared-listener mode (multiplex secondary): no bind; served at /p/<profile>/line/webhook.
  379. self._runner = await bind_listener(
  380. self, self._app, self.webhook_host, self.webhook_port, self.webhook_path,
  381. reuse_address=False if sys.platform == "darwin" else None)
  382. except OSError as exc:
  383. return self._fail(
  384. "bind_failed",
  385. f"Could not bind LINE webhook on {self.webhook_host or 'all IPv4+IPv6 interfaces'}:"
  386. f"{self.webhook_port}: {exc}",
  387. retryable=True)
  388. self._mark_connected()
  389. if self._runner is not None:
  390. logger.info(
  391. "LINE: webhook listening on %s:%s%s%s",
  392. self.webhook_host or "* (all interfaces, IPv4+IPv6)",
  393. self.webhook_port,
  394. self.webhook_path,
  395. f" (public: {self.public_base_url})" if self.public_base_url else "")
  396. return True
  397. async def disconnect(self) -> None:
  398. self._mark_disconnected()
  399. for attr, method in (("_site", "stop"), ("_runner", "cleanup")):
  400. obj = getattr(self, attr)
  401. if obj is not None:
  402. with contextlib.suppress(Exception):
  403. await getattr(obj, method)()
  404. setattr(self, attr, None)
  405. self._app = None
  406. for path in list(self._media_temp_paths):
  407. _unlink_quietly(path)
  408. self._media_temp_paths.clear()
  409. self._media_tokens.clear()
  410. with contextlib.suppress(Exception):
  411. self._release_platform_lock()
  412. async def _handle_health(self, request) -> Any:
  413. from aiohttp import web
  414. return web.json_response({"status": "ok", "platform": "line"})
  415. async def _handle_webhook(self, request) -> Any:
  416. from aiohttp import web
  417. try: # explicit body cap: aiohttp's client_max_size only covers some body modes
  418. body = await request.read()
  419. except Exception as exc:
  420. logger.debug("LINE: read failed: %s", exc)
  421. return web.Response(status=400, text="bad request")
  422. if len(body) > WEBHOOK_BODY_MAX_BYTES:
  423. return web.Response(status=413, text="payload too large")
  424. if not verify_line_signature(body, request.headers.get("X-Line-Signature", ""), self.channel_secret):
  425. return web.Response(status=401, text="invalid signature")
  426. try:
  427. payload = json.loads(body.decode("utf-8"))
  428. except (UnicodeDecodeError, json.JSONDecodeError):
  429. return web.Response(status=400, text="bad json")
  430. for event in payload.get("events", []) or []:
  431. try:
  432. await self._dispatch_event(event)
  433. except Exception:
  434. logger.exception("LINE: dispatch_event failed")
  435. return web.Response(status=200, text="ok")
  436. async def _dispatch_event(self, event: dict[str, Any]) -> None:
  437. event_type = event.get("type")
  438. source = event.get("source") or {}
  439. webhook_event_id = event.get("webhookEventId", "") or ""
  440. if webhook_event_id and self._dedup.is_duplicate(webhook_event_id): # at-least-once redelivery
  441. logger.debug("LINE: ignoring duplicate webhook event %s", webhook_event_id)
  442. return
  443. if self._bot_user_id and source.get("userId", "") == self._bot_user_id:
  444. return
  445. if not _allowed_for_source(source, allow_all=self.allow_all, user_ids=self.allowed_users,
  446. group_ids=self.allowed_groups, room_ids=self.allowed_rooms):
  447. logger.info("LINE: rejecting unauthorized source %s", source)
  448. return
  449. if event_type == "message":
  450. await self._handle_message_event(event)
  451. elif event_type == "postback":
  452. await self._handle_postback_event(event)
  453. elif event_type in _LIFECYCLE_EVENTS:
  454. logger.info("LINE: lifecycle event %s from %s", event_type, source)
  455. else:
  456. logger.debug("LINE: ignoring event type %r", event_type)
  457. async def _handle_message_event(self, event: dict[str, Any]) -> None:
  458. msg = event.get("message") or {}
  459. msg_type, message_id = msg.get("type", ""), msg.get("id", "")
  460. reply_token = event.get("replyToken", "")
  461. source = event.get("source") or {}
  462. chat_id, chat_type = _resolve_chat(source)
  463. user_id = source.get("userId", "") or chat_id
  464. if chat_id and reply_token: # stash the reply token for outbound use
  465. self._reply_tokens[chat_id] = (reply_token, time.time() + LINE_REPLY_TOKEN_TTL_SECONDS)
  466. media_urls: list[str] = []
  467. media_types: list[str] = []
  468. if msg_type == "text":
  469. text = msg.get("text", "") or ""
  470. elif msg_type in _INBOUND_MEDIA_EXT: # fetch, cache, surface a vision-friendly local path
  471. local_path, media_type = await self._download_media(
  472. message_id, msg_type, filename=msg.get("fileName") or msg.get("file_name"))
  473. if local_path:
  474. media_urls, media_types = [local_path], [media_type]
  475. text = f"[{msg_type}]"
  476. elif msg_type == "sticker":
  477. text = f"[sticker: {', '.join(msg['keywords'])}]" if msg.get("keywords") else "[sticker]"
  478. elif msg_type == "location":
  479. text = f"[location: {msg.get('title', '')} {msg.get('address', '')}]".strip()
  480. else:
  481. text = f"[unsupported message type: {msg_type}]"
  482. if chat_type == "dm" and self._client: # best-effort typing indicator (DM only)
  483. asyncio.create_task(self._client.loading(chat_id))
  484. source_obj = self.build_source(
  485. chat_id=chat_id, chat_type=chat_type, user_id=user_id, user_name=user_id, chat_name=chat_id,
  486. message_id=message_id)
  487. await self.handle_message(MessageEvent(
  488. text=text, message_type=_LINE_MESSAGE_TYPES.get(msg_type, MessageType.TEXT), source=source_obj,
  489. raw_message=event, message_id=message_id, media_urls=media_urls, media_types=media_types))
  490. async def _handle_postback_event(self, event: dict[str, Any]) -> None:
  491. """User tapped the slow-LLM postback button — deliver the cached payload. READY replies (push
  492. fallback) and ERROR replies settle the entry; DELIVERED / PENDING just re-issue their notice."""
  493. reply_token = event.get("replyToken", "")
  494. chat_id, _ = _resolve_chat(event.get("source") or {})
  495. try:
  496. parsed = json.loads((event.get("postback") or {}).get("data", "") or "")
  497. except (TypeError, json.JSONDecodeError):
  498. return
  499. request_id = parsed.get("request_id", "") if parsed.get("action") == "show_response" else ""
  500. entry = self._cache.get(request_id) if request_id else None
  501. if not self._client or not reply_token:
  502. return
  503. if entry is None:
  504. # The tap targets a button whose entry is gone (expired / lost with
  505. # process state). Tell the user instead of leaving the chat stuck,
  506. # and drop any mapping that still points at the dead request so
  507. # later answers reach the wire. See #106446.
  508. if request_id and self._pending_buttons.get(chat_id) == request_id:
  509. self._pending_buttons.pop(chat_id, None)
  510. messages = [_text_message(self.expired_text)]
  511. try:
  512. await self._client.reply(reply_token, messages)
  513. except Exception as exc:
  514. logger.debug("LINE: postback expired-notice reply failed: %s", exc)
  515. return
  516. state = entry.state
  517. if state is State.READY:
  518. messages = _text_messages(str(entry.payload or ""))
  519. elif state is State.ERROR:
  520. messages = [_text_message(str(entry.payload or self.interrupted_text))]
  521. else:
  522. messages = [_text_message(self.delivered_text if state is State.DELIVERED else self.pending_text)]
  523. try:
  524. await self._client.reply(reply_token, messages)
  525. except Exception as exc:
  526. if state is not State.READY:
  527. if state is State.ERROR:
  528. logger.warning("LINE: postback ERROR reply failed: %s", exc)
  529. return
  530. logger.warning("LINE: postback reply failed (%s); falling back to push", exc)
  531. try:
  532. await self._client.push(chat_id, messages)
  533. except Exception as exc2:
  534. logger.error("LINE: postback push fallback failed: %s", exc2)
  535. return
  536. if state in (State.READY, State.ERROR):
  537. self._cache.mark_delivered(request_id)
  538. self._pending_buttons.pop(chat_id, None)
  539. async def _download_media(
  540. self, message_id: str, msg_type: str, *, filename: Optional[str] = None) -> tuple[Optional[str], str]:
  541. if not self._client or not message_id:
  542. return None, ""
  543. try:
  544. data = await self._client.fetch_content(message_id)
  545. except Exception as exc:
  546. logger.warning("LINE: failed to fetch %s content for %s: %s", msg_type, message_id, exc)
  547. return None, ""
  548. ext = _INBOUND_MEDIA_EXT.get(msg_type, ".bin")
  549. try:
  550. if msg_type == "image":
  551. return await cache_image_from_bytes_async(data, ext=ext), "image/jpeg"
  552. if msg_type in _INBOUND_AV_CACHERS:
  553. return await _INBOUND_AV_CACHERS[msg_type](data, ext=ext), mimetypes.guess_type(f"{msg_type}{ext}")[0] or f"{msg_type}/mp4"
  554. document_name = filename or f"line_file{ext}"
  555. mime = mimetypes.guess_type(document_name)[0] or "application/octet-stream"
  556. return await cache_document_from_bytes_async(data, document_name), mime
  557. except Exception as exc:
  558. logger.warning("LINE: failed to cache %s payload: %s", msg_type, exc)
  559. return None, ""
  560. async def send(
  561. self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[dict[str, Any]] = None
  562. ) -> SendResult:
  563. if not self._client:
  564. return SendResult(success=False, error="LINE adapter not connected")
  565. # A PENDING postback button caches the response for the tap — except interim /
  566. # system sends (progress heartbeats, busy-acks), which must land as visible
  567. # bubbles. Interim detection is purpose-first: the gateway marks every mid-turn
  568. # status send with ``_interim_send`` (see ``gateway.run._interim_metadata``);
  569. # the text prefixes stay as belt-and-suspenders for metadata-less callers.
  570. pending_rid = self._pending_buttons.get(chat_id)
  571. if pending_rid and not _is_interim_send(content, metadata):
  572. entry = self._cache.get(pending_rid)
  573. if entry is not None and entry.state is State.PENDING:
  574. self._cache.set_ready(pending_rid, content)
  575. return SendResult(success=True, message_id=pending_rid)
  576. # Stale mapping: the entry is READY/DELIVERED/ERROR or gone entirely —
  577. # absorbing this send would silently swallow the answer behind a dead
  578. # button. Clear the mapping and deliver on the wire. See #106446.
  579. self._pending_buttons.pop(chat_id, None)
  580. # System busy-acks (interrupting / queued / steered) and progress heartbeats
  581. # bypass the postback cache and route directly to LINE so they reach the user
  582. # as visible bubbles. Source: PR #18153, #106446.
  583. return await self._send_text_chunks(chat_id, content, force_push=False)
  584. async def _send_text_chunks(self, chat_id: str, content: str, *, force_push: bool) -> SendResult:
  585. return await self._send_messages(chat_id, _text_messages(content), force_push=force_push, text=True)
  586. def _consume_reply_token(self, chat_id: str) -> tuple[str, bool]:
  587. """Consume a stashed reply token if present and unexpired → ``(token, used_reply)``."""
  588. token, expires_at = self._reply_tokens.pop(chat_id, None) or ("", 0.0)
  589. return (token, True) if token and time.time() < expires_at else ("", False)
  590. async def send_typing(self, chat_id: str, metadata=None) -> None:
  591. """Trigger LINE's loading-animation indicator (DM only)."""
  592. if self._client and chat_id:
  593. await self._client.loading(chat_id)
  594. async def get_chat_info(self, chat_id: str) -> dict[str, Any]:
  595. """Best-effort chat info inferred from the ID prefix (U=user, C=group, R=room)."""
  596. chat_type = {"U": "dm", "C": "group", "R": "channel"}.get((chat_id or "")[:1], "dm")
  597. return {"name": chat_id or "", "type": chat_type}
  598. def format_message(self, content: str) -> str:
  599. """Strip Markdown that LINE can't render. URLs are preserved."""
  600. return strip_markdown_preserving_urls(content)
  601. async def _keep_typing(self, chat_id: str, *args, **kwargs) -> None:
  602. """Wrap the base typing heartbeat; fire the slow-LLM postback button at threshold."""
  603. if self.slow_response_threshold <= 0 or not self._client or not chat_id:
  604. await super()._keep_typing(chat_id, *args, **kwargs)
  605. return
  606. async def _fire_postback() -> None:
  607. await asyncio.sleep(self.slow_response_threshold)
  608. # Only fire while a usable reply token remains (the agent responding
  609. # consumes it) and no button is already outstanding.
  610. if chat_id not in self._reply_tokens or chat_id in self._pending_buttons:
  611. return
  612. rid = self._cache.register_pending(chat_id)
  613. self._pending_buttons[chat_id] = rid
  614. token, used = self._consume_reply_token(chat_id)
  615. if not used:
  616. self._pending_buttons.pop(chat_id, None)
  617. return
  618. msg = build_postback_button_message(self.pending_text, self.button_label, rid)
  619. try:
  620. await self._client.reply(token, [msg])
  621. logger.info("LINE: sent slow-LLM postback button for chat %s (rid=%s)", chat_id, rid)
  622. except Exception as exc:
  623. logger.warning("LINE: postback button send failed: %s", exc)
  624. self._pending_buttons.pop(chat_id, None)
  625. post_task = asyncio.create_task(_fire_postback())
  626. try:
  627. await super()._keep_typing(chat_id, *args, **kwargs)
  628. finally:
  629. await cancel_task(post_task)
  630. async def interrupt_session_activity(self, session_key: str, chat_id: str) -> None:
  631. """Resolve any orphan PENDING postback so the button doesn't loop."""
  632. await super().interrupt_session_activity(session_key, chat_id)
  633. rid = self._pending_buttons.pop(chat_id, None)
  634. if rid:
  635. self._cache.set_error(rid, self.interrupted_text)
  636. def _register_media(self, file_path: str, *, cleanup: bool = False) -> str:
  637. """Register a local file for HTTPS serving (evicting expired tokens); return the URL token."""
  638. now = time.time()
  639. for token, (path, exp) in list(self._media_tokens.items()):
  640. if now > exp:
  641. self._media_tokens.pop(token, None)
  642. if path in self._media_temp_paths:
  643. self._media_temp_paths.discard(path)
  644. _unlink_quietly(path)
  645. resolved = str(Path(file_path).resolve())
  646. token = secrets.token_urlsafe(32)
  647. self._media_tokens[token] = (resolved, now + self._media_ttl)
  648. if cleanup:
  649. self._media_temp_paths.add(resolved)
  650. return token
  651. def _media_url(self, token: str, filename: str) -> str:
  652. if self.public_base_url:
  653. base = self.public_base_url
  654. elif getattr(self, "_shared_ingress_base", None):
  655. base = self._shared_ingress_base # default listener's /p/<profile> prefix (multiplex secondary)
  656. else:
  657. # Wildcard/dual-stack binds have no fetchable hostname (the _missing_public_url
  658. # guard should have fired); fall back to localhost so the URL is well-formed.
  659. host = "127.0.0.1" if self._missing_public_url() else self.webhook_host
  660. base = f"https://{host}" if self.webhook_port == 443 else f"https://{host}:{self.webhook_port}"
  661. return f"{base}{DEFAULT_MEDIA_PATH_PREFIX}/{token}/{_urlquote(filename, safe='')}"
  662. def _serve_file(self, path: Path) -> str:
  663. return self._media_url(self._register_media(str(path.resolve())), path.name)
  664. def _missing_public_url(self) -> bool:
  665. """True when no LINE_PUBLIC_URL is set and the bind host is wildcard/dual-stack ``None``."""
  666. if self.public_base_url or getattr(self, "_shared_ingress_base", None):
  667. return False
  668. return self.webhook_host is None or self.webhook_host in _WILDCARD_HOSTS
  669. def _check_media_file(self, kind: str, file_path: str) -> tuple[Optional[Path], Optional[SendResult]]:
  670. """Shared preflight for send_image_file/send_voice/send_video → ``(path, error)``."""
  671. max_bytes, size_error, url_error = _OUTBOUND_MEDIA[kind]
  672. path = Path(file_path)
  673. if not path.is_file():
  674. return None, SendResult(success=False, error=f"{kind} file not found: {file_path}")
  675. for failed, error in (
  676. (path.stat().st_size > max_bytes, size_error),
  677. (not self._client, "LINE adapter not connected"),
  678. (self._missing_public_url(), url_error)):
  679. if failed:
  680. return None, SendResult(success=False, error=error)
  681. return path, None
  682. async def _handle_media(self, request) -> Any:
  683. """Serve a registered local file for LINE's media URLs. Defence-in-depth: the resolved
  684. path is rechecked against allowed roots (tempdir, ``/tmp``→``/private/tmp`` on macOS, HERMES_HOME).
  685. Defence-in-depth: even though ``_register_media`` is only called from trusted internal code, we
  686. recheck the resolved path against an allowed-roots set before serving. Sources allowed:
  687. ``tempfile.gettempdir()``, ``/tmp`` (which resolves to ``/private/tmp`` on macOS), and
  688. ``HERMES_HOME``. PR #8398.
  689. """
  690. from aiohttp import web
  691. token = request.match_info["token"]
  692. file_path, expires_at = self._media_tokens.get(token) or ("", 0.0)
  693. if not file_path:
  694. return web.Response(status=404, text="not found")
  695. if time.time() > expires_at:
  696. self._media_tokens.pop(token, None)
  697. return web.Response(status=410, text="gone")
  698. path = Path(file_path)
  699. if not path.is_file():
  700. return web.Response(status=404, text="not found")
  701. try:
  702. from hermes_constants import get_hermes_home
  703. hermes_home = Path(get_hermes_home()).resolve()
  704. except Exception:
  705. hermes_home = Path.home().joinpath(".hermes").resolve()
  706. resolved = path.resolve()
  707. if not any(resolved.is_relative_to(r) for r in (Path(tempfile.gettempdir()).resolve(), Path("/tmp").resolve(), hermes_home)): # no-tmp: ok — macOS /private/tmp alias in the allowed-roots check, not a write target
  708. logger.warning("LINE: refusing to serve outside allowed roots: %s", resolved)
  709. return web.Response(status=403, text="forbidden")
  710. content_type = mimetypes.guess_type(str(path))[0] or "application/octet-stream"
  711. return web.FileResponse(path, headers={"Content-Type": content_type})
  712. async def send_image_file(
  713. self, chat_id: str, image_path: str, caption: Optional[str] = None, metadata: Optional[dict[str, Any]] = None
  714. ) -> SendResult:
  715. path, err = self._check_media_file("image", image_path)
  716. if err:
  717. return err
  718. url = self._serve_file(path)
  719. if not url.lower().startswith("https://"):
  720. return SendResult(success=False, error=f"LINE image URL must be HTTPS: {url}")
  721. msgs: list[dict[str, Any]] = [{"type": "image", "originalContentUrl": url, "previewImageUrl": url}]
  722. return await self._send_messages(chat_id, msgs + ([_text_message(caption)] if caption else []))
  723. async def send_voice(
  724. self, chat_id: str, audio_path: str, duration_ms: int = 1000, metadata: Optional[dict[str, Any]] = None,
  725. **kwargs: Any,
  726. ) -> SendResult:
  727. path, err = self._check_media_file("audio", audio_path)
  728. if err:
  729. return err
  730. msg = {"type": "audio", "originalContentUrl": self._serve_file(path), "duration": int(duration_ms)}
  731. return await self._send_messages(chat_id, [msg])
  732. async def send_video(
  733. self, chat_id: str, video_path: str, preview_path: Optional[str] = None,
  734. metadata: Optional[dict[str, Any]] = None) -> SendResult:
  735. path, err = self._check_media_file("video", video_path)
  736. if err:
  737. return err
  738. # LINE requires previewImageUrl: use the supplied preview, else a stdlib 1×1 PNG.
  739. # Use one if supplied, otherwise write a stdlib 1×1 PNG to /tmp and serve it. PR #8398.
  740. if preview_path and Path(preview_path).is_file():
  741. preview_url = self._serve_file(Path(preview_path))
  742. else:
  743. tmp = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
  744. try:
  745. tmp.write(_FALLBACK_PNG_PREVIEW)
  746. tmp.flush()
  747. tmp.close()
  748. preview_url = self._media_url(self._register_media(tmp.name, cleanup=True), "preview.png")
  749. except Exception:
  750. _unlink_quietly(tmp.name)
  751. raise
  752. msg = {"type": "video", "originalContentUrl": self._serve_file(path), "previewImageUrl": preview_url}
  753. return await self._send_messages(chat_id, [msg])
  754. async def _send_messages(
  755. self, chat_id: str, messages: list[dict[str, Any]], *, force_push: bool = False, text: bool = False
  756. ) -> SendResult:
  757. """Send built message objects, batched at 5/call: reply token first, then push. ``text``
  758. selects the text contract: reply success reports the token as message_id; push failure logs at error."""
  759. if not self._client:
  760. return SendResult(success=False, error="LINE adapter not connected")
  761. if not messages:
  762. return SendResult(success=True, message_id=None)
  763. n = LINE_MAX_MESSAGES_PER_CALL
  764. batches = [messages[i:i + n] for i in range(0, len(messages), n)]
  765. token, used_reply = self._consume_reply_token(chat_id)
  766. start = 0
  767. if used_reply and not force_push:
  768. try:
  769. await self._client.reply(token, batches[0])
  770. if text:
  771. return SendResult(success=True, message_id=token)
  772. start = 1
  773. except Exception as exc:
  774. logger.info("LINE: reply token rejected (%s); falling back to push", exc)
  775. for i in range(start, len(batches)): # push the rest (reply token is single-use)
  776. try:
  777. await self._client.push(chat_id, batches[i])
  778. except Exception as exc:
  779. if i > 0:
  780. logger.warning("LINE: push for follow-up batch failed: %s", exc)
  781. elif text:
  782. logger.error("LINE: push send failed: %s", exc)
  783. return SendResult(success=False, error=str(exc))
  784. return SendResult(success=True, message_id=None)
  785. def _unlink_quietly(path: str) -> None:
  786. with contextlib.suppress(OSError):
  787. os.unlink(path)
  788. def _env_credentials_present() -> bool:
  789. return all(str(_get_scoped_secret(k) or "").strip() for k in ("LINE_CHANNEL_ACCESS_TOKEN", "LINE_CHANNEL_SECRET"))
  790. def check_requirements() -> bool:
  791. """Plugin gate: require credentials AND aiohttp at runtime."""
  792. if not _env_credentials_present():
  793. return False
  794. try:
  795. import aiohttp
  796. return True
  797. except ImportError:
  798. return False
  799. def validate_config(config) -> bool:
  800. return all(_credentials(config))
  801. def is_connected(config) -> bool:
  802. """Surface in ``hermes status`` even before the adapter is instantiated."""
  803. return validate_config(config)
  804. def _env_enablement() -> Optional[dict[str, Any]]:
  805. """``env_enablement_fn``: seed ``PlatformConfig.extra`` from env-only setups so ``hermes status`` sees them."""
  806. if not _env_credentials_present():
  807. return None
  808. return _seed_extra_from_env(_ENV_SEED_KEYS, home_env="LINE_HOME_CHANNEL")
  809. async def _standalone_send(
  810. pconfig, chat_id: str, message: str, *,
  811. thread_id: Optional[str] = None, media_files: Optional[list[str]] = None, force_document: bool = False,
  812. ) -> dict[str, Any]:
  813. """Out-of-process Push delivery for cron jobs detached from the gateway (no inbound event → no
  814. reply token). ``thread_id`` is ignored (no threads); ``media_files`` need the webhook server."""
  815. token = _credentials(pconfig)[0]
  816. if not token or not chat_id:
  817. return send_error("LINE standalone send: missing token or chat_id")
  818. messages = _text_messages(message or "") or [_text_message("")]
  819. if media_files: # tell the recipient media was generated but not delivered
  820. messages.append(_text_message(
  821. t("platform.line.standalone.attachments_not_deliverable", count=str(len(media_files)))))
  822. messages = messages[:LINE_MAX_MESSAGES_PER_CALL]
  823. try:
  824. await _LineClient(token).push(chat_id, messages)
  825. return {"success": True, "message_id": None}
  826. except Exception as exc:
  827. return send_error(str(exc))
  828. _SETUP_PROMPTS = ( # (env var, prompt, masked)
  829. ("LINE_CHANNEL_ACCESS_TOKEN", "Channel access token", True),
  830. ("LINE_CHANNEL_SECRET", "Channel secret", True),
  831. ("LINE_PUBLIC_URL", "Public HTTPS base URL (optional, e.g. https://my-tunnel.example.com)", False),
  832. ("LINE_ALLOWED_USERS", "Allowed user IDs (comma-separated; blank=skip)", False))
  833. def interactive_setup() -> None:
  834. """``hermes setup line`` wizard (writes ``~/.hermes/.env``); CLI helpers are lazy-imported."""
  835. from hermes_cli.config import get_env_value, save_env_value
  836. from hermes_cli.cli_output import print_header, print_info, prompt
  837. from hermes_cli.setup_platforms import declines_reconfigure
  838. print_header("LINE Messaging API")
  839. if declines_reconfigure("LINE", "Reconfigure LINE?", "LINE_CHANNEL_ACCESS_TOKEN"):
  840. return
  841. print_info("Create a Messaging API channel at https://developers.line.biz/console/ then copy the values below.")
  842. for var, question, secret in _SETUP_PROMPTS:
  843. suffix = " [keep current]" if get_env_value(var) else ""
  844. value = prompt(f"{question}{suffix}", password=secret)
  845. if value:
  846. save_env_value(var, value)
  847. print_info("Done. Set the webhook URL in the LINE console to <your-public-url>/line/webhook and enable 'Use webhook'.")
  848. def register(ctx) -> None:
  849. ctx.register_platform(
  850. name="line", label="LINE", adapter_factory=lambda cfg: LineAdapter(cfg), check_fn=check_requirements,
  851. dashboard_description="Use Hermes from LINE via the LINE Messaging API webhook.",
  852. docs_url="https://hermes-agent.nousresearch.com/docs/user-guide/messaging/line",
  853. validate_config=validate_config, is_connected=is_connected,
  854. required_env=["LINE_CHANNEL_ACCESS_TOKEN", "LINE_CHANNEL_SECRET"], install_hint="pip install aiohttp",
  855. setup_fn=interactive_setup, env_enablement_fn=_env_enablement, cron_deliver_env_var="LINE_HOME_CHANNEL",
  856. standalone_sender_fn=_standalone_send, allowed_users_env="LINE_ALLOWED_USERS",
  857. allow_all_env="LINE_ALLOW_ALL_USERS",
  858. max_message_length=LINE_SAFE_BUBBLE_CHARS, # per-bubble cap is 5000; smart-chunker uses 4500
  859. emoji="💚", pii_safe=False, allow_update_command=True,
  860. platform_hint=(
  861. "You are chatting via LINE Messaging API. LINE does NOT render "
  862. "Markdown — text bubbles show ** and # literally. Bare URLs are "
  863. "auto-linked, but \\[label\\](url) syntax is not. Each text bubble "
  864. "is capped at 5000 characters and at most 5 bubbles are sent per "
  865. "reply, so keep responses concise. Image/audio/video sending "
  866. "requires LINE_PUBLIC_URL configured to a publicly reachable HTTPS "
  867. "host. Slow responses surface a 'Get answer' button the user taps "
  868. "to fetch the reply via a fresh free token."))