The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
P18a: the backend plays the desktop setup opening (hello, name, accent) as real setup_choose calls (#129346)
Siddharth Balyanfc6a0a1a3955
diff --git a/agent/AGENTS.md b/agent/AGENTS.mdindex d76bfa6187e..751e5c58728 100644--- a/agent/AGENTS.md+++ b/agent/AGENTS.md@@ -39,7 +39,8 @@ Each phase of an iteration is its own sibling, so a change to (say) overflow han~600-line file: `turn_preflight*`, `turn_iteration_prep`, `turn_request_assembly`/`turn_api_request`,`turn_api_call`, `turn_api_error`, `turn_response_intake`/`turn_response_check`,`turn_empty_response`, `turn_tool_round`/`turn_tool_validation`, `turn_overflow`,-`turn_truncation`, `turn_context_compaction`, `turn_recovery`, `turn_recovery_autorecover`+`turn_truncation`, `turn_scripted_prelude` (tool calls a prompt built-in plays before the first model+call), `turn_context_compaction`, `turn_recovery`, `turn_recovery_autorecover`(post-exhaustion wait-and-retry ladder), `turn_retry_state`,`turn_stop_gates`, `turn_liveness`, `turn_usage`, `turn_final_response`, `turn_finalizer`,`turn_summary`. Find the phase with `grep -rn "def X" agent/turn_*.py`.diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 8a8025aeaef..f9bbbb6ffa8 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -36,6 +36,7 @@ from agent.surface_switch import (from agent.turn_context import PreflightCompressionTimedOut, build_turn_contextfrom hermes_cli.observability.shared_metrics_efficiency import record_cache_break, record_prompt_rebuildfrom agent.turn_retry_state import TurnRetryState+from agent.turn_scripted_prelude import Prelude, run_scripted_prelude# Phase helpers of the turn loop, bound at import so a source-tree swap cannot load a# skewed phase mid-turn.from agent.turn_api_call import handle_api_interrupt, nous_rate_limit_guard, perform_api_call@@ -1545,6 +1546,7 @@ def _run_conversation_turn(turn_author: Optional[Dict[str, Any]] = None,moa_config: Optional[dict[str, Any]] = None,title_user_message: Optional[str] = None,+ prelude: Optional[Prelude] = None,) -> Dict[str, Any]:"""Run a complete conversation with tool calling until completion; returns the result dict.@@ -1554,7 +1556,8 @@ def _run_conversation_turn(``title_user_message``: optional pre-injection text for titles only (None uses themodel-facing message; an empty string suppresses titling for this turn).``persist_user_display_*``:- display-only event rendering; the model still receives the message unchanged."""+ display-only event rendering; the model still receives the message unchanged.+ ``prelude``: scripted tool calls played before the first model call (``agent/turn_scripted_prelude.py``)."""if moa_config is None:user_message, moa_config, persist_user_message = _decode_inline_moa_turn(user_message, persist_user_message@@ -1633,7 +1636,13 @@ def _run_conversation_turn(s.api_call_count = int(codex_result.get("api_calls") or 0)s.active_system_prompt = _sync_failover_system_message(agent, None, s.active_system_prompt)- while (s.api_call_count < agent.max_iterations and agent.iteration_budget.remaining > 0) or agent._budget_grace_call:+ _prelude = run_scripted_prelude(agent, s, prelude) if prelude is not None else None+ if _prelude is not None and _prelude.action == "return":+ return _prelude.result+ _prelude_ended_turn = _prelude is not None and _prelude.action == "break"+ while not _prelude_ended_turn and (+ (s.api_call_count < agent.max_iterations and agent.iteration_budget.remaining > 0) or agent._budget_grace_call+ ):if _run_phase(begin_iteration, agent, s).action == "break":break_run_phase(prepare_iteration, agent, s)@@ -1707,6 +1716,7 @@ def run_conversation(moa_config: Optional[dict[str, Any]] = None,turn_author: Optional[Dict[str, Any]] = None,title_user_message: Optional[str] = None,+ prelude: Optional[Prelude] = None,) -> Dict[str, Any]:"""Run one turn (see ``_run_conversation_turn``) and export the current-turn boundary.@@ -1736,6 +1746,7 @@ def run_conversation(moa_config=moa_config,turn_author=turn_author,title_user_message=title_user_message,+ prelude=prelude,)result = export_current_turn_boundary(agent, result, user_message)_close_durable_failed_turn(agent, result)diff --git a/agent/initiate_setup_prompt.py b/agent/initiate_setup_prompt.pyindex 569db962045..305d5260072 100644--- a/agent/initiate_setup_prompt.py+++ b/agent/initiate_setup_prompt.py@@ -11,6 +11,8 @@ from typing import NamedTuplefrom hermes_constants import get_optional_skills_dir, hermes_home_keyHEADER = "[/initiate-setup]"+# The desktop opening the backend plays before the first model call (English only, app-owned copy).+INTRO = "Hi, I'm Hermes.\n\nLet's set things up for you. Then we'll get something cool done."# The skill's inline-shell hook for host facts. The builder fills it in-process on every surface:# skills.inline_shell is on only in the setup profile, and on Windows it needs Git Bash.@@ -79,3 +81,89 @@ def build_initiate_setup_prompt(surface: str, tools, primary_profile: str) -> stskill = _HOST_FACTS_HOOK.sub(lambda _: host, skill)facts = json.dumps(block, indent=2, ensure_ascii=False)return f"{HEADER}\n\n{skill}\n\n```json\n{facts}\n```"+++_NAME_QUESTION = "What should I call you?"+# A closed card counts as answered: the skill takes the default and never re-asks it.+_ANSWERED = ("submitted", "cancelled")+++def _json_object(text) -> dict:+ try:+ value = json.loads(text) if isinstance(text, str) else text+ except ValueError:+ return {}+ return value if isinstance(value, dict) else {}+++def _opening_step(call) -> str | None:+ """``name`` or ``accent`` for the opening's cards, ``""`` for any other setup card, None otherwise."""+ function = (call.get("function") or {}) if isinstance(call, dict) else {}+ if function.get("name") != "setup_choose":+ return None+ args = _json_object(function.get("arguments"))+ if args.get("kind") == "accent":+ return "accent"+ return "name" if args.get("kind") == "question" and args.get("question") == _NAME_QUESTION else ""+++def _opening_so_far(history):+ """``(lines said, {card: reply})`` for the opening in ``history``; None once any other setup card was asked.++ Lines are matched by text: a resumed history keeps an unanswered card's row but drops its call."""+ said, replies, card_by_call = set(), {}, {}+ for message in history:+ if message.get("role") == "assistant" and isinstance(message.get("content"), str):+ said.add(message["content"])+ for call in message.get("tool_calls") or ():+ step = _opening_step(call)+ if step == "":+ return None+ if step:+ card_by_call[call.get("id")] = step+ step = card_by_call.get(message.get("tool_call_id")) if message.get("role") == "tool" else None+ reply = _json_object(message.get("content")) if step else {}+ if reply.get("outcome") in _ANSWERED:+ replies[step] = reply+ return said, replies+++def initiate_setup_prelude(message, surface: str, tools, history):+ """The desktop opening as a scripted prelude (``agent/turn_scripted_prelude.py``), or None.++ Only a desktop ``/initiate-setup`` turn gets it, and only for the opening cards the history has no+ answer for: the app sends the command again after a relaunch cut the opening off, and a line+ already in the chat is not said twice. Other surfaces keep the model-only opening. The+ skill starts after the accent answer.+ """+ if (surface != "desktop" or "setup_choose" not in tools or not isinstance(message, str)+ or not message.startswith(HEADER)):+ return None+ so_far = _opening_so_far(history)+ if so_far is None or {"name", "accent"} <= so_far[1].keys():+ return None+ return _opening(_host_facts_module(_skill_dir()).suggested_name(), *so_far)+++def intro_resends(prompt: str) -> bool:+ """True while the desktop intro owns recovery of this ``/initiate-setup`` turn: after a relaunch the+ app sends the command again (the prelude replays only the unanswered opening cards), so a generic+ auto-continue of the cut-off turn would race it."""+ from hermes_cli.setup_profile import onboarding_eligible, read_state++ return prompt.startswith(HEADER) and onboarding_eligible() and read_state().get("intro") == "unseen"+++def _opening(suggested: str | None, said: set, replies: dict):+ reply = replies.get("name")+ if reply is None:+ card = {"kind": "question", "question": _NAME_QUESTION, "multi_select": False}+ if suggested:+ card["options"] = [{"id": "suggested", "label": suggested}]+ reply = _json_object((yield "" if INTRO in said else INTRO, "setup_choose", card))+ if "accent" in replies:+ return+ picked = reply.get("picked")+ name = (suggested or "") if picked == "suggested" else picked.strip() if isinstance(picked, str) else ""+ line = f"Good to meet you, {name}." if name else "Good to meet you."+ yield "" if line in said else line, "setup_choose", {"kind": "accent", "question": "Which colour?", "multi_select": False}diff --git a/agent/onboarding.py b/agent/onboarding.pyindex fffe8664f43..52efe5f6a5e 100644--- a/agent/onboarding.py+++ b/agent/onboarding.py@@ -161,9 +161,13 @@ def first_contact_turn_note(contact (non-empty session history or prior sessions exist on the install)."""from agent.initiate_setup_prompt import HEADER+ from hermes_cli.profiles import SETUP_PROFILE_MARKERif not session_history_empty or install_has_prior_sessions or message.startswith(HEADER):return None+ # The setup chat opens with its own welcome, whatever its first message says.+ if (config_path.parent / SETUP_PROFILE_MARKER).is_file():+ return Nonetry:if (profile_build_mode(config) == "ask"diff --git a/agent/skill_commands.py b/agent/skill_commands.pyindex 909305e7887..8ff2ab505ea 100644--- a/agent/skill_commands.py+++ b/agent/skill_commands.py@@ -9,6 +9,7 @@ from pathlib import Pathfrom typing import Any, Dict, Optionalfrom hermes_constants import display_hermes_home+from agent.initiate_setup_prompt import HEADER as INITIATE_SETUP_HEADERfrom agent.prompt_cache_boundary import register_stable_prefixfrom agent.skill_preprocessing import load_skills_config as _load_skills_config, preprocess_skill_content@@ -152,6 +153,8 @@ def describe_skill_invocation(content: Any, separator: str = " — ") -> Optiona"""if not isinstance(content, str):return None+ if content.startswith(INITIATE_SETUP_HEADER):+ return "/initiate-setup"if content.startswith(_AUTO_LOAD_PREFIX):return _describe_auto_loaded_skill_turn(content)if not content.startswith(_SKILL_INVOCATION_PREFIX):diff --git a/agent/turn_facade.py b/agent/turn_facade.pyindex d54b4dc0b81..17bfcb775b0 100644--- a/agent/turn_facade.py+++ b/agent/turn_facade.py@@ -8,7 +8,7 @@ MRO unchanged.import loggingimport uuidfrom contextlib import suppress-from typing import Any, Dict, List, Optional+from typing import Any, Dict, Generator, List, Optionalfrom agent.lazy_forward import forward as _forward@@ -29,6 +29,7 @@ class TurnFacadeMixin:turn_author: Optional[Dict[str, Any]] = None,relay_metadata: Optional[Dict[str, Any]] = None,title_user_message: Optional[str]=None,+ prelude: Optional[Generator]=None,) -> Dict[str, Any]:"""Forwarder — see ``agent.conversation_loop.run_conversation``."""# A review shares this session_id for cache parity: fence review startup or interrupt@@ -153,6 +154,7 @@ class TurnFacadeMixin:persist_user_platform_id=persist_user_platform_id, moa_config=moa_config,turn_author=turn_author,title_user_message=title_user_message,+ prelude=prelude,)finally:# Post-loop relay/task finalization must not receive a late refresh interrupt;diff --git a/agent/turn_scripted_prelude.py b/agent/turn_scripted_prelude.pynew file mode 100644index 00000000000..1e65343834b--- /dev/null+++ b/agent/turn_scripted_prelude.py@@ -0,0 +1,47 @@+"""Scripted prelude: tool calls a prompt built-in plays before the turn's first model call.++A prelude is a generator owned by the built-in (``agent.initiate_setup_prompt.initiate_setup_prelude``+is the one today). Each step it yields ``(content, tool_name, args)``: the assistant text and the one+tool call that row carries. The loop runs it through the unchanged ``run_tool_round`` (row persisted+before the tool runs, interim text and tool events emitted, tool hooks fired) and sends the tool's+result string back into the generator, so a later step can use an earlier answer.++It runs before any provider call, so the rows sit between this turn's user message and the first+model call: nothing cached is mutated, the system prompt is untouched, no user row is added, and+roles alternate ``user -> assistant(tool_calls) -> tool -> ... -> assistant(model)``. No API call is+counted and no ``pre/post_api_request`` hook fires for a step.+"""++from __future__ import annotations++import uuid+from typing import Any, Generator, Optional, Tuple++from agent.transports.types import NormalizedResponse, build_tool_call+from agent.turn_tool_round import run_tool_round++Prelude = Generator[Tuple[str, str, dict], Optional[str], None]+++def run_scripted_prelude(agent: Any, s: Any, prelude: Prelude) -> Any:+ """Play ``prelude`` into the loop state ``s``; returns the last tool round's verdict, or None when+ no step ran. The caller ends the turn on ``return`` and skips the model on ``break``."""+ from agent.conversation_loop import _run_phase++ verdict, result = None, None+ while not agent._interrupt_requested:+ try:+ content, name, args = prelude.send(result)+ except StopIteration:+ break+ s.finish_reason = "tool_calls"+ s.assistant_message = NormalizedResponse(+ content=content, finish_reason="tool_calls",+ tool_calls=[build_tool_call(f"call_{uuid.uuid4().hex[:24]}", name, args)])+ verdict = _run_phase(run_tool_round, agent, s)+ if verdict.action != "continue":+ break+ tail = s.messages[-1] if s.messages else {}+ result = tail.get("content") if tail.get("role") == "tool" else None+ prelude.close()+ return verdictdiff --git a/optional-skills/productivity/initiate-setup/scripts/host_facts.py b/optional-skills/productivity/initiate-setup/scripts/host_facts.pyindex 4495564cf06..6c39578dcf8 100644--- a/optional-skills/productivity/initiate-setup/scripts/host_facts.py+++ b/optional-skills/productivity/initiate-setup/scripts/host_facts.py@@ -164,6 +164,12 @@ def _suggested_name(login: str, full: str) -> str | None:return name+def suggested_name() -> str | None:+ """``account.suggested_name`` alone: the desktop's name card offers it before the first model call."""+ login, full, _home = _account()+ return _suggested_name(login, full)++def _home_age_days(home: str) -> int | None:"""Home-folder birth time approximates account age. Linux exposes no birth time here."""if not home:diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.pyindex d35ec8f854f..d5d980f5b62 100644--- a/tui_gateway/prompt_turn.py+++ b/tui_gateway/prompt_turn.py@@ -801,6 +801,12 @@ def _invoke_agent(run_kwargs["persist_user_display_metadata"] = display_metadataif turn_author and "turn_author" in run_params:run_kwargs["turn_author"] = turn_author+ if "prelude" in run_params:+ from agent.initiate_setup_prompt import initiate_setup_prelude+ prelude = initiate_setup_prelude(+ text, _resolve_agent_platform(_session_source(session)), agent.valid_tool_names, st.history)+ if prelude is not None:+ run_kwargs["prelude"] = prelude_adopt_submit_user_row(session, agent, run_kwargs["persist_user_message"], text)# Live-rename hook: auto-titling fires inside the turn prologue._title_key = session.get("session_key") or siddiff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.pyindex 68d2f2b176b..c62a38aeb3c 100644--- a/tui_gateway/session_auto_continue.py+++ b/tui_gateway/session_auto_continue.py@@ -68,6 +68,10 @@ def _maybe_schedule_auto_continue(sid: str, session: dict, session_key: str) ->return Noneif not marker.get("auto_continue", True):return None # The mailbox owns recovery and receipt identity for imported turns.+ from agent.initiate_setup_prompt import intro_resends+ if intro_resends(marker["prompt"]):+ clear_turn_marker(home, session_key) # the desktop intro sends /initiate-setup again itself+ return None# Ownership, not forensics: a sibling backend sharing this HERMES_HOME can be mid-turn on this very session, so# its live marker says "someone is working on it", never "someone crashed". Leave the marker for its writer —# clearing it would cancel the live turn's own account of itself. See #94778.diff --git a/website/docs/reference/slash-commands.md b/website/docs/reference/slash-commands.mdindex 0ca613855b5..d31bc618740 100644--- a/website/docs/reference/slash-commands.md+++ b/website/docs/reference/slash-commands.md@@ -110,7 +110,7 @@ Type `/` in the CLI to open the autocomplete menu. Built-in commands are case-in| `/bundles` | List configured skill bundles — `/<name>` slash aliases that preload several skills at once. Configure under `bundles:` in `~/.hermes/config.yaml`. See [Skill Bundles](../user-guide/features/skills.md#skill-bundles). || `/learn <what to learn from>` | Distill a reusable skill from anything you describe — a directory, a URL, the workflow you just walked the agent through, or pasted notes. Open-ended: the agent gathers the sources with its own tools and authors a `SKILL.md` following the house authoring standards. Works in the CLI, the messaging gateway, the TUI, and the dashboard Skills page. || `/plan [task]` | Write a markdown implementation plan to `.hermes/plans/` in the active workspace — planning only, no execution. Empty argument infers the task from the conversation. (Formerly the bundled `plan` skill; now built-in so it survives the Telegram/Discord command-menu caps.) |-| `/initiate-setup` (alias: `/initiate_setup`) | Run the first-run setup: the agent learns about you and sets Hermes up around you. Sends the `initiate-setup` skill plus facts about this session and machine (surface, tools present, OS, RAM, GPU), plus a derived summary of an automatic machine scan (see [The setup chat's machine scan](../user-guide/desktop.md#the-setup-chats-machine-scan)), as one normal turn. The first message ever ends with a one-line offer to run it (see [Onboarding](../user-guide/configuration.md#onboarding)). Works in the CLI, the messaging gateway, the TUI, and the desktop app. |+| `/initiate-setup` (alias: `/initiate_setup`) | Run the first-run setup: the agent learns about you and sets Hermes up around you. Sends the `initiate-setup` skill plus facts about this session and machine (surface, tools present, OS, RAM, GPU), plus a derived summary of an automatic machine scan (see [The setup chat's machine scan](../user-guide/desktop.md#the-setup-chats-machine-scan)), as one normal turn. The first message ever ends with a one-line offer to run it (see [Onboarding](../user-guide/configuration.md#onboarding)). Works in the CLI, the messaging gateway, the TUI, and the desktop app. In the desktop app, Hermes itself asks the opening questions (your name, then an accent colour) before the model's first reply. || `/init [notes]` | Generate or update `AGENTS.md` project instructions from a repo scan (port of Codex `/init`). The agent inspects manifests, layout, and toolchain configs with its read-only tools, then writes a concise `AGENTS.md` — or, if one exists, merge-updates it preserving your content. Optional notes steer the emphasis. Works in the CLI, the messaging gateway, and the TUI. || `/cron` | Manage scheduled tasks (list, add/create, edit, pause, resume, run, remove) || `/suggestions [accept\|dismiss N\|catalog\|clear]` (alias: `/suggest`) | Review suggested automations. Use `/suggestions` to list pending suggestions, `/suggestions accept <id>` to create the proposed automation, `/suggestions dismiss <id>` to reject one, `/suggestions catalog` to add curated starter automations, and `/suggestions clear` to clear resolved suggestion records. Accepted jobs preserve the current surface as the delivery origin. |diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex a7ddf91df46..8a507e6c850 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -3057,7 +3057,7 @@ onboarding:seen: {} # internal latch — leave empty```-- `profile_build` — controls the setup offer on the first message ever, in the CLI, the TUI, the desktop app and messaging direct messages (never in a group chat). `"ask"` (default) adds one closing line to the agent's intro that offers `/initiate-setup` (`/initiate_setup` on Telegram). The offer is skipped when the first message is `/initiate-setup` itself. `"off"` stops only the offer line; the agent still gives a plain intro. The offer fires at most once per profile. `/initiate-setup` also scans the machine automatically; see [The setup chat's machine scan](./desktop.md#the-setup-chats-machine-scan).+- `profile_build` — controls the setup offer on the first message ever, in the CLI, the TUI, the desktop app and messaging direct messages (never in a group chat). `"ask"` (default) adds one closing line to the agent's intro that offers `/initiate-setup` (`/initiate_setup` on Telegram). The offer is skipped when the first message is `/initiate-setup` itself, and always in the desktop app's setup profile. `"off"` stops only the offer line; the agent still gives a plain intro. The offer fires at most once per profile. `/initiate-setup` also scans the machine automatically; see [The setup chat's machine scan](./desktop.md#the-setup-chats-machine-scan).- `seen` — internal state. Hermes latches each shown hint here so it never fires again; the setup offer is also recorded here once shown. Don't hand-edit it — wipe the whole `onboarding` section if you want to re-see all hints.## Dashboard