onboarding_record.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. """Where a first-run onboarding run lives: one ``onboarding_run`` key in the session's
  2. ``sessions.model_config`` (no schema change; a compression rotation carries it, see
  3. ``hermes_state_compression._CONVERSATION_MODEL_CONFIG_KEYS``).
  4. ``advance`` is the one writer after ``start``: load, ``onboarding_flow.apply``, save, and when the
  5. run ends write the install-level flag in the root config so the next launch does not reopen it.
  6. """
  7. from __future__ import annotations
  8. import json
  9. import logging
  10. import time
  11. import uuid
  12. from collections.abc import Callable, Mapping
  13. from typing import Any
  14. from agent.onboarding_flow import (
  15. Applied, End, Event, Facts, Step, applies_to, apply, is_active, new_record,
  16. )
  17. from agent.onboarding_text import reminder
  18. logger = logging.getLogger(__name__)
  19. KEY = "onboarding_run"
  20. # Told when a run stops being in progress: ``{run_id, stored_session_id, outcome}``. The gateway sends
  21. # it to every window (tui_gateway/methods_onboarding.py::register).
  22. _ended_listeners: list[Callable[[dict], None]] = []
  23. def on_ended(listener: Callable[[dict], None]) -> None:
  24. _ended_listeners.append(listener)
  25. def load(db, session_id: str) -> dict | None:
  26. record = db.get_session_model_config_value(session_id, KEY) if db is not None and session_id else None
  27. return record if isinstance(record, dict) else None
  28. def _announce(run_id: str | None, session_id: str, outcome: str) -> None:
  29. ended = {"run_id": run_id or "", "stored_session_id": session_id, "outcome": outcome}
  30. for listener in _ended_listeners:
  31. listener(ended)
  32. def _transition(db, session_id: str, event: Event) -> Step | None:
  33. """Apply *event* and write the result in one database transaction at the compression tip, so Skip
  34. setup pressed while a card answer is being applied is never overwritten by the older copy, and an id
  35. read before a rotation published still lands on the copy the chat reads. An ended run then closes the
  36. install flag (a Skip or Done retried after a failed config write repairs it), unless another run
  37. is still open: the flag belongs to that run, and an old chat must not end it."""
  38. holder: dict[str, Any] = {}
  39. def update(current: Any) -> Any:
  40. holder.clear()
  41. if not isinstance(current, dict):
  42. return current
  43. holder["was_active"] = is_active(current)
  44. holder["step"] = apply(current, event, Facts.from_stored(current["facts"]), now=time.time())
  45. return holder["step"].record
  46. db.update_conversation_model_config_value(session_id, KEY, update)
  47. step = holder.get("step")
  48. # Told before the flag write, which can fail: the record already says the run ended.
  49. if step is not None and holder["was_active"] and not is_active(step.record):
  50. _announce(step.record.get("run_id"), session_id, step.record["ended_by"])
  51. if step is not None and not is_active(step.record) and active_session_id(db) is None:
  52. _close_install_flag()
  53. return step
  54. def _close_install_flag() -> None:
  55. from hermes_cli import config as config_mod
  56. from hermes_cli.onboarding_run import set_run
  57. from hermes_constants import get_default_hermes_root
  58. from agent.onboarding import PROFILE_BUILD_FLAG
  59. section = config_mod.read_user_config_raw(get_default_hermes_root() / "config.yaml").get("onboarding")
  60. section = section if isinstance(section, dict) else {}
  61. seen = section.get("seen") if isinstance(section.get("seen"), dict) else {}
  62. if section.get("run") is not False or not seen.get(PROFILE_BUILD_FLAG):
  63. set_run(False, mark_profile_offered=True)
  64. def start(db, session_id: str, facts: Facts) -> dict:
  65. """Write a fresh run record (the row must exist) and mark the install as mid-onboarding, so a
  66. crash or a quit before the end runs onboarding again on the next launch (which starts over:
  67. ``onboarding.start`` with ``fresh_launch``)."""
  68. from hermes_cli.onboarding_run import set_run
  69. record = new_record(facts, now=time.time(), run_id=uuid.uuid4().hex)
  70. db.patch_session_model_config(session_id, {KEY: record})
  71. set_run(True)
  72. return record
  73. def advance(db, session_id: str, event: Event) -> Step:
  74. """Apply one event to the stored run; LookupError when this session has no run."""
  75. step = _transition(db, session_id, event) if db is not None and session_id else None
  76. if step is None:
  77. raise LookupError(f"session {session_id} has no onboarding run")
  78. return step
  79. def open_session_ids(db) -> list[str]:
  80. """The chats whose run is still in progress, newest first. Rotation leaves the active copy on the
  81. compression parent, so each id is read at its compression tip."""
  82. tips: set[str] = set()
  83. open_ids: list[str] = []
  84. for sid in db.session_ids_with_model_config_key(KEY):
  85. tip = db.resolve_resume_session_id(sid) or sid
  86. if tip not in tips:
  87. tips.add(tip)
  88. if is_active(load(db, tip)):
  89. open_ids.append(tip)
  90. return open_ids
  91. def active_session_id(db) -> str | None:
  92. return next(iter(open_session_ids(db)), None)
  93. def delete_chat(db, session_id: str, delete: Callable[[], bool]) -> bool:
  94. """Run *delete*; when it removed the chat holding the live run, end that run (``deleted``) on every
  95. compression copy and tell windows once. Only the compression tip holds the live run, so deleting an
  96. older copy ends nothing. The install flag closes before the delete when no other run is open: a
  97. failed flag write keeps the chat for a retry, and a refused delete sets the flag again."""
  98. from hermes_cli.onboarding_run import set_run
  99. record = load(db, session_id)
  100. live = is_active(record) and (db.resolve_resume_session_id(session_id) or session_id) == session_id
  101. last = live and all(sid == session_id for sid in open_session_ids(db))
  102. if last:
  103. _close_install_flag()
  104. deleted = False
  105. try:
  106. deleted = delete()
  107. finally:
  108. if last and not deleted:
  109. set_run(True)
  110. if not deleted:
  111. return False
  112. if live:
  113. # Each older copy is written on its own row: a tip-routed write would land every copy on the
  114. # newest one left.
  115. for sid in db.session_ids_with_model_config_key(KEY) if record.get("run_id") else ():
  116. if ((older := load(db, sid)) or {}).get("run_id") == record["run_id"]:
  117. db.patch_session_model_config(sid, {KEY: _end_deleted(older)})
  118. _announce(record.get("run_id"), session_id, "deleted")
  119. return True
  120. def _end_deleted(current: Any) -> Any:
  121. if not is_active(current):
  122. return current
  123. return apply(current, End("deleted"), Facts.from_stored(current["facts"]), now=time.time()).record
  124. def observe_tool_result(agent, name: str, args: Mapping[str, Any], result: Any) -> Any:
  125. """Settle a beat from a general tool's result (``set_theme``, ``manage_connections`` display,
  126. ``gui_tour``). Runs for every tool result; only an onboarding chat (one whose agent carries
  127. ``setup_beat``) reads its record. Returns *result*, with the next-step reminder added when it
  128. settled a beat."""
  129. if not applies_to(name) or "setup_beat" not in (getattr(agent, "valid_tool_names", None) or ()):
  130. return result
  131. db, session_id = getattr(agent, "_session_db", None), getattr(agent, "session_id", "") or ""
  132. try:
  133. parsed = json.loads(result) if isinstance(result, str) else result
  134. if isinstance(parsed, dict) and load(db, session_id) is not None:
  135. step = advance(db, session_id, Applied(name, dict(args or {}), parsed))
  136. text = reminder(step.reminder, step.record, Facts.from_stored(step.record["facts"]))
  137. if text and isinstance(result, str):
  138. return json.dumps({**parsed, "reminder": text}, ensure_ascii=False)
  139. except Exception:
  140. logger.warning("onboarding: %s result did not update the run record", name, exc_info=True)
  141. return result