platform_config.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. """
  2. Chatto Platform Config
  3. """
  4. import os
  5. import re
  6. # Put the vendored dependencies for THIS platform on sys.path before importing
  7. # anything from chattolib. Imported relatively as part of the plugin package and
  8. # absolutely when this module is loaded standalone (e.g. by the tests).
  9. try:
  10. from .vendor_path import setup_vendor_path
  11. except ImportError: # pragma: no cover - depends on how the module is loaded
  12. from vendor_path import setup_vendor_path
  13. setup_vendor_path()
  14. import logging
  15. from typing import Any, ClassVar, Generic, TypeVar
  16. import utils
  17. # Absolute import — the vendor dir is on sys.path (see above) and chattolib's
  18. # own modules import each other absolutely ("from chattolib.x import y").
  19. # Importing it relatively as well would load a *second* copy of every module
  20. # under a different name, so isinstance() checks across the two would fail.
  21. from chattolib import ChattoClient
  22. from gateway.config import PlatformConfig
  23. logger = logging.getLogger(__name__)
  24. # --------------------------------------------------------------------------- #
  25. # Constants
  26. # --------------------------------------------------------------------------- #
  27. class ChattoConstants:
  28. """
  29. Chatto Platform Constants
  30. """
  31. def __init__(self):
  32. pass
  33. PLATFORM_NAME: str = "chatto-platform"
  34. PLATFORM_LABEL: str = "Chatto"
  35. INSTALL_HINT = "Requires a Chatto server. See https://docs.chatto.run"
  36. # NOTE: env var names live on the ConfigFields below (ConfigField.env_name),
  37. # so there is exactly one source of truth for them.
  38. MAX_MESSAGE_LENGTH = 10000
  39. # Outgoing text is split below this rather than at MAX_MESSAGE_LENGTH, so
  40. # a full chunk plus the gateway's multi-chunk "(1/2)" label stays under
  41. # the server limit.
  42. SPLIT_THRESHOLD = 9900
  43. SEEN_CAP = 500
  44. # Members fetched per roster delivery (the context block handed to the
  45. # agent alongside every channel turn). The roster rides on each message,
  46. # so the cap keeps the prompt block small; larger rooms get an "and N
  47. # more" note instead.
  48. ROSTER_MEMBER_LIMIT = 20
  49. # Thread messages handed to the agent on the FIRST turn of a thread (see
  50. # ChattoAdapter._thread_context_for). A thread session starts empty, so
  51. # without this block a reply that roots a thread is answered without the
  52. # thread it replies to. Both caps bound the one-shot block: the message
  53. # count bounds the fetch, the character count bounds what reaches the
  54. # prompt — the oldest messages are dropped first when the second bites.
  55. THREAD_CONTEXT_MESSAGE_LIMIT = 20
  56. THREAD_CONTEXT_CHAR_LIMIT = 2000
  57. # WebSocket reconnect backoff (the realtime transport itself lives in
  58. # chattolib.realtime, which owns protocol-level constants).
  59. WS_RECONNECT_INITIAL_BACKOFF = 1.0
  60. WS_RECONNECT_MAX_BACKOFF = 30.0
  61. # A candidate @-handle, not a confirmed one — every match is resolved
  62. # against the member directory before it counts. Pattern mirrors the Chatto
  63. # web frontend's mention extraction: dots are internal separators only, so
  64. # a sentence-ending "frag @bob." yields the handle "bob", and a leading
  65. # hyphen ("per @-mention") yields nothing to look up. The lookbehind keeps
  66. # the domain half of an e-mail address from becoming a candidate.
  67. MENTION_RE = re.compile(
  68. r"(?<![\w.])@([A-Za-z0-9_](?:[A-Za-z0-9_-]|\.(?=[A-Za-z0-9_-]))*)"
  69. )
  70. # Handles that address the room rather than a person — the bot is one of
  71. # the addressees, so these do not mean "this is for someone else".
  72. # Chatto defines exactly these two virtual handles (FDR-006); anything
  73. # else must resolve to a real user in the directory.
  74. BROADCAST_MENTIONS = frozenset({"all", "here"})
  75. # Presence is a TTL the server lets lapse — chattolib refuses to set OFFLINE
  76. # at all ("stop refreshing to go offline"), so staying online means
  77. # re-announcing ONLINE on this interval for as long as we are connected.
  78. PRESENCE_REFRESH_INTERVAL = 60.0
  79. # HTTP timeout used for outbound URL fetches
  80. HTTP_TIMEOUT = 30
  81. # Emoji shortcode mapping (Chatto uses shortcode names, not unicode emoji)
  82. EMOJI_TO_SHORTCODE: ClassVar[dict[str, str]] = {
  83. "👍": "thumbsup",
  84. "👎": "thumbsdown",
  85. "❤️": "heart",
  86. "❤": "heart",
  87. "✅": "white_check_mark",
  88. "❌": "x",
  89. "🚫": "no_entry_sign",
  90. "⛔": "no_entry",
  91. "👀": "eyes",
  92. "🫥": "dotted_line_face",
  93. "🎉": "tada",
  94. "😂": "joy",
  95. "🚀": "rocket",
  96. "🔥": "fire",
  97. "💯": "100",
  98. "🤔": "thinking_face",
  99. "👏": "clap",
  100. "🙏": "pray",
  101. "😅": "sweat_smile",
  102. "😴": "sleeping",
  103. "⏳": "hourglass",
  104. "💭": "thought_balloon",
  105. "👓": "glasses",
  106. "👁️‍🗨️": "eye_in_speech_bubble",
  107. "💬": "speech_balloon",
  108. "🗨️": "left_speech_bubble",
  109. "🗯️": "right_anger_bubble",
  110. "🦾": "mechanical_arm",
  111. "🦿": "mechanical_leg",
  112. }
  113. # Chunk size for asset uploads (256 KB)
  114. UPLOAD_CHUNK_SIZE = 256 * 1024
  115. def _get_env_or_extra_str_opt(
  116. env_var: str, extra_val: str | bool | None, default: str | None = None
  117. ) -> str | None:
  118. """Get a value from environment variable or extra config."""
  119. env_value = os.getenv(env_var)
  120. if env_value is not None:
  121. return env_value.strip()
  122. if extra_val is not None:
  123. if isinstance(extra_val, str):
  124. return extra_val.strip()
  125. elif isinstance(extra_val, bool):
  126. return str(extra_val)
  127. else:
  128. logger.error(
  129. "extra_val: %s is supposed to be str, but %s was found.",
  130. extra_val,
  131. str(type(extra_val)),
  132. )
  133. if default is not None:
  134. logger.debug("Chatto: Defaulting to '%s'", default)
  135. return default.strip()
  136. return None
  137. def _get_env_or_extra_str(
  138. env_var: str, extra_val: str | bool | None, default: str | None = None
  139. ) -> str:
  140. """Get a value from environment variable or extra config."""
  141. my_string = _get_env_or_extra_str_opt(env_var, extra_val, default)
  142. if my_string:
  143. return my_string
  144. return ""
  145. def _get_env_or_extra_truthy(
  146. env_var: str, extra_val: str | bool | None, default: bool = False
  147. ) -> bool:
  148. """Get a boolean value from environment variable or extra config."""
  149. return utils.is_truthy_value(
  150. _get_env_or_extra_str(env_var, extra_val, str(default)), default
  151. )
  152. def _split_str_to_list(mystring: str) -> list[str]:
  153. """Split a comma-separated string, trimming whitespace and dropping empties."""
  154. return [part.strip() for part in mystring.split(",") if part.strip()]
  155. def _get_env_or_extra_list(env_var: str, extra_val: list[str] | None) -> list[str]:
  156. """Get a list of values from environment variable or extra config."""
  157. env_value = os.getenv(env_var)
  158. if env_value is not None:
  159. return _split_str_to_list(env_value)
  160. if extra_val is not None:
  161. if isinstance(extra_val, list):
  162. return [str(c).strip() for c in extra_val if str(c).strip()]
  163. if isinstance(extra_val, str):
  164. return _split_str_to_list(extra_val)
  165. return []
  166. def _get_env_or_extra_int(env_var: str, extra_val: Any, default: int) -> int:
  167. """Get an integer value from environment variable or extra config.
  168. Unparseable values fall back to the default with a warning rather than
  169. raising — a typo in an env var must not keep the plugin from starting.
  170. """
  171. raw = os.getenv(env_var)
  172. if raw is None or not raw.strip():
  173. raw = extra_val
  174. if isinstance(raw, bool): # a YAML true/false is not a number
  175. raw = None
  176. elif isinstance(raw, (int, float)):
  177. return int(raw)
  178. elif isinstance(raw, str) and raw.strip():
  179. try:
  180. return int(raw.strip())
  181. except ValueError:
  182. logger.warning(
  183. "Chatto: %s=%r is not an integer, using default %d",
  184. env_var,
  185. raw,
  186. default,
  187. )
  188. return default
  189. T = TypeVar("T")
  190. class ConfigValue(Generic[T]):
  191. """The resolved value of a single config field, bound to one configuration
  192. instance.
  193. Access the payload via ``.value``. ``__bool__``/``__eq__`` delegate to it,
  194. so a forgotten ``.value`` (``if config.allow_all_users:``) still evaluates
  195. the actual setting instead of the always-truthy wrapper object.
  196. """
  197. __slots__ = ("env_name", "field_name", "value")
  198. def __init__(self, value: T, field_name: str, env_name: str) -> None:
  199. self.value = value
  200. self.field_name = field_name
  201. self.env_name = env_name
  202. def __bool__(self) -> bool:
  203. return bool(self.value)
  204. def __eq__(self, other: object) -> bool:
  205. if isinstance(other, ConfigValue):
  206. return self.value == other.value
  207. return self.value == other
  208. def __hash__(self) -> int:
  209. return hash(self.value)
  210. def __contains__(self, item: Any) -> bool:
  211. return item in self.value # type: ignore[operator]
  212. def __iter__(self):
  213. return iter(self.value) # type: ignore[call-overload]
  214. def __str__(self) -> str:
  215. return str(self.value)
  216. def __repr__(self) -> str:
  217. return f"{self.field_name}={self.value!r}"
  218. class ConfigField(Generic[T]):
  219. """Declarative descriptor for one config field.
  220. Declares *how* a field is read (kind, env var name, default); the resolved
  221. payload lives per configuration instance in ``instance._values``, never on
  222. the descriptor itself. Reading a field on the class (rather than on an
  223. instance) yields the descriptor, so ``ChattoConfiguration.token.env_name``
  224. keeps working for the registration hooks.
  225. """
  226. field_name: str = ""
  227. env_name: str = ""
  228. def __init__(
  229. self,
  230. kind: str,
  231. *,
  232. default: Any = None,
  233. config_key: str | None = None,
  234. doc: str = "",
  235. ) -> None:
  236. # kind: "str" | "str_opt" | "bool" | "list"
  237. self.kind = kind
  238. self.default = default
  239. # config_key: the name used in config.yaml's "extra" block and (upper-cased,
  240. # CHATTO_-prefixed) as the env var, where it differs from the attribute name.
  241. self._config_key = config_key
  242. self.__doc__ = doc
  243. def __set_name__(self, owner: Any, name: str) -> None:
  244. self.field_name = str(name).lower().replace("chatto_", "", 1)
  245. self.config_key = self._config_key or self.field_name
  246. self.env_name = f"CHATTO_{self.config_key.upper()}"
  247. def __get__(self, instance: Any, owner: Any = None) -> "ConfigValue[T]":
  248. if instance is None:
  249. return self # type: ignore[return-value]
  250. return instance._values[self.field_name]
  251. def __set__(self, instance: Any, value: Any) -> None:
  252. raise AttributeError(
  253. f"Chatto: config field '{self.field_name}' is read-only; "
  254. f"set '{self.field_name}.value' if you really need to override it."
  255. )
  256. def resolve(self, extra: dict[str, Any]) -> ConfigValue:
  257. """Read this field from the environment, then from ``extra``, then the default."""
  258. raw = extra.get(self.config_key)
  259. if self.kind == "list":
  260. value: Any = _get_env_or_extra_list(self.env_name, raw)
  261. elif self.kind == "bool":
  262. value = _get_env_or_extra_truthy(self.env_name, raw, bool(self.default))
  263. elif self.kind == "int":
  264. value = _get_env_or_extra_int(self.env_name, raw, int(self.default))
  265. elif self.kind == "str_opt":
  266. value = _get_env_or_extra_str_opt(self.env_name, raw, self.default)
  267. else:
  268. value = _get_env_or_extra_str(self.env_name, raw, self.default)
  269. return ConfigValue(value, self.field_name, self.env_name)
  270. class ChattoConfiguration:
  271. """Chatto platform configuration.
  272. Every field is resolved once per instance, in this order:
  273. environment variable → ``PlatformConfig.extra`` → declared default.
  274. """
  275. base_url = ConfigField("str", default=ChattoClient.DEFAULT_BASE_URL)
  276. token = ConfigField("str_opt")
  277. home_channel = ConfigField("str")
  278. allowed_users = ConfigField("list")
  279. # Participation in multi-person rooms is opt-in: require_mention_rooms
  280. # lists rooms where the bot answers only when addressed
  281. # (@name/@all/@here), optional_mention_rooms lists rooms where it answers
  282. # everything. A room in neither list stays silent — read-only, never
  283. # seeded into context or answered. Chatto has no group rooms like Signal:
  284. # every non-DM surface is a channel-kind room, so these two lists are the
  285. # only inbound gate; DMs always answer.
  286. require_mention_rooms = ConfigField("list")
  287. optional_mention_rooms = ConfigField("list")
  288. # Auto-thread: by default, Chatto creates a thread for replies to room
  289. # messages (not DMs, not already in a thread). This keeps conversations
  290. # organized in the room. Can be disabled via extra.auto_thread=false.
  291. auto_thread = ConfigField("bool", default=True)
  292. allow_all_users = ConfigField("bool", default=False)
  293. reactions = ConfigField("bool", default=True)
  294. # Inbound edits: a message_edited event re-runs the admission gates against
  295. # the new body. A message currently being processed is cancelled and
  296. # re-dispatched with the corrected text; a message that never passed the
  297. # gates (e.g. a forgotten @mention) gets a fresh turn; an already-answered
  298. # message stays answered.
  299. edit_dispatch = ConfigField("bool", default=True)
  300. # How long after posting an edit may still land, in seconds — edits to
  301. # hours-old messages must not resurrect old conversations. Parsed by
  302. # ConfigField's "int" kind; unparseable input falls back to the default.
  303. edit_window = ConfigField("int", default=300)
  304. def __init__(self, pconfig: PlatformConfig):
  305. """Resolve every declared ConfigField against env vars and
  306. ``PlatformConfig.extra`` (which Hermes pre-populates from config.yaml).
  307. """
  308. extra: dict[str, Any] = getattr(pconfig, "extra", None) or {}
  309. self._values: dict[str, ConfigValue] = {
  310. field.field_name: field.resolve(extra) for field in self.fields()
  311. }
  312. logger.debug("ChattoConfiguration: %s", self)
  313. @classmethod
  314. def fields(cls) -> list[ConfigField]:
  315. """All declared config fields, in declaration order."""
  316. return [v for v in vars(cls).values() if isinstance(v, ConfigField)]
  317. def __str__(self) -> str:
  318. redacted = {"token"}
  319. parts = [
  320. f"{name}={'***' if name in redacted and cv.value else cv.value!r}"
  321. for name, cv in self._values.items()
  322. ]
  323. return "ChattoConfiguration(" + ", ".join(parts) + ")"