turn_author.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. """Who wrote the user side of a turn, carried from the dispatcher into the recipient's turn.
  2. The dispatcher sets ``HERMES_TURN_AUTHOR`` on the recipient's one-shot subprocess only. A cached
  3. gateway agent sees several authors over its lifetime, so the author is read per turn, never per agent.
  4. """
  5. from __future__ import annotations
  6. import json
  7. import os
  8. import socket
  9. import unicodedata
  10. from typing import Any, Dict, Mapping, MutableMapping, Optional
  11. TURN_AUTHOR_ENV = "HERMES_TURN_AUTHOR"
  12. _MAX_FIELD_LEN = 200
  13. _MAX_CHAIN_HOPS = 1000
  14. _DROPPED_CATEGORIES = frozenset({"Cc", "Cs", "Cn", "Co"})
  15. _TRUTHY = frozenset({"true", "1", "yes"})
  16. def _clean_text(value: Any) -> Optional[str]:
  17. """Strip whitespace, control and unassigned characters, then cap the length. None when nothing is left.
  18. Format characters and non-breaking spaces stay so emoji sequences and display names survive."""
  19. if not isinstance(value, str):
  20. return None
  21. text = "".join(ch for ch in value if unicodedata.category(ch) not in _DROPPED_CATEGORIES).strip()
  22. if not text:
  23. return None
  24. return text[:_MAX_FIELD_LEN]
  25. def _bot_flag(value: Any) -> bool:
  26. if isinstance(value, str):
  27. return value.strip().lower() in _TRUTHY
  28. return isinstance(value, (bool, int)) and bool(value)
  29. def bot_author_id(profile: str, origin: Optional[str] = None) -> str:
  30. """``bot:<profile>`` for a bot on the recipient's own install, ``bot:<origin>/<profile>`` for one on another
  31. install. The origin is the Desktop's connection id on a relayed dm and the sender's hostname on a peer dm."""
  32. origin = (origin or "").strip()
  33. return f"bot:{origin}/{profile}" if origin else f"bot:{profile}"
  34. def local_origin() -> str:
  35. """This machine's hostname as an author-id origin, cleaned like any author field. Empty when unknown."""
  36. try:
  37. host = socket.gethostname()
  38. except Exception:
  39. return ""
  40. # A slash would split the id into a different origin and profile at parse time.
  41. return (_clean_text(host) or "").replace("/", "")
  42. def parse_turn_author(raw: Any) -> Optional[dict[str, Any]]:
  43. """Normalize a dict or JSON string into ``{"id", "name", "is_bot"}``; None for anything else or without id and name.
  44. The id is whatever the transport knows the sender by: ``bot:<profile>`` on a bot-mode delivery inside one
  45. install, ``bot:<connection>/<profile>`` when the Desktop relayed it from another machine,
  46. ``bot:<hostname>/<profile>`` on a peer dm, the platform user id elsewhere.
  47. An ``origin`` field qualifies a bare ``bot:<profile>`` id the same way."""
  48. try:
  49. if isinstance(raw, (str, bytes)):
  50. raw = json.loads(raw)
  51. if not isinstance(raw, Mapping):
  52. return None
  53. author = {
  54. "id": _clean_text(raw.get("id")),
  55. "name": _clean_text(raw.get("name")),
  56. "is_bot": _bot_flag(raw.get("is_bot")),
  57. }
  58. if author["id"] is None and author["name"] is None:
  59. return None
  60. # Runtime-written chain fields of a bot-to-bot delivery (agent/bot_chain.py); never model input.
  61. hops = raw.get("hops")
  62. if isinstance(hops, int) and not isinstance(hops, bool) and 0 < hops <= _MAX_CHAIN_HOPS:
  63. author["hops"] = hops
  64. origin = _clean_text(raw.get("origin"))
  65. if origin and author["id"] and author["id"].startswith("bot:") and "/" not in author["id"]:
  66. author["id"] = _clean_text(bot_author_id(author["id"][len("bot:"):], origin))
  67. return author
  68. except Exception:
  69. return None
  70. def turn_author_from_env(environ: Mapping[str, str] = os.environ) -> Optional[dict[str, Any]]:
  71. """The author the dispatcher placed in ``HERMES_TURN_AUTHOR``, or None."""
  72. return parse_turn_author(environ.get(TURN_AUTHOR_ENV))
  73. def take_turn_author_from_env(environ: MutableMapping[str, str] = os.environ) -> Optional[dict[str, Any]]:
  74. """Read and remove ``HERMES_TURN_AUTHOR`` so subprocesses started during the turn do not inherit it."""
  75. return parse_turn_author(environ.pop(TURN_AUTHOR_ENV, None))
  76. def turn_author_env(author: dict[str, Any]) -> dict[str, str]:
  77. """The environment entry a dispatcher merges into a child's env."""
  78. return {TURN_AUTHOR_ENV: json.dumps(author, separators=(",", ":"))}
  79. def a2a_key(author: Optional[dict[str, Any]]) -> Optional[str]:
  80. """``a2a:<bot id>``, the shared name for a bot author's turns. None for a human or an id-less bot."""
  81. if not isinstance(author, dict) or not author.get("is_bot") or not author.get("id"):
  82. return None
  83. return f"a2a:{author['id']}"