The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(onboarding): the model picks the build card from the catalog, strictly checked
alt-glitch05f34800aaec
diff --git a/agent/onboarding_first_tasks.py b/agent/onboarding_first_tasks.pyindex d3009474452..5f4a60f999c 100644--- a/agent/onboarding_first_tasks.py+++ b/agent/onboarding_first_tasks.py@@ -14,8 +14,12 @@ from typing import TYPE_CHECKING, Anyif TYPE_CHECKING:from agent.onboarding_flow import Facts+MAX_PICKS = 4+MAX_LABEL = 32# The one fixed row: always last on the card, never one of the model's picks.FIXED_ID = "hermes"+# The value a task the user names in words records; it is never on the card.+OWN_ID = "own"@dataclass(frozen=True)@@ -93,3 +97,43 @@ EVERY_TASK_SKILL = "humanizer"def eligible_tasks(facts: Facts, picks: Mapping[str, Any]) -> tuple[FirstTask, ...]:"""The rows the model may pick from on this machine and run, in catalog order."""return tuple(task for task in FIRST_TASKS if task.id != FIXED_ID and task.gate(facts, picks))+++def card_options(chosen: Any) -> list[dict]:+ """The build card: the model's picks as given, then the fixed row."""+ return [*(dict(option) for option in chosen or ()), {"id": FIXED_ID, "label": TASK_BY_ID[FIXED_ID].label}]+++def _option_error(option: Any, eligible: set[str], seen: set[str]) -> str | None:+ if not isinstance(option, Mapping) or not isinstance(option.get("id"), str):+ return 'each option is {"id": ..., "label": ...}'+ if option["id"] == FIXED_ID:+ return f"{FIXED_ID} is added last by itself; do not pick it"+ if option["id"] not in eligible:+ return f"{option['id']!r} is not an eligible id"+ if option["id"] in seen:+ return f"{option['id']!r} is picked twice"+ label = option.get("label")+ if not isinstance(label, str) or not label.strip() or len(label) > MAX_LABEL:+ return f"the label for {option['id']} must be 1 to {MAX_LABEL} characters"+ return None+++def pick_error(options: Any, facts: Facts, picks: Mapping[str, Any]) -> str | None:+ """Why the model's build picks are refused, naming the eligible ids; None when they are valid."""+ eligible = [task.id for task in eligible_tasks(facts, picks)]+ problem = None+ if not isinstance(options, list) or not options:+ problem = "options is required"+ elif len(options) > MAX_PICKS:+ problem = f"pick at most {MAX_PICKS}"+ else:+ seen: set[str] = set()+ for option in options:+ if problem := _option_error(option, set(eligible), seen):+ break+ seen.add(option["id"])+ if problem is None:+ return None+ return (f'{problem}. Call setup_beat(beat="build", options=[{{"id": ..., "label": ...}}]) with up to '+ f"{MAX_PICKS} of these ids: {', '.join(eligible)}.")diff --git a/agent/onboarding_flow.py b/agent/onboarding_flow.pyindex b6c8ce722f3..cd903d451e8 100644--- a/agent/onboarding_flow.py+++ b/agent/onboarding_flow.py@@ -12,6 +12,8 @@ from collections.abc import Callable, Mappingfrom dataclasses import asdict, dataclass, fieldfrom typing import Any+from agent.onboarding_first_tasks import FIXED_ID, OWN_ID, card_options, pick_error+PENDING, SHOWN, DONE, SKIPPED = "pending", "shown", "done", "skipped"ONBOARDING, COMPLETE, PHASE_SKIPPED = "onboarding", "complete", "skipped"CARD_TIMEOUT_S = 300@@ -56,8 +58,11 @@ class Facts:@dataclass(frozen=True)class Shown:+ """``options``: the model's build picks, ``[{id, label}]``; empty brings back the card already shown."""+beat: strtool_call_id: str = ""+ options: Any = None@dataclass(frozen=True)@@ -120,20 +125,9 @@ class Step:# ── beats ─────────────────────────────────────────────────────────────────────────────────────-def build_options(facts: Facts, picks: Mapping[str, Any]) -> list[dict]:- """Two tasks that fit the facts and picks, then the three fixed rows."""- installed, connected = set(picks.get("installed") or ()), list(picks.get("connected") or ())- tasks = [- ("games", "Set up my games and streaming", facts.os == "windows" and facts.nvidia_platform == "discrete"),- ("blender", "Help me make something in Blender", "blender" in installed),- ("brief", "A daily brief from my apps", bool(connected)),- ("week", "A summary of my week", True),- ("scan", f"Look around this {facts.machine_kind} and suggest something", True),- ]- rows = [{"id": task_id, "label": label} for task_id, label, fits in tasks if fits][:2]- return [*rows, {"id": "mind", "label": "I have something in mind"},- {"id": "machine", "label": f"Help me set up this {facts.machine_kind}"},- {"id": "together", "label": "Let's figure it out together"}]+def build_values(facts: Facts, picks: Mapping[str, Any]) -> tuple[str, ...]:+ """Ids the build beat accepts: what its card showed, plus a task they named in words."""+ return (*_option_ids(picks.get("build_options") or ()), FIXED_ID, OWN_ID)def _option_ids(options) -> tuple[str, ...]:@@ -170,8 +164,8 @@ BEATS: tuple[Beat, ...] = (when=lambda facts, picks: bool(facts.plugins)),Beat("tour", lambda facts, picks: {"options": list(TOUR_OPTIONS)}, picks=("tour",), value="tour",values=lambda facts, picks: _option_ids(TOUR_OPTIONS), when=lambda facts, picks: facts.tours),- Beat("build", lambda facts, picks: {"options": build_options(facts, picks)}, picks=("build",), value="build",- values=lambda facts, picks: _option_ids(build_options(facts, picks))),+ Beat("build", lambda facts, picks: {"options": card_options(picks.get("build_options"))}, picks=("build",),+ value="build", values=build_values),)BEAT_BY_ID = {beat.id: beat for beat in BEATS}BEAT_IDS = tuple(BEAT_BY_ID)@@ -181,7 +175,8 @@ def new_record(facts: Facts, *, now: float = 0.0) -> dict:record = {"phase": ONBOARDING, "beats": {beat.id: PENDING for beat in BEATS}, "waiting": None,"picks": {"name": None, "accent": None, "mode": None, "layout": None, "connected": [],- "newly_connected": [], "installed": [], "tour": None, "build": None},+ "newly_connected": [], "installed": [], "tour": None, "build": None,+ "build_options": []},"look_around": "not_offered", "facts": facts.stored(), "ended_by": None,"started_at": now, "updated_at": now,}@@ -225,11 +220,23 @@ def _settle(record: dict, beat: str, patch: Mapping[str, Any]) -> None:record["picks"].update({key: value for key, value in patch.items() if key in BEAT_BY_ID[beat].picks})+def _build_picks_error(record: dict, event: Shown, facts: Facts) -> str | None:+ """Stores the model's build picks; a bring-back without picks reuses the ones already on the card."""+ if not event.options and record["picks"].get("build_options"):+ return None+ if error := pick_error(event.options, facts, record["picks"]):+ return error+ record["picks"]["build_options"] = [{"id": o["id"], "label": o["label"].strip()} for o in event.options]+ return None++def _shown(record: dict, event: Shown, facts: Facts, now: float) -> Step:if not BEAT_BY_ID[event.beat].when(facts, record["picks"]):record["beats"][event.beat] = SKIPPEDreturn Step(record, {"beat": event.beat, "skipped": True, "next": _next_field(record)},f"after_{event.beat}")+ if event.beat == "build" and (error := _build_picks_error(record, event, facts)):+ return Step(record, {"beat": "build", "error": error})# A later card on screen means the user moved on from an earlier card left open.for earlier in BEAT_IDS[:BEAT_IDS.index(event.beat)]:if record["beats"][earlier] == SHOWN:diff --git a/agent/onboarding_text.py b/agent/onboarding_text.pyindex 92ce55ab747..d259d6665af 100644--- a/agent/onboarding_text.py+++ b/agent/onboarding_text.py@@ -108,7 +108,8 @@ _TYPED_ANSWER = {"connectors": 'setup_beat(beat="connectors", value="continue") for "done" or "continue", skip=true for "skip"',"plugins": 'setup_beat(beat="plugins", value="continue") for "done" or "continue", skip=true for "skip"',"tour": 'setup_beat(beat="tour", value="quick", "full" or "skip"), bucketing their words into one of the three',- "build": 'a task they name is setup_beat(beat="build", value="mind"), then build it',+ "build": ('setup_beat(beat="build", value=<id>) for an option on the card; a task of their own is '+ 'setup_beat(beat="build", value="own"), then build it'),}_CLOSE = ('When the first thing is built and shown, ask with clarify: "How does this look?" with the choices 'diff --git a/tests/agent/test_onboarding_flow.py b/tests/agent/test_onboarding_flow.pyindex 18ada3e5146..d1a86793f65 100644--- a/tests/agent/test_onboarding_flow.py+++ b/tests/agent/test_onboarding_flow.py@@ -11,10 +11,13 @@ import pytestfrom agent import onboarding_flow as flowfrom agent.onboarding_flow import (DONE, PENDING, SHOWN, SKIPPED, Answered, Applied, Done, Facts, Recorded, Said, Shown, SkipAll, Skipped,- TimedOut, apply, build_options, expire, new_record, next_beat,+ TimedOut, apply, expire, new_record, next_beat,)+from agent.onboarding_first_tasks import eligible_tasksfrom agent.onboarding_text import opening_prompt, reminder, turn_note+NOTES = [{"id": "notes", "label": "Notes to wiki"}]+MACHINES = {"mac": Facts(os="macos", arch="arm64", machine_kind="Mac", plugins=("blender",)),"windows_rtx": Facts(os="windows", arch="arm64", machine_kind="Spark", nvidia_platform="rtx_spark",@@ -44,8 +47,10 @@ def answer_all(facts: Facts) -> list:"plugins": {"installed": list(facts.plugins[:1])}, "tour": {"tour": "quick"}}record, events = new_record(facts), []while (beat := next_beat(record)) is not None:- answer = answers.get(beat) or {"build": build_options(facts, record["picks"])[0]["id"]}- for event in (Shown(beat, f"call_{beat}"), Answered(beat, answer)):+ first = eligible_tasks(facts, record["picks"])[0]+ answer = answers.get(beat) or {"build": first.id}+ options = [{"id": first.id, "label": first.label}] if beat == "build" else None+ for event in (Shown(beat, f"call_{beat}", options), Answered(beat, answer)):events.append(event)record = apply(record, event, facts).recordreturn [*events, Done()]@@ -224,24 +229,31 @@ def test_results_that_pick_nothing_settle_nothing(tool, args, result):assert set(step.record["beats"].values()) <= {PENDING, SKIPPED}[email protected](("machine", "first_two", "machine_row"), [- ("windows_laptop", ["games", "week"], "Help me set up this PC"),- ("windows_rtx", ["week", "scan"], "Help me set up this Spark"),- ("spark", ["week", "scan"], "Help me set up this Spark"),- ("mac", ["week", "scan"], "Help me set up this Mac"),[email protected]("options", [+ None, [], [{"id": "games", "label": "Games"}], [{"id": "scan", "label": "Scan"}],+ [{"id": "hermes", "label": "How Hermes works"}], [{"id": x, "label": x} for x in ("notes", "site", "repo", "watch", "explain")],+ [{"id": "notes", "label": "A"}, {"id": "notes", "label": "B"}], [{"id": "notes", "label": "x" * 33}],+ [{"id": "notes", "label": " "}], ["notes"],])-def test_build_options_fit_the_machine(machine, first_two, machine_row):- options = build_options(MACHINES[machine], {"connected": [], "installed": []})+def test_build_picks_are_refused_with_the_eligible_ids_and_no_card(options):+ step = run(MACHINES["linux"], Shown("build", "call_b", options))[-1]- assert [row["id"] for row in options[:2]] == first_two- assert [row["id"] for row in options[2:]] == ["mind", "machine", "together"]- assert options[3]["label"] == machine_row+ assert "notes, explain, youtube, watch, site, repo" in step.result["error"]+ assert step.record["beats"]["build"] == PENDING and step.record["waiting"] is None-def test_build_options_follow_the_picks():- options = build_options(MACHINES["mac"], {"connected": ["notion", "slack"], "installed": ["blender"]})+def test_valid_picks_are_the_card_with_how_hermes_works_last_and_any_card_id_answers_it():+ facts = MACHINES["mac"]+ picks = [{"id": "mac", "label": "Your Mac, sorted"}, {"id": "repo", "label": "Map your repo"}]+ shown = run(facts, Shown("build", "call_b", picks))[-1]+ card = flow.BEAT_BY_ID["build"].card(facts, shown.record["picks"])- assert [row["id"] for row in options[:2]] == ["blender", "brief"]+ assert card == {"options": [*picks, {"id": "hermes", "label": "How Hermes works"}]}+ # Brought back without picks, the same card returns.+ assert apply(shown.record, Shown("build", "call_c"), facts).result == {}+ for value in ("repo", "hermes", "own"):+ assert apply(shown.record, Recorded("build", value), facts).record["picks"]["build"] == value+ assert "error" in apply(shown.record, Recorded("build", "notes"), facts).result@pytest.mark.parametrize(("machine", "present", "absent"), [@@ -260,7 +272,7 @@ def test_build_guidance_carries_only_this_hosts_commands(machine, present, absendef test_quiet_spell_after_the_build_card_completes_the_run():facts = MACHINES["mac"]- record = run(facts, Shown("build"))[-1].record+ record = run(facts, Shown("build", "", NOTES))[-1].recordassert expire(record, now=record["updated_at"] + flow.QUIET_COMPLETE_S - 1)["phase"] == flow.ONBOARDINGended = expire(record, now=record["updated_at"] + flow.QUIET_COMPLETE_S)@@ -270,7 +282,7 @@ def test_quiet_spell_after_the_build_card_completes_the_run():def test_a_card_answer_outside_the_cards_options_is_refused_and_the_beat_stays_open():facts = MACHINES["mac"]- record = run(facts, Shown("build", "call_b"))[-1].record+ record = run(facts, Shown("build", "call_b", NOTES))[-1].recordstep = apply(record, Answered("build", {"build": "games"}), facts, now=2.0)assert "error" in step.result and step.record["beats"]["build"] == SHOWNdiff --git a/tests/tools/test_setup_beat_tool.py b/tests/tools/test_setup_beat_tool.pyindex 570f7722bce..ef63e32b9f8 100644--- a/tests/tools/test_setup_beat_tool.py+++ b/tests/tools/test_setup_beat_tool.py@@ -110,8 +110,12 @@ def test_done_ends_the_run_only_after_the_build_card(db, desktop):# The model cannot end it early: a user who wants to stop is pointed at the Skip setup button.quit_in_words = call(db, desktop, beat="done", skip=True)assert "Skip setup" in quit_in_words["error"] and onboarding_record.load(db, SID)["phase"] == "onboarding"- desktop.replies.append({"answer": {"build": "week"}})- build = call(db, desktop, beat="build")+ # No picks: refused with the eligible ids, and no card goes out.+ no_picks = call(db, desktop, beat="build")+ assert "notes" in no_picks["error"] and desktop.shown == []+ desktop.replies.append({"answer": {"build": "notes"}})+ build = call(db, desktop, beat="build", options=[{"id": "notes", "label": "Notes to wiki"}])+ assert desktop.shown[-1]["card"]["options"][-1] == {"id": "hermes", "label": "How Hermes works"}done = call(db, desktop, beat="done")assert "error" in refuseddiff --git a/tests/tui_gateway/test_onboarding_e2e.py b/tests/tui_gateway/test_onboarding_e2e.pyindex 0ccf4ce1f0d..5611185c8c0 100644--- a/tests/tui_gateway/test_onboarding_e2e.py+++ b/tests/tui_gateway/test_onboarding_e2e.py@@ -78,7 +78,7 @@ def test_every_beat_from_the_name_card_to_done(chat):assert '"preset":"quick"' in tour["reminder"]observe_tool_result(chat.agent, "gui_tour", {"action": "start", "preset": "quick"}, json.dumps({"success": True}))- build = beat(chat, {"answer": {"build": "games"}}, beat="next")+ build = beat(chat, {"answer": {"build": "games"}}, beat="next", options=[{"id": "games", "label": "Tune my games"}])assert "--accept-package-agreements" in build["reminder"] and "How does this look?" in build["reminder"]assert beat(chat, beat="done")["completed"] is Truediff --git a/tests/tui_gateway/test_onboarding_session.py b/tests/tui_gateway/test_onboarding_session.pyindex 15be327f4b5..17768f2b712 100644--- a/tests/tui_gateway/test_onboarding_session.py+++ b/tests/tui_gateway/test_onboarding_session.py@@ -334,7 +334,7 @@ def test_the_first_state_read_after_the_quiet_spell_says_do_not_run(root):db = server._get_db()db.create_session("onb", "desktop")onboarding_record.start(db, "onb", FACTS)- for event in (Shown("build"), Answered("build", {"build": "week"})):+ for event in (Shown("build", options=[{"id": "notes", "label": "Notes"}]), Answered("build", {"build": "notes"})):onboarding_record.advance(db, "onb", event)record = onboarding_record.load(db, "onb")db.patch_session_model_config("onb", {"onboarding_run": {**record, "updated_at": record["updated_at"] - QUIET_COMPLETE_S}})diff --git a/tools/setup_beat_tool.py b/tools/setup_beat_tool.pyindex 78374289ff0..191ecd569b7 100644--- a/tools/setup_beat_tool.py+++ b/tools/setup_beat_tool.py@@ -80,7 +80,7 @@ def setup_beat_tool(args: Mapping[str, Any], *, db=None, session_id: str = "", telse {"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))+ shown = records.advance(db, session_id, flow.Shown(beat, tool_call_id, args.get("options")))if shown.result: # refused, or a beat this machine skipsreturn _result(shown)question = str(args.get("question") or "").strip() or QUESTIONS[beat]@@ -97,7 +97,8 @@ SETUP_BEAT_SCHEMA = {"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 "+ "they gave in words, skip to record that they skipped a beat. The build card needs options: your picks "+ "from the list its reminder gives. beat=done ends onboarding after the first ""build is shown and its close card is answered. Nothing here ends it early: a user who wants to stop ""presses Skip setup."),@@ -106,11 +107,15 @@ SETUP_BEAT_SCHEMA = {"required": ["beat"],"properties": {"beat": {"type": "string", "enum": list(BEATS)},- "question": {"type": "string", "description": "Your line above the card. The app fixes the options."},+ "question": {"type": "string", "description": "Your line above the card."},"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."},+ "options": {"type": "array", "maxItems": 4, "description": "build only: up to four picks, ids from the list.",+ "items": {"type": "object", "required": ["id", "label"],+ "properties": {"id": {"type": "string"},+ "label": {"type": "string", "maxLength": 32}}}},},},}