slash_commands_session.py 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  1. """Gateway slash commands that rotate, switch, fork or rewrite the session transcript:
  2. /new, /resume, /sessions, /branch, /title, /save, /undo, /retry, /topic, /compress.
  3. Split out of ``gateway/slash_commands.py``; bound onto ``GatewayRunner`` through
  4. ``GatewaySlashCommandsMixin``. Origin internals are imported lazily inside the bodies to avoid
  5. the import cycle."""
  6. from __future__ import annotations
  7. import asyncio
  8. import contextlib
  9. import dataclasses
  10. import logging
  11. import os
  12. import shlex
  13. from typing import Optional, Union
  14. from agent.i18n import t
  15. from agent.turn_context import extract_api_content_sidecar
  16. from gateway.config import Platform
  17. from gateway.platforms.base import EphemeralReply
  18. from gateway.platforms.event import MessageEvent, MessageType
  19. from gateway.session import SessionSource, build_session_key, is_shared_multi_user_session
  20. from gateway.session_transcript import TranscriptReadError
  21. from gateway.slash_commands_branch_thread import (
  22. BRANCH_THREAD_PLATFORMS, branch_dest_source, branch_thread_parent, format_thread_ref, parse_branch_args,
  23. )
  24. from gateway.slash_commands_status import history_unreadable
  25. logger = logging.getLogger("gateway.run") # log-record parity with gateway/run.py
  26. # Bound on the off-loop agent cleanup during /new; past it the reset proceeds and the teardown
  27. # finishes (or leaks) in its worker thread rather than blocking the event loop.
  28. _RESET_CLEANUP_TIMEOUT_S = 30.0
  29. # chat_type values whose session key is per-user (DM-like), incl. the unknown/blank case.
  30. _DM_CHAT_TYPES = {"dm", "direct", "private", ""}
  31. _BRANCH_COPIED_FIELDS = ("content", "tool_calls", "tool_call_id", "finish_reason", "reasoning",
  32. "reasoning_content", "reasoning_details", "codex_reasoning_items",
  33. "codex_message_items", "timestamp", "data_use")
  34. def _sattr(obj, name: str) -> str:
  35. """``str(getattr(obj, name) or "")`` — normalized identity field for origin comparisons."""
  36. return str(getattr(obj, name, "") or "")
  37. def _manual_compression_reply_lines(summary: dict, compressor, focus_topic) -> list[str]:
  38. """Manual /compress confirmation lines, surfacing summariser/aux-model failures.
  39. ``_last_compress_aborted`` = no usable summary, messages unchanged. Provider exception text is
  40. force-redacted at this UI boundary even when global redaction is off; an aux model recovered
  41. via main is an info note so the user can fix their config."""
  42. lines = [f"🗜️ {summary['headline']}"]
  43. if focus_topic:
  44. lines.append(t("gateway.compress.focus_line", topic=focus_topic))
  45. lines.append(summary["token_line"])
  46. if summary["note"]:
  47. lines.append(summary["note"])
  48. summary_err = getattr(compressor, "_last_summary_error", None)
  49. if summary_err:
  50. from agent.redact import redact_sensitive_text
  51. summary_err = redact_sensitive_text(summary_err, force=True)
  52. aux_fail_model = getattr(compressor, "_last_aux_model_failure_model", None)
  53. if getattr(compressor, "_last_compress_aborted", False):
  54. lines.append(t("gateway.compress.aborted", error=(summary_err or t("gateway.shared.unknown_error"))))
  55. elif aux_fail_model:
  56. aux_err = getattr(compressor, "_last_aux_model_failure_error", None) or t("gateway.shared.unknown_error")
  57. lines.append(t("gateway.compress.aux_failed", model=aux_fail_model, error=aux_err))
  58. return lines
  59. def _compress_preview_reply(history, partial: bool, keep_last, focus_topic, agg_note: str) -> str:
  60. """``/compress --preview``: report what WOULD be compressed — no agent, no writes."""
  61. from agent.model_metadata import estimate_request_tokens_rough
  62. from hermes_cli.partial_compress import summarize_compress_preview
  63. pv_msgs = [{"role": m.get("role"), "content": m.get("content")} for m in history
  64. if m.get("role") in {"user", "assistant"} and m.get("content")]
  65. report = summarize_compress_preview(pv_msgs, partial, keep_last, focus_topic,
  66. estimate_request_tokens_rough(pv_msgs))
  67. lines = [f"🗜️ {line}" for line in report["lines"]]
  68. if agg_note:
  69. lines.append(agg_note)
  70. return "\n".join(lines)
  71. def _reset_process_scoped_tool_state() -> None:
  72. """Drop env-passthrough and credential-file state at a conversation boundary (best-effort)."""
  73. with contextlib.suppress(Exception):
  74. from tools.env_passthrough import clear_env_passthrough
  75. clear_env_passthrough()
  76. with contextlib.suppress(Exception):
  77. from tools.credential_files import clear_credential_files
  78. clear_credential_files()
  79. def _branch_row(msg: dict) -> dict:
  80. """/branch child row; keeps the api_content sidecar so the branch's first turn replays the
  81. parent's exact wire bytes (warm provider prompt cache) instead of a cold prefill."""
  82. row = {k: msg.get(k) for k in _BRANCH_COPIED_FIELDS}
  83. row["role"] = msg.get("role", "user")
  84. row["tool_name"] = msg.get("tool_name") or msg.get("name")
  85. row["api_content"] = extract_api_content_sidecar(msg)
  86. return row
  87. def _strip_resume_name(parts: list[str]) -> str:
  88. """Join the non-flag /resume tokens; strip literal ``<...>``/``[...]``/quotes typed from the
  89. usage hint (mirrors the CLI)."""
  90. name = " ".join(p for p in parts if p not in {"--all", "--cross-room"}).strip()
  91. if len(name) >= 2 and (name[0], name[-1]) in {("<", ">"), ("[", "]"), ('"', '"'), ("'", "'")}:
  92. name = name[1:-1].strip()
  93. return name
  94. async def discard_lost_turns(authority, session_id) -> str:
  95. """Messaging ``/discard`` (#134889 GW-10): acknowledge every ``unknown`` (lost-in-restart) turn
  96. of this chat's FIFO through the owner's fenced ``resolve_unknown``, the path Desktop's Discard,
  97. the TUI queue and ``hermes sessions discard`` use. Never replays the input; the saved
  98. followers run once it commits."""
  99. from gateway.session_contract import SessionRef
  100. from hermes_state_runtime import RuntimeStoreError, list_session_admissions
  101. rows = await asyncio.to_thread(list_session_admissions, authority.db, session_id=session_id)
  102. lost = [row for row in rows if row['status'] == 'unknown']
  103. if not lost:
  104. return t("gateway.discard.nothing")
  105. ref = SessionRef(authority.profile_id, session_id)
  106. done = 0
  107. for row in lost:
  108. try:
  109. await authority.resolve_unknown_as_owner(ref, row['admission_id'], row['generation'])
  110. except RuntimeStoreError as exc:
  111. logger.warning("/discard of %s refused: %s", row['admission_id'], exc.reason)
  112. continue
  113. done += 1
  114. return t("gateway.discard.done", count=done) if done else t("gateway.discard.nothing")
  115. class GatewaySessionCommandsMixin:
  116. """Session-transcript slash commands (/new, /resume, /sessions, /branch, /title, /save, /undo, /retry, /topic, /compress)."""
  117. # ------------------------------------------------------------------ /new, /reset
  118. async def _cleanup_old_agent_for_reset(self, session_key: str) -> None:
  119. """Close the old agent's tool resources (sandboxes, browsers, subprocesses) before eviction.
  120. Blocking work on the event loop (confirm-button click) → offloaded with a bounded timeout.
  121. wait_for cancels the await, not the worker thread: a wedged teardown keeps running (or
  122. leaks); the reset proceeds either way."""
  123. _old_agent = self._cached_agent_for(session_key)
  124. if _old_agent is None:
  125. return
  126. try:
  127. await asyncio.wait_for(
  128. self._run_housekeeping_in_executor(self._cleanup_agent_resources, _old_agent),
  129. timeout=_RESET_CLEANUP_TIMEOUT_S)
  130. except TimeoutError:
  131. logger.warning(
  132. "Agent resource cleanup for session %s exceeded %ss during /new reset; proceeding with "
  133. "reset (the worker thread is left to finish on its own). (#35994)",
  134. session_key, _RESET_CLEANUP_TIMEOUT_S)
  135. except Exception as cleanup_exc:
  136. logger.warning(
  137. "Agent resource cleanup for session %s failed during /new reset: %s (#35994)",
  138. session_key, cleanup_exc)
  139. async def _fire_session_reset_hooks(self, source: SessionSource, session_key: str, old_sid,
  140. new_sid) -> None:
  141. """Session-boundary hooks: plugin finalize (off-loop + bounded — trace exports can block
  142. arbitrarily), then session:end and session:reset."""
  143. platform_value = source.platform.value if source.platform else ""
  144. with contextlib.suppress(Exception):
  145. messages = await self._finalize_session_off_loop(
  146. session_id=old_sid, platform=platform_value, reason="new_session",
  147. old_session_id=old_sid, new_session_id=new_sid)
  148. await self._deliver_session_end_messages(messages, source=source, session_key=session_key)
  149. hook_payload = {"platform": platform_value, "user_id": source.user_id, "session_key": session_key}
  150. await self.hooks.emit("session:end", dict(hook_payload))
  151. await self.hooks.emit("session:reset", dict(hook_payload))
  152. async def _handle_discard_command(self, event: MessageEvent) -> str:
  153. """``/discard``: drop this chat's turn lost in a gateway restart so its queue runs again."""
  154. from gateway.session_authorities import active_authority
  155. if not self._is_user_authorized_for_source(event.source):
  156. return t("gateway.discard.nothing")
  157. authority = active_authority(self)
  158. session_key = self._session_key_for_source(event.source)
  159. sid = authority.logical_owner(self.session_store.peek_session_id(session_key)) if authority else None
  160. if not sid:
  161. return t("gateway.discard.nothing")
  162. if sid not in authority.sessions:
  163. # A conversation /resume brought back after a restart is the chat's route but not yet
  164. # live: publish the peeked conversation on its route (review #141357). Never through
  165. # get-or-create: a suspended route would rotate to a new session and strand the lost turn.
  166. authority._publish_route(event.source, sid, session_key)
  167. return await discard_lost_turns(authority, sid)
  168. async def _handle_reset_command(self, event: MessageEvent) -> str | EphemeralReply:
  169. """Handle /new or /reset command."""
  170. source = event.source
  171. session_key = self._session_key_for_source(source)
  172. await self._hm_stop_owner_turn(session_key) # idle and confirmed resets too (N53)
  173. self._invalidate_session_run_generation(session_key, reason="session_reset")
  174. # Evict the running-agent slot now that the generation is bumped: the in-flight run's own
  175. # guarded release (old generation) returns False and would leave a zombie slot that silently
  176. # drops all later messages. Idempotent, so the run's finally calling it again is harmless.
  177. self._release_running_agent_state(session_key)
  178. # Snapshot the old entry so on_session_finalize can report the expiring session id.
  179. # Evict the running-agent slot now that the generation is bumped. The in-flight run's own guarded
  180. # release (run_generation=old) will return False and leave its dead agent behind; clearing here
  181. # keeps the slot from becoming a zombie that silently drops all later messages (#28686). Idempotent,
  182. # so the run's finally calling it again is harmless.
  183. old_entry = self.session_store._entries.get(session_key)
  184. await self._cleanup_old_agent_for_reset(session_key)
  185. self._evict_cached_agent(session_key)
  186. # Conversation boundary: ALL conversation-scoped per-session state + security state in one
  187. # funnel call (see _CONVERSATION_SCOPED_STATE in gateway/run.py).
  188. self._clear_conversation_scope(session_key, reason="session_reset")
  189. # In-flight async delegations end WITH the conversation: once the id rotates their
  190. # completions have no live owner. Expire by durable id, routing key as legacy fallback.
  191. with contextlib.suppress(Exception):
  192. from tools.async_delegation import interrupt_for_session
  193. interrupt_for_session(session_key=session_key, reason="session_reset",
  194. parent_session_id=str(getattr(old_entry, "session_id", "") or ""))
  195. _reset_process_scoped_tool_state()
  196. _old_sid = old_entry.session_id if old_entry else None
  197. from gateway.session_automation import move_route_wakes, route_owner_lock
  198. async with route_owner_lock(self, _old_sid):
  199. new_entry = await self.async_session_store.reset_session(session_key)
  200. await move_route_wakes(self, session_key, _old_sid) # main #114456: a parked wake survives /new
  201. await self._fire_session_reset_hooks(source, session_key, _old_sid,
  202. new_entry.session_id if new_entry else None)
  203. # Scoped to the profile serving this source so a multiplexed /new banner reports the
  204. # profile's model, not the base config's.
  205. try:
  206. session_info = await asyncio.to_thread(self._reset_notice_session_info, source)
  207. except Exception:
  208. session_info = ""
  209. if new_entry:
  210. default_header = t("gateway.reset.header_default")
  211. else: # no existing session: create one
  212. new_entry = await self.async_session_store.get_or_create_session(source, force_new=True)
  213. default_header = t("gateway.reset.header_new")
  214. header = await asyncio.to_thread(self._telegram_topic_new_header, source) or default_header
  215. _title_arg = event.get_command_args().strip()
  216. if _title_arg and self._session_db and new_entry:
  217. header = await self._reset_titled_header(header, new_entry.session_id, _title_arg)
  218. # Telegram DM topic lane: rebind (chat_id, thread_id) → session_id so the next message uses
  219. # the fresh session instead of switching back to the old one.
  220. if await asyncio.to_thread(self._is_telegram_topic_lane, source) and new_entry is not None:
  221. try:
  222. await asyncio.to_thread(self._record_telegram_topic_binding, source, new_entry)
  223. except Exception:
  224. logger.debug("Failed to rebind Telegram topic after /new", exc_info=True)
  225. _new_sid = new_entry.session_id if new_entry else None
  226. # Plugin on_session_reset hook (new session guaranteed to exist); best-effort.
  227. try:
  228. from hermes_cli.lifecycle import invoke_hook as _invoke_hook
  229. _invoke_hook("on_session_reset", session_id=_new_sid, reason="new_session",
  230. platform=source.platform.value if source.platform else "",
  231. old_session_id=_old_sid, new_session_id=_new_sid)
  232. except Exception:
  233. pass
  234. try:
  235. from hermes_cli.tips import get_random_tip
  236. _tip_line = t("gateway.reset.tip", tip=get_random_tip())
  237. except Exception:
  238. _tip_line = ""
  239. body = f"{header}\n\n{session_info}" if session_info else header
  240. return EphemeralReply(f"{body}{_tip_line}")
  241. async def _reset_titled_header(self, header: str, session_id: str, title_arg: str) -> str:
  242. """``/new <title>``: titled header on success, else the header plus a rejection note."""
  243. from hermes_state import SessionDB
  244. note = ""
  245. try:
  246. sanitized = SessionDB.sanitize_title(title_arg)
  247. except ValueError as e:
  248. sanitized = None
  249. note = t("gateway.reset.title_rejected", error=str(e))
  250. if sanitized:
  251. try:
  252. await self._session_db.set_session_title(session_id, sanitized)
  253. header = t("gateway.reset.header_titled", title=sanitized)
  254. except ValueError as e:
  255. note = t("gateway.reset.title_error_untitled", error=str(e))
  256. except Exception:
  257. pass
  258. elif not note: # sanitize_title returned empty (whitespace-only / unprintable)
  259. note = t("gateway.reset.title_empty_untitled")
  260. return header + note
  261. # ------------------------------------------------------- origin / ownership guards
  262. def _gateway_session_origin_for_id(self, session_id: str) -> Optional[SessionSource]:
  263. """Best-effort origin lookup for gateway session IDs."""
  264. lookup = getattr(type(self.session_store), "lookup_by_session_id", None)
  265. if callable(lookup):
  266. entry = lookup(self.session_store, session_id)
  267. return getattr(entry, "origin", None) if entry is not None else None
  268. # Test doubles / older stores lack the public lookup; fail closed when nothing resolves.
  269. entries = getattr(self.session_store, "_entries", {}) or {}
  270. return next((getattr(e, "origin", None) for e in entries.values()
  271. if getattr(e, "session_id", None) == session_id), None)
  272. @staticmethod
  273. def _same_matrix_room(current: SessionSource, origin: Optional[SessionSource]) -> bool:
  274. # thread_id is part of the session key, so another thread of the SAME room is a DIFFERENT
  275. # session; non-threaded rooms compare "" == "".
  276. return (origin is not None and origin.platform == Platform.MATRIX
  277. and current.platform == Platform.MATRIX and origin.chat_id == current.chat_id
  278. and _sattr(current, "thread_id") == _sattr(origin, "thread_id"))
  279. def _same_origin_chat(self, current: SessionSource, origin: Optional[SessionSource]) -> bool:
  280. """Platform-agnostic counterpart to ``_same_matrix_room``. Per-participant sessions must be
  281. participant-scoped here too, else a co-member could resume another member's live session
  282. (IDOR); only an explicitly shared group/thread shares."""
  283. if origin is None or current is None:
  284. return False
  285. if origin.platform != current.platform or origin.chat_id != current.chat_id:
  286. return False
  287. # thread_id is part of every session key: threads of one chat are DIFFERENT sessions.
  288. if _sattr(current, "thread_id") != _sattr(origin, "thread_id"):
  289. return False
  290. if _sattr(current, "chat_type").lower() in _DM_CHAT_TYPES:
  291. # An equal non-empty chat_id IS the DM key. build_session_key falls back to the
  292. # participant (``user_id_alt or user_id`` — Signal/Feishu key on alt) only without a
  293. # chat_id; mirror that and fail closed on a missing/different participant.
  294. if _sattr(current, "chat_id"):
  295. return True
  296. cur_pid = str(current.user_id_alt or current.user_id or "")
  297. org_pid = str(origin.user_id_alt or origin.user_id or "")
  298. return bool(cur_pid) and cur_pid == org_pid
  299. # Non-DM: a shared key is one session for everyone; a per-user key compares the participant
  300. # it is built from, failing closed when either side lacks one.
  301. if self._is_shared_session_source(current):
  302. return True
  303. cur_pid = current.user_id_alt or current.user_id
  304. org_pid = origin.user_id_alt or origin.user_id
  305. return bool(cur_pid and org_pid) and cur_pid == org_pid
  306. def _is_shared_session_source(self, source: SessionSource) -> bool:
  307. """Whether *source*'s session key is shared by every participant (not per-user); mirrors
  308. build_session_key's isolation rules so the guards stay in lock-step with the key."""
  309. return is_shared_multi_user_session(
  310. source, group_sessions_per_user=getattr(self.config, "group_sessions_per_user", True),
  311. thread_sessions_per_user=getattr(self.config, "thread_sessions_per_user", False))
  312. def _resume_caller_is_admin(self, source: SessionSource) -> bool:
  313. """Whether *source* is an EXPLICITLY-configured admin (cross-origin /resume, /sessions).
  314. Stricter than ``SlashAccessPolicy.is_admin()``, which is True for every caller when slash
  315. gating is DISABLED — the default config would make everyone cross-origin-capable (IDOR)."""
  316. try:
  317. from gateway.slash_access import policy_for_runner_source
  318. policy = policy_for_runner_source(self, source)
  319. uid = getattr(source, "user_id", None)
  320. return bool(policy.enabled and uid and policy.is_admin(uid))
  321. except Exception:
  322. return False
  323. def _persisted_row_proves_owner(self, source: SessionSource, row: dict) -> bool:
  324. """Whether a persisted (inactive) session *row* provably belongs to *source*'s session key.
  325. Rows once stored only source + user_id, so the persisted chat/thread origin is compared too
  326. and legacy NULL rows fail closed. The table has no user_id_alt column, so an alt-keyed
  327. (Signal/Feishu) caller is never proven by user_id alone (CWE-639)."""
  328. caller_src = source.platform.value if source.platform else None
  329. row_src = row.get("source")
  330. caller_uid = _sattr(source, "user_id")
  331. if not caller_uid:
  332. return False
  333. row_thread = str(row.get("thread_id") or "")
  334. if not (row_src and caller_src and str(row_src) == str(caller_src)
  335. and row_thread == _sattr(source, "thread_id")):
  336. return False # blank/legacy source cannot prove the platform; other thread = other session
  337. row_uid = str(row.get("user_id") or "")
  338. row_chat = str(row.get("chat_id") or "")
  339. caller_chat = _sattr(source, "chat_id")
  340. caller_keys_on_alt = bool(_sattr(source, "user_id_alt"))
  341. if _sattr(source, "chat_type").lower() in _DM_CHAT_TYPES:
  342. # A no-chat_id DM is keyed PURELY on the participant (alt-keyed caller fails closed).
  343. if caller_keys_on_alt and not (row_chat and caller_chat):
  344. return False
  345. return bool(row_uid) and row_uid == caller_uid and row_chat == caller_chat
  346. # Non-DM: both sides must carry chat_id and match (legacy NULL-chat rows fail closed).
  347. if not (row_chat and caller_chat and row_chat == caller_chat):
  348. return False
  349. # A SHARED group/thread is one session for everyone: same-chat proof suffices (a user-id
  350. # check would block co-members). A per-user key still requires the same owner.
  351. if self._is_shared_session_source(source):
  352. return True
  353. if caller_keys_on_alt:
  354. return False
  355. return bool(row_uid) and row_uid == caller_uid
  356. async def _resume_target_allowed(self, source: SessionSource, target_id: str,
  357. allow_override: bool = False) -> bool:
  358. """Whether *source* may resume session *target_id* (IDOR guard for every adapter). The live
  359. origin decides when the target is active; otherwise the DB row must PROVE ownership or fail
  360. closed. Admin ``--all`` bypasses."""
  361. if allow_override and self._resume_caller_is_admin(source):
  362. return True
  363. # Only a real SessionSource origin decides; unresolvable/error falls through to DB scoping.
  364. try:
  365. origin = self._gateway_session_origin_for_id(target_id)
  366. except Exception:
  367. origin = None
  368. if isinstance(origin, SessionSource):
  369. return self._same_origin_chat(source, origin)
  370. try:
  371. row = await self._session_db.get_session(target_id) or {}
  372. except Exception:
  373. return False
  374. return self._persisted_row_proves_owner(source, row)
  375. async def _resume_row_visible(self, source: SessionSource, row: dict, allow_all: bool) -> bool:
  376. """Whether a listing *row* belongs to the caller's origin (blocks cross-origin enumeration of
  377. ids/previews); Matrix is room-scoped, ``--all`` needs a configured admin everywhere."""
  378. if allow_all and self._resume_caller_is_admin(source):
  379. return True
  380. sid = str(row.get("id") or "")
  381. if source.platform == Platform.MATRIX:
  382. return self._same_matrix_room(source, self._gateway_session_origin_for_id(sid))
  383. return await self._resume_target_allowed(source, sid, allow_override=False)
  384. # ------------------------------------------------------------------ /retry, /undo
  385. async def _handle_retry_command(self, event: MessageEvent) -> str:
  386. """Handle /retry command - re-send the last user message."""
  387. # The canonical projection skips bookkeeping rows (role=user + display_kind) and pure
  388. # handoffs while still recognizing a real ask embedded in a compaction carrier.
  389. from agent.context_compressor import (
  390. history_before_user_originated_turn, retryable_user_text, split_user_originated_turn,
  391. user_originated_turn_view)
  392. source = event.source
  393. session_entry = await self.async_session_store.get_or_create_session(source)
  394. # Under a session authority the rewrite commits in the re-send's own admission, fenced on
  395. # the active rows read here (before the transcript, so any later write fails the fence).
  396. owned = self._retry_owned_store(session_entry.session_id)
  397. try:
  398. pinned = owned and await asyncio.to_thread(owned.get_active_message_ids, session_entry.session_id)
  399. history = await self.async_session_store.load_transcript(session_entry.session_id)
  400. except TranscriptReadError:
  401. return history_unreadable()
  402. except Exception:
  403. logger.debug("/retry could not read the active rows of %s", session_entry.session_id, exc_info=True)
  404. return history_unreadable()
  405. last_user_idx = next((i for i in range(len(history) - 1, -1, -1)
  406. if user_originated_turn_view(history[i]) is not None), None)
  407. if last_user_idx is None:
  408. return t("gateway.retry.no_previous")
  409. # Resolve text + scaffold-preserving prefix BEFORE any write; messaging retries cannot
  410. # reconstruct attachments, so media/unknown content is rejected with the session untouched.
  411. try:
  412. truncated, live_view = history_before_user_originated_turn(history, last_user_idx)
  413. last_user_msg = retryable_user_text(live_view.get("content"))
  414. handoff, _ = split_user_originated_turn(history[last_user_idx])
  415. except ValueError as exc:
  416. return t("gateway.retry.unsafe", error=exc)
  417. # Answer the refusals the re-sent turn would hit BEFORE the transcript rewrite: /retry
  418. # passes the post-command gates as a canonical command, the plain-text re-send does not,
  419. # and a refusal after the rewrite leaves the transcript shorter and loses the user's turn.
  420. readmission_reply = self._retry_readmission_reply(source, last_user_msg)
  421. if readmission_reply is not None:
  422. return readmission_reply
  423. if owned:
  424. return await self._retry_in_admission(
  425. event, session_entry, owned, pinned, truncated, last_user_msg, handoff is not None)
  426. if handoff is not None:
  427. # Composite carrier (one row = retained summary + live ask): the carrier-aware rewind
  428. # archives it and inserts the pure scaffold atomically, reselecting the latest carrier
  429. # on the same snapshot so a concurrent newer turn is never removed for stale text.
  430. try:
  431. # Plain turns keep the existing rewrite path below; #84078 owns its separate
  432. # archive_dropped/prefix-CAS semantics.
  433. rewind_result = await self.async_session_store.rewind_session(
  434. session_entry.session_id, 1, require_retryable_composite=True)
  435. except ValueError as exc:
  436. return t("gateway.retry.unsafe", error=exc)
  437. if rewind_result is None:
  438. return t("gateway.retry.failed_unchanged")
  439. last_user_msg = rewind_result["target_text"]
  440. # active_only preserves the active=0/compacted=1 archive left by in-place compaction.
  441. elif not await self.async_session_store.rewrite_transcript(
  442. session_entry.session_id, truncated, active_only=True, reject_active_turn_lease=True):
  443. return t("gateway.retry.failed_unchanged")
  444. session_entry.last_prompt_tokens = 0 # transcript was truncated
  445. self._record_model_friction("retry", source, session_entry.session_id)
  446. # The re-sent turn is the /retry event's own turn, built on its authenticated source: carry
  447. # that event's native callback to it, or admission refuses it under multiplex (#139040).
  448. from gateway.session_ingress_context import carry_callback
  449. turn = MessageEvent(
  450. text=last_user_msg, message_type=MessageType.TEXT, source=source,
  451. raw_message=event.raw_message, channel_prompt=event.channel_prompt)
  452. carry_callback(event, turn)
  453. return await self._handle_message(turn)
  454. def _retry_owned_store(self, session_id: str):
  455. """The SessionDB that holds both *session_id*'s transcript and its authority's admission
  456. ledger, or None (no authority: the rewrite-then-send path). One handle means one write
  457. transaction can carry the rewrite and the admission (#139257 step 2)."""
  458. from gateway.session_authorities import active_authority
  459. authority = active_authority(self)
  460. if authority is None:
  461. return None
  462. db = self.session_store._db_for_session_id(session_id)
  463. return db if db is not None and db is authority.db else None
  464. async def _retry_in_admission(self, event, session_entry, db, pinned, truncated, resend_text,
  465. composite: bool) -> Optional[str]:
  466. """Plan the rewrite, bind it to the re-send and let ``admit_native`` commit both in one write
  467. (``gateway.session_retry_admission``). A refusal leaves the transcript as it was; a
  468. transcript changed since the read refuses both."""
  469. from gateway import session_retry_admission as retry_admission
  470. from gateway.session_ingress_context import carry_callback
  471. from hermes_state_rewind import RewindTargetUnavailableError
  472. from hermes_state_runtime import RuntimeStoreError
  473. session_id = session_entry.session_id
  474. if composite:
  475. # The carrier-aware rewind, planned on the same snapshot: archive the carrier, keep its scaffold.
  476. try:
  477. plan = await asyncio.to_thread(db.plan_user_turn_rewind, session_id, -1,
  478. require_retryable=True, require_composite=True)
  479. except ValueError as exc:
  480. if isinstance(exc, RewindTargetUnavailableError):
  481. return t("gateway.retry.failed_unchanged")
  482. return t("gateway.retry.unsafe", error=exc)
  483. except RuntimeError: # the history changed under the plan, or the target has no row id
  484. logger.debug("/retry carrier plan refused for %s", session_id, exc_info=True)
  485. return t("gateway.retry.failed_unchanged")
  486. if plan.expected_active_ids != pinned:
  487. return t("gateway.retry.failed_unchanged")
  488. resend_text = plan.live_text
  489. def write(conn):
  490. from hermes_state_mutation_transcript import rewind_in_transaction
  491. rewind_in_transaction(db, conn, session_id, plan.target_row_id, preserve_compaction_handoff=True,
  492. expected_active_ids=plan.expected_active_ids,
  493. expected_target_content=plan.expected_target_content)
  494. else:
  495. def write(conn):
  496. db.replace_messages_in_transaction(conn, session_id, [dict(m) for m in truncated], active_only=True,
  497. reject_active_turn_lease=True, expected_active_ids=pinned)
  498. def committed():
  499. self.session_store._clear_dirty_transcript(session_id)
  500. session_entry.last_prompt_tokens = 0 # transcript was truncated
  501. self._record_model_friction("retry", event.source, session_id)
  502. rewrite = retry_admission.RetryRewrite(db=db, session_id=session_id, source=event.source,
  503. write=write, on_commit=committed)
  504. turn = MessageEvent(
  505. text=resend_text, message_type=MessageType.TEXT, source=event.source,
  506. raw_message=event.raw_message, channel_prompt=event.channel_prompt)
  507. carry_callback(event, turn)
  508. token = retry_admission.bind(rewrite)
  509. try:
  510. return await self._handle_message(turn)
  511. except retry_admission.RetryRewriteRefused as exc:
  512. logger.info("/retry refused with the transcript unchanged for %s: %s", session_id, exc)
  513. return t("gateway.retry.failed_unchanged")
  514. except RuntimeStoreError as exc:
  515. if not rewrite.applied and exc.reason == 'runtime_draining':
  516. # The drain began after the pre-check: the re-send was refused, nothing rewritten.
  517. return t("gateway.busy.drain_rejected", action=self._status_action_gerund())
  518. raise
  519. finally:
  520. retry_admission.unbind(token)
  521. def _retry_readmission_reply(self, source: SessionSource, resend_text: str) -> Optional[str]:
  522. """Refusal the /retry re-send would meet in ``_handle_message``, if any — checked before the
  523. transcript rewrite so a refused /retry leaves the transcript untouched. Mirrors the gates
  524. the re-sent plain-text turn passes after canonical command dispatch: the emergency-stop
  525. pause (canonical commands pass it, plain turns do not), the external-drain new-turn refusal
  526. and the active-session cap. Not race-free — a drain can engage or the cap can fill between
  527. this check and the re-send — but every refusal known up front is answered with the
  528. transcript intact."""
  529. resend = MessageEvent(text=resend_text, message_type=MessageType.TEXT, source=source)
  530. paused_notice = self._hm_estop_gate(resend, source, False)
  531. if paused_notice is not None:
  532. return paused_notice
  533. if getattr(self, "_external_drain_active", False):
  534. return t("gateway.busy.draining_maintenance")
  535. authority_reply = self._retry_authority_refusal(source)
  536. if authority_reply is not None:
  537. return authority_reply
  538. return self._active_session_limit_message(self._session_key_for_source(source))
  539. def _retry_authority_refusal(self, source: SessionSource) -> Optional[str]:
  540. """The routed authority's own admission refusals for the re-send (#139257): a draining or
  541. retiring runtime (``runtime_draining``) and a full FIFO (``queue_full``), the gates
  542. ``admit_native`` applies. Same not-race-free caveat as the caller."""
  543. from gateway.session_authorities import active_authority
  544. authority = active_authority(self)
  545. if authority is None:
  546. return None
  547. import hermes_state_runtime
  548. from hermes_state_runtime import RuntimeStoreError
  549. try:
  550. authority._require_admission_open()
  551. except RuntimeStoreError:
  552. return t("gateway.busy.drain_rejected", action=self._status_action_gerund())
  553. entry = self.session_store.lookup_by_session_key(self._session_key_for_source(source))
  554. if entry is None:
  555. return None
  556. rows = hermes_state_runtime.list_session_admissions(
  557. authority.db, session_id=authority.logical_owner(entry.session_id))
  558. if sum(row["status"] == "queued" for row in rows) >= hermes_state_runtime.ADMISSION_QUEUE_MAX:
  559. from gateway.session_ingress import QUEUE_FULL_REPLY
  560. return QUEUE_FULL_REPLY
  561. return None
  562. def _record_model_friction(self, signal: str, source, session_id: str, turns: int = 1) -> None:
  563. """Slash dispatch does not install the routed profile's scope, so a multiplexed runner
  564. names the owning home explicitly."""
  565. from hermes_cli.observability.shared_metrics_model import record_model_friction
  566. home = None
  567. if getattr(getattr(self, "config", None), "multiplex_profiles", False):
  568. with contextlib.suppress(Exception):
  569. home = self._resolve_profile_home_for_source(source)
  570. record_model_friction(signal, session_id=session_id, hermes_home=home, turns=turns)
  571. async def _handle_undo_command(self, event: MessageEvent) -> str:
  572. """Handle /undo [N] — back up N user turns (default 1), soft-deleting the truncated rows and
  573. echoing the backed-up text; evicts the cached agent so the next turn rebuilds from the
  574. active-only transcript."""
  575. source = event.source
  576. n = 1
  577. raw_args = event.get_command_args().strip()
  578. if raw_args:
  579. try:
  580. n = max(1, int(raw_args.split()[0]))
  581. except ValueError:
  582. return t("gateway.undo.invalid_count", arg=raw_args.split()[0])
  583. session_entry = await self.async_session_store.get_or_create_session(source)
  584. result = await self.async_session_store.rewind_session(session_entry.session_id, n)
  585. if result is None:
  586. return t("gateway.undo.nothing")
  587. session_entry.last_prompt_tokens = 0 # transcript was truncated
  588. self._record_model_friction("undo", source, session_entry.session_id, result.get("turns_undone") or 1)
  589. try:
  590. # The cache is keyed by the profile-namespaced key; a bare build_session_key(source)
  591. # yields ``agent:main:…`` and misses for every secondary profile.
  592. self._evict_cached_agent(self._session_key_for_source(source))
  593. except Exception as e:
  594. logger.debug("undo: cached-agent eviction skipped: %s", e)
  595. target_text = result["target_text"]
  596. preview = target_text[:200] + "..." if len(target_text) > 200 else target_text
  597. return t("gateway.undo.removed", turns=result["turns_undone"],
  598. count=result["rewound_count"], preview=preview)
  599. # --------------------------------------------------------------------- /compress
  600. async def _handle_compress_command(self, event: MessageEvent) -> str:
  601. """Profile-scoping wrapper around manual /compress: multiplexed gateways resolve credentials
  602. through the fail-closed per-profile secret scope, which slash dispatch (unlike ``_run_agent``)
  603. does not install — unscoped, /compress would raise ``UnscopedSecretError``."""
  604. if not getattr(getattr(self, "config", None), "multiplex_profiles", False):
  605. return await self._handle_compress_command_inner(event)
  606. from gateway.run import _profile_runtime_scope
  607. with _profile_runtime_scope(self._resolve_profile_home_for_source(event.source)):
  608. return await self._handle_compress_command_inner(event)
  609. async def _compress_codex_app_server_session(self, session_key: str, session_id: str) -> str:
  610. """Manual /compress for codex_app_server sessions: compacts the LIVE cached agent's
  611. app-server thread (``force=True`` bypasses the ``codex_app_server_auto`` gate) and keeps it
  612. cached. A temporary agent or a mirror rewrite cannot shrink the server-side thread.
  613. See #73503.
  614. """
  615. from gateway.run import _AGENT_PENDING_SENTINEL
  616. agent = self._cached_agent_for(session_key, lockless_fallback=True)
  617. if agent is None or agent is _AGENT_PENDING_SENTINEL or getattr(agent, "_codex_session", None) is None:
  618. return t("gateway.compress.codex_nothing")
  619. compressor = getattr(agent, "context_compressor", None)
  620. count_before = getattr(compressor, "compression_count", 0)
  621. try:
  622. await self._run_in_executor_with_context(
  623. lambda: agent._compress_context([], "", force=True, task_id=session_id or "default"))
  624. except Exception as exc:
  625. return t("gateway.compress.failed", error=exc)
  626. if getattr(compressor, "compression_count", 0) > count_before:
  627. return t("gateway.compress.codex_compacted")
  628. return t("gateway.compress.codex_incomplete")
  629. async def _handle_compress_command_inner(self, event: MessageEvent) -> str:
  630. """Handle /compress -- manually compress conversation context; ``/compress <focus>`` tells
  631. the summariser what to preserve. Flags/positional forms are parsed by the shared core."""
  632. from agent.conversation_compression_manual import MIN_MESSAGES, parse_compress_args
  633. source = event.source
  634. session_entry = await self.async_session_store.get_or_create_session(source)
  635. try:
  636. history = await self.async_session_store.load_transcript(session_entry.session_id)
  637. except TranscriptReadError:
  638. return history_unreadable()
  639. if not history or len(history) < MIN_MESSAGES:
  640. return t("gateway.compress.not_enough")
  641. request = parse_compress_args(event.get_command_args() or "")
  642. _agg_note = t("gateway.compress.aggressive_unsupported") if request.aggressive else ""
  643. if request.aggressive and not request.preview:
  644. return _agg_note
  645. if request.preview:
  646. return _compress_preview_reply(history, request.partial, request.keep_last, request.focus_topic, _agg_note)
  647. try:
  648. return await self._run_manual_compression(source, session_entry, history, request)
  649. except Exception as e:
  650. logger.warning("Manual compress failed: %s", e)
  651. return t("gateway.compress.failed", error=e)
  652. async def _run_manual_compression(self, source, session_entry, history: list, request) -> str:
  653. """Build a temporary agent, run the shared compress core, persist, and describe the outcome."""
  654. from agent.conversation_compression import finalize_context_engine_compression_notification
  655. from agent.conversation_compression_manual import compress_now, render_compress_result
  656. from gateway.run import _platform_config_key
  657. session_key = self._session_key_for_source(source)
  658. # Platform + stable gateway session key bind this agent (for external context engines) to
  659. # the original conversation, not a default "cli" host.
  660. platform_key = _platform_config_key(source.platform) if source.platform else None
  661. model, runtime_kwargs = self._resolve_session_agent_runtime(source=source, session_key=session_key)
  662. if str(runtime_kwargs.get("api_mode") or "").lower() == "codex_app_server":
  663. # Context lives in the server-side thread of the LIVE cached agent; a temporary agent
  664. # has none (and finally-eviction would destroy the real context).
  665. return await self._compress_codex_app_server_session(session_key, session_entry.session_id)
  666. if not runtime_kwargs.get("api_key"):
  667. return t("gateway.compress.no_provider")
  668. # FULL transcript (tool results included), like auto-compress: user/assistant-only starves
  669. # tool-result pruning and can trip the protect-first/last early-return.
  670. msgs = [m for m in history if m.get("role") in {"user", "assistant", "tool"}]
  671. # Assign, not setdefault (a resolver value would be a stale placeholder); platform only when
  672. # known so None -> "cli" holds.
  673. if platform_key is not None:
  674. runtime_kwargs["platform"] = platform_key
  675. runtime_kwargs["gateway_session_key"] = session_key
  676. # Same reasoning setting as a live turn (session ``/reasoning`` > per-model > global): without it
  677. # the transport applies its default effort — a 400 on non-reasoning models.
  678. runtime_kwargs["reasoning_config"] = self._resolve_session_reasoning_config(source=source, model=model)
  679. tmp_agent = await self._build_manual_compression_agent(session_entry.session_id, model, runtime_kwargs)
  680. try:
  681. # Not a bare run_in_executor: the profile secret scope is a contextvar the default
  682. # executor hop would drop, failing aux-client credential resolution closed.
  683. result = await self._run_in_executor_with_context(
  684. lambda: compress_now(tmp_agent, msgs, request, system_message="", skip_without_window=True,
  685. task_id=session_entry.session_id or "default"))
  686. if result.status == "nothing_to_do":
  687. return t("gateway.compress.nothing_to_do")
  688. if result.status != "compressed":
  689. return "\n".join(render_compress_result(result))
  690. await self._persist_manual_compression(tmp_agent, session_entry, source, result.after_messages)
  691. finalize_context_engine_compression_notification(tmp_agent, committed=True)
  692. compressor = tmp_agent.context_compressor
  693. summary = result.summary
  694. finally:
  695. finalize_context_engine_compression_notification(tmp_agent, committed=False)
  696. self._evict_cached_agent(session_key) # next turn rebuilds the prompt from current files
  697. # Off-loop + bounded: teardown can block on subprocess/network/SQLite.
  698. await self._cleanup_agent_resources_off_loop(tmp_agent, context="manual compression")
  699. return "\n".join(_manual_compression_reply_lines(summary, compressor, request.focus_topic))
  700. async def _build_manual_compression_agent(self, session_id: str, model, runtime_kwargs: dict):
  701. """Build the throwaway AIAgent that performs a manual /compress rewrite of *session_id*."""
  702. from run_agent import AIAgent
  703. from gateway.run import _GATEWAY_HYGIENE_PLATFORM, _seed_hygiene_system_prompt
  704. from hermes_cli.config import load_config as _load_cfg
  705. from utils import is_truthy_value as _is_truthy
  706. # _compress_context may persist its cached system prompt, and this agent runs outside the
  707. # live session's prompt environment — restore the exact live prompt so provider blocks stay.
  708. session_row = None
  709. get_session = getattr(self._session_db, "get_session", None)
  710. if callable(get_session):
  711. try:
  712. session_row = await get_session(session_id)
  713. except Exception as exc:
  714. logger.warning(
  715. "Manual compression could not restore the system prompt for session %s: %s. "
  716. "Preserving an empty prompt so the live turn rebuilds it with its configured "
  717. "providers.", session_id, exc, exc_info=True)
  718. # compression.checkpoint_required needs the memory provider loaded so _compress_context()
  719. # can write the pre-compression checkpoint; otherwise keep the fast path (no provider init).
  720. _checkpoint_required = _is_truthy(
  721. ((_load_cfg() or {}).get("compression") or {}).get("checkpoint_required"),
  722. default=False)
  723. tmp_agent = AIAgent(**runtime_kwargs, model=model, max_iterations=4, quiet_mode=True,
  724. skip_memory=not _checkpoint_required, enabled_toolsets=["memory"],
  725. session_id=session_id,
  726. session_db=getattr(self._session_db, "_db", self._session_db))
  727. _seed_hygiene_system_prompt(tmp_agent, session_row)
  728. # Real platform during construction (context engines bind correctly); the stamp afterwards
  729. # only marks this agent as no real surface. Since #104414 Platform is not a restore-identity
  730. # field, so it no longer forces the next live turn to rebuild; the seed's retain flag is what
  731. # keeps the reduced-toolset build out of the session row (#122822).
  732. tmp_agent.platform = _GATEWAY_HYGIENE_PLATFORM
  733. tmp_agent._print_fn = lambda *a, **kw: None
  734. # close() must not end the rotated session the gateway entry now points at.
  735. tmp_agent._end_session_on_close = False
  736. return tmp_agent
  737. async def _persist_manual_compression(self, tmp_agent, session_entry, source, compressed) -> None:
  738. """Commit a manual /compress result to the session store. Rotation (new continuation id)
  739. makes the NEW session durable (already published, else rewritten) so the original stays searchable;
  740. persist BEFORE repointing so a failed write is fatal and old history stays reachable.
  741. In-place compaction already archived + inserted rows, and a rewrite would DELETE the
  742. archive; an unchanged id without in-place means rotation FAILED."""
  743. new_session_id = tmp_agent.session_id
  744. if new_session_id != session_entry.session_id:
  745. # Published child is already durable; a rewrite would drop rows cloned at publish.
  746. if not await self.async_session_store.persist_rotated_compression_child(
  747. session_entry.session_id, new_session_id, compressed):
  748. raise RuntimeError(f"failed to persist compressed transcript for session {new_session_id}")
  749. session_entry.session_id = new_session_id
  750. await self.async_session_store._save()
  751. await asyncio.to_thread(self._sync_telegram_topic_binding, source, session_entry,
  752. reason="compress-command")
  753. elif not getattr(tmp_agent, "_last_compaction_in_place", False):
  754. logger.warning(
  755. "Manual /compress: session rotation did not occur (session_id unchanged) and in-place "
  756. "mode is off — preserving original transcript instead of overwriting it (#44794).")
  757. await self.async_session_store.update_session(session_entry.session_key, last_prompt_tokens=0)
  758. # ------------------------------------------------------------------------ /topic
  759. async def _handle_topic_command(self, event: MessageEvent, args: str = "") -> str:
  760. """Handle /topic for Telegram DM user-managed topic sessions."""
  761. source = event.source
  762. if source.platform != Platform.TELEGRAM or source.chat_type != "dm":
  763. return t("gateway.topic.not_telegram_dm")
  764. if not self._session_db:
  765. return self._session_db_unavailable_reply()
  766. # Defense in depth: /topic mutates SQLite side tables, so re-check the allowlist here.
  767. try:
  768. if not self._is_user_authorized_for_source(source):
  769. return t("gateway.topic.unauthorized")
  770. except Exception:
  771. logger.debug("Topic auth check failed", exc_info=True)
  772. args = event.get_command_args().strip()
  773. if args.lower() in {"help", "?", "-h", "--help"}:
  774. return self._telegram_topic_help_text()
  775. if args.lower() in {"off", "disable", "stop"}:
  776. return await self._disable_telegram_topic_mode_for_chat(source)
  777. if args:
  778. if not source.thread_id:
  779. return t("gateway.topic.restore_needs_topic")
  780. return await self._restore_telegram_topic_session(event, args)
  781. capabilities = await self._get_telegram_topic_capabilities(source)
  782. if capabilities.get("checked"):
  783. blocked_key = None
  784. if capabilities.get("has_topics_enabled") is False:
  785. blocked_key = "gateway.topic.topics_disabled"
  786. elif capabilities.get("allows_users_to_create_topics") is False:
  787. blocked_key = "gateway.topic.topics_user_disallowed"
  788. if blocked_key: # debounced BotFather screenshot
  789. if self._should_send_telegram_capability_hint(source):
  790. await self._send_telegram_topic_setup_image(source)
  791. return t(blocked_key)
  792. profile_name = self._telegram_topic_profile_name(source)
  793. try:
  794. await self._session_db.enable_telegram_topic_mode(
  795. chat_id=str(source.chat_id), user_id=str(source.user_id), profile_name=profile_name,
  796. has_topics_enabled=capabilities.get("has_topics_enabled"),
  797. allows_users_to_create_topics=capabilities.get("allows_users_to_create_topics"))
  798. except Exception as exc:
  799. logger.exception("Failed to enable Telegram topic mode")
  800. return t("gateway.topic.enable_failed", error=exc)
  801. if not source.thread_id:
  802. await self._ensure_telegram_system_topic(source)
  803. return await self._telegram_topic_root_status_message(source)
  804. try:
  805. binding = await self._session_db.get_telegram_topic_binding(
  806. chat_id=str(source.chat_id), thread_id=str(source.thread_id),
  807. profile_name=profile_name)
  808. except Exception:
  809. logger.debug("Failed to read Telegram topic binding", exc_info=True)
  810. binding = None
  811. if not binding:
  812. return t("gateway.topic.thread_ready")
  813. session_id = str(binding.get("session_id") or "")
  814. try:
  815. title = await self._session_db.get_session_title(session_id)
  816. except Exception:
  817. title = None
  818. return t("gateway.topic.bound_status", label=title or t("gateway.topic.untitled_session"),
  819. session_id=session_id)
  820. # ------------------------------------------------------------------ /save, /title
  821. async def _handle_save_command(self, event: MessageEvent) -> str:
  822. """Handle /save — export the current session and send it as a document."""
  823. import tempfile
  824. from hermes_cli.session_export import (
  825. SAVE_USAGE, default_save_filename, load_save_snapshot, normalize_save_format, render_session_for_save)
  826. parts = event.get_command_args().split()
  827. redact = bool(parts) and parts[-1].lower() in ("redact", "--redact")
  828. if redact:
  829. parts = parts[:-1]
  830. if not parts:
  831. return SAVE_USAGE
  832. try:
  833. fmt = normalize_save_format(parts[0])
  834. except ValueError as e:
  835. return f"{e}\n\n{SAVE_USAGE}"
  836. source = event.source
  837. session_entry = await self.async_session_store.get_or_create_session(source)
  838. session_id = session_entry.session_id
  839. if not self._session_db:
  840. return t("gateway.shared.session_db_unavailable")
  841. # Never trust path separators from chat input; the filename is only echoed to the platform.
  842. filename = parts[1] if len(parts) > 1 else default_save_filename(session_id, fmt)
  843. filename = os.path.basename(filename) or default_save_filename(session_id, fmt)
  844. from hermes_state import SessionExportTooLargeError
  845. try:
  846. # One off-loop hop for the cap check + read; the helper is shared with the CLI and TUI /save.
  847. export_data = await asyncio.to_thread(load_save_snapshot, self._session_db._db, session_id, fmt)
  848. except SessionExportTooLargeError as e:
  849. return str(e)
  850. if not export_data:
  851. return t("gateway.save.no_messages", session_id=session_id)
  852. if redact:
  853. from hermes_cli.session_export_md import redact_session_data
  854. export_data = redact_session_data(export_data)
  855. temp_dir = tempfile.mkdtemp(prefix="hermes_save_")
  856. temp_path = os.path.join(temp_dir, filename)
  857. try:
  858. # Off-loop: render + write scale with transcript size (multi-MB) and would stall the loop.
  859. def _render_and_write() -> None:
  860. rendered = render_session_for_save(export_data, fmt)
  861. with open(temp_path, "w", encoding="utf-8") as f:
  862. f.write(rendered)
  863. await asyncio.to_thread(_render_and_write)
  864. # Profile-aware: under multiplex the requester's bot lives in _profile_adapters, not self.adapters.
  865. adapter = self._delivery_adapter_for(source)
  866. if not adapter:
  867. return t("gateway.save.no_adapter")
  868. await adapter.send_document(chat_id=source.chat_id, file_path=temp_path,
  869. caption=t("gateway.save.caption", filename=filename), file_name=filename)
  870. return t("gateway.save.complete")
  871. except Exception as e:
  872. logger.warning("Session /save failed: %s", e)
  873. return t("gateway.save.failed", error=e)
  874. finally:
  875. with contextlib.suppress(Exception):
  876. os.remove(temp_path)
  877. os.rmdir(temp_dir)
  878. async def _handle_title_command(self, event: MessageEvent) -> str:
  879. """Handle /title command — set or show the current session's title."""
  880. source = event.source
  881. session_entry = await self.async_session_store.get_or_create_session(source)
  882. session_id = session_entry.session_id
  883. if not self._session_db:
  884. return self._session_db_unavailable_reply()
  885. # The session may only exist in session_store so far (first command in a new session).
  886. # The messaging origin is persisted so a later /resume of this titled-but-inactive session
  887. # can prove it belongs to the caller's chat/thread (IDOR scoping).
  888. if await self._session_db.get_session_title(session_id) is None:
  889. with contextlib.suppress(Exception): # may already exist
  890. await self._session_db.create_session(
  891. session_id=session_id,
  892. source=source.platform.value if source.platform else "unknown",
  893. user_id=source.user_id, chat_id=source.chat_id, chat_type=source.chat_type,
  894. thread_id=source.thread_id)
  895. title_arg = event.get_command_args().strip()
  896. if not title_arg:
  897. title = await self._session_db.get_session_title(session_id)
  898. if title:
  899. return t("gateway.title.current_with_title", session_id=session_id, title=title)
  900. return t("gateway.title.current_no_title", session_id=session_id)
  901. try:
  902. from hermes_state import SessionDB
  903. sanitized = SessionDB.sanitize_title(title_arg)
  904. except ValueError as e:
  905. return t("gateway.shared.warn_passthrough", error=e)
  906. if not sanitized:
  907. return t("gateway.title.empty_after_clean")
  908. try:
  909. if not await self._session_db.set_session_title(session_id, sanitized):
  910. return t("gateway.title.not_found")
  911. except ValueError as e:
  912. return t("gateway.shared.warn_passthrough", error=e)
  913. # Mirror the title onto the Telegram forum topic name (auto titles already do this).
  914. try:
  915. await asyncio.to_thread(self._schedule_telegram_topic_title_rename, source, session_id, sanitized)
  916. except Exception:
  917. logger.debug("Failed to rename Telegram topic from /title", exc_info=True)
  918. return t("gateway.title.set_to", title=sanitized)
  919. # -------------------------------------------------------------- /resume, /sessions
  920. async def _list_titled_sessions(self, source, session_key: str, allow_all: bool) -> list[dict]:
  921. """Titled sessions visible to the caller (origin-scoped unless admin ``--all``)."""
  922. widen = allow_all and self._resume_caller_is_admin(source)
  923. # Rank by lineage activity, not root started_at: a lineage compressed for days is projected
  924. # onto its live tip and must sit where the user last touched it (#114271).
  925. sessions = await self._session_db.list_sessions_rich(
  926. source=source.platform.value if source.platform else None,
  927. session_key=None if widen else session_key, limit=10, order_by_last_active=True)
  928. titled = [s for s in sessions if s.get("title")][:10]
  929. return [s for s in titled if await self._resume_row_visible(source, s, allow_all)]
  930. async def _resolve_resume_target(self, source, session_key: str, name: str, allow_all: bool):
  931. """``(target_id, name)`` for a numbered choice, session id or title; else the error reply."""
  932. if name.isdigit():
  933. try:
  934. titled = await self._list_titled_sessions(source, session_key, allow_all)
  935. except Exception as e:
  936. logger.debug("Failed to list titled sessions for numeric resume: %s", e)
  937. return t("gateway.resume.list_failed", error=e)
  938. index = int(name)
  939. if index < 1 or index > len(titled):
  940. return t("gateway.resume.out_of_range", index=index)
  941. target = titled[index - 1]
  942. target_id, name = target.get("id"), target.get("title") or name
  943. else: # session id first, then title
  944. session = await self._session_db.get_session(name)
  945. target_id = session["id"] if session else await self._session_db.resolve_session_by_title(name)
  946. if not target_id:
  947. return t("gateway.resume.not_found", name=name)
  948. # Follow compression continuations to the live transcript (matches CLI /resume).
  949. try:
  950. # Follow that chain so gateway /resume matches CLI behavior (#15000).
  951. target_id = await self._session_db.resolve_resume_session_id(target_id)
  952. except Exception as e:
  953. logger.debug("Failed to resolve resume continuation for %s: %s", target_id, e)
  954. return target_id, name
  955. async def _resume_access_denied_reply(self, source, target_id: str, name: str, allow_all: bool,
  956. allow_cross_room: bool) -> Optional[str]:
  957. """IDOR guard: a session id/title is a routing handle, not authority — bind /resume to the
  958. caller's own room (Matrix) or platform/user/chat (other adapters)."""
  959. if source.platform == Platform.MATRIX:
  960. target_origin = self._gateway_session_origin_for_id(target_id)
  961. if self._same_matrix_room(source, target_origin) or allow_cross_room:
  962. return None
  963. if target_origin is None:
  964. return t("gateway.resume.matrix_blocked_no_origin", name=name)
  965. return t("gateway.resume.matrix_blocked_other_room", name=name,
  966. room=target_origin.chat_name or target_origin.chat_id)
  967. if await self._resume_target_allowed(source, target_id, allow_override=(allow_all or allow_cross_room)):
  968. return None
  969. return t("gateway.resume.blocked_not_owner", name=name)
  970. async def _handle_resume_command(self, event: MessageEvent) -> str:
  971. """Handle /resume command — list or switch to a previous session."""
  972. if not self._session_db:
  973. return self._session_db_unavailable_reply()
  974. source = await asyncio.to_thread(self._normalize_source_for_session_key, event.source)
  975. session_key = self._session_key_for_source(source)
  976. try:
  977. parts = shlex.split(event.get_command_args().strip())
  978. except ValueError as exc:
  979. return t("gateway.resume.parse_error", error=exc)
  980. allow_all = "--all" in parts
  981. allow_cross_room = "--cross-room" in parts
  982. name = _strip_resume_name(parts)
  983. if not name:
  984. try:
  985. titled = await self._list_titled_sessions(source, session_key, allow_all)
  986. return self._resume_listing_reply(source, titled, allow_all)
  987. except Exception as e:
  988. logger.debug("Failed to list titled sessions: %s", e)
  989. return t("gateway.resume.list_failed", error=e)
  990. resolved = await self._resolve_resume_target(source, session_key, name, allow_all)
  991. if isinstance(resolved, str):
  992. return resolved
  993. target_id, name = resolved
  994. # A local conversation moves onto this lane from its current head, as /handoff carries it: a
  995. # title naming its first segment (a local /new moved on) would strand the live one (#143286).
  996. from gateway.session_route_recovery import conversation_head, follow_hand_off
  997. authority, local_owner, head = await conversation_head(self, target_id)
  998. if local_owner is not None:
  999. target_id = head
  1000. denied = await self._resume_access_denied_reply(source, target_id, name, allow_all, allow_cross_room)
  1001. if denied is not None:
  1002. return denied
  1003. current_entry = await self.async_session_store.get_or_create_session(source)
  1004. if current_entry.session_id == target_id:
  1005. return t("gateway.resume.already_on", name=name)
  1006. self._release_running_agent_state(session_key)
  1007. new_entry = await self.async_session_store.switch_session(
  1008. session_key, target_id, preserve_prompt_pin=False,
  1009. )
  1010. if not new_entry:
  1011. return t("gateway.resume.switch_failed")
  1012. if local_owner is not None and authority is not None: # a Desktop still viewing it follows it
  1013. follow_hand_off(authority, source, session_key, authority.logical_owner(target_id), local_owner)
  1014. # Conversation boundary: all conversation-scoped state + security state in one funnel call.
  1015. # Conversation boundary: clear ALL conversation-scoped per-session state (model/reasoning overrides
  1016. # #10702, one-turn restores, model notes, last-resolved cache #58403, /queue overflow) + security
  1017. # state in one funnel call. See _CONVERSATION_SCOPED_STATE in gateway/run.py.
  1018. self._clear_conversation_scope(session_key, reason="resume")
  1019. # switch_session keeps the route's persisted /model pin (a re-pin is not a boundary,
  1020. # #119864); /resume IS one, and the funnel above clears only in-memory state — without this
  1021. # the next turn's _rehydrate_session_model_override resurrects the pin it just cleared.
  1022. await self.async_session_store.set_model_override(session_key, None)
  1023. # Evict so the next turn rebuilds with the right session_id — the cached AIAgent's memory
  1024. # provider cached _session_id at initialize() and would keep writing to the wrong session.
  1025. self._evict_cached_agent(session_key)
  1026. title = await self._session_db.get_session_title(target_id) or name
  1027. try:
  1028. history = await self.async_session_store.load_transcript(target_id)
  1029. except TranscriptReadError:
  1030. # The resume itself succeeded; only the count is missing — say so rather than "empty".
  1031. return t("gateway.resume.resumed_no_count", title=title) + "\n" + history_unreadable()
  1032. msg_count = len([m for m in history if m.get("role") == "user"]) if history else 0
  1033. if source.platform == Platform.MATRIX and allow_cross_room:
  1034. msg_part = t("gateway.resume.msg_count_one" if msg_count == 1 else "gateway.resume.msg_count_other",
  1035. count=msg_count) if msg_count else ""
  1036. return t("gateway.resume.matrix_cross_room_success", title=title,
  1037. room=source.chat_name or source.chat_id, msg_part=msg_part)
  1038. if not msg_count:
  1039. return t("gateway.resume.resumed_no_count", title=title)
  1040. if msg_count == 1:
  1041. return t("gateway.resume.resumed_one", title=title, count=msg_count)
  1042. return t("gateway.resume.resumed_many", title=title, count=msg_count)
  1043. def _resume_listing_reply(self, source, titled: list[dict], allow_all: bool) -> str:
  1044. """Numbered /resume list; a non-admin ``--all`` falls back to same-origin scoping and says so
  1045. (sibling of the /sessions notice)."""
  1046. scope_note = None
  1047. if allow_all and not self._resume_caller_is_admin(source):
  1048. scope_note = t("gateway.resume.all_requires_admin")
  1049. if not titled:
  1050. if source.platform == Platform.MATRIX and not allow_all:
  1051. return t("gateway.resume.matrix_no_named_sessions")
  1052. base = t("gateway.resume.no_named_sessions")
  1053. return f"{base}\n{scope_note}" if scope_note else base
  1054. lines = [t("gateway.resume.list_header")]
  1055. for idx, s in enumerate(titled[:10], start=1):
  1056. title = s["title"]
  1057. if source.platform == Platform.MATRIX and allow_all:
  1058. origin = self._gateway_session_origin_for_id(str(s.get("id") or ""))
  1059. if origin:
  1060. title = f"{title} — {origin.chat_name or origin.chat_id}"
  1061. preview = s.get("preview", "")[:40]
  1062. preview_part = t("gateway.resume.list_preview_suffix", preview=preview) if preview else ""
  1063. lines.append(t("gateway.resume.list_item_numbered", index=idx, title=title, preview_part=preview_part))
  1064. if scope_note:
  1065. lines.append(scope_note)
  1066. lines.append(t("gateway.resume.list_footer_numbered"))
  1067. return "\n".join(lines)
  1068. async def _handle_sessions_command(self, event: MessageEvent) -> str:
  1069. """Handle /sessions — list previous sessions for gateway chats."""
  1070. if not self._session_db:
  1071. return self._session_db_unavailable_reply()
  1072. from hermes_cli.session_listing import (
  1073. format_gateway_session_listing, parse_session_listing_args, query_session_listing)
  1074. try:
  1075. include_all, include_unnamed, target, search_query = parse_session_listing_args(
  1076. event.get_command_args().strip())
  1077. except ValueError as exc:
  1078. return t("gateway.resume.parse_error", error=exc)
  1079. if search_query == "":
  1080. return t("gateway.sessions.usage_search")
  1081. if target:
  1082. return await self._handle_resume_command(dataclasses.replace(event, text=f"/resume {target}"))
  1083. source = await asyncio.to_thread(self._normalize_source_for_session_key, event.source)
  1084. session_key = self._session_key_for_source(source)
  1085. # `/sessions all` is admin-only like `/resume --all` (else any caller could enumerate other
  1086. # origins' ids/titles/previews); a non-admin gets explicit feedback, not a silent narrowing.
  1087. cross_origin = include_all and self._resume_caller_is_admin(source)
  1088. scope_notice = None
  1089. if include_all and not cross_origin:
  1090. scope_notice = t("gateway.sessions.all_requires_admin")
  1091. current_entry = await self.async_session_store.get_or_create_session(source)
  1092. rows = await asyncio.to_thread(
  1093. query_session_listing, getattr(self._session_db, "_db", self._session_db),
  1094. source=source.platform.value if source.platform else None,
  1095. session_key=None if cross_origin else session_key,
  1096. current_session_id=current_entry.session_id, include_current_session=True,
  1097. include_all_sources=cross_origin, include_unnamed=include_unnamed,
  1098. search_query=search_query,
  1099. # Search filters in SQL: over-fetch so origin-invisible matches don't consume the page.
  1100. limit=50 if search_query else 10, exclude_sources=["tool"])
  1101. if not cross_origin:
  1102. rows = [row for row in rows if await self._resume_row_visible(source, row, allow_all=False)]
  1103. rows = rows[:10]
  1104. if search_query:
  1105. title = t("gateway.sessions.title_matching", query=search_query)
  1106. else:
  1107. title = t("gateway.sessions.title_all" if include_unnamed else "gateway.sessions.title_named")
  1108. return format_gateway_session_listing(rows, include_source=cross_origin, title=title,
  1109. notice=scope_notice)
  1110. # ----------------------------------------------------------------------- /branch
  1111. async def _handle_branch_command(self, event: MessageEvent) -> str:
  1112. """Handle /branch [--here] [name] — fork the current session into an independent copy.
  1113. Thread-capable platforms (Discord/Telegram/Slack/Matrix) open a NEW sibling thread bound
  1114. to the clone and leave this chat on the original session; ``--here`` (and every platform
  1115. without threads) switches the current chat onto the clone instead (#66023).
  1116. """
  1117. import json as _json
  1118. import uuid as _uuid
  1119. from datetime import datetime as _dt
  1120. if not self._session_db:
  1121. return self._session_db_unavailable_reply()
  1122. source = event.source
  1123. session_key = self._session_key_for_source(source)
  1124. current_entry = await self.async_session_store.get_or_create_session(source)
  1125. try:
  1126. history = await self.async_session_store.load_transcript(current_entry.session_id)
  1127. except TranscriptReadError:
  1128. return history_unreadable()
  1129. if not history:
  1130. return t("gateway.branch.no_conversation")
  1131. new_session_id = f"{_dt.now().strftime('%Y%m%d_%H%M%S')}_{_uuid.uuid4().hex[:6]}"
  1132. stay_here, branch_title = parse_branch_args(event.get_command_args())
  1133. if not branch_title:
  1134. current_title = await self._session_db.get_session_title(current_entry.session_id)
  1135. branch_title = await self._session_db.get_next_title_in_lineage(current_title or "branch")
  1136. parent_session_id = current_entry.session_id
  1137. # The thread is created BEFORE the clone so a failed create never orphans a branch row;
  1138. # ``None`` = branch in place (--here, no threads here, or the adapter could not open one).
  1139. dest_source = None if stay_here else await self._branch_open_thread(source, branch_title)
  1140. in_place = dest_source is None
  1141. if in_place:
  1142. dest_source = source
  1143. dest_key = session_key if in_place else self._session_key_for_source(dest_source)
  1144. # Full origin (same shape as the reset path in gateway/session.py); the live entry's origin
  1145. # may hold richer metadata than the triggering event's source (#82633). A thread branch
  1146. # is routed by the NEW thread, so its origin is the destination.
  1147. _branch_origin_json = None
  1148. with contextlib.suppress(Exception):
  1149. _origin = (current_entry.origin or source) if in_place else dest_source
  1150. _branch_origin_json = _json.dumps(_origin.to_dict())
  1151. # ``_branched_from`` keeps the branch visible in /resume and /sessions after the parent is
  1152. # reopened and re-ended. ALL routing columns go in at CREATE time: a crash before
  1153. # switch_session() records the peer would otherwise leave the branch unroutable.
  1154. # The child sends the parent's exact system prompt: a row without one makes the branch's
  1155. # first turn rebuild (re-probing the workspace) and forfeits the warm cache the copied
  1156. # transcript buys.
  1157. try:
  1158. parent = await self._session_db.get_session(parent_session_id)
  1159. await self._session_db.create_session(
  1160. session_id=new_session_id,
  1161. source=source.platform.value if source.platform else "gateway",
  1162. model=(self.config.get("model", {}) or {}).get("default") if isinstance(self.config, dict) else None,
  1163. model_config={"_branched_from": parent_session_id},
  1164. parent_session_id=parent_session_id, user_id=dest_source.user_id,
  1165. session_key=dest_key, chat_id=dest_source.chat_id, chat_type=dest_source.chat_type,
  1166. thread_id=dest_source.thread_id, origin_json=_branch_origin_json,
  1167. display_name=current_entry.display_name, system_prompt=(parent or {}).get("system_prompt") or None)
  1168. except Exception as e:
  1169. logger.error("Failed to create branch session: %s", e)
  1170. return t("gateway.branch.create_failed", error=e)
  1171. # Chunked transactions; best-effort — a failed copy still yields a usable (partial) branch.
  1172. with contextlib.suppress(Exception):
  1173. # Copy conversation history to the new session in bounded-chunk transactions (see #23254): one
  1174. # txn per row was the removed write-amplification pattern, and a history can be hundreds of
  1175. # rows.
  1176. await self._session_db.append_messages_batch(
  1177. new_session_id, [_branch_row(msg) for msg in history], chunk_rows=500)
  1178. with contextlib.suppress(Exception):
  1179. await self._session_db.set_session_title(new_session_id, branch_title)
  1180. if not in_place:
  1181. # Materialize the thread's own entry, then point IT at the clone; ``session_key`` (this
  1182. # chat) is never touched, so the original conversation stays live here.
  1183. await self.async_session_store.get_or_create_session(dest_source)
  1184. new_entry = await self.async_session_store.switch_session(dest_key, new_session_id)
  1185. if not new_entry:
  1186. return t("gateway.branch.switch_failed")
  1187. self._clear_session_boundary_security_state(dest_key)
  1188. self._evict_cached_agent(dest_key)
  1189. msg_count = len([m for m in history if m.get("role") == "user"])
  1190. if in_place:
  1191. key = "gateway.branch.branched_one" if msg_count == 1 else "gateway.branch.branched_many"
  1192. reply = t(key, title=branch_title, count=msg_count, parent=parent_session_id, new=new_session_id)
  1193. if not stay_here and source.platform in BRANCH_THREAD_PLATFORMS:
  1194. reply += "\n" + t("gateway.branch.thread_fallback")
  1195. return reply
  1196. key = "gateway.branch.branched_thread_one" if msg_count == 1 else "gateway.branch.branched_thread_many"
  1197. return t(key, title=branch_title, count=msg_count, parent=parent_session_id, new=new_session_id,
  1198. thread=format_thread_ref(source.platform, dest_source.thread_id))
  1199. async def _branch_open_thread(self, source: SessionSource, title: str) -> Optional[SessionSource]:
  1200. """Open the sibling thread a plain ``/branch`` clones into; the destination source, or
  1201. None when this chat cannot host one (in-place fallback)."""
  1202. parent_id = branch_thread_parent(source)
  1203. adapter = self._delivery_adapter_for(source) if parent_id else None
  1204. if adapter is None:
  1205. return None
  1206. try:
  1207. thread_id = await adapter.create_handoff_thread(parent_id, title)
  1208. except Exception:
  1209. logger.warning("Branch: create_handoff_thread failed on %s; branching in place",
  1210. source.platform.value, exc_info=True)
  1211. return None
  1212. if not thread_id:
  1213. return None
  1214. # Discord only answers un-mentioned follow-ups in threads it has participated in.
  1215. threads = getattr(adapter, "_threads", None)
  1216. if threads is not None:
  1217. await threads.mark_async(str(thread_id))
  1218. return branch_dest_source(source, parent_id=parent_id, thread_id=str(thread_id), title=title)