Skip to content

The agent that grows with you

feat(onboarding): setup_beat, the one onboarding-only tool

alt-glitchd8cefac352b4
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 57b84fac893..b3e982ca600 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -2352,7 +2352,7 @@ _CALLBACK_PARAMS = (
"thinking_callback", "reasoning_callback", "clarify_callback",
"read_terminal_callback", "read_preview_callback", "drive_preview_callback",
"read_window_below_callback", "connection_callback", "tour_callback",
- "setup_choose_callback", "step_callback", "stream_delta_callback", "interim_assistant_callback",
+ "setup_choose_callback", "setup_beat_callback", "step_callback", "stream_delta_callback", "interim_assistant_callback",
"status_callback", "notice_callback", "notice_clear_callback",
"event_callback", "reaction_callback", "tool_gen_callback",
)
@@ -2375,7 +2375,7 @@ def init_agent(
clarify_callback: Callable[..., Any] | None = None, read_terminal_callback: Callable[..., Any] | None = None,
read_preview_callback: Callable[..., Any] | None = None, drive_preview_callback: Callable[..., Any] | None = None,
read_window_below_callback: Callable[..., Any] | None = None, connection_callback: Callable[..., Any] | None = None,
- tour_callback: Callable[..., Any] | None = None, setup_choose_callback: Callable[..., Any] | None = None, step_callback: Callable[..., Any] | None = None,
+ tour_callback: Callable[..., Any] | None = None, setup_choose_callback: Callable[..., Any] | None = None, setup_beat_callback: Callable[..., Any] | None = None, step_callback: Callable[..., Any] | None = None,
stream_delta_callback: Callable[..., Any] | None = None, interim_assistant_callback: Callable[..., Any] | None = None,
tool_gen_callback: Callable[..., Any] | None = None, status_callback: Callable[..., Any] | None = None,
notice_callback: Callable[..., Any] | None = None, notice_clear_callback: Callable[..., Any] | None = None,
diff --git a/agent/inline_tool_executors.py b/agent/inline_tool_executors.py
index a5407865642..768f284acef 100644
--- a/agent/inline_tool_executors.py
+++ b/agent/inline_tool_executors.py
@@ -226,6 +226,16 @@ def _manage_catalog(agent, args: dict, ctx: InlineToolContext) -> Any:
)
+def _setup_beat(agent, args: dict, ctx: InlineToolContext) -> Any:
+ # The run record lives on the session row and the card callback on the agent.
+ from tools.setup_beat_tool import setup_beat_tool
+
+ return setup_beat_tool(
+ args, db=getattr(agent, "_session_db", None), session_id=getattr(agent, "session_id", None) or "",
+ tool_call_id=ctx.tool_call_id or "", callback=getattr(agent, "setup_beat_callback", None),
+ )
+
+
def _setup_mcp_shim(agent, args: dict, ctx: InlineToolContext) -> Any:
# Replay shim for conversations whose cached prompt still names setup_mcp.
# Not in _LEGACY_TOOL_ALIASES: inline tools bypass handle_function_call.
@@ -284,6 +294,7 @@ _RAW_INLINE_TOOL_EXECUTORS: dict[str, InlineToolExecutor] = {
callback=lambda agent, ctx: getattr(agent, "setup_choose_callback", None),
session_id=lambda agent, ctx: getattr(agent, "session_id", None),
),
+ "setup_beat": _setup_beat,
"manage_connections": _manage_connections,
"manage_catalog": _manage_catalog,
"setup_mcp": _setup_mcp_shim,
diff --git a/agent/tool_dispatch_helpers.py b/agent/tool_dispatch_helpers.py
index 297cd635bf5..498034239c2 100644
--- a/agent/tool_dispatch_helpers.py
+++ b/agent/tool_dispatch_helpers.py
@@ -27,7 +27,7 @@ from tools.threat_patterns import scan_for_threats
logger = logging.getLogger(__name__)
# Interactive / user-facing tools never run concurrently: any of these in a batch is a barrier.
-_NEVER_PARALLEL_TOOLS = frozenset({"clarify", "manage_connections", "manage_catalog", "setup_choose"})
+_NEVER_PARALLEL_TOOLS = frozenset({"clarify", "manage_connections", "manage_catalog", "setup_choose", "setup_beat"})
# Read-only tools with no shared mutable session state.
_PARALLEL_SAFE_TOOLS = frozenset({
diff --git a/agent/tool_executor.py b/agent/tool_executor.py
index f0783edaa75..556e01069e7 100644
--- a/agent/tool_executor.py
+++ b/agent/tool_executor.py
@@ -33,6 +33,7 @@ from agent.display import (
from agent.compression_marker import _COMPRESSION_MARKER_PREFIX
from agent.interrupt_control import _REASON_USER_INTERRUPT, interrupt_skip_wording
from agent.message_sanitization import coalesce_tool_call_id
+from agent.onboarding import observe_tool_result as observe_onboarding_result
from agent.inline_tool_executors import (
INLINE_TOOL_EXECUTORS,
InlineToolContext,
@@ -1086,6 +1087,8 @@ def _commit_tool_result(
from hermes_cli.observability.shared_metrics_harness import observe_tool_outcome
observe_tool_outcome(agent, function_name, is_error)
+ if not (blocked or is_error):
+ observe_onboarding_result(agent, function_name, function_args, function_result)
if observed:
if not blocked:
function_result = agent._append_guardrail_observation(
diff --git a/agent/turn_tool_round.py b/agent/turn_tool_round.py
index 412b6cf8a4b..457fe024d1b 100644
--- a/agent/turn_tool_round.py
+++ b/agent/turn_tool_round.py
@@ -21,6 +21,9 @@ logger = logging.getLogger("agent.conversation_loop")
# Post-response housekeeping tools: a round made only of these mutes tool progress.
_HOUSEKEEPING_TOOLS = frozenset({"memory", "todo_list", "skill_manage", "session_search"})
+# Rounds whose visible line is the turn's reply if the follow-up is empty (no empty-response nudge):
+# housekeeping, and setup_beat, whose card already blocked for the user's answer.
+_LINE_IS_REPLY_TOOLS = _HOUSEKEEPING_TOOLS | {"setup_beat"}
@dataclass
@@ -263,6 +266,8 @@ def stage_tool_call_message(
_all_housekeeping = all(
tc.function.name in _HOUSEKEEPING_TOOLS for tc in assistant_message.tool_calls
)
+ # The line written with a blocking card is the reply when the follow-up comes back empty.
+ _line_is_reply = all(tc.function.name in _LINE_IS_REPLY_TOOLS for tc in assistant_message.tool_calls)
if assistant_message.tool_calls and not _all_housekeeping:
agent._last_content_with_tools = None
agent._last_content_tools_all_housekeeping = False
@@ -273,7 +278,7 @@ def stage_tool_call_message(
# post-response housekeeping; substantive tools keep output on.
if turn_content and agent._has_content_after_think_block(turn_content):
agent._last_content_with_tools = turn_content
- agent._last_content_tools_all_housekeeping = _all_housekeeping
+ agent._last_content_tools_all_housekeeping = _line_is_reply
if _all_housekeeping and agent._has_stream_consumers():
agent._mute_post_response = True
elif agent._should_emit_quiet_tool_messages():
diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
index 4b1621a1dd9..a093aa7dd98 100644
--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
@@ -3651,6 +3651,7 @@
"image_gen",
"kanban",
"memory",
+ "onboarding",
"project",
"safe",
"search",
diff --git a/run_agent.py b/run_agent.py
index 7d38b2e1fb2..97c7d7184b2 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -254,7 +254,7 @@ class AIAgent(
read_terminal_callback: Callable[..., Any] | None = None, read_preview_callback: Callable[..., Any] | None = None,
drive_preview_callback: Callable[..., Any] | None = None, read_window_below_callback: Callable[..., Any] | None = None,
connection_callback: Callable[..., Any] | None = None, tour_callback: Callable[..., Any] | None = None,
- setup_choose_callback: Callable[..., Any] | None = None, step_callback: Callable[..., Any] | None = None,
+ setup_choose_callback: Callable[..., Any] | None = None, setup_beat_callback: Callable[..., Any] | None = None, step_callback: Callable[..., Any] | None = None,
stream_delta_callback: Callable[..., Any] | None = None, interim_assistant_callback: Callable[..., Any] | None = None,
tool_gen_callback: Callable[..., Any] | None = None, status_callback: Callable[..., Any] | None = None,
notice_callback: Callable[..., Any] | None = None, notice_clear_callback: Callable[..., Any] | None = None,
diff --git a/tests/agent/test_setup_beat_card_round.py b/tests/agent/test_setup_beat_card_round.py
new file mode 100644
index 00000000000..28decbcf087
--- /dev/null
+++ b/tests/agent/test_setup_beat_card_round.py
@@ -0,0 +1,53 @@
+"""A setup_beat round never ends in the empty-response nudge: the line written with the card is the
+turn's reply when the follow-up comes back empty (agent/turn_tool_round.py ``_LINE_IS_REPLY_TOOLS``)."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from agent.agent_init import _CALLBACK_PARAMS
+from agent.turn_empty_response import recover_empty_response
+from agent.turn_tool_round import stage_tool_call_message
+from run_agent import AIAgent
+
+
+def _agent():
+ agent = AIAgent.__new__(AIAgent)
+ agent.provider, agent.model, agent.session_id, agent.tools = "nous", "m", "s1", []
+ agent.log_prefix, agent.quiet_mode, agent.verbose_logging = "", True, False
+ agent._mute_post_response, agent._base_url, agent.api_mode = False, "", "chat_completions"
+ agent._current_streamed_assistant_text = ""
+ agent._stream_callback = None
+ for name in _CALLBACK_PARAMS:
+ setattr(agent, name, None)
+ return agent
+
+
+def _call(name: str):
+ return SimpleNamespace(id=f"call_{name}", type="function",
+ function=SimpleNamespace(name=name, arguments="{}"))
+
+
[email protected](("tool", "reused"), [("setup_beat", True), ("terminal", False)])
+def test_an_empty_follow_up_after_a_card_round_keeps_the_cards_line(tool, reused):
+ agent = _agent()
+ messages = [{"role": "user", "content": "hi"}]
+ staged, _ = stage_tool_call_message(
+ agent, assistant_message=SimpleNamespace(content="Pick a colour whenever you're back.",
+ tool_calls=[_call(tool)], reasoning=None),
+ finish_reason="tool_calls", messages=messages)
+ messages += [staged, {"role": "tool", "tool_call_id": f"call_{tool}", "content": "{}"}]
+
+ verdict = recover_empty_response(
+ agent, SimpleNamespace(content="", tool_calls=None, reasoning=None), None, "stop", final_response="",
+ messages=messages, api_messages=[], conversation_history=[], active_system_prompt="",
+ api_call_count=2, turn_exit_reason=None, preflight_compression_blocked=False)
+
+ if reused:
+ assert verdict.action == "break" and verdict.final_response == "Pick a colour whenever you're back."
+ assert verdict.turn_exit_reason == "fallback_prior_turn_content"
+ else:
+ assert verdict.final_response != "Pick a colour whenever you're back."
+ assert agent._mute_post_response is False
diff --git a/tests/tools/test_setup_beat_tool.py b/tests/tools/test_setup_beat_tool.py
new file mode 100644
index 00000000000..22a5a59b309
--- /dev/null
+++ b/tests/tools/test_setup_beat_tool.py
@@ -0,0 +1,123 @@
+"""``setup_beat`` through the agent's inline executor, with a real session store and a fake card
+answer standing in for the desktop."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from agent import onboarding_record
+from agent.inline_tool_executors import INLINE_TOOL_EXECUTORS, InlineToolContext
+from agent.onboarding_flow import Facts, SkipAll
+from hermes_state import SessionDB
+from tools.registry import registry
+
+SID = "onb-session"
+FACTS = Facts(os="macos", arch="arm64", machine_kind="Mac", plugins=("blender",))
+
+
+def db(tmp_path, monkeypatch):
+ # The run's start and end write the install flag in the root config; that is not under test here.
+ monkeypatch.setattr("hermes_cli.onboarding_run.set_run", lambda *a, **k: None)
+ store = SessionDB(db_path=tmp_path / "state.db")
+ store.create_session(SID, "desktop")
+ yield store
+ store.close()
+
+
+def desktop():
+ """A card answerer: replies come off a queue; every payload it was shown is kept."""
+ shown, replies = [], []
+
+ def answer(payload):
+ shown.append(payload)
+ return replies.pop(0) if replies else None
+ return SimpleNamespace(shown=shown, replies=replies, answer=answer)
+
+
+def call(db, desktop, call_id="call_1", **args):
+ agent = SimpleNamespace(_session_db=db, session_id=SID, setup_beat_callback=desktop.answer)
+ return json.loads(INLINE_TOOL_EXECUTORS["setup_beat"](agent, args, InlineToolContext("task", call_id)))
+
+
+def test_a_card_answer_settles_the_beat_and_names_the_next(db, desktop):
+ onboarding_record.start(db, SID, FACTS)
+ desktop.replies.append({"answer": {"accent": "Ultraviolet"}})
+
+ result = call(db, desktop, beat="theme", question="Pick one.")
+
+ assert desktop.shown == [{"beat": "theme", "question": "Pick one.", "card": {"picker": "accent"}}]
+ assert result["answer"] == {"accent": "Ultraviolet"} and result["next"] == "name"
+ assert "Ultraviolet" in result["reminder"]
+ assert onboarding_record.load(db, SID)["beats"]["theme"] == "done"
+
+
+def test_next_shows_the_first_open_beat_and_the_name_card_offers_the_account_name(db, desktop, monkeypatch):
+ monkeypatch.setattr("agent.onboarding_facts.suggested_name", lambda: "Ada Lovelace")
+ onboarding_record.start(db, SID, FACTS)
+ desktop.replies.append({"said": "Ada"})
+
+ result = call(db, desktop, beat="next")
+
+ assert desktop.shown[0]["beat"] == "name" and desktop.shown[0]["card"] == {"suggested": "Ada Lovelace"}
+ # Words typed while the name card waits are the name; the account name reaches the model only if picked.
+ assert result["answer"] == {"name": "Ada"} and "Ada Lovelace" not in json.dumps(result)
+
+
+def test_no_answer_closes_the_card_and_typed_words_come_back_as_said(db, desktop):
+ onboarding_record.start(db, SID, FACTS)
+ timed_out = call(db, desktop, beat="layout")
+ desktop.replies.append({"said": "what is Elite?"})
+ said = call(db, desktop, beat="layout", call_id="call_2")
+
+ assert timed_out["timed_out"] is True and "five minutes" in timed_out["reminder"]
+ assert said["said"] == "what is Elite?" and 'setup_beat(beat="layout")' in said["reminder"]
+ assert onboarding_record.load(db, SID)["waiting"] is None
+
+
+def test_suggest_pins_connectors_and_value_or_skip_records_without_a_card(db, desktop):
+ onboarding_record.start(db, SID, FACTS)
+ desktop.replies.append({"answer": {"connected": ["slack"], "newly_connected": ["slack"]}})
+ call(db, desktop, beat="connectors", suggest=["slack", "linear"])
+ recorded = call(db, desktop, beat="tour", value="skip")
+ skipped = call(db, desktop, beat="plugins", skip=True)
+
+ assert desktop.shown[0]["card"] == {"suggested": ["slack", "linear"]} and len(desktop.shown) == 1
+ assert recorded["recorded"] == "tour" and "No tour" in recorded["reminder"]
+ assert skipped["skipped"] is True
+
+
+def test_skip_setup_during_a_card_returns_skipped_all(db, desktop):
+ onboarding_record.start(db, SID, FACTS)
+
+ def skip_pressed(payload):
+ onboarding_record.advance(db, SID, SkipAll())
+
+ desktop.answer = skip_pressed
+ result = call(db, desktop, beat="theme")
+
+ assert result["skipped_all"] is True and "stop guiding" in result["reminder"]
+ assert "error" in call(db, desktop, beat="next")
+
+
+def test_done_ends_the_run_only_after_the_build_card(db, desktop):
+ onboarding_record.start(db, SID, FACTS)
+ refused = call(db, desktop, beat="done")
+ desktop.replies.append({"answer": {"build": "week"}})
+ build = call(db, desktop, beat="build")
+ done = call(db, desktop, beat="done")
+
+ assert "error" in refused
+ assert "How does this look?" in build["reminder"]
+ assert done == {"completed": True, "reminder": done["reminder"]}
+ assert onboarding_record.load(db, SID)["phase"] == "complete"
+
+
+def test_outside_an_onboarding_chat_the_tool_refuses(db, desktop):
+ assert "not running" in call(db, desktop, beat="next")["error"]
+ # A bare registry dispatch has no session store or card callback.
+ assert "error" in json.loads(registry.dispatch("setup_beat", {"beat": "next"}))
diff --git a/tools/setup_beat_tool.py b/tools/setup_beat_tool.py
new file mode 100644
index 00000000000..73de53d62ba
--- /dev/null
+++ b/tools/setup_beat_tool.py
@@ -0,0 +1,124 @@
+"""``setup_beat``: the one onboarding-only tool. It shows a beat's card through the desktop, waits
+for the user (``CARD_TIMEOUT_S``), and returns their answer with a short reminder of the next beat.
+
+The ``onboarding`` toolset carrying it is folded in only for the onboarding chat, at agent build
+(``tui_gateway/methods_onboarding.py``). The run record is the session's ``onboarding_run``
+(``agent/onboarding_record.py``); the order and the options are ``agent/onboarding_flow.py``.
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Callable, Mapping
+from typing import Any
+
+from agent import onboarding_flow as flow
+from agent.onboarding_text import QUESTIONS, finish_reminder, reminder
+from tools.registry import registry, tool_error
+
+BEATS = ("next", *flow.BEAT_IDS, "done")
+
+
+def _direct_event(beat: str, args: Mapping[str, Any]) -> flow.Event | None:
+ """An event the call carries in itself (no card): done, a value given in words, or a skip."""
+ if beat == "done":
+ return flow.SkipAll() if args.get("skip") else flow.Done()
+ if args.get("skip"):
+ return flow.Skipped(beat)
+ value = args.get("value")
+ return flow.Recorded(beat, value.strip()) if isinstance(value, str) and value.strip() else None
+
+
+def _reply_event(beat: str, reply: Mapping[str, Any] | None) -> flow.Event:
+ reply = reply or {}
+ said = reply.get("said")
+ if isinstance(said, str) and said.strip():
+ # Words typed while the name card waits are the name, like its own text box.
+ return flow.Answered(beat, {"name": said.strip()}) if beat == "name" else flow.Said(beat, said.strip())
+ answer = reply.get("answer")
+ return flow.Answered(beat, answer) if isinstance(answer, dict) and answer else flow.TimedOut(beat)
+
+
+def _result(step: flow.Step, beat: str | None = None) -> str:
+ facts = flow.Facts.from_stored(step.record["facts"])
+ text = reminder(step.reminder, step.record, facts, beat)
+ return json.dumps({**step.result, **({"reminder": text} if text else {})}, ensure_ascii=False)
+
+
+def _card(beat: str, step: flow.Step, args: Mapping[str, Any]) -> dict:
+ facts = flow.Facts.from_stored(step.record["facts"])
+ card = flow.BEAT_BY_ID[beat].card(facts, step.record["picks"])
+ if beat == "name":
+ from agent.onboarding_facts import suggested_name
+
+ # The account name goes to the card only; the model reads it if the user picks it.
+ card = {"suggested": name} if (name := suggested_name()) else {}
+ if beat == "connectors":
+ card = {"suggested": [str(slug) for slug in args.get("suggest") or () if str(slug).strip()]}
+ return card
+
+
+def setup_beat_tool(args: Mapping[str, Any], *, db=None, session_id: str = "", tool_call_id: str = "",
+ callback: Callable[[dict], dict | None] | None = None) -> str:
+ """``callback(payload) -> {answer?, said?} | {timed_out: true} | None`` asks the desktop to show
+ ``{beat, question, card}`` and blocks until the user answers or the card closes."""
+ from agent import onboarding_record as records
+
+ beat = args.get("beat")
+ if beat not in BEATS:
+ return tool_error(f"beat must be one of: {', '.join(BEATS)}.")
+ record = records.load(db, session_id)
+ if record is None:
+ return tool_error("Onboarding is not running in this chat.")
+ if beat != "next" and (event := _direct_event(beat, args)) is not None:
+ return _result(records.advance(db, session_id, event))
+ if beat == "next":
+ beat = flow.next_beat(record) if flow.is_active(record) else None
+ if beat is None:
+ return json.dumps({"next": "done", "reminder": finish_reminder(record)} if flow.is_active(record)
+ else {"error": "Onboarding is over in this chat; it is a normal chat now."})
+ if callback is None:
+ return tool_error("setup_beat cards show only in the Hermes desktop app.")
+ shown = records.advance(db, session_id, flow.Shown(beat, tool_call_id))
+ if shown.result: # refused, or a beat this machine skips
+ return _result(shown)
+ question = str(args.get("question") or "").strip() or QUESTIONS[beat]
+ reply = callback({"beat": beat, "question": question, "card": _card(beat, shown, args)})
+ after = records.load(db, session_id)
+ if after is not None and after["phase"] == flow.PHASE_SKIPPED:
+ # Skip setup closed the card (onboarding.skip already wrote the record).
+ return _result(flow.Step(after, {"skipped_all": True}, "skip_all"))
+ return _result(records.advance(db, session_id, _reply_event(beat, reply)), beat)
+
+
+SETUP_BEAT_SCHEMA = {
+ "name": "setup_beat",
+ "description": (
+ "Run the first-run onboarding in this chat. Shows the card for a beat and waits for the user, then "
+ "returns their answer and what to do next. beat=next shows the next beat. Pass value to record an answer "
+ "they gave in words, skip to record that they skipped a beat. beat=done ends onboarding after the first "
+ "build is shown and its close card is answered; beat=done with skip=true ends it early because they "
+ "asked to stop."
+ ),
+ "parameters": {
+ "type": "object",
+ "required": ["beat"],
+ "properties": {
+ "beat": {"type": "string", "enum": list(BEATS)},
+ "question": {"type": "string", "description": "Your line above the card. The app fixes the options."},
+ "value": {"type": "string", "description": "Record an answer given in words (a name, or an option id). No card."},
+ "skip": {"type": "boolean", "description": "They skipped this beat in words. No card."},
+ "suggest": {"type": "array", "items": {"type": "string"},
+ "description": "connectors only: slugs pinned as Suggested."},
+ },
+ },
+}
+
+
+registry.register(
+ name="setup_beat", toolset="onboarding", schema=SETUP_BEAT_SCHEMA,
+ # The agent loop runs it inline with the session's record and card callback
+ # (agent/inline_tool_executors.py); a bare registry dispatch has neither.
+ handler=lambda args, **kw: setup_beat_tool(args),
+ emoji="🎛",
+)
diff --git a/toolsets.py b/toolsets.py
index 7d457447eca..3b7f3a18b48 100644
--- a/toolsets.py
+++ b/toolsets.py
@@ -145,6 +145,8 @@ TOOLSETS = {
),
"setup": _ts("Onboarding-only surface for the setup profile: question and picker cards", ["setup_choose"],
platforms=frozenset({"desktop"})),
+ "onboarding": _ts("First-run onboarding cards; folded in only for the onboarding chat (tui_gateway/methods_onboarding.py)",
+ ["setup_beat"], platforms=frozenset({"desktop"})),
"start_chat": _ts("Start a new visible desktop chat that runs a task in a chosen profile", ["start_chat"],
platforms=frozenset({"desktop"})),
# ``platforms``: the session platforms this toolset exists for (TOOLSET_SESSION_PLATFORMS).