bot_mode_probe.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. """Bot Mode roster probe — canonical Bot Chat system prompt section.
  2. When any profile carries ``ui_meta['hermes-bots']`` in profile.yaml (Bot-Mode-managed),
  3. a bot's canonical "Bot Chat" session — ONLY that session (agent/system_prompt.py enforces
  4. the ``BOT_CHAT_TITLE`` gate) — gets a "Messaging other agents" section. Silent (``""``)
  5. when no profile is managed or on any error. Older desktop builds appended a frozen copy of
  6. the section to SOUL.md; ``strip_legacy_protocol`` drops it at load time so the live roster
  7. here is the only copy any session sees. Cached per (process, home) so compression rebuilds
  8. produce identical bytes. Toggle: ``agent.bot_mode_protocol``. Also hosts path/roster
  9. helpers shared by ``bot_mode_dm`` and ``bot_relay``.
  10. """
  11. from __future__ import annotations
  12. import os
  13. import re
  14. import threading
  15. from collections.abc import Collection
  16. from pathlib import Path
  17. _PROTOCOL_HEADING = "## Messaging other agents"
  18. # The legacy section through the next H2 heading (or EOF), plus the blank lines before it.
  19. _LEGACY_PROTOCOL_RE = re.compile(r"\n*" + re.escape(_PROTOCOL_HEADING) + r"[ \t]*\n.*?(?=\n## |\Z)", re.DOTALL)
  20. # v3: the single-reply contract (final response captured by the transport) replaced the
  21. # "reply concisely via message_agent" bounce that double-delivered every teammate DM.
  22. _BOT_MODE_PROTOCOL_VERSION = 3
  23. # Leads a notify-only DM's body (after the attribution colon, so every sender-card parser keeps it).
  24. NO_REPLY_MARKER = "[no reply needed]"
  25. def strip_legacy_protocol(text: str) -> str:
  26. """SOUL text without the plugin-era "## Messaging other agents" section (idempotent)."""
  27. return _LEGACY_PROTOCOL_RE.sub("\n", text).strip() + "\n" if _PROTOCOL_HEADING in text else text
  28. # The only session title that receives the protocol section. Must match the
  29. # desktop plugin's createCanonicalChat title and the `-c "Bot Chat"` resume target.
  30. BOT_CHAT_TITLE = "Bot Chat"
  31. _lock = threading.Lock()
  32. _cached: dict[str, str] = {}
  33. # ── shared path / roster helpers ─────────────────────────────────────────────
  34. def _default_home() -> str:
  35. """Ambient process HERMES_HOME (env, else the platform default) as a string."""
  36. from hermes_constants import get_process_hermes_home
  37. return str(get_process_hermes_home())
  38. def _resolve_home(home: str | os.PathLike | None) -> Path:
  39. return Path(str(home) if home else _default_home())
  40. def _swallow(fn, default):
  41. """``fn()`` or ``default`` on any exception — the probe must never crash a prompt build."""
  42. try:
  43. return fn()
  44. except Exception:
  45. return default
  46. def _hermes_root(home: Path) -> Path:
  47. """Root ~/.hermes for both the default profile and named profiles."""
  48. return home.parent.parent if home.parent.name == "profiles" else home
  49. def _profile_name(home: Path) -> str:
  50. return home.name if home.parent.name == "profiles" else "default"
  51. def _handle(name: str, names: Collection[str]) -> str:
  52. """The @handle a local profile answers to; ``names`` are the roster's folder ids. The default
  53. profile is @hermes only while no real profile holds that name: a pre-reservation
  54. ``profiles/hermes`` keeps @hermes, and the default answers to @default."""
  55. return "hermes" if name == "default" and "hermes" not in names else name
  56. def _profile_for_handle(handle: str, names: Collection[str]) -> str:
  57. """The folder id a bare @handle names on this install: @hermes is the default profile's alias
  58. only while no real profile holds that name (a pre-reservation ``profiles/hermes`` keeps it)."""
  59. return "default" if handle == "hermes" and "hermes" not in names else handle
  60. def _roster(root: Path) -> list[tuple[str, Path]]:
  61. """(name, dir) for the default profile + every live named profile, sorted. Same identity
  62. predicate as ``profile list``: infra dirs (``sessions/``, ``logs/``) and tombstones are not
  63. teammates (#99392), and neither is a marker-carrying dir whose name is not a profile id —
  64. a parked backup or staging dir must never become a ``message_agent`` target (#116905)."""
  65. from hermes_constants import PROFILE_ID_RE, named_profile_is_live
  66. profiles = root / "profiles"
  67. named = _swallow(
  68. lambda: [
  69. (c.name, c)
  70. for c in sorted(profiles.iterdir())
  71. if c.name != "default" and PROFILE_ID_RE.match(c.name) and named_profile_is_live(c)
  72. ]
  73. if profiles.is_dir()
  74. else [],
  75. [],
  76. )
  77. return [("default", root), *named]
  78. def _read_yaml_dict(path: Path, needle: str | None = None) -> dict | None:
  79. """YAML mapping at ``path``, or None when missing / not a mapping / unreadable. ``needle``:
  80. cheap substring precheck that skips the YAML parse on the dominant (unmanaged) path."""
  81. def _load():
  82. if not path.is_file():
  83. return None
  84. raw = path.read_text(encoding="utf-8-sig", errors="replace")
  85. if needle is not None and needle not in raw:
  86. return None
  87. import hermes_yaml as yaml
  88. data = yaml.safe_load(raw)
  89. return data if isinstance(data, dict) else None
  90. return _swallow(_load, None)
  91. def _bots_meta(data: dict | None) -> dict | None:
  92. """The ``ui_meta['hermes-bots']`` block of a parsed profile.yaml, if a dict."""
  93. ui_meta = data.get("ui_meta") if data else None
  94. bots = ui_meta.get("hermes-bots") if isinstance(ui_meta, dict) else None
  95. return bots if isinstance(bots, dict) else None
  96. def _is_bot_managed(profile_dir: Path) -> bool:
  97. return _bots_meta(_read_yaml_dict(profile_dir / "profile.yaml", "hermes-bots")) is not None
  98. def _any_managed(root: Path) -> bool:
  99. return any(_is_bot_managed(d) for _n, d in _roster(root))
  100. def is_bot_mode_managed(home: str | os.PathLike | None = None) -> bool:
  101. """True when ANY profile on this install is Bot-Mode-managed. Never raises. The
  102. ``message_agent`` injection gate — deliberately independent of the protocol section's
  103. emptiness: a SOUL.md carrying the legacy protocol gets an empty section but still gets the tool."""
  104. return _swallow(lambda: _any_managed(_hermes_root(_resolve_home(home))), False)
  105. def _role_line(*parts: str) -> str:
  106. """'title — description' from the non-empty parts (either may be absent)."""
  107. return " — ".join(p for p in parts if p)
  108. def _bullet(handle: str, *parts: str) -> str:
  109. """Roster line: '- `handle`' plus ' — part' for each non-empty part."""
  110. return _role_line(f"- `{handle}`", *parts)
  111. def _profile_role(profile_dir: Path) -> str:
  112. """Teammate role line: Bot Mode title — profile description; tells a teammate
  113. WHO to message for a job. A friendly ``display_name`` (``hermes profile rename``) that
  114. differs from both the folder id and the title leads the line, so an untagged
  115. "talk to Scribe" maps to the folder handle without a disk search (#100671).
  116. Single-line, ≤160 chars, "" when nothing. Never raises."""
  117. def _role() -> str:
  118. data = _read_yaml_dict(profile_dir / "profile.yaml") or {}
  119. title = str((_bots_meta(data) or {}).get("title") or "").strip()
  120. display = str(data.get("display_name") or "").strip()
  121. if display.lower() in (profile_dir.name.lower(), title.lower()):
  122. display = ""
  123. line = _role_line(display, title, str(data.get("description") or "").strip())
  124. return " ".join(line.split())[:160]
  125. return _swallow(_role, "")
  126. def _friendly_names(profile_dir: Path) -> tuple[str, str]:
  127. """(Bot Mode title, profile.yaml ``display_name``) for a profile, "" when unset. Never raises."""
  128. def _read() -> tuple[str, str]:
  129. data = _read_yaml_dict(profile_dir / "profile.yaml") or {}
  130. return (str((_bots_meta(data) or {}).get("title") or "").strip(),
  131. str(data.get("display_name") or "").strip())
  132. return _swallow(_read, ("", ""))
  133. def _display_name(name: str, profile_dir: Path, names: Collection[str]) -> str:
  134. """Human-facing sender name, in the Desktop's ``botFriendlyNames`` order: Bot Mode title,
  135. then profile.yaml ``display_name`` (``hermes profile rename``), else the @handle — the
  136. renamed primary signs as ``Maia (@hermes)``, not ``hermes (@hermes)`` (#89720)."""
  137. return next((n for n in _friendly_names(profile_dir) if n), None) or _handle(name, names)
  138. # Tokens the Desktop mention parser reserves; a bot titled "Hermes" never hijacks @hermes.
  139. _RESERVED_ALIASES = frozenset({"all", "everyone", "user", "default", "hermes"})
  140. def alias_forms(value: str) -> set[str]:
  141. """Lower-cased mention forms of a friendly name, mirroring the Desktop's
  142. ``mentionNameForms``: slugified (``"Dr. Foo"`` → ``dr-foo``, what autocomplete inserts)
  143. and collapsed (``drfoo``). Reserved tokens and empty forms are dropped."""
  144. name = str(value or "").strip().lower()
  145. slug = re.sub(r"[^a-z0-9_-]+", "-", name).strip("-")
  146. collapsed = re.sub(r"[^a-z0-9_-]+", "", name)
  147. return {f for f in (slug, collapsed)
  148. if f and re.fullmatch(r"[a-z0-9][a-z0-9_-]*", f) and f not in _RESERVED_ALIASES}
  149. def local_alias_map(root: Path) -> dict[str, set[str]]:
  150. """``alias form → {folder ids}`` for every local profile's friendly names (profile.yaml
  151. ``display_name`` and the Bot Mode title). Folder ids themselves are not aliases: the
  152. caller matches those first, so a target that is an exact folder id always addresses that
  153. folder — a friendly name colliding with ANOTHER folder id never steals it. Ambiguity
  154. (one alias form shared by several profiles) surfaces as a multi-id set. Never raises."""
  155. def _build() -> dict[str, set[str]]:
  156. aliases: dict[str, set[str]] = {}
  157. for name, profile_dir in _roster(root):
  158. for form in set().union(*(alias_forms(f) for f in _friendly_names(profile_dir))):
  159. aliases.setdefault(form, set()).add(name)
  160. return aliases
  161. return _swallow(_build, {})
  162. def _peers(root: Path) -> list[str]:
  163. """Registered peer gateway names (``hermes peer``) from config.yaml, read
  164. directly (no config-loader import; the section is absent on most installs). Never raises."""
  165. def _names() -> list[str]:
  166. from hermes_cli.config_backend import read_config_doc_readonly
  167. doc = read_config_doc_readonly(root / "config.yaml")
  168. peers = doc.get("bot_peers") if isinstance(doc, dict) else None
  169. return sorted(str(n) for n in peers if str(n).strip()) if isinstance(peers, dict) else []
  170. return _swallow(_names, [])
  171. def _remote_roster(root: Path) -> list[dict]:
  172. """Desktop relay roster (``tools/bot_relay.py``); [] on any failure."""
  173. def _read():
  174. from tools.bot_relay import read_remote_roster
  175. return read_remote_roster(root)
  176. return _swallow(_read, [])
  177. def local_taken_forms(home: Path) -> set[str]:
  178. """Bare forms this install's own profiles answer to: folder ids, @handles and friendly-name
  179. slugs. A remote row must not be offered under any of them, since local resolution wins
  180. (``_resolve_local_name`` accepts the folder id ``default`` even while the default shows as
  181. @hermes). Read from the install root, so a named profile's home sees its siblings too."""
  182. root = _hermes_root(home)
  183. names = [name for name, _d in _roster(root)]
  184. return set(names) | {_handle(name, names) for name in names} | set(local_alias_map(root))
  185. def _remote_paragraph(root: Path) -> str:
  186. """Addendum for agents on OTHER connected machines; only when the relay roster is non-empty."""
  187. roster = _remote_roster(root)
  188. if not roster:
  189. return ""
  190. from tools.bot_relay import remote_target_forms
  191. lines = [
  192. _bullet(f"@{form}", f"on {row['connection_label'] or row['connection_id']}", row["title"], row["description"])
  193. for row, form in zip(roster, remote_target_forms(roster, local_taken_forms(root)))
  194. ]
  195. return (
  196. "\n\nTeammates on OTHER connected machines (reachable through the "
  197. "Desktop relay — message them with message_agent exactly like local "
  198. "teammates; replies arrive as completion notifications the same "
  199. "way, or via reply_delivery=\"poll\" as below):\n" + "\n".join(lines)
  200. )
  201. def _peer_paragraph(root: Path) -> str:
  202. """Addendum for cross-machine DMs — only when peers exist."""
  203. peers = _peers(root)
  204. if not peers:
  205. return ""
  206. listed = ", ".join(f"`{p}`" for p in peers)
  207. return (
  208. "\n\nTeammates on OTHER machines: this install also has peer gateways "
  209. f"registered ({listed}). Message an agent on a peer the same way — "
  210. 'message_agent with target "<peer>/<agent-name>" (or "<peer>" alone '
  211. "for the peer's main agent). Run `hermes peer list` for the live "
  212. "peer list."
  213. )
  214. def _build_section(home: Path) -> str:
  215. root = _hermes_root(home)
  216. me = _profile_name(home)
  217. if not _any_managed(root):
  218. return ""
  219. roster = _roster(root)
  220. names = [name for name, _d in roster]
  221. roster_lines = [_bullet(f"@{_handle(name, names)}", _profile_role(d)) for name, d in roster if name != me]
  222. roster_block = "\n".join(roster_lines) or "- (no teammates yet)"
  223. return (
  224. f"{_PROTOCOL_HEADING}\n"
  225. "This install runs Bot Mode: each Hermes profile is an agent teammate with "
  226. 'one canonical "Bot Chat" conversation, and you have the `message_agent` '
  227. "tool to DM any of them. It is FIRE-AND-FORGET: it delivers your message "
  228. "with your attribution prefixed automatically and returns an acknowledgement "
  229. "immediately — it never returns the reply. Send it, finish your turn, and "
  230. "the reply arrives later as a background-process completion notification "
  231. "that wakes you; relay it to the user then, attributed to that agent — unless "
  232. "the ack returns reply_delivery=\"poll\", in which case follow its "
  233. "process(action=\"wait\") instruction before ending the turn. "
  234. "COMPOSE every message yourself — say what YOU need from that agent; never "
  235. "forward the user's words verbatim, and never reveal private 1:1 chat "
  236. "content. When the user says \"ask <name>\" or \"tell <name> ...\", that is "
  237. "a handoff: pick the right teammate from the roster below, message them "
  238. "with message_agent, and report back naming which agent replied. Message "
  239. "ONE clearly relevant teammate; don't fan out to several unless the user "
  240. "explicitly asked (then comma-separate the targets in one call: one combined "
  241. "reply wakes you). expects_reply=false sends an FYI that nothing answers. "
  242. "Put limits in constraints and what you need back in expecting.\n"
  243. f'When YOU receive a "Message from 🤖 <name> (@<handle>):" message, a '
  244. "teammate agent is talking to you (not the user): address them and return "
  245. "your concise, substantive reply as this turn's final response. Do not call "
  246. "message_agent merely to reply; the transport already captures your final "
  247. "response and delivers it to the sender. Use message_agent only to initiate "
  248. "a separate message or independent follow-up. If it is marked "
  249. f"\"{NO_REPLY_MARKER}\" or is a pure FYI with nothing to add, end your turn "
  250. "with an intentional silence token "
  251. "([SILENT] or NO_REPLY) — the transport swallows it, so the sender gets "
  252. "no acknowledgement ping-pong.\n"
  253. f"You are `@{_handle(me, names)}`. Your teammates (live roster; roles from their "
  254. "profiles):\n"
  255. f"{roster_block}"
  256. + _remote_paragraph(home)
  257. + _peer_paragraph(root)
  258. )
  259. def get_bot_mode_protocol_section(home: str | os.PathLike | None = None, *, force_refresh: bool = False) -> str:
  260. """Cached probe entry point — one filesystem pass per (process, home). ``home`` should be
  261. the AGENT'S OWN resolved home (session-db derived), not ambient HERMES_HOME — build threads
  262. can lose the ContextVar override and the env var would then name the wrong profile."""
  263. resolved = str(_resolve_home(home))
  264. with _lock:
  265. if force_refresh or resolved not in _cached:
  266. _cached[resolved] = _swallow(lambda: _build_section(Path(resolved)), "")
  267. return _cached[resolved]
  268. # ── capability epoch ─────────────────────────────────────────────────────────
  269. # Bot Chat sessions are effectively eternal, so "build the prompt once" would strand
  270. # capability changes (skills, toolsets, MCP, SOUL, roster, peers, model capability
  271. # overrides that change the prompt) forever. The fingerprint hashes exactly that
  272. # surface; the built prompt embeds it and agent/conversation_loop.py rebuilds only
  273. # when the stored epoch differs from disk — once per change, never per-turn drift.
  274. _EPOCH_PREFIX = "Capability epoch: "
  275. _EPOCH_RE_TEXT = r"Capability epoch: ([0-9a-f]{12})"
  276. def _model_prompt_capability_surface(model_cfg: object) -> dict:
  277. """``model.*`` overrides whose flip changes a rebuilt prompt, coerced like their consumers.
  278. ``supports_vision`` uses image routing's strict bool so YAML ``yes`` and ``true`` share
  279. one epoch. ``context_length`` is the cap ``build_system_prompt_parts`` uses to truncate
  280. context files. Routing keys (provider, default, base_url) are identity lines, not this
  281. surface — and no model id is special-cased.
  282. """
  283. from agent.image_routing import _coerce_capability_bool
  284. if not isinstance(model_cfg, dict):
  285. model_cfg = {}
  286. raw_ctx = model_cfg.get("context_length")
  287. ctx = None
  288. # bool is an int subclass; ``context_length: true`` is not a window.
  289. if isinstance(raw_ctx, bool):
  290. ctx = None
  291. elif isinstance(raw_ctx, int):
  292. ctx = raw_ctx if raw_ctx > 0 else None
  293. elif isinstance(raw_ctx, str) and raw_ctx.strip().isdigit():
  294. parsed = int(raw_ctx.strip())
  295. ctx = parsed if parsed > 0 else None
  296. return {
  297. "supports_vision": _coerce_capability_bool(model_cfg.get("supports_vision")),
  298. "context_length": ctx,
  299. }
  300. def capability_fingerprint(home: str | os.PathLike | None = None) -> str:
  301. """12-hex digest of the capability surface for ``home``'s profile: disabled skills +
  302. enabled toolsets + MCP config, model capability overrides that change the prompt
  303. (``supports_vision``, ``context_length``), SOUL.md bytes, installed skill names, the
  304. Bot-Mode roster (+ roles), peers and the relay roster. Deliberately NOT cached — the
  305. point is detecting on-disk drift against a stored prompt's epoch. Never raises
  306. ("unavailable" on failure)."""
  307. import hashlib
  308. import json
  309. resolved = _resolve_home(home)
  310. root = _hermes_root(resolved)
  311. surface: dict = {}
  312. try:
  313. # Canonical loader (managed overlay + env expansion + normalization),
  314. # scoped to the bot's home via the override the loaders already honor.
  315. from agent.skill_utils import parse_config_string_list
  316. from hermes_cli.config import load_config_readonly
  317. from hermes_constants import reset_hermes_home_override, set_hermes_home_override
  318. token = set_hermes_home_override(str(resolved))
  319. try:
  320. cfg = load_config_readonly() or {}
  321. finally:
  322. reset_hermes_home_override(token)
  323. skills_cfg = cfg.get("skills") if isinstance(cfg.get("skills"), dict) else {}
  324. model_cfg = cfg.get("model") if isinstance(cfg.get("model"), dict) else {}
  325. surface["model_capabilities"] = _model_prompt_capability_surface(model_cfg)
  326. surface["disabled_skills"] = sorted(str(s).lower() for s in (skills_cfg.get("disabled") or []))
  327. # The live selection is platform_toolsets.<platform> minus agent.disabled_toolsets;
  328. # tools.enabled_toolsets is written by no surface, so watching it left Bot Chats
  329. # blind to `hermes tools enable/disable` (#124211). Raw slices: an edit that leaves
  330. # the effective selection unchanged costs one spurious rebuild at most.
  331. agent_cfg = cfg.get("agent") if isinstance(cfg.get("agent"), dict) else {}
  332. surface["platform_toolsets"] = json.dumps(cfg.get("platform_toolsets") or {}, sort_keys=True, default=str)
  333. surface["disabled_toolsets"] = sorted(parse_config_string_list(agent_cfg.get("disabled_toolsets")))
  334. mcp = cfg.get("mcp_servers")
  335. surface["mcp"] = json.dumps(mcp, sort_keys=True, default=str) if isinstance(mcp, dict) else ""
  336. except Exception:
  337. pass
  338. def _soul() -> str:
  339. soul = resolved / "SOUL.md"
  340. return hashlib.sha256(soul.read_bytes()).hexdigest() if soul.is_file() else ""
  341. def _skills() -> list[str]:
  342. skills_root = resolved / "skills"
  343. if not skills_root.is_dir():
  344. return []
  345. # The same walk every other reader of this tree uses (skills_list/skill_view, the prompt's
  346. # skills index, skill_count): it prunes EXCLUDED_SKILL_DIRS — ``.archive``, ``.curator_backups``,
  347. # ``node_modules`` … — and each skill's support dirs. A raw ``**/SKILL.md`` glob counted files
  348. # the model can never invoke, so archiving a skill, or the curator writing a backup, flipped the
  349. # epoch and forced every Bot Chat to rebuild a system prompt whose skills index had not changed.
  350. # iter_skill_index_files is also org-token-gated, so the epoch moves on an org switch as well —
  351. # intended: a different org sees a different skills index, so it needs a different prompt.
  352. from agent.skill_utils import iter_skill_index_files
  353. return sorted(str(p.parent.relative_to(skills_root))
  354. for p in iter_skill_index_files(skills_root, "SKILL.md"))
  355. surface["soul"] = _swallow(_soul, "")
  356. surface["skills"] = _swallow(_skills, [])
  357. try:
  358. roster = _roster(root)
  359. surface["roster"] = sorted(n for n, d in roster if _is_bot_managed(d))
  360. # Roles are part of the messaging surface: renaming a bot or editing a
  361. # description must refresh the roster block teammates pick recipients from.
  362. surface["roster_roles"] = sorted(f"{n}:{_profile_role(d)}" for n, d in roster)
  363. except Exception:
  364. surface["roster"] = []
  365. # Protocol-text version salt: bumping it refreshes every eternal Bot Chat
  366. # prompt ONCE so existing bots adopt a new protocol section (v2: the
  367. # message_agent tool replacing the shellout instructions; v3: the
  368. # single-reply contract replacing the message_agent reply bounce).
  369. surface["protocol_version"] = _BOT_MODE_PROTOCOL_VERSION
  370. # Peer gateways and the Desktop relay roster are part of the messaging
  371. # surface too: registering a peer or (dis)connecting a machine must show up.
  372. surface["peers"] = _peers(root)
  373. surface["remote_roster"] = sorted(
  374. f"{r['connection_id']}:{r['profile']}:{r['title']}" for r in _remote_roster(resolved)
  375. )
  376. return _swallow(
  377. lambda: hashlib.sha256(json.dumps(surface, sort_keys=True).encode("utf-8")).hexdigest()[:12],
  378. "unavailable",
  379. )
  380. def epoch_line(home: str | os.PathLike | None = None) -> str:
  381. """The epoch stamp appended to a Bot Chat prompt."""
  382. return f"{_EPOCH_PREFIX}{capability_fingerprint(home)}"
  383. def stored_prompt_capability_stale(stored_prompt: str, home: str | os.PathLike | None = None) -> bool:
  384. """True when ``stored_prompt`` is a Bot Chat prompt whose embedded epoch no
  385. longer matches disk. Unstamped prompts are never stale. Fails closed to
  386. "not stale" — a broken probe must not become a rebuild-every-turn cache burner."""
  387. import re
  388. m = re.search(_EPOCH_RE_TEXT, stored_prompt or "")
  389. if not m:
  390. return False
  391. current = _swallow(lambda: capability_fingerprint(home), "unavailable")
  392. return current != "unavailable" and m.group(1) != current
  393. def stored_bot_chat_prompt_needs_upgrade(stored_prompt: str, home: str | os.PathLike | None = None) -> bool:
  394. """True when a Bot Chat session's stored prompt PREDATES the epoch mechanism (no stamp —
  395. including SOUL-era prompts whose frozen roster rode in from SOUL.md). The caller must only
  396. ask for sessions titled "Bot Chat"; we rebuild only when the probe would actually emit a
  397. section, and every rebuilt prompt is stamped so this fires once. Fails closed."""
  398. if _EPOCH_PREFIX in (stored_prompt or ""):
  399. return False
  400. return _swallow(lambda: bool(get_bot_mode_protocol_section(home)), False)
  401. def _reset_cache_for_tests() -> None:
  402. with _lock:
  403. _cached.clear()