Skip to content

The agent that grows with you

feat(onboarding): run record in sessions.model_config and the safe facts

alt-glitchbd0bc527570e
diff --git a/agent/onboarding.py b/agent/onboarding.py
index 3dc1cc0e2dc..a96367e214b 100644
--- a/agent/onboarding.py
+++ b/agent/onboarding.py
@@ -1,8 +1,12 @@
-"""Contextual first-touch onboarding hints.
+"""Contextual first-touch onboarding hints, and the entry points of desktop first-run onboarding.
Each hint is shown once per install the *first* time a user hits a behavior
fork, tracked in ``config.yaml`` under ``onboarding.seen.<flag>``. Kept tiny and
dependency-free so both the CLI and gateway can import it.
+
+First-run onboarding (one chat in the default profile, driven by ``setup_beat``) lives in the
+siblings: ``onboarding_flow`` (beats and the run record, pure), ``onboarding_text`` (the words),
+``onboarding_facts`` (the safe facts) and ``onboarding_record`` (where the run is stored).
"""
from __future__ import annotations
@@ -11,6 +15,8 @@ import logging
from pathlib import Path
from typing import Any, Mapping, Optional
+from agent.onboarding_record import observe_tool_result
+
logger = logging.getLogger(__name__)
@@ -160,6 +166,7 @@ def first_contact_turn_note(
message: str,
command: str = "/initiate-setup",
setup_handoff: bool = False,
+ onboarding_run_active: bool = False,
) -> Optional[str]:
"""Return a one-shot sidecar note for the install's first-ever message.
@@ -169,11 +176,13 @@ def first_contact_turn_note(
return the plain intro note. Returns ``None`` when this is not the first
contact (non-empty session history or prior sessions exist on the install). ``setup_handoff``
marks the task chat setup started (``start_chat``), told by the caller, never read from the text.
+ ``onboarding_run_active``: the chat is running first-run onboarding, whose opening replaces this note.
"""
from agent.initiate_setup_prompt import HEADER
from hermes_cli.profiles import SETUP_PROFILE_MARKER
- if not session_history_empty or install_has_prior_sessions or message.startswith(HEADER):
+ if (not session_history_empty or install_has_prior_sessions or onboarding_run_active
+ or message.startswith(HEADER)):
return None
# The task chat setup hands off to is the user's first chat in their own profile; setup already ran.
if setup_handoff:
@@ -265,6 +274,7 @@ __all__ = [
"first_contact_turn_note",
"is_seen",
"mark_seen",
+ "observe_tool_result",
"openclaw_residue_hint_cli",
"profile_build_directive",
"profile_build_mode",
diff --git a/agent/onboarding_facts.py b/agent/onboarding_facts.py
new file mode 100644
index 00000000000..6f6a6a99cc6
--- /dev/null
+++ b/agent/onboarding_facts.py
@@ -0,0 +1,35 @@
+"""The safe facts (class A) a first-run onboarding is built from, read once when the run starts.
+
+No consent is needed for any of them: OS, architecture, machine kind, the NVIDIA platform, the
+locale, which onboarding plugins this OS runs, and whether tours are on. They describe the machine
+running this backend; the desktop says when that is not the user's own computer (``facts_source``).
+"""
+
+from __future__ import annotations
+
+from agent.onboarding_flow import Facts
+
+_OS = {"darwin": "macos", "win32": "windows"}
+
+
+def read_facts(*, facts_source: str = "local", locale: str | None = None) -> Facts:
+ """``locale``: the desktop's UI language, preferred over the backend OS locale for wording."""
+ from hermes_cli.plugin_catalog_presence import onboarding_names
+ from hermes_platform.host.summary import summary
+ from tools.tour_tool import check_tours_enabled
+
+ host = summary()
+ machine = host["machine"]
+ return Facts(
+ os=_OS.get(machine.get("os_family", ""), "linux"), arch=machine.get("native_arch", ""),
+ machine_kind=host["machine_kind"], nvidia_platform=host["nvidia_platform"],
+ facts_source="remote" if facts_source == "remote" else "local", locale=locale or host["locale"],
+ plugins=tuple(onboarding_names()), tours=check_tours_enabled())
+
+
+def suggested_name() -> str | None:
+ """The OS account's real name for the name card. It goes to the card only: the model sees it
+ when the user picks it."""
+ from hermes_platform.host.summary import summary
+
+ return summary()["full_name"]
diff --git a/agent/onboarding_record.py b/agent/onboarding_record.py
new file mode 100644
index 00000000000..b9aa3053760
--- /dev/null
+++ b/agent/onboarding_record.py
@@ -0,0 +1,88 @@
+"""Where a first-run onboarding run lives: one ``onboarding_run`` key in the session's
+``sessions.model_config`` (no schema change; a compression rotation carries it, see
+``hermes_state_compression._CONVERSATION_MODEL_CONFIG_KEYS``).
+
+``advance`` is the one writer after ``start``: load, ``onboarding_flow.apply``, save, and when the
+run ends write the install-level flag in the root config so the next launch does not reopen it.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import time
+from collections.abc import Mapping
+from typing import Any
+
+from agent.onboarding_flow import (
+ Applied, Event, Facts, Step, applies_to, apply, expire, is_active, new_record,
+)
+
+logger = logging.getLogger(__name__)
+
+KEY = "onboarding_run"
+
+
+def load(db, session_id: str) -> dict | None:
+ """The run record, with the quiet-spell fallback applied (and saved) when it is due."""
+ record = db.get_session_model_config_value(session_id, KEY) if db is not None and session_id else None
+ if not isinstance(record, dict):
+ return None
+ expired = expire(record, now=time.time())
+ if expired is not record:
+ _save(db, session_id, record, expired)
+ return expired
+
+
+def _save(db, session_id: str, before: Mapping[str, Any], after: dict) -> None:
+ db.patch_session_model_config(session_id, {KEY: after})
+ if is_active(before) and not is_active(after):
+ _close_install_flag()
+
+
+def _close_install_flag() -> None:
+ from hermes_cli.onboarding_run import set_run
+
+ set_run(False, mark_profile_offered=True)
+
+
+def start(db, session_id: str, facts: Facts) -> dict:
+ """Write a fresh run record (the row must exist) and mark the install as mid-onboarding, so a
+ crash before the end reopens this chat on the next launch."""
+ from hermes_cli.onboarding_run import set_run
+
+ record = new_record(facts, now=time.time())
+ db.patch_session_model_config(session_id, {KEY: record})
+ set_run(True)
+ return record
+
+
+def advance(db, session_id: str, event: Event) -> Step:
+ """Apply one event to the stored run; LookupError when this session has no run."""
+ record = load(db, session_id)
+ if record is None:
+ raise LookupError(f"session {session_id} has no onboarding run")
+ step = apply(record, event, Facts.from_stored(record["facts"]), now=time.time())
+ if step.record != record:
+ _save(db, session_id, record, step.record)
+ return step
+
+
+def active_session_id(db) -> str | None:
+ """The newest session whose run is still in progress."""
+ return next((sid for sid in db.session_ids_with_model_config_key(KEY) if is_active(load(db, sid))), None)
+
+
+def observe_tool_result(agent, name: str, args: Mapping[str, Any], result: Any) -> None:
+ """Settle a beat from a general tool's result (``set_theme``, ``manage_connections`` display,
+ ``gui_tour``). Runs for every tool result; only an onboarding chat (one whose agent carries
+ ``setup_beat``) reads its record."""
+ if not applies_to(name) or "setup_beat" not in (getattr(agent, "valid_tool_names", None) or ()):
+ return
+ db, session_id = getattr(agent, "_session_db", None), getattr(agent, "session_id", "") or ""
+ try:
+ parsed = json.loads(result) if isinstance(result, str) else result
+ if isinstance(parsed, dict) and load(db, session_id) is not None:
+ advance(db, session_id, Applied(name, dict(args or {}), parsed))
+ except Exception:
+ logger.warning("onboarding: %s result did not update the run record", name, exc_info=True)
diff --git a/hermes_cli/plugin_catalog_presence.py b/hermes_cli/plugin_catalog_presence.py
index c2a30d3647d..0aa262f1fb8 100644
--- a/hermes_cli/plugin_catalog_presence.py
+++ b/hermes_cli/plugin_catalog_presence.py
@@ -124,18 +124,27 @@ def presence(entry: Any) -> Presence:
return min(found, key=lambda p: rank[p.state]) if found else UNKNOWN
-def onboarding_entries() -> list[dict[str, Any]]:
- """Catalog entries curated for the onboarding card (``onboarding: true``) that this OS can run,
- each with its app state. Platform mismatch is the only exclusion; a missing app is reported."""
+def _onboarding_catalog() -> list:
+ """Catalog entries curated for onboarding (``onboarding: true``) that this OS can run."""
from hermes_cli.plugin_catalog import load_catalog_live
from hermes_cli.plugins_cmd_catalog import normalized_platforms
from hermes_platform.host.facts import os_family
here = os_family()
+ return [entry for entry in load_catalog_live()
+ if entry.onboarding and (not entry.platforms or here in normalized_platforms(entry.platforms))]
+
+
+def onboarding_names() -> list[str]:
+ """The onboarding plugins this OS runs, by catalog name; no presence probe."""
+ return [entry.name for entry in _onboarding_catalog()]
+
+
+def onboarding_entries() -> list[dict[str, Any]]:
+ """Catalog entries curated for the onboarding card (``onboarding: true``) that this OS can run,
+ each with its app state. Platform mismatch is the only exclusion; a missing app is reported."""
rows = []
- for entry in load_catalog_live():
- if not entry.onboarding or (entry.platforms and here not in normalized_platforms(entry.platforms)):
- continue
+ for entry in _onboarding_catalog():
found = presence(entry)
rows.append({
"name": entry.name,
diff --git a/hermes_state_compression.py b/hermes_state_compression.py
index f80b91980c1..6539d5690fa 100644
--- a/hermes_state_compression.py
+++ b/hermes_state_compression.py
@@ -81,6 +81,11 @@ def _claim_lease_row(conn, table: str, key_col: str, key: str, holder: str, now:
_CHAIN_CAP = 1000
+# model_config keys that belong to the whole conversation, not one compression segment: a rotation
+# carries them onto the child (per-segment keys such as usage anchors stay behind).
+_CONVERSATION_MODEL_CONFIG_KEYS = ("onboarding_run",)
+
+
class SessionCompressionMixin:
"""Compression lineage, cooldown/streak counters, locks and turn leases."""
@@ -217,6 +222,10 @@ class SessionCompressionMixin:
"""INSERT the compression child's ``sessions`` row copied from *parent*. Same contract as
_insert_session_row's compression-fork backfill: the child stays on the parent's profile and keeps
gateway routing/origin columns; no owner on either side -> this store's profile."""
+ from hermes_state_sessions import _parse_model_config
+ carried = {key: value for key, value in _parse_model_config(parent["model_config"]).items()
+ if key in _CONVERSATION_MODEL_CONFIG_KEYS}
+ model_config = {**carried, **(model_config or {})}
system_prompt_hash = self._store_system_prompt(conn, system_prompt)
# The child continues the parent's tools[] pin (the compaction refresh re-pinned it just
# before publish), or its first hop to another surface re-derives the array.
@@ -283,7 +292,7 @@ class SessionCompressionMixin:
"""SELECT ended_at, end_reason, cwd, git_branch, git_repo_root,
user_id, session_key, chat_id, chat_type,
thread_id, display_name, origin_json, profile_name, tool_names,
- archived, auto_archived, pinned
+ archived, auto_archived, pinned, model_config
FROM sessions WHERE id = ?""",
(parent_session_id,),
).fetchone()
diff --git a/hermes_state_sessions.py b/hermes_state_sessions.py
index a3435dd5f3d..816903a827e 100644
--- a/hermes_state_sessions.py
+++ b/hermes_state_sessions.py
@@ -832,6 +832,14 @@ class SessionSessionsMixin:
session = self.get_session(session_id) or {}
return _parse_model_config(session.get("model_config")).get(key, default)
+ def session_ids_with_model_config_key(self, key: str) -> list[str]:
+ """Ids of the sessions whose model_config carries ``key``, newest first."""
+ with self._read_ctx() as conn:
+ rows = conn.execute(
+ f"SELECT id FROM sessions WHERE {_sql_json_extract('model_config', '$.' + key)} IS NOT NULL "
+ "ORDER BY started_at DESC").fetchall()
+ return [row["id"] for row in rows]
+
def update_session_runtime_lock(
self, session_id: str, *, model: Optional[str] = None, provider: Optional[str] = None,
model_options: Optional[dict[str, Any]] = None, route_source: Optional[str] = None,