system_prompt.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. """System-prompt assembly for :class:`AIAgent`.
  2. Built once per session and reused across turns (only context compression
  3. triggers a rebuild) so the upstream prefix cache stays warm. Three tiers are
  4. joined with ``\\n\\n``: ``stable`` (identity, guidance, env hints, coding brief,
  5. platform hints), ``context`` (workspace snapshot, caller ``system_message``,
  6. context files) and ``volatile`` (skills index, memory, USER.md, external memory
  7. provider, timestamp line). See ``references/system-prompt-invariant.md``.
  8. """
  9. from __future__ import annotations
  10. import json
  11. import logging
  12. import os
  13. import re
  14. from pathlib import Path
  15. from typing import Any, Dict, List, Optional, Tuple
  16. from agent.delegation_context import owned_kanban_task
  17. from agent.prompt_builder import (
  18. DEFAULT_AGENT_IDENTITY, EXECUTION_GUIDANCE_MODELS, GOOGLE_MODEL_OPERATIONAL_GUIDANCE,
  19. HERMES_AGENT_HELP_GUIDANCE, HERMES_AGENT_HELP_GUIDANCE_NO_SKILLS, KANBAN_GUIDANCE,
  20. PARALLEL_TOOL_CALL_GUIDANCE, PLATFORM_HINTS, SESSION_SEARCH_GUIDANCE,
  21. SKILLS_GUIDANCE, STEER_CHANNEL_NOTE, TASK_COMPLETION_GUIDANCE, TELEGRAM_RICH_MESSAGES_HINT,
  22. TOOL_USE_ENFORCEMENT_GUIDANCE, TOOL_USE_ENFORCEMENT_MODELS, drain_truncation_warnings,
  23. )
  24. from agent import prompt_builder as _pb
  25. from agent import runtime_context as _embedded_runtime
  26. from agent.runtime_cwd import resolve_agent_cwd, resolve_context_cwd
  27. from hermes_constants import get_default_hermes_root, get_hermes_home
  28. from utils import is_truthy_value
  29. logger = logging.getLogger(__name__)
  30. _PLUGIN_SECTION_FRAME_RE = re.compile(
  31. r"^## Plugin Context: (?P<id>[a-z0-9][a-z0-9._-]{0,127})\n<!-- hermes-plugin-section-chars:(?P<chars>[0-9]{1,4}) -->\n\n",
  32. re.MULTILINE,
  33. )
  34. _GATE_WORDS = {**dict.fromkeys(("true", "always", "yes", "on"), True), **dict.fromkeys(("false", "never", "no", "off"), False)}
  35. def _model_gate(setting: Any, model: Optional[str], default_models) -> bool:
  36. """Resolve a config gate: True/"true"-ish -> on, False/"false"-ish -> off,
  37. list -> case-insensitive model-substring match, anything else ("auto") ->
  38. match against *default_models*."""
  39. if setting is True or setting is False:
  40. return setting
  41. if isinstance(setting, str) and setting.lower() in _GATE_WORDS:
  42. return _GATE_WORDS[setting.lower()]
  43. model_lower = (model or "").lower()
  44. if isinstance(setting, list):
  45. return any(p.lower() in model_lower for p in setting if isinstance(p, str))
  46. return any(p in model_lower for p in default_models)
  47. def _resolve_platform_hint(agent: Any, platform_key: str, default_hint: str) -> str:
  48. """Apply the ``platform_hints.<platform>`` config override: ``replace``
  49. substitutes the default, ``append`` adds text (a bare string is shorthand
  50. for append). Malformed entries fall back to the unmodified default so bad
  51. config can never break prompt assembly or leak across platforms."""
  52. overrides = getattr(agent, "_platform_hint_overrides", None)
  53. spec = overrides.get(platform_key) if platform_key and isinstance(overrides, dict) else None
  54. if isinstance(spec, str):
  55. spec = {"append": spec}
  56. if not isinstance(spec, dict):
  57. return default_hint
  58. replace_text, append_text = (v.strip() if isinstance(v, str) else "" for v in (spec.get("replace"), spec.get("append")))
  59. base = replace_text or default_hint
  60. return f"{base}\n\n{append_text}".strip() if append_text else base
  61. _TUI_EMBEDDED_PANE_CLARIFIER = (
  62. " You're in its embedded terminal pane, beside the GUI chat — the user can "
  63. "select your output (Option-drag on macOS, Shift-drag elsewhere) and press "
  64. "Cmd/Ctrl+L to send it to the chat composer."
  65. )
  66. def _tui_embedded_pane_clarifier(hint: str) -> str:
  67. """Append the desktop embedded-terminal clarifier when ``HERMES_DESKTOP_TERMINAL``
  68. is set (only the desktop's TUI PTY, never the chat backend). Idempotent."""
  69. if not hint or _TUI_EMBEDDED_PANE_CLARIFIER in hint or not is_truthy_value(os.getenv("HERMES_DESKTOP_TERMINAL")):
  70. return hint
  71. return hint + _TUI_EMBEDDED_PANE_CLARIFIER
  72. def _plugin_session_info(agent: Any) -> dict[str, str]:
  73. """Return immutable-at-render-time metadata exposed to prompt sections."""
  74. try:
  75. cwd = str(resolve_context_cwd() or "")
  76. except Exception:
  77. cwd = ""
  78. info = {k: str(getattr(agent, k, None) or "") for k in ("session_id", "model", "provider", "platform")}
  79. info.update(profile_name=_active_profile_name(agent, _ambient_plugin_profile_name), cwd=cwd)
  80. return info
  81. def _ambient_plugin_profile_name() -> str:
  82. from hermes_cli.profiles import get_active_profile_name
  83. return str(get_active_profile_name() or "default")
  84. def _active_profile_name(agent: Any, ambient) -> str:
  85. """Profile name from the agent's OWN home, else *ambient()*; "default" on any
  86. failure. Ambient resolution misreports on threads that lost the HERMES_HOME
  87. ContextVar, which is why the agent's home is preferred."""
  88. try:
  89. home = _agent_home(agent)
  90. return _profile_name_for_home(home) if home is not None else ambient()
  91. except Exception:
  92. return "default"
  93. def _frozen_plugin_prompt_sections(agent: Any) -> tuple:
  94. """Render plugin sections once per session and freeze them on the agent.
  95. A restored ``_cached_system_prompt`` is parsed instead of re-running plugin
  96. code; a render that raises at a rebuild boundary keeps the previous bytes
  97. (stashed by ``invalidate_system_prompt``) instead of silently vanishing."""
  98. if hasattr(agent, "_plugin_system_prompt_sections_snapshot"):
  99. return agent._plugin_system_prompt_sections_snapshot
  100. stored_prompt = getattr(agent, "_cached_system_prompt", None)
  101. if isinstance(stored_prompt, str) and stored_prompt:
  102. rendered = _restore_plugin_prompt_sections(stored_prompt)
  103. else:
  104. try:
  105. from hermes_cli.plugins import render_system_prompt_sections
  106. rendered = tuple(render_system_prompt_sections(_plugin_session_info(agent)))
  107. except Exception as exc:
  108. rendered = getattr(agent, "_plugin_system_prompt_sections_previous", None)
  109. if rendered:
  110. logger.warning("Plugin system prompt sections failed to re-render (%s); keeping the previous frozen sections", exc)
  111. else:
  112. logger.warning("Plugin system prompt sections could not be rendered: %s", exc)
  113. rendered = ()
  114. agent._plugin_system_prompt_sections_snapshot = rendered
  115. return rendered
  116. def _restore_plugin_prompt_sections(prompt: str) -> tuple:
  117. """Recover frozen section bytes from the persisted full prompt. Only the
  118. exact canonical container emitted by core is accepted — user/project text
  119. may resemble a frame."""
  120. from hermes_cli.plugins import (
  121. MAX_SYSTEM_PROMPT_SECTION_CHARS, PLUGIN_SECTIONS_END, PLUGIN_SECTIONS_START,
  122. RenderedPluginSystemPromptSection, format_system_prompt_sections,
  123. )
  124. start = prompt.rfind(PLUGIN_SECTIONS_START)
  125. end = prompt.find(PLUGIN_SECTIONS_END, start + len(PLUGIN_SECTIONS_START)) if start >= 0 else -1
  126. if end < 0:
  127. return ()
  128. after_end = end + len(PLUGIN_SECTIONS_END)
  129. if not prompt[after_end:].startswith("\n\nConversation started:"):
  130. return ()
  131. framed = prompt[start:after_end]
  132. restored = []
  133. for match in _PLUGIN_SECTION_FRAME_RE.finditer(framed):
  134. content_len = int(match.group("chars"))
  135. content = framed[match.end() : match.end() + content_len]
  136. if content_len > MAX_SYSTEM_PROMPT_SECTION_CHARS or len(content) != content_len:
  137. continue
  138. restored.append(RenderedPluginSystemPromptSection(id=match.group("id"), content=content,
  139. position="after_memory", plugin="persisted-prompt"))
  140. return tuple(restored) if format_system_prompt_sections(restored) == framed else ()
  141. def restore_plugin_prompt_sections(agent: Any, prompt: str) -> None:
  142. """Seed a resumed agent's frozen snapshot from persisted prompt bytes."""
  143. agent._plugin_system_prompt_sections_snapshot = _restore_plugin_prompt_sections(prompt)
  144. def _plugin_section_blocks(sections: tuple, position: str) -> list[str]:
  145. from hermes_cli.plugins import format_system_prompt_sections
  146. block = format_system_prompt_sections([s for s in sections if s.position == position])
  147. return [block] if block else []
  148. def _session_start_like(agent: Any, now: Any) -> Any:
  149. """Best-known conversation start time, or ``now`` as a fallback.
  150. ``Conversation started:`` must be byte-stable across rebuilds (compression,
  151. resume, fresh gateway turns), so prefer immutable sources in order: the
  152. lineage-root session id's embedded stamp (compaction rotates ids, each with
  153. its own mint time), the current session id's stamp, ``agent.session_start``,
  154. then ``now``. Stamps are box-local wall-clock: attach that zone first, then
  155. convert to ``now``'s zone so the date matches the per-turn clock.
  156. 0. the LINEAGE-ROOT session id's embedded timestamp — compaction can rotate the session id, and each
  157. rotated id embeds its OWN mint time, so after months of compactions rung 1 alone would quietly re-birth
  158. the conversation at its latest rotation. Walking to the lineage root (same walk as
  159. ``_conversation_root_id``) recovers the ORIGINAL birth stamp — a Bot Mode forever-chat keeps knowing
  160. when it was first born, across every compaction (maintainer-directed, #98426); 1. the timestamp embedded
  161. in ``session_id`` (``YYYYMMDD_HHMMSS_...``) — immutable for the life of the session, so the line is
  162. byte-stable across every rebuild boundary (preserving prefix-cache KV); 2. 3. ``now`` (initial/legacy
  163. build without either).
  164. """
  165. from datetime import datetime
  166. def _to_display_tz(dt: Any) -> Any:
  167. if dt.tzinfo is None:
  168. try:
  169. # The offset in force at dt, not today's: a stamp from the other DST half differs by an hour.
  170. dt = dt.astimezone()
  171. except (ValueError, OSError):
  172. pass
  173. if getattr(now, "tzinfo", None) is not None and dt.tzinfo is not None:
  174. try:
  175. dt = dt.astimezone(now.tzinfo)
  176. except (ValueError, OSError):
  177. pass
  178. return dt
  179. session_id = getattr(agent, "session_id", None)
  180. db = getattr(agent, "_session_db", None)
  181. try:
  182. root_id = db.get_conversation_root(session_id) if db is not None and isinstance(session_id, str) and session_id else None
  183. except Exception:
  184. root_id = None
  185. for candidate in (root_id, session_id):
  186. m = re.match(r"^(\d{8})_(\d{6})", candidate) if isinstance(candidate, str) else None
  187. if m:
  188. try:
  189. return _to_display_tz(datetime.strptime(f"{m.group(1)}_{m.group(2)}", "%Y%m%d_%H%M%S"))
  190. except ValueError:
  191. pass
  192. session_start = getattr(agent, "session_start", None)
  193. return _to_display_tz(session_start) if hasattr(session_start, "astimezone") else now
  194. def _agent_home(agent: Any) -> Optional[Path]:
  195. """The agent's OWN profile home, or None to use ambient resolution.
  196. A bound HERMES_HOME ContextVar override wins (the gateway multiplexes
  197. profiles over one shared session DB and binds the home per turn); else the
  198. parent of ``_session_db.db_path`` — ground truth on threads that lost the
  199. ContextVar, where ambient resolution would leak the launch profile.
  200. 1. Surfaces that multiplex several profiles over ONE shared session DB (the messaging gateway:
  201. ``gateway/run.py`` hands every agent the launch-home ``state.db`` and binds the profile home per turn
  202. via ``_profile_runtime_scope`` + ``copy_context``) would otherwise have the db-derived launch home STOMP
  203. the correctly-bound profile — inverting the leak this helper exists to fix (found by @kshitijk4poor's
  204. post-merge probe on #86313). 2. Fallback: the home containing the agent's ``_session_db.db_path``
  205. (``<home>/state.db``) — ground truth on threads that lost the ContextVar (ContextVars don't propagate
  206. into ``threading.Thread``), where the unbound build previously fell back to the launch home and leaked
  207. the default profile's skills/identity into a bot prompt.
  208. """
  209. try:
  210. from hermes_constants import get_hermes_home_override
  211. override = get_hermes_home_override()
  212. if override:
  213. return Path(override)
  214. except Exception:
  215. pass
  216. try:
  217. db_path = getattr(getattr(agent, "_session_db", None), "db_path", None)
  218. return Path(db_path).parent if db_path else None
  219. except Exception:
  220. return None
  221. def _agent_skills_dir(agent: Any) -> Optional[Path]:
  222. """The agent's own ``<home>/skills`` dir, or None to use ambient home."""
  223. home = _agent_home(agent)
  224. return home / "skills" if home is not None else None
  225. def _profile_name_for_home(home: Path) -> str:
  226. """``<root>/profiles/X`` -> ``"X"``; anything else -> ``"default"``.
  227. Uses ``get_default_hermes_root()`` (NOT ``get_hermes_home()``): on a bound
  228. profile session the ambient home IS the profile dir, so every profile
  229. would misreport as "default"."""
  230. try:
  231. from hermes_constants import get_default_hermes_root
  232. rel = home.resolve().relative_to((get_default_hermes_root() / "profiles").resolve())
  233. return rel.parts[0] if rel.parts else "default"
  234. except (ValueError, OSError):
  235. return "default"
  236. def _tool_guidance_block(agent: Any) -> Optional[str]:
  237. """Tool-aware behavioral guidance, injected only when the tools are loaded."""
  238. names = agent.valid_tool_names
  239. # With both memory stores disabled no store is built, so the full guidance
  240. # would steer the model at a tool that always answers "Memory is not
  241. # available"; with only USER.md enabled the narrower block is used.
  242. memory_guidance = None
  243. if "memory" in names:
  244. memory_guidance = _pb.build_memory_guidance(
  245. getattr(agent, "_memory_enabled", True),
  246. getattr(agent, "_user_profile_enabled", True),
  247. skill_manage_available="skill_manage" in names,
  248. )
  249. elif "workspace_memory_write" in names:
  250. # Yaovi product mode: the workspace store is the only long-term memory.
  251. memory_guidance = (
  252. "Long-term memory lives in the Yaoyao workspace. Before saving, call workspace_memory_search to "
  253. "find an existing fact; save durable, sourced facts with workspace_memory_write (update an existing "
  254. "fact by id or factKey with its current revision) and remove facts with workspace_memory_forget. "
  255. "There is no separate memory tool or MEMORY.md/USER.md file."
  256. )
  257. # Kanban lifecycle: resolved once at __init__ (_kanban_worker_guidance);
  258. # fallback paths must also limit task protocol guidance to dispatcher workers.
  259. _kanban_guidance = getattr(agent, "_kanban_worker_guidance", None)
  260. if _kanban_guidance is None and "kanban_show" in names and owned_kanban_task():
  261. _kanban_guidance = KANBAN_GUIDANCE
  262. tool_guidance = [
  263. memory_guidance,
  264. SESSION_SEARCH_GUIDANCE if "session_search" in names else None,
  265. SKILLS_GUIDANCE if "skill_manage" in names else None,
  266. _kanban_guidance,
  267. ]
  268. return " ".join(g for g in tool_guidance if g) or None
  269. def _skills_prompt(agent: Any) -> str:
  270. """Skills index (empty without skills tools). Focus mode demotes non-coding
  271. categories to names-only — never hidden, every name stays visible."""
  272. if not any(name in agent.valid_tool_names for name in ['skills_list', 'skill_view', 'skill_manage']):
  273. return ""
  274. import model_tools
  275. avail_toolsets = {model_tools.get_toolset_for_tool(tool_name) for tool_name in agent.valid_tool_names} - {None, ""}
  276. try:
  277. from agent.coding_context import coding_compact_skill_categories
  278. _compact_cats = coding_compact_skill_categories(platform=agent.platform, cwd=resolve_context_cwd())
  279. except Exception:
  280. _compact_cats = frozenset()
  281. return _pb.build_skills_system_prompt(available_tools=agent.valid_tool_names, available_toolsets=avail_toolsets,
  282. compact_categories=_compact_cats or None, skills_dir_override=_agent_skills_dir(agent))
  283. def _auto_load_parts(agent: Any) -> list[str]:
  284. """``skills.auto_load`` blocks, resolved once per agent lifecycle (config, skill files and
  285. HERMES_IGNORE_RULES are read on the first build only) so the prompt stays byte-stable
  286. across model switches, compression and static-prefix restoration.
  287. Same gate as ``_skills_prompt``: nothing without the skills toolset, and nothing for agents that skip
  288. context files (delegate children, curator/review forks, gateway hygiene agents) — pinned skills are
  289. operator guidance for the user's session, not payload for every internal fork."""
  290. if getattr(agent, "skip_context_files", False) or not any(
  291. name in agent.valid_tool_names for name in ("skills_list", "skill_view", "skill_manage")):
  292. return []
  293. if not getattr(agent, "_auto_load_skills_resolved", False):
  294. result: tuple[str, list[str], list[str]] = ("", [], [])
  295. try:
  296. if not is_truthy_value(os.environ.get("HERMES_IGNORE_RULES")):
  297. from agent.skill_commands import build_auto_load_prompt
  298. result = build_auto_load_prompt(task_id=getattr(agent, "session_id", None), home_override=_agent_home(agent))
  299. if result[2]:
  300. logger.warning("skills.auto_load: skill(s) not found or disabled, skipped: %s", ", ".join(result[2]))
  301. except Exception:
  302. logger.debug("skills.auto_load: injection skipped", exc_info=True) # config errors never block session start
  303. agent._auto_load_skills_result = result
  304. agent._auto_load_skills_resolved = True
  305. prompt = agent._auto_load_skills_result[0]
  306. return [prompt] if prompt else []
  307. def _bot_mode_parts(agent: Any) -> list[str]:
  308. """Bot Mode teammate protocol — only in a bot's canonical "Bot Chat" session.
  309. Marks the prompt timeless (the volatile date line is dropped) since a birth
  310. date pinned in a months-long session is misinformation."""
  311. parts: list[str] = []
  312. try:
  313. from tools.bot_mode_probe import BOT_CHAT_TITLE, epoch_line, get_bot_mode_protocol_section
  314. _title = str(getattr(agent, "_session_title_hint", "") or "").strip()
  315. if not _title:
  316. _sdb = getattr(agent, "_session_db", None)
  317. _sid = getattr(agent, "session_id", None)
  318. _title = str((_sdb.get_session_title(_sid) if (_sdb and _sid) else None) or "").strip()
  319. _bot_section = get_bot_mode_protocol_section(_agent_home(agent)) if _title == BOT_CHAT_TITLE else None
  320. if _bot_section:
  321. parts.append(_bot_section)
  322. # Capability epoch lets the restore path rebuild ONCE per
  323. # user-initiated capability change in an eternal session.
  324. parts.append(epoch_line(_agent_home(agent)))
  325. agent._bot_chat_timeless_prompt = True
  326. except Exception:
  327. pass
  328. return parts
  329. def _ambient_file_safety_profile_name() -> str:
  330. from agent.file_safety import _resolve_active_profile_name
  331. return _resolve_active_profile_name()
  332. def _active_profile_line(agent: Any) -> str:
  333. """Name the running profile so the agent doesn't conflate ``~/.hermes/skills``
  334. (default) with ``~/.hermes/profiles/<active>/skills``. Resolved from the
  335. agent's OWN home first (a build thread that lost the ContextVar would
  336. otherwise print "default" for a bot profile)."""
  337. _agent_home_path = _agent_home(agent)
  338. active_profile = _active_profile_name(agent, _ambient_file_safety_profile_name)
  339. if active_profile == "default":
  340. # With an explicit agent home, the default profile's data lives at the
  341. # ROOT (get_hermes_home() on a bound profile session is the PROFILE dir).
  342. # Without one, keep the ambient (patchable) resolution byte-identical.
  343. _root_str = str(get_default_hermes_root() if _agent_home_path is not None else get_hermes_home())
  344. return (
  345. "Active Hermes profile: default. Other profiles (if any) live "
  346. "under " + _root_str + "/profiles/<name>/. Each profile has its own "
  347. "skills/, plugins/, cron/, and memories/ that affect a different "
  348. "session than this one. Do not modify another profile's "
  349. "skills/plugins/cron/memories unless the user explicitly directs "
  350. "you to."
  351. )
  352. # A non-default name is only returned when the resolved home is ALREADY
  353. # <root>/profiles/<name>, so the profile home is the session home itself.
  354. profile_home = str(_agent_home_path) if _agent_home_path is not None else str(get_hermes_home())
  355. # A non-default name is only ever returned when the resolved home is ALREADY <root>/profiles/<name> —
  356. # that is exactly how both _profile_name_for_home() and _resolve_active_profile_name() derive it. So the
  357. # profile home is the session home itself; appending /profiles/<name> again doubled it (#72894). The
  358. # default profile's data sits at the ROOT (get_default_hermes_root()), which in ambient profile mode is
  359. # NOT get_hermes_home().
  360. default_root = get_default_hermes_root()
  361. return (
  362. f"Active Hermes profile: {active_profile}. This session reads "
  363. f"and writes {profile_home}/. The default "
  364. f"profile's data lives at {default_root}/skills/, {default_root}/plugins/, "
  365. f"{default_root}/cron/, {default_root}/memories/ — those belong to a "
  366. f"different session run from a different shell. Do NOT modify "
  367. f"another profile's skills/plugins/cron/memories unless the user "
  368. f"explicitly directs you to."
  369. )
  370. def _default_platform_hint(platform_key: str) -> str:
  371. """Built-in hint, else the plugin adapter's ``platform_hint``, else ``""``."""
  372. hint = PLATFORM_HINTS.get(platform_key, "")
  373. if not hint and platform_key:
  374. try:
  375. from gateway.platform_registry import platform_registry
  376. _entry = platform_registry.get(platform_key)
  377. if _entry is None:
  378. # A prompt can be built before anything ran plugin discovery (direct builders,
  379. # one-shot callers); the hint lives on the plugin's entry, so discover (idempotent).
  380. from hermes_cli.plugins import discover_plugins
  381. discover_plugins()
  382. _entry = platform_registry.get(platform_key)
  383. hint = (_entry and _entry.platform_hint) or ""
  384. except Exception:
  385. pass
  386. if platform_key == "telegram" and hint and _telegram_rich_messages_enabled():
  387. hint = hint.rstrip() + " " + TELEGRAM_RICH_MESSAGES_HINT
  388. return hint
  389. def _cron_delivery_hint(agent: Any) -> str:
  390. """The destination channel's hint (default + its ``platform_hints`` override) for a cron agent.
  391. A cron agent runs as platform ``cron`` but its final response lands on the job's ``deliver``
  392. channel, so without this the model never learns that MEDIA: tags become Slack/Telegram
  393. attachments or that tables do not render there — and a user's ``platform_hints.slack.append``
  394. never reached scheduled jobs at all. The scheduler publishes the primary auto-deliver target
  395. into the session ContextVar before the agent runs (same seam ``send_message`` routes by).
  396. """
  397. from gateway.session_context import get_session_env
  398. deliver_key = get_session_env("HERMES_CRON_AUTO_DELIVER_PLATFORM", "").lower().strip()
  399. if not deliver_key or deliver_key == "cron":
  400. return ""
  401. hint = _resolve_platform_hint(agent, deliver_key, _default_platform_hint(deliver_key))
  402. return f"Delivery destination ({deliver_key}): {hint}" if hint else ""
  403. def platform_hint(agent: Any) -> str:
  404. """Built-in/plugin platform hint + Telegram rich-messages opt-in + config
  405. override + desktop TUI clarifier; cron agents also carry their delivery channel's hint."""
  406. platform_key = (agent.platform or "").lower().strip()
  407. _effective_hint = _resolve_platform_hint(agent, platform_key, _default_platform_hint(platform_key))
  408. if platform_key == "tui" and _effective_hint:
  409. _effective_hint = _tui_embedded_pane_clarifier(_effective_hint)
  410. if platform_key == "cron":
  411. _delivery = _cron_delivery_hint(agent)
  412. if _delivery:
  413. _effective_hint = f"{_effective_hint}\n\n{_delivery}".strip()
  414. return _effective_hint
  415. def _telegram_rich_messages_enabled() -> bool:
  416. """``rich_messages`` from the Telegram ``extra`` config; same precedence the
  417. adapter uses (top-level ``platforms.telegram.extra`` overrides
  418. ``gateway.platforms.telegram.extra`` at the leaf). False on any read failure."""
  419. try:
  420. from hermes_cli.config import load_config_readonly
  421. _cfg = load_config_readonly()
  422. _gw = (((_cfg.get("gateway") or {}).get("platforms") or {}).get("telegram") or {}).get("extra")
  423. _top = ((_cfg.get("platforms") or {}).get("telegram") or {}).get("extra")
  424. merged = {**(_gw if isinstance(_gw, dict) else {}), **(_top if isinstance(_top, dict) else {})}
  425. return bool(merged.get("rich_messages"))
  426. except Exception:
  427. return False
  428. def _zone_bits(now: Any, tz: Any) -> list[str]:
  429. """IANA key, abbreviation (if different) and UTC offset — all constant for
  430. the day, so the byte-stable date line stays cacheable."""
  431. _iana = getattr(tz, "key", None)
  432. from hermes_time import safe_strftime
  433. _abbrev = safe_strftime(now, "%Z")
  434. _offset = safe_strftime(now, "%z") # '-0400' -> 'UTC-04:00'
  435. bits = [_iana] if _iana else []
  436. if _abbrev and _abbrev != _iana:
  437. bits.append(_abbrev)
  438. if _offset:
  439. bits.append(f"UTC{_offset[:3]}:{_offset[3:]}")
  440. return bits
  441. def _timestamp_line(agent: Any) -> str:
  442. """Date-only so the prompt is byte-stable for the day; zone + offset so
  443. tools needn't guess EST vs EDT. Long-lived sessions get an "as of" line on
  444. rebuild days (the cache prefix is already invalidated at that boundary)."""
  445. from hermes_time import get_timezone as _hermes_tz, now as _hermes_now, safe_strftime
  446. now = _hermes_now()
  447. _bits = _zone_bits(now, _hermes_tz())
  448. _zone_suffix = f" ({', '.join(_bits)})" if _bits else ""
  449. _start = _session_start_like(agent, now)
  450. timestamp_line = f"Conversation started: {safe_strftime(_start, '%A, %B %d, %Y')}{_zone_suffix}"
  451. # Second line (maintainer design, salvaging #96224's anchor): long-lived sessions — Bot Mode
  452. # forever-chats, messenger channels people never close — span many days and many compactions. A lone
  453. # birth date leads the model to believe it is still living in that old day. The prompt is rebuilt at
  454. # every compaction boundary, so stamp the rebuild day too: 'started' stays anchored and byte-stable, 'as
  455. # of' refreshes exactly when the cache prefix is already being invalidated (compaction), so the added
  456. # line costs no extra cache churn. Same-day sessions skip the second line entirely — nothing to correct,
  457. # and the single-line shape stays byte-identical for the day (prefix-cache safe).
  458. if now.strftime("%Y%m%d") != _start.strftime("%Y%m%d"):
  459. timestamp_line += (f"\nToday's date (as of the last context rebuild): {safe_strftime(now, '%A, %B %d, %Y')} "
  460. "— trust this over the start date for what day it is now; query tools for exact time.")
  461. if getattr(agent, "_bot_chat_timeless_prompt", False):
  462. timestamp_line = f"Timezone: {', '.join(_bits)}" if _bits else ""
  463. trailer = (("Session ID", agent.session_id if agent.pass_session_id else None), ("Model", agent.model),
  464. ("Provider", agent.provider), ("Platform", agent.platform))
  465. return timestamp_line + "".join(f"\n{label}: {value}" for label, value in trailer if value)
  466. def _memory_parts(agent: Any) -> list[str]:
  467. """Built-in memory/USER.md blocks plus the external provider block (gated on
  468. the same check ``inject_memory_provider_tools`` uses, so we never advertise
  469. tools the toolset config gated off)."""
  470. parts: list[str] = []
  471. if agent._memory_store:
  472. for enabled, kind in ((agent._memory_enabled, "memory"), (agent._user_profile_enabled, "user")):
  473. block = agent._memory_store.format_for_system_prompt(kind) if enabled else None
  474. if block:
  475. parts.append(block)
  476. # External memory provider system prompt block (additive to built-in). Gated on the same check
  477. # ``inject_memory_provider_tools`` uses so we never advertise provider tools that the agent's toolset
  478. # configuration has already gated off (#81014).
  479. if agent._memory_manager:
  480. try:
  481. from agent.memory_manager_tools import memory_provider_tools_exposed as _mem_exposed
  482. except Exception:
  483. _mem_exposed = None
  484. if _mem_exposed is None or _mem_exposed(agent):
  485. try:
  486. _ext_mem_block = agent._memory_manager.build_system_prompt()
  487. except Exception:
  488. _ext_mem_block = None
  489. if _ext_mem_block:
  490. parts.append(_ext_mem_block)
  491. return parts
  492. def _identity_parts(agent: Any, ctx_len: Optional[int]) -> tuple[list[str], bool]:
  493. """SOUL.md (primary identity; cron keeps the persona while skipping cwd
  494. instructions, scoped to the agent's OWN home) or the default identity.
  495. Returns ``(parts, soul_loaded)``."""
  496. product_identity = _embedded_runtime.product_identity()
  497. if product_identity is not None:
  498. return [product_identity], False
  499. wants_soul = agent.load_soul_identity or not agent.skip_context_files
  500. _soul_content = _pb.load_soul_md(ctx_len, home_override=_agent_home(agent)) if wants_soul else None
  501. return ([_soul_content], True) if _soul_content else ([DEFAULT_AGENT_IDENTITY], False)
  502. def _guidance_parts(agent: Any) -> list[str]:
  503. """Universal + tool-aware + model-gated guidance blocks, each gated by its config.yaml key."""
  504. parts: list[str] = []
  505. if agent.valid_tool_names:
  506. parts += [
  507. text for flag, text in (
  508. ("_task_completion_guidance", TASK_COMPLETION_GUIDANCE),
  509. ("_parallel_tool_call_guidance", PARALLEL_TOOL_CALL_GUIDANCE),
  510. ) if getattr(agent, flag, True)
  511. ]
  512. parts.append(_tool_guidance_block(agent)) # None/empty entries are dropped by _join_tier
  513. if not agent.valid_tool_names:
  514. return parts
  515. # Steering only lands inside tool results, so only reachable with tools; a one-shot has nobody to steer it.
  516. from agent.oneshot_footprint import agent_is_oneshot
  517. if not agent_is_oneshot(agent):
  518. parts.append(STEER_CHANNEL_NOTE)
  519. # agent.tool_use_enforcement / agent.execution_guidance: "auto" (default)
  520. # matches the hardcoded model lists; true/false force; a list gives custom
  521. # model-name substrings. Execution guidance is an independent gate so
  522. # DeepSeek/Kimi/Qwen-class models get it even with enforcement off.
  523. if _model_gate(agent._tool_use_enforcement, agent.model, TOOL_USE_ENFORCEMENT_MODELS):
  524. parts.append(TOOL_USE_ENFORCEMENT_GUIDANCE)
  525. if any(g in (agent.model or "").lower() for g in ("gemini", "gemma")):
  526. parts.append(GOOGLE_MODEL_OPERATIONAL_GUIDANCE)
  527. if _model_gate(getattr(agent, "_execution_guidance", "auto"), agent.model, EXECUTION_GUIDANCE_MODELS):
  528. from agent.prompt_builder import execution_guidance_text
  529. parts.append(execution_guidance_text(agent.valid_tool_names))
  530. return parts
  531. def _alibaba_identity_part(agent: Any) -> list[str]:
  532. """Alibaba Coding Plan always reports "glm-4.7" as the model name; inject
  533. the real identity so the agent can answer correctly."""
  534. if agent.provider != "alibaba":
  535. return []
  536. _model_short = agent.model.rsplit("/", 1)[-1]
  537. return [
  538. f"You are powered by the model named {_model_short}. "
  539. f"The exact model ID is {agent.model}. "
  540. f"When asked what model you are, always answer based on this information, "
  541. f"not on any model name returned by the API."
  542. ]
  543. def _workspace_pin_key() -> str:
  544. """The directory the workspace probe inspects, which is also the prompt's ``Current working
  545. directory``: a build with no cwd bound (launch dir) and a later one binding that same dir
  546. (TUI ``/compress``) are one workspace, not two."""
  547. try:
  548. return str(resolve_context_cwd() or resolve_agent_cwd())
  549. except OSError: # deleted cwd
  550. return ""
  551. def _persisted_workspace_block(prompt: str, key: str) -> Optional[str]:
  552. """The workspace snapshot inside ``prompt`` taken for ``key`` (its ``- Root:`` is ``key`` or an
  553. ancestor); "" when the prompt has none; None when it has one for another root."""
  554. from agent.coding_context import WORKSPACE_BLOCK_HEADER
  555. head = f"\n\n{WORKSPACE_BLOCK_HEADER}\n- Root: "
  556. start = prompt.find(head)
  557. if start < 0:
  558. return ""
  559. cwd = Path(key).resolve()
  560. while start >= 0:
  561. block = prompt[start + 2:].split("\n\n", 1)[0]
  562. root = Path(block.split("\n", 2)[1][len("- Root: "):]).resolve()
  563. if root == cwd or root in cwd.parents:
  564. return block
  565. start = prompt.find(head, start + 2)
  566. return None
  567. def _session_prompt(agent: Any) -> Optional[str]:
  568. """Prompt bytes this session already sends: the cached copy, else its persisted row."""
  569. cached = getattr(agent, "_cached_system_prompt", None)
  570. if isinstance(cached, str) and cached:
  571. return cached
  572. db, session_id = getattr(agent, "_session_db", None), getattr(agent, "session_id", None)
  573. if db is None or not isinstance(session_id, str) or not session_id:
  574. return None
  575. try:
  576. row = db.get_session(session_id)
  577. except Exception:
  578. logger.debug("workspace snapshot: session row read failed (session=%s)", session_id, exc_info=True)
  579. return None
  580. prompt = row.get("system_prompt") if isinstance(row, dict) else None
  581. return prompt if isinstance(prompt, str) and prompt else None
  582. def _seed_workspace_pin(agent: Any, key: str) -> None:
  583. """Pin the snapshot the session's existing prompt already carries. An agent that did not
  584. build those bytes (resumed, or a fresh gateway/TUI agent whose first act is ``/compress``)
  585. would otherwise re-probe git at its first rebuild and rewrite the prompt for any repo that
  586. moved since session start. Only a snapshot provably taken in this cwd is adopted."""
  587. from agent.surface_switch import runtime_host_value
  588. prompt = _session_prompt(agent)
  589. if not prompt:
  590. return
  591. stored_cwd = runtime_host_value(prompt, "Current working directory")
  592. if stored_cwd and stored_cwd != key:
  593. return
  594. block = _persisted_workspace_block(prompt, key)
  595. # Only a real snapshot is adopted: a prompt without one (built on a surface without the
  596. # coding posture, or with tools off) leaves the pin open so this build captures one.
  597. if block:
  598. agent._frozen_workspace_snapshot = (key, block)
  599. def _coding_parts(agent: Any) -> tuple[list[str], list[str], list[str]]:
  600. """``(prefix, workspace, trailing)`` coding-posture blocks; all empty
  601. without tools or when probing fails (it must never block prompt build).
  602. The workspace block is a live git probe after project context, ahead of the whole
  603. volatile band; re-probing at the compaction rebuild re-emits different bytes for any
  604. repo that moved and defeats the keep-prompt fast path. So the bytes are pinned per
  605. session on the agent, keyed by the probed cwd (a gateway serves many cwds), seeded from
  606. the session's existing prompt when this agent did not build it, and replayed on
  607. rebuilds; ``reset_session_state`` drops the pin at a session boundary.
  608. """
  609. try:
  610. from agent.coding_context import coding_system_prompt_parts
  611. if not agent.valid_tool_names:
  612. return [], [], []
  613. cwd = resolve_context_cwd()
  614. cwd_key = _workspace_pin_key()
  615. if getattr(agent, "_frozen_workspace_snapshot", None) is None:
  616. _seed_workspace_pin(agent, cwd_key)
  617. pinned = getattr(agent, "_frozen_workspace_snapshot", None)
  618. # "" is a real pinned value (no workspace here) — only a cwd mismatch re-probes.
  619. replay = pinned[1] if pinned is not None and pinned[0] == cwd_key else None
  620. parts = coding_system_prompt_parts(platform=agent.platform, cwd=cwd, model=agent.model,
  621. valid_tool_names=agent.valid_tool_names, workspace_block=replay)
  622. if replay is None:
  623. agent._frozen_workspace_snapshot = (cwd_key, parts[1][0] if parts[1] else "")
  624. return parts
  625. except Exception:
  626. pass
  627. return [], [], []
  628. def _post_workspace_parts(agent: Any) -> list[str]:
  629. """Blocks that follow the worktree-specific context: environment probe
  630. (config.yaml agent.environment_probe; one line, nothing when clean, skipped
  631. for remote backends), bot-mode protocol, platform hint."""
  632. parts: list[str] = []
  633. if getattr(agent, "_environment_probe", True):
  634. try:
  635. from tools.env_probe import get_environment_probe_line
  636. parts.append(get_environment_probe_line())
  637. except Exception:
  638. pass # Probe failure must never block prompt build.
  639. if getattr(agent, "_bot_mode_protocol", True):
  640. parts.extend(_bot_mode_parts(agent))
  641. parts.append(platform_hint(agent))
  642. return parts
  643. def _context_files_part(agent: Any, ctx_len: Optional[int], soul_loaded: bool) -> list[str]:
  644. """Project context files (AGENTS.md etc.) for the context tier. TERMINAL_CWD
  645. when set (gateway); None lets discovery fall back to the launch dir. The
  646. install-tree fallback is only legitimate for cli/tui where the launch dir
  647. IS the user's shell cwd. Desktop launch artifacts skip the session cwd but
  648. still honor the profile-scoped TERMINAL_CWD; without one, the fallback guard
  649. can reject Hermes's bundled AGENTS.md."""
  650. if agent.skip_context_files:
  651. return []
  652. launch_artifact = getattr(agent, "_context_cwd_is_launch_artifact", False)
  653. cwd = resolve_context_cwd(include_session_override=not launch_artifact)
  654. return [_pb.build_context_files_prompt(
  655. cwd=cwd, skip_soul=soul_loaded, context_length=ctx_len,
  656. allow_install_tree_fallback=agent.platform in ("cli", "tui"), home_override=_agent_home(agent))]
  657. def _join_tier(parts: list[Optional[str]]) -> str:
  658. """Join non-empty parts; None/blank entries are dropped."""
  659. return "\n\n".join(p.strip() for p in parts if p and p.strip())
  660. def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) -> dict[str, str]:
  661. """Assemble the system prompt as three ordered cache tiers: ``stable`` (identity,
  662. guidance and the coding brief), ``context`` (caller ``system_message``, project
  663. context files, workspace snapshot and remaining workspace guidance) and
  664. ``volatile`` (skills index, memory, user profile, external memory block,
  665. timestamp line, runtime environment hints). Worktree-dependent blocks follow project context so a
  666. shared context file can remain in the longest common prefix across worktrees.
  667. Never re-rendered mid-session."""
  668. # Model context window scales the context-file caps; stable per conversation.
  669. _cc_len = getattr(getattr(agent, "context_compressor", None), "context_length", None)
  670. _ctx_len = _cc_len if isinstance(_cc_len, int) and _cc_len > 0 else None
  671. # ── Stable tier ────────────────────────────────────────────────
  672. stable_parts, _soul_loaded = _identity_parts(agent, _ctx_len)
  673. # The skill_view() pointer dangles without skill tools OR without the
  674. # hermes-agent skill installed, so the variant is chosen after the skills
  675. # index is built; this slot holds its position.
  676. _help_guidance_slot = len(stable_parts)
  677. product_help = _embedded_runtime.product_help_guidance()
  678. stable_parts.append(product_help or HERMES_AGENT_HELP_GUIDANCE_NO_SKILLS)
  679. stable_parts.extend(_guidance_parts(agent))
  680. skills_prompt = _skills_prompt(agent)
  681. # Skill-pointer variant requires BOTH skill_view AND the hermes-agent skill
  682. # in the rendered index (pure string check — inherits the index's stability).
  683. if not product_help and "skill_view" in (agent.valid_tool_names or set()) and "- hermes-agent:" in skills_prompt:
  684. stable_parts[_help_guidance_slot] = HERMES_AGENT_HELP_GUIDANCE
  685. stable_parts.extend(_alibaba_identity_part(agent))
  686. # Pinned skills are per-agent constants (resolved once), so they live in the stable prefix.
  687. stable_parts.extend(_auto_load_parts(agent))
  688. # Coding posture: the operating brief stays in the stable prefix. The
  689. # environment block contains the current cwd/backend and belongs after
  690. # project context, not ahead of a large shared AGENTS.md block.
  691. environment_hints = _pb.build_environment_hints() if _embedded_runtime.environment_hints_enabled() else ""
  692. coding_prefix_parts, coding_workspace_parts, coding_trailing_parts = _coding_parts(agent)
  693. stable_parts.extend(coding_prefix_parts)
  694. post_workspace_parts = _post_workspace_parts(agent)
  695. # ── Context tier (project/worktree-dependent, may change between sessions) ──
  696. context_parts: list[str] = []
  697. # ephemeral_system_prompt is injected at API-call time only, never cached.
  698. if system_message is not None:
  699. context_parts.append(system_message)
  700. context_parts.extend(_context_files_part(agent, _ctx_len, _soul_loaded))
  701. if coding_workspace_parts:
  702. context_parts.extend([*coding_workspace_parts, *coding_trailing_parts, *post_workspace_parts])
  703. else:
  704. # Preserve the stable placement for non-workspace sessions; there is no
  705. # worktree snapshot whose later position would improve their prefix.
  706. stable_parts.extend([*coding_trailing_parts, *post_workspace_parts])
  707. # ── Volatile tier (most likely to differ on a rebuild; kept last so the stable prefix stays reusable) ──
  708. # Skills are runtime-mutable, so the index leads the volatile band: on a longest-prefix
  709. # backend an unchanged index stays inside the reused prefix; a changed one re-prefills from here.
  710. volatile_parts: list[str] = [skills_prompt, *_memory_parts(agent)]
  711. # Plugin sections are confined to one coarse anchor in the volatile tail so
  712. # a resumed process can reconstruct the stable prefix without re-running plugins.
  713. volatile_parts.extend(_plugin_section_blocks(_frozen_plugin_prompt_sections(agent), "after_memory"))
  714. # The profile line names this home's path, so it rides in the volatile tier: the stable
  715. # prefix then stays byte-identical across every profile (and home) on the host.
  716. volatile_parts.append(_active_profile_line(agent))
  717. volatile_parts.append(_timestamp_line(agent))
  718. # Keep the renderer-owned runtime anchor after all user/plugin prose so quoted
  719. # host examples cannot shadow it during persisted-prompt validation.
  720. if environment_hints:
  721. # Embedder hints are prose too; reserve the delimiter for the renderer.
  722. environment_hints = environment_hints.replace(_pb.RUNTIME_ENVIRONMENT_HEADING, "> " + _pb.RUNTIME_ENVIRONMENT_HEADING)
  723. volatile_parts.append(f"{_pb.RUNTIME_ENVIRONMENT_HEADING}\n\n{environment_hints}\n\n{_pb.RUNTIME_ENVIRONMENT_END}")
  724. return {"stable": _join_tier(stable_parts), "context": _join_tier(context_parts), "volatile": _join_tier(volatile_parts)}
  725. def build_system_prompt(agent: Any, system_message: Optional[str] = None) -> str:
  726. """Assemble the full prompt; cached on ``agent._cached_system_prompt`` and
  727. only rebuilt after compression. Tiers are ordered stable -> context ->
  728. volatile so implicit longest-prefix caches keep the unchanged scaffold."""
  729. parts = build_system_prompt_parts(agent, system_message=system_message)
  730. agent._cached_system_prompt_static = parts["stable"]
  731. # Surface context-file truncation warnings in chat, not only in logs.
  732. for warning in drain_truncation_warnings():
  733. agent._emit_diagnostic_status(warning)
  734. return "\n\n".join(p for p in (parts["stable"], parts["context"], parts["volatile"]) if p)
  735. def invalidate_system_prompt(agent: Any) -> None:
  736. """Force a rebuild on the next turn (after compression): reload memory from
  737. disk and clear the frozen plugin snapshot (previous bytes stashed as the
  738. fail-open fallback) so plugins re-render at the same boundary.
  739. Called after context compression events. Also reloads memory from disk so the rebuilt prompt captures
  740. any writes from this session, and clears the frozen plugin-section snapshot so plugins re-render at the
  741. same boundary (maintainer-directed, #95681 arc): a plugin section is just another prompt block carrying
  742. state — freezing it while memory, skills, and guidance refresh would recreate the stale-block disease
  743. inside plugin-land. The previous bytes are stashed so a plugin whose render RAISES falls back to its
  744. last good section instead of vanishing (fail-open guard, not a freeze).
  745. """
  746. agent._cached_system_prompt = None
  747. agent._cached_system_prompt_static = None
  748. if hasattr(agent, "_plugin_system_prompt_sections_snapshot"):
  749. agent._plugin_system_prompt_sections_previous = agent._plugin_system_prompt_sections_snapshot
  750. del agent._plugin_system_prompt_sections_snapshot
  751. if agent._memory_store:
  752. agent._memory_store.load_from_disk()
  753. def reconstruct_static_prefix(agent: Any, system_message: Optional[str] = None, *, log_label: str = "restore") -> None:
  754. """Reconstruct ``_cached_system_prompt_static`` for a stored prompt.
  755. Only the full prompt is persisted, so restore / keep-prompt compression /
  756. mid-turn failover to a cache-on provider must rebuild the stable tier to
  757. regain the ``[static, volatile]`` layout. The rebuilt tier is used ONLY
  758. when the stored prompt literally starts with it; otherwise static stays
  759. None and the stored bytes are sent untouched. A failed rebuild is memoized
  760. per stored prompt so the retry-loop hot path doesn't redo the file I/O."""
  761. stored = getattr(agent, "_cached_system_prompt", None)
  762. existing = getattr(agent, "_cached_system_prompt_static", None)
  763. if (
  764. not getattr(agent, "_use_prompt_caching", False)
  765. or not isinstance(stored, str) or not stored
  766. or (isinstance(existing, str) and existing and stored.startswith(existing))
  767. or getattr(agent, "_static_rebuild_failed_for", None) == stored
  768. ):
  769. return
  770. try:
  771. static = build_system_prompt_parts(agent, system_message=system_message)["stable"]
  772. if static and stored.startswith(static):
  773. agent._cached_system_prompt_static = static
  774. agent._static_rebuild_failed_for = None
  775. return
  776. except Exception:
  777. logger.debug("static system-prefix reconstruction failed on %s", log_label, exc_info=True)
  778. agent._cached_system_prompt_static = None
  779. agent._static_rebuild_failed_for = stored
  780. def format_tools_for_system_message(agent: Any) -> str:
  781. """JSON tool definitions in the trajectory format."""
  782. if not agent.tools:
  783. return "[]"
  784. return json.dumps([{"name": t["function"]["name"], "description": t["function"].get("description", ""),
  785. "parameters": t["function"].get("parameters", {}),
  786. "required": None} # Match the format in the example
  787. for t in agent.tools], ensure_ascii=False)
  788. __all__ = [
  789. "build_system_prompt",
  790. "build_system_prompt_parts",
  791. "format_tools_for_system_message",
  792. "invalidate_system_prompt",
  793. "platform_hint",
  794. "restore_plugin_prompt_sections",
  795. ]