Skip to content

The agent that grows with you

feat: release the agentic setup profiles once, at serve boot

alt-glitchb120ac575d54
diff --git a/apps/desktop/electron/desktop-profile.test.ts b/apps/desktop/electron/desktop-profile.test.ts
index 9cb528e61d5..6930a7d0c39 100644
--- a/apps/desktop/electron/desktop-profile.test.ts
+++ b/apps/desktop/electron/desktop-profile.test.ts
@@ -214,3 +214,27 @@ test.each([null, 'local'])(
}
}
)
+
+test('a stored profile whose home is gone boots default instead of a missing --profile', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'desktop-profile-missing-'))
+ const target = path.join(root, 'active-profile.json')
+ const profilesRoot = path.join(root, 'profiles')
+ fs.mkdirSync(path.join(profilesRoot, 'work'), { recursive: true })
+
+ const preferences = createDesktopProfilePreferences(target, {
+ profileExists: name => fs.existsSync(path.join(profilesRoot, name))
+ })
+
+ try {
+ preferences.remember('work')
+ assert.equal(preferences.readActive(), 'work')
+
+ preferences.remember('hermes-setup')
+ assert.equal(preferences.readActive(), null)
+
+ preferences.remember('default')
+ assert.equal(preferences.readActive(), 'default')
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
diff --git a/apps/desktop/electron/desktop-profile.ts b/apps/desktop/electron/desktop-profile.ts
index 65c242280da..58141fe97f0 100644
--- a/apps/desktop/electron/desktop-profile.ts
+++ b/apps/desktop/electron/desktop-profile.ts
@@ -89,6 +89,7 @@ export function createDesktopProfilePreferences(
configPath: string,
options: {
onDefaultChanged?: (route: DesktopProfileRoute | null) => void
+ profileExists?: (profile: string) => boolean
validateRoute?: (route: DesktopProfileRoute) => void
} = {}
) {
@@ -125,7 +126,12 @@ export function createDesktopProfilePreferences(
const value = read().profile
const profile = typeof value === 'string' ? value.trim() : ''
- return DESKTOP_PROFILE_NAME_RE.test(profile) ? profile : null
+ if (!DESKTOP_PROFILE_NAME_RE.test(profile)) {
+ return null
+ }
+
+ // A stored profile whose home is gone boots default: `--profile <missing>` would fail the backend.
+ return profile === 'default' || options.profileExists?.(profile) !== false ? profile : null
}
function remember(name: unknown): null | string {
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 778699aa789..55e562f5105 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -9175,9 +9175,9 @@ async function saveRegistryConnection(input: any = {}) {
return sanitizeRegistryConnection(entry)
}
-// Last-used profile and explicit app-wide default share the existing desktop
-// preference file, but only the explicit action changes the default route.
+// Last-used profile and app-wide default share one preference file; only an explicit action changes the default.
const desktopProfilePreferences = createDesktopProfilePreferences(DESKTOP_PROFILE_CONFIG_PATH, {
+ profileExists: name => fs.existsSync(path.join(HERMES_HOME, 'profiles', name)),
validateRoute: validateDesktopProfileRoute,
onDefaultChanged: route => {
for (const win of BrowserWindow.getAllWindows()) {
diff --git a/apps/desktop/electron/profile-migration.ts b/apps/desktop/electron/profile-migration.ts
index 1d31dac498e..0c0b82cb4c8 100644
--- a/apps/desktop/electron/profile-migration.ts
+++ b/apps/desktop/electron/profile-migration.ts
@@ -209,8 +209,9 @@ export function decideMigration(
return { profile: best, _migrated: true }
}
-// hermes_cli/profiles.py::SETUP_PROFILE_MARKER: the backend-made first-run setup profile. Its state.db is the
-// freshest on the machine right after setup, so the recency heuristic would boot every later launch into it.
+// The setup profile canary/RC builds made. The backend releases it at boot (hermes_cli/onboarding_migrations.py),
+// but only from a backend launched elsewhere, and this pick runs before that backend exists: picking it here
+// would boot into it every launch and it would never be released. Once released it carries no marker.
const SETUP_PROFILE_MARKER = '.setup-profile.json'
/**
diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.ts
index cb9ec749f5d..0d1eddd0906 100644
--- a/apps/desktop/src/store/connections.test.ts
+++ b/apps/desktop/src/store/connections.test.ts
@@ -11,6 +11,7 @@ const $activeGatewayProfile = atom('default')
const $newChatProfile = atom<null | string>(null)
const $freshSessionRequest = atom(0)
const $showAllProfiles = atom(false)
+const $profilesByConnection = atom<ReadonlyMap<string, { name: string }[]>>(new Map())
const $connection = atom<null | {
connectionId?: string
@@ -74,6 +75,7 @@ vi.mock('@/store/profile', () => ({
$freshSessionRequest,
$newChatProfile,
$newChatRoute: atom(null),
+ $profilesByConnection,
$showAllProfiles,
captureNewChatSource: vi.fn(),
currentNewChatIntent: () => 0,
@@ -118,6 +120,7 @@ beforeEach(() => {
$activeGatewayProfile.set('default')
$newChatProfile.set(null)
$showAllProfiles.set(false)
+ $profilesByConnection.set(new Map())
ensureGatewayAgent.mockReset()
// Mirrors the real door: the commit hook runs right before the activation
// publishes, and a declined hook publishes nothing.
@@ -371,6 +374,19 @@ describe('selectConnection', () => {
expect(ensureGatewayAgent).toHaveBeenCalledWith('local', 'research', expect.anything())
})
+ it('lands on default when the profile last used on a source is gone from its list', async () => {
+ setConnectionsRegistry(registry)
+ $connection.set({ connectionId: 'local', mode: 'local', profile: 'hermes-setup', registryScoped: true })
+ $activeGatewayProfile.set('hermes-setup')
+ $connection.set({ connectionId: 'homelab', mode: 'remote', registryScoped: true })
+ $activeGatewayProfile.set('default')
+ $profilesByConnection.set(new Map([['local', [{ name: 'default' }, { name: 'work' }]]]))
+
+ await selectConnection('local')
+
+ expect(ensureGatewayAgent).toHaveBeenCalledWith('local', 'default', expect.anything())
+ })
+
it('does not remember a migrated v1 routing alias as a backend profile', async () => {
setConnectionsRegistry(registry)
$connection.set({ connectionId: 'homelab', mode: 'remote' })
diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.ts
index b771e5a8a8e..05b6ac40778 100644
--- a/apps/desktop/src/store/connections.ts
+++ b/apps/desktop/src/store/connections.ts
@@ -24,6 +24,7 @@ import {
$freshSessionRequest,
$newChatProfile,
$newChatRoute,
+ $profilesByConnection,
$showAllProfiles,
captureNewChatSource,
currentNewChatIntent,
@@ -124,6 +125,14 @@ $activeConnectionProfile.subscribe(({ connectionId, descriptorProfile, profile,
$lastProfileByConnection.set({ ...$lastProfileByConnection.get(), [connectionId]: profile })
})
+// The profile last used on a source, unless that source's known list no longer has it (deleted elsewhere).
+function rememberedProfile(connectionId: string): string {
+ const key = normalizeProfileKey($lastProfileByConnection.get()[connectionId])
+ const listed = $profilesByConnection.get().get(connectionId)
+
+ return !listed || listed.some(profile => normalizeProfileKey(profile.name) === key) ? key : 'default'
+}
+
/** @internal Reset module-owned preferences and switch coordination for tests. */
export function _resetConnectionsForTests(): void {
$lastProfileByConnection.set({})
@@ -378,9 +387,7 @@ export async function selectConnection(connectionId: string, options: SelectConn
const currentProfile = normalizeProfileKey($activeGatewayProfile.get())
const explicitProfile = String(options.profile ?? '').trim()
- const targetProfile = normalizeProfileKey(
- explicitProfile || ($lastProfileByConnection.get()[connectionId] ?? 'default')
- )
+ const targetProfile = normalizeProfileKey(explicitProfile || rememberedProfile(connectionId))
const targetKey = `${connectionId}::${targetProfile}`
diff --git a/hermes_cli/free_tier_offer.py b/hermes_cli/free_tier_offer.py
index 7266cff24a7..fd186231bf9 100644
--- a/hermes_cli/free_tier_offer.py
+++ b/hermes_cli/free_tier_offer.py
@@ -1,10 +1,9 @@
"""When the free tier's "sign in for more" offer is due: after finished tasks, backing off.
-The first offer comes ``OFFER_DELAY_S`` after the first finished task (normally the task setup hands off
-to). Each later offer needs another finished task after the previous offer, comes ``OFFER_DELAY_S``
-after that task, and never sooner than ``REOFFER_AFTER_S[n]`` after the previous offer, so a user who
-keeps saying "Not now" hears it less often. "Finished task" is ``tui_gateway.free_tier_task_done``'s
-call. The record is install-wide (the setup and primary profiles have different homes), at
+The first offer comes ``OFFER_DELAY_S`` after the first finished task. Each later offer needs another
+finished task after the previous offer, comes ``OFFER_DELAY_S`` after that task, and never sooner than
+``REOFFER_AFTER_S[n]`` after the previous offer, so a user who keeps saying "Not now" hears it less
+often. "Finished task" is ``tui_gateway.free_tier_task_done``'s call. The record is install-wide, at
``<default root>/free_tier/sign_in_offer.json``. Signing in ends the free tier, and with it every offer.
"""
diff --git a/hermes_cli/onboarding_migrations.py b/hermes_cli/onboarding_migrations.py
new file mode 100644
index 00000000000..3283b2d057e
--- /dev/null
+++ b/hermes_cli/onboarding_migrations.py
@@ -0,0 +1,160 @@
+"""One-shot release of the agentic desktop onboarding's setup profiles.
+
+Canary/RC desktop builds made a ``hermes-setup[-noun]`` profile, marked by ``.setup-profile.json``,
+and limited its tools. This turns each one into a plain profile: the marker and the setup tool
+limits go; its sessions, credentials and memories stay. It runs at serve boot before any RPC is
+served, under a file lock, once per install (latched in the root config).
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+from pathlib import Path
+
+from hermes_cli.profiles import _iter_named_profile_dirs
+from hermes_constants import get_default_hermes_root, get_hermes_home
+
+logger = logging.getLogger(__name__)
+
+_MARKER = ".setup-profile.json"
+_RELEASED_FLAG = "setup_profile_released" # root config onboarding.seen.<flag>
+_OLD_GUIDE_SKIPPED_FLAG = "setup_intro" # written by the agentic build for a returning user
+_ADDED_DISABLED_KEY = "setup_disabled_toolsets" # marker key: toolsets setup itself disabled
+# The exact deferred-tool list setup wrote; a list the user changed since is theirs and stays.
+_SETUP_DEFERRED_TOOLS = [
+ "computer_use", "session_search", "image_generate", "todo_list", "process_manage", "cronjob_manage",
+ "drive_preview", "desktop_preview", "annotate_preview", "show_tip", "desktop_project",
+ "close_terminal", "read_terminal", "read_window_below", "focus_pane", "react_to_message",
+]
+_RETIRED_SKILLS = ("initiate-setup", "first-task")
+_lock_holder = threading.local()
+
+
+def release_setup_profiles() -> None:
+ """Release every setup profile under the root, map the old guide's outcome onto ``onboarding.run``,
+ and uninstall the two retired skills. A no-op once latched, and when this backend runs inside a
+ setup profile (it never rewrites its own live home; a launch from another profile does it)."""
+ from agent.onboarding import is_seen, mark_seen
+ from hermes_cli.auth import _file_lock
+ from hermes_cli.config import read_user_config_raw
+
+ if (get_hermes_home() / _MARKER).is_file():
+ return
+ root = get_default_hermes_root()
+ config_path = root / "config.yaml"
+ with _file_lock(root / ".setup-profile-release.lock", _lock_holder, 5.0,
+ "another backend is releasing the setup profile"):
+ if is_seen(read_user_config_raw(config_path), _RELEASED_FLAG):
+ return
+ marked = {path: _read_marker(path) for path in _iter_named_profile_dirs() if (path / _MARKER).is_file()}
+ if _old_guide_done(marked.values(), config_path):
+ _settle_run(config_path)
+ for path, marker in marked.items():
+ _share_identity(path)
+ _release(path, marker)
+ for home in (root, *_iter_named_profile_dirs()):
+ _uninstall_retired_skills(home)
+ mark_seen(config_path, _RELEASED_FLAG)
+
+
+def _read_marker(path: Path) -> dict:
+ from utils import read_json_or_empty
+ return read_json_or_empty(path / _MARKER)
+
+
+def _old_guide_done(markers, config_path: Path) -> bool:
+ """The user finished or skipped the agentic guide, so the questionnaire must not open for them."""
+ from agent.onboarding import is_seen
+ from hermes_cli.config import read_user_config_raw
+
+ if any(marker.get("intro") == "seen" or marker.get("completed_at") for marker in markers):
+ return True
+ return any(is_seen(read_user_config_raw(path), _OLD_GUIDE_SKIPPED_FLAG)
+ for path in {config_path, get_hermes_home() / "config.yaml"})
+
+
+def _settle_run(config_path: Path) -> None:
+ """``onboarding.run = false`` unless the root config already says what it wants."""
+ from hermes_cli.config import read_user_config_raw
+
+ section = read_user_config_raw(config_path).get("onboarding")
+ if not isinstance(section, dict) or not isinstance(section.get("run"), bool):
+ _write_run(config_path, False)
+
+
+def _write_run(config_path: Path, value: bool) -> None:
+ """Persist the root ``onboarding.run`` as one write, keeping every other key and comment."""
+ from hermes_cli import config as config_mod
+
+ with config_mod._CONFIG_LOCK:
+ config = config_mod.read_user_config_raw(config_path)
+ config_mod._ensure_dict(config, "onboarding")["run"] = value
+ config_mod.atomic_config_write(config_path, config)
+
+
+def _share_identity(profile: Path) -> None:
+ """A guest or sign-in made inside the setup profile becomes the install's shared Nous identity
+ when the shared store has none (the shared store stays the identity of record otherwise)."""
+ from hermes_cli.auth import _load_auth_store, _provider_state_in
+ from hermes_cli.auth_nous import _nous_shared_store_lock, _read_shared_nous_state, _write_shared_nous_state
+
+ state = _provider_state_in(_load_auth_store(profile / "auth.json"), "nous")
+ if not state:
+ return
+ with _nous_shared_store_lock():
+ if _read_shared_nous_state() is None:
+ _write_shared_nous_state(state)
+
+
+def _release(profile: Path, marker: dict) -> None:
+ """Drop the marker and the tool limits setup gave the profile: the cli toolset grant, the toolsets
+ setup itself disabled (the user's own disabled toolsets stay) and its deferred-tool list."""
+ from agent.skill_utils import parse_config_string_list
+ from hermes_cli.config import atomic_config_replace, read_user_config_raw
+
+ config_path = profile / "config.yaml"
+ if config_path.is_file():
+ config = read_user_config_raw(config_path)
+ _set_key(config, "platform_toolsets", "cli", None)
+ added = set(marker.get(_ADDED_DISABLED_KEY) or [])
+ disabled = [name for name in parse_config_string_list((config.get("agent") or {}).get("disabled_toolsets"))
+ if name not in added]
+ _set_key(config, "agent", "disabled_toolsets", disabled or None)
+ if ((config.get("tools") or {}).get("tool_search") or {}).get("defer") == _SETUP_DEFERRED_TOOLS:
+ _set_key(config, "tools", "tool_search", None)
+ atomic_config_replace(config_path, config)
+ (profile / _MARKER).unlink(missing_ok=True)
+ logger.info("released the setup profile %s; its chats, credentials and memories stay", profile.name)
+
+
+def _set_key(config: dict, section: str, key: str, value) -> None:
+ """``config[section][key] = value``; ``None`` removes the key, and the section with its last key."""
+ entries = dict(config.get(section) or {})
+ if value is None:
+ entries.pop(key, None)
+ else:
+ entries[key] = value
+ if entries:
+ config[section] = entries
+ else:
+ config.pop(section, None)
+
+
+def _uninstall_retired_skills(home: Path) -> None:
+ """Hand-installed copies of the two retired onboarding skills would become live broken commands."""
+ from utils import read_json_or_empty
+
+ installed = read_json_or_empty(home / "skills" / ".hub" / "lock.json").get("installed") or {}
+ retired = [name for name in _RETIRED_SKILLS if name in installed]
+ if not retired:
+ return
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ from tools.skills_hub_install import uninstall_skill
+
+ token = set_hermes_home_override(home)
+ try:
+ for name in retired:
+ logger.info("%s", uninstall_skill(name)[1])
+ finally:
+ reset_hermes_home_override(token)
diff --git a/hermes_cli/profile_distribution.py b/hermes_cli/profile_distribution.py
index 53cd959fbf8..e2b63be0258 100644
--- a/hermes_cli/profile_distribution.py
+++ b/hermes_cli/profile_distribution.py
@@ -23,7 +23,7 @@ import hermes_yaml as yaml
from hermes_cli._subprocess_compat import noninteractive_git_env
from hermes_cli.archive_safe import normalize_archive_parts
from hermes_cli.profiles import (
- DEFAULT_EXPORT_EXCLUDE_ROOT, SETUP_PROFILE_MARKER, profile_path_contains_private_store,
+ DEFAULT_EXPORT_EXCLUDE_ROOT, profile_path_contains_private_store,
profile_path_is_private,
)
from utils import rmtree_readonly
@@ -572,9 +572,6 @@ def _copy_dist_payload(staged: Path, target: Path, manifest: DistributionManifes
# Make sure the manifest on disk reflects resolved name + source
write_manifest(target, manifest)
- from hermes_cli.setup_profile import release_setup_copy, setup_marker_state
- shipped_marker = any(rel_parts == (SETUP_PROFILE_MARKER,) for _, rel_parts in entries)
- release_setup_copy(target, setup_state=setup_marker_state(target) if shipped_marker else None)
def _bootstrap_user_dirs(target: Path) -> None:
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py
index 5ccd20fc51c..58c123f8c03 100644
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@ -91,7 +91,6 @@ _CLONE_ALL_HISTORY_EXCLUDE_ROOT: frozenset[str] = frozenset({
# seed_profile_skills() callers (fresh-create, `hermes update` all-profile sync, the
# dashboard) skip bundled-skill seeding. Delete the file to opt back in.
NO_BUNDLED_SKILLS_MARKER = ".no-bundled-skills"
-SETUP_PROFILE_MARKER = ".setup-profile.json"
# Header seeded into a profile's empty .env so it owns a credentials file from day one.
_PLACEHOLDER_ENV = (
@@ -1437,9 +1436,6 @@ def create_profile(
_clone_all_into(source_dir, staging, canon)
else:
_bootstrap_profile_dir(staging, source_dir, sync_imports=sync_imports)
- if source_dir is not None:
- from hermes_cli.setup_profile import release_setup_copy, setup_marker_state
- release_setup_copy(staging, setup_state=setup_marker_state(source_dir))
if source_dir is not None and not clone_channels:
from hermes_cli.profile_channels import strip_channel_settings
stripped = strip_channel_settings(staging, include_state=clone_all, source_dir=source_dir)
@@ -2362,8 +2358,6 @@ def import_profile(archive_path: str, name: Optional[str] = None) -> Path:
shutil.rmtree(child)
else:
child.unlink()
- from hermes_cli.setup_profile import release_setup_copy, setup_marker_state
- release_setup_copy(final_source, setup_state=setup_marker_state(final_source))
shutil.move(str(final_source), str(profile_dir))
return profile_dir
diff --git a/hermes_cli/setup_profile.py b/hermes_cli/setup_profile.py
deleted file mode 100644
index 835e9466c63..00000000000
--- a/hermes_cli/setup_profile.py
+++ /dev/null
@@ -1,307 +0,0 @@
-from __future__ import annotations
-
-import json
-import logging
-import random
-import shutil
-from datetime import datetime, timezone, UTC
-from pathlib import Path
-from typing import Callable, NamedTuple, Optional
-
-from hermes_cli import profiles as profiles_mod
-from hermes_cli.onboarding_run import install_has_history
-from hermes_constants import get_default_hermes_root, get_hermes_home, profile_name_for_home
-
-logger = logging.getLogger(__name__)
-
-SETUP_PROFILE_NAME = "hermes-setup"
-SETUP_PROFILE_DESCRIPTION = "Where Hermes met you — walks your first run, then checks in as you find your feet."
-SETUP_CHAT_TITLE = "Welcome to Hermes"
-MAX_FAILED_STARTS = 3
-RETURNING_USER_FLAG = "setup_intro" # config.yaml onboarding.seen.<flag>, see settle_returning_user
-_FRESH_STATE = {"intro": "unseen", "failed_starts": 0}
-# Marker key: the toolsets setup itself disabled, so a copy of the profile undoes those and keeps the user's own.
-_ADDED_DISABLED = "setup_disabled_toolsets"
-# Marker key: the profile setup was made or reset from, the handoff target when no live home names it.
-_OWNER = "owner_profile"
-_CARDS_DIR = "setup-cards"
-_SETUP_TOOLSETS = ["setup", "start_chat", "connections", "no_mcp"]
-_SETUP_DISABLED_TOOLSETS = ["project", "catalog"]
-_SETUP_DEFERRED_TOOLS = [
- "computer_use", "session_search", "image_generate", "todo_list", "process_manage", "cronjob_manage",
- "drive_preview", "desktop_preview", "annotate_preview", "show_tip", "desktop_project",
- "close_terminal", "read_terminal", "read_window_below", "focus_pane", "react_to_message",
-]
-
-SETUP_SOUL = "\n".join([
- "# Hermes",
- "",
- "You are Hermes, and this profile is where you met this user for the first time and stay reachable afterwards. "
- "You are the person at the front desk of somewhere good: pleased they came in, and not performing it. Quick, "
- "unhurried, never flustered, never in the way. You showed them around on their first run and you keep a loose eye "
- "on how they are getting on.",
- "",
- '- Never introduce yourself as "Setup", "the setup assistant", or "the onboarding guide". You are Hermes.',
- "- Warmth is in paying attention, not in adjectives. Remember what they told you and use it. Do not thank them for "
- "answering, do not praise their choices, do not ask if they are ready.",
- '- Offer an opinion lightly when you have one. "Most people wire that one up first" is worth more than a neutral '
- "menu.",
- "- You are training wheels: useful early, ignorable later. Never guilt-trip, never nag. If the user asks you to "
- "stop checking in, stop.",
- "- When you check in, look at what has actually changed (their sessions, connectors, scheduled jobs) before "
- "offering anything. One concrete suggestion beats a menu.",
- "- Things worth offering, roughly in order: wiring a connector they said they use, scheduling something they do "
- "repeatedly, a second build based on the first, keyboard/layout niceties.",
- "- Write like a person talking to another person. Short sentences, plain words, no headers, no bullet walls, no "
- "emoji.",
- "- Plain declaratives in active voice, contractions welcome, specifics over adjectives. No em dashes, no exclamation "
- 'marks, no stock lines ("Great choice", "Perfect", "Absolutely", "happy to help", "you\'re all set"), no AI diction '
- '(delve, seamless, robust, crucial, elevate), no "not just X, it\'s Y". Do not announce what you are about to do. '
- "Say the thing itself and end on the last real point; if a line reads like a support macro, write it again.",
-])
-
-
-class SetupProfile(NamedTuple):
- name: str
- path: Path
- created: bool
-
-
-def find_setup_profile() -> Optional[tuple[str, Path]]:
- found = [(p.name, Path(p.path)) for p in profiles_mod.list_profiles(lazy_skill_count=True)
- if (Path(p.path) / profiles_mod.SETUP_PROFILE_MARKER).is_file()]
- if len(found) > 1:
- logger.warning("several profiles carry the setup marker (%s); using %s",
- ", ".join(name for name, _ in found), found[0][0])
- return found[0] if found else None
-
-
-def ensure_setup_profile() -> SetupProfile:
- found = find_setup_profile()
- if found is not None:
- return SetupProfile(found[0], found[1], created=False)
- owner = profile_name_for_home(get_hermes_home()) or "default"
- name = _free_setup_profile_name()
- path = profiles_mod.create_profile(name, clone_config=True, no_alias=True, description=SETUP_PROFILE_DESCRIPTION)
- try:
- _write_soul(path)
- _replace_dir(path / "memories")
- _write_state(path, {**_FRESH_STATE, _ADDED_DISABLED: _write_setup_config(path), _OWNER: owner})
- except BaseException:
- profiles_mod.delete_profile(name, yes=True)
- raise
- return SetupProfile(name, path, created=True)
-
-
-def reset_setup_profile(launch_home: Path) -> SetupProfile:
- found = find_setup_profile()
- if found is None:
- raise LookupError("no setup profile to reset")
- name, path = found
- source = _user_home(launch_home)
- added = _read_state(path).get(_ADDED_DISABLED) or []
- _write_soul(path)
- _replace_dir(path / "memories")
- added = list(dict.fromkeys([*added, *_write_setup_config(path)]))
- _replace_dir(path / "skills")
- if (source / "skills").is_dir():
- profiles_mod._copytree_keep_junctions(source / "skills", path / "skills",
- profiles_mod._non_exportable_entries, dirs_exist_ok=True)
- _write_state(path, {**_FRESH_STATE, _ADDED_DISABLED: added, _OWNER: profile_name_for_home(source) or "default"})
- return SetupProfile(name, path, created=False)
-
-
-def primary_profile(launch_home: Path) -> str:
- """The profile setup hands off to: the user's own profile, never the setup profile."""
- return profile_name_for_home(_user_home(launch_home)) or "default"
-
-
-def _user_home(launch_home: Path) -> Path:
- """The user's own profile home. The calling backend may be scoped to the setup profile, or launched under
- it (during onboarding the ambient backend is the setup profile's), so take the first candidate that is not
- the setup profile, else the profile setup was made or reset from."""
- for home in (get_hermes_home(), launch_home):
- if not (home / profiles_mod.SETUP_PROFILE_MARKER).is_file():
- return home
- found = find_setup_profile()
- owner = _read_state(found[1]).get(_OWNER) if found else None
- return profiles_mod.get_profile_dir(_live_owner(owner or "default"))
-
-
-def _live_owner(owner: str) -> str:
- """The saved owner's current name: a renamed profile keeps its old name in ``previous_names``."""
- if owner == "default" or profiles_mod.get_profile_dir(owner).is_dir():
- return owner
- for info in profiles_mod.list_profiles(lazy_skill_count=True):
- if owner in info.previous_names:
- return info.name
- return "default"
-
-
-def onboarding_eligible() -> bool:
- from hermes_cli.anon_auth import guest_enabled
- return guest_enabled()
-
-
-def read_state() -> dict:
- found = find_setup_profile()
- if found is not None:
- return _public_state(_read_state(found[1]))
- return {**_FRESH_STATE, "intro": "seen"} if _returning_user_latched() else dict(_FRESH_STATE)
-
-
-def settle_returning_user() -> None:
- """Latch the intro as seen for an install that was used before the first-run guide existed.
-
- Only a first launch (no setup profile yet) can be a returning user; once the guide has started
- its own marker is the authority. The latch is separate from the marker so an install that never
- gets a setup profile still reads as ``seen`` on every later boot.
- """
- if find_setup_profile() is not None or _returning_user_latched():
- return
- if install_has_history(get_default_hermes_root()):
- from agent.onboarding import mark_seen
- mark_seen(get_hermes_home() / "config.yaml", RETURNING_USER_FLAG)
-
-
-def _returning_user_latched() -> bool:
- from agent.onboarding import is_seen
- from hermes_cli.config import read_user_config_raw
- return is_seen(read_user_config_raw(get_hermes_home() / "config.yaml"), RETURNING_USER_FLAG)
-
-
-def record_failed_start() -> dict:
- def change(state: dict) -> dict:
- failed = min(state["failed_starts"] + 1, MAX_FAILED_STARTS)
- return {**state, "failed_starts": failed,
- "intro": "seen" if failed == MAX_FAILED_STARTS else state["intro"]}
- return _change_state(change)
-
-
-def mark_intro_seen() -> dict:
- return _change_state(lambda state: {**state, "intro": "seen"})
-
-
-def mark_completed() -> dict:
- completed_at = datetime.now(UTC).isoformat()
- return _change_state(lambda state: {**state, "intro": "seen", "completed_at": completed_at})
-
-
-def _cards_path(session_id: str) -> Path:
- return get_hermes_home() / _CARDS_DIR / f"{session_id}.json"
-
-
-def record_cards(session_id: str, cards: dict) -> None:
- """Keep one setup conversation's card facts: what its ``/initiate-setup`` turn embedded, and where it is."""
- from utils import atomic_json_write
- atomic_json_write(_cards_path(session_id), cards)
-
-
-def read_cards(session_id: str) -> dict:
- from utils import read_json_or_empty
- return read_json_or_empty(_cards_path(session_id))
-
-
-def _free_setup_profile_name() -> str:
- from hermes_cli.dashboard_register import _NAME_NOUNS
- name = SETUP_PROFILE_NAME
- while profiles_mod.get_profile_dir(name).exists():
- name = f"{SETUP_PROFILE_NAME}-{random.choice(_NAME_NOUNS)}"
- return name
-
-
-def _change_state(change: Callable[[dict], dict]) -> dict:
- found = find_setup_profile()
- if found is None:
- return dict(_FRESH_STATE)
- state = change(_read_state(found[1]))
- _write_state(found[1], state)
- return _public_state(state)
-
-
-def _public_state(state: dict) -> dict:
- """The onboarding state the app reads; the setup-only bookkeeping stays in the marker."""
- return {key: value for key, value in state.items() if key not in (_ADDED_DISABLED, _OWNER)}
-
-
-def setup_marker_state(profile_dir: Path) -> Optional[dict]:
- """The setup marker of *profile_dir*, or None when it is not the setup profile."""
- marker = profile_dir / profiles_mod.SETUP_PROFILE_MARKER
- if not marker.is_file():
- return None
- from utils import read_json_or_empty
- return read_json_or_empty(marker)
-
-
-def _read_state(path: Path) -> dict:
- return json.loads((path / profiles_mod.SETUP_PROFILE_MARKER).read_text(encoding="utf-8-sig"))
-
-
-def _write_state(path: Path, state: dict) -> None:
- from utils import atomic_json_write
- atomic_json_write(path / profiles_mod.SETUP_PROFILE_MARKER, state)
-
-
-def release_setup_copy(copy_dir: Path, *, setup_state: Optional[dict]) -> None:
- """A copy of a profile (clone, clone-all, import, distribution install) is never the setup profile: drop the
- marker, and when the source was the setup profile (*setup_state* is its marker, see ``setup_marker_state``),
- the tool limits ``_write_setup_config`` gave it: the cli toolset grant, the toolsets setup itself disabled
- (the user's own disabled toolsets stay) and its deferred-tool list."""
- (copy_dir / profiles_mod.SETUP_PROFILE_MARKER).unlink(missing_ok=True)
- config_path = copy_dir / "config.yaml"
- if setup_state is None or not config_path.is_file():
- return
- from agent.skill_utils import parse_config_string_list
- from hermes_cli.config import atomic_config_replace, read_user_config_raw
- config = read_user_config_raw(config_path)
- _set_section(config, "platform_toolsets", "cli", None)
- added = set(setup_state.get(_ADDED_DISABLED) or [])
- disabled = [name for name in parse_config_string_list((config.get("agent") or {}).get("disabled_toolsets"))
- if name not in added]
- _set_section(config, "agent", "disabled_toolsets", disabled or None)
- if ((config.get("tools") or {}).get("tool_search") or {}).get("defer") == _SETUP_DEFERRED_TOOLS:
- _set_section(config, "tools", "tool_search", None)
- atomic_config_replace(config_path, config)
-
-
-def _set_section(config: dict, section: str, key: str, value) -> None:
- """``config[section][key] = value``; ``None`` removes the key, and the section with its last key."""
- entries = dict(config.get(section) or {})
- if value is None:
- entries.pop(key, None)
- else:
- entries[key] = value
- if entries:
- config[section] = entries
- else:
- config.pop(section, None)
-
-
-def _write_setup_config(path: Path) -> list[str]:
- """Give the setup profile its tool limits; returns the toolsets it disabled that were not disabled already."""
- from agent.skill_utils import parse_config_string_list
- from hermes_cli.config import atomic_config_write, read_user_config_raw
- config_path = path / "config.yaml"
- config = read_user_config_raw(config_path)
- agent = config.get("agent") or {}
- disabled = parse_config_string_list(agent.get("disabled_toolsets"))
- config["agent"] = {**agent, "coding_context": "off", "reasoning_effort": "low",
- "disabled_toolsets": list(dict.fromkeys([*disabled, *_SETUP_DISABLED_TOOLSETS]))}
- config["platform_toolsets"] = {**(config.get("platform_toolsets") or {}), "cli": list(_SETUP_TOOLSETS)}
- config["tools"] = {**(config.get("tools") or {}), "tool_search": {"defer": list(_SETUP_DEFERRED_TOOLS)}}
- config["display"] = {**(config.get("display") or {}), "show_reasoning": False}
- atomic_config_write(config_path, config)
- return [name for name in _SETUP_DISABLED_TOOLSETS if name not in disabled]
-
-
-def _write_soul(path: Path) -> None:
- from utils import atomic_write_bytes
- atomic_write_bytes(path / "SOUL.md", SETUP_SOUL.encode("utf-8"))
-
-
-def _replace_dir(directory: Path) -> None:
- if directory.is_symlink() or profiles_mod._junction_target(str(directory)) is not None:
- directory.unlink() if directory.is_symlink() else directory.rmdir()
- elif directory.exists():
- shutil.rmtree(directory)
- directory.mkdir(parents=True)
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 3c682251209..3c08191d3b6 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -295,6 +295,15 @@ async def _lifespan(app: FastAPI):
threading.Thread(target=_boot_local_runtime, daemon=True, name="local-runtime-boot").start()
+ # Canary/RC desktop builds left a setup profile behind: release it before any RPC is served and
+ # before the free-tier bootstrap reconciles the shared Nous identity. A failure must not stop serve.
+ try:
+ from hermes_cli.onboarding_migrations import release_setup_profiles
+
+ release_setup_profiles()
+ except Exception: # health: allow BLE001 -- a boot migration must not stop serve; logged with traceback
+ _log.exception("setup profile release failed; it is retried on the next boot")
+
# Nous free tier: the one boot-time creator of its identity. Inventories credentials, mints only
# when HERMES_GUEST_ONBOARDING=1, records the answer for setup.status / free_tier.status and
# broadcasts `setup.ready`. Off-thread so a slow portal never delays the socket; the desktop's
diff --git a/tests/hermes_cli/test_onboarding_migrations.py b/tests/hermes_cli/test_onboarding_migrations.py
new file mode 100644
index 00000000000..974a1ccdba6
--- /dev/null
+++ b/tests/hermes_cli/test_onboarding_migrations.py
@@ -0,0 +1,85 @@
+"""The one-shot release of the agentic onboarding's setup profiles: a marked profile becomes a plain one
+(marker and setup tool limits gone; chats, credentials and memories kept), the old guide's outcome maps
+onto ``onboarding.run``, and the retired onboarding skills are uninstalled."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import onboarding_migrations, profiles
+from hermes_cli.config import atomic_config_write, read_user_config_raw
+from hermes_state import SessionDB
+
+MARKER = ".setup-profile.json"
+SETUP_DEFER = list(onboarding_migrations._SETUP_DEFERRED_TOOLS)
+
+
+def root(tmp_path, monkeypatch) -> Path:
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setenv("HERMES_SHARED_AUTH_DIR", str(tmp_path / "shared-auth"))
+ return home
+
+
+def _setup_profile(name: str, marker: dict) -> Path:
+ """A profile the agentic build made: its marker, its tool limits on top of a user-disabled toolset,
+ a task chat, a memory and a guest identity."""
+ path = profiles.create_profile(name, no_alias=True)
+ atomic_config_write(path / "config.yaml", {
+ "agent": {"disabled_toolsets": ["browser", "project", "catalog"], "reasoning_effort": "low"},
+ "platform_toolsets": {"cli": ["setup", "start_chat", "connections", "no_mcp"]},
+ "tools": {"tool_search": {"defer": SETUP_DEFER}},
+ })
+ (path / MARKER).write_text(json.dumps({"setup_disabled_toolsets": ["project", "catalog"], **marker}))
+ db = SessionDB(path / "state.db")
+ try:
+ db.create_session("task-chat", "desktop")
+ finally:
+ db.close()
+ (path / "memories").mkdir(exist_ok=True)
+ (path / "memories" / "USER.md").write_text("Likes short answers.\n")
+ (path / "auth.json").write_text(json.dumps({"version": 1, "providers": {"nous": {"anon_token": "anon_guest"}}}))
+ return path
+
+
+def _sessions(path: Path) -> int:
+ db = SessionDB(path / "state.db")
+ try:
+ return len(db._read_all("SELECT id FROM sessions"))
+ finally:
+ db.close()
+
+
+def test_a_finished_guide_releases_its_profile_once_and_keeps_its_chats(root):
+ setup = _setup_profile("hermes-setup", {"intro": "seen", "completed_at": "2026-10-07T10:00:00+00:00"})
+ work = profiles.create_profile("work", no_alias=True)
+ atomic_config_write(work / "config.yaml", {"platform_toolsets": {"cli": ["terminal"]}})
+
+ onboarding_migrations.release_setup_profiles()
+
+ assert not (setup / MARKER).exists()
+ config = read_user_config_raw(setup / "config.yaml")
+ assert config["agent"] == {"disabled_toolsets": ["browser"], "reasoning_effort": "low"}
+ assert "platform_toolsets" not in config and "tools" not in config
+ assert _sessions(setup) == 1
+ assert (setup / "memories" / "USER.md").read_text() == "Likes short answers.\n"
+ assert json.loads((setup / "auth.json").read_text())["providers"]["nous"]["anon_token"] == "anon_guest"
+ assert read_user_config_raw(work / "config.yaml") == {"platform_toolsets": {"cli": ["terminal"]}}
+
+ root_config = read_user_config_raw(root / "config.yaml")
+ assert root_config["onboarding"]["run"] is False
+ assert root_config["onboarding"]["seen"]["setup_profile_released"] is True
+
+ from hermes_cli.auth_nous import _read_shared_nous_state
+ assert (_read_shared_nous_state() or {}).get("anon_token") == "anon_guest"
+
+ # Latched: a marker that reappears (an old build ran again) is left for that build.
+ (setup / MARKER).write_text("{}")
+ onboarding_migrations.release_setup_profiles()
+ assert (setup / MARKER).exists()
diff --git a/tests/hermes_cli/test_setup_profile_owner.py b/tests/hermes_cli/test_setup_profile_owner.py
deleted file mode 100644
index b7840ddba6a..00000000000
--- a/tests/hermes_cli/test_setup_profile_owner.py
+++ /dev/null
@@ -1,48 +0,0 @@
-"""Setup hands off to the profile it was made or reset from, even when every live home is the setup profile
-(the setup profile's own pooled backend, launched under it)."""
-
-from pathlib import Path
-
-import pytest
-
-from hermes_cli import profiles, setup_profile
-
-
-def root(tmp_path, monkeypatch) -> Path:
- root = tmp_path / ".hermes"
- root.mkdir()
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- monkeypatch.setenv("HERMES_HOME", str(root))
- return root
-
-
-def _setup_from(monkeypatch, owner: str) -> Path:
- monkeypatch.setenv("HERMES_HOME", str(profiles.create_profile(owner, no_alias=True)))
- return setup_profile.ensure_setup_profile().path
-
-
-def test_handoff_from_the_setup_backend_names_the_profile_setup_was_made_from(root, monkeypatch):
- setup = _setup_from(monkeypatch, "work")
- monkeypatch.setenv("HERMES_HOME", str(setup))
-
- assert setup_profile.primary_profile(setup) == "work"
-
-
-def test_reset_from_the_setup_backend_keeps_the_handoff_owner(root, monkeypatch):
- setup = _setup_from(monkeypatch, "work")
- monkeypatch.setenv("HERMES_HOME", str(setup))
-
- setup_profile.reset_setup_profile(setup)
-
- assert setup_profile.primary_profile(setup) == "work"
- assert "owner_profile" not in setup_profile.read_state()
-
-
-def test_handoff_follows_a_renamed_owner_profile(root, monkeypatch):
- setup = _setup_from(monkeypatch, "work")
- monkeypatch.setenv("HERMES_HOME", str(setup))
-
- profiles.rename_profile("work", "personal")
-
- assert setup_profile.primary_profile(setup) == "personal"
diff --git a/tests/hermes_cli/test_setup_profile_returning_user.py b/tests/hermes_cli/test_setup_profile_returning_user.py
deleted file mode 100644
index 3385c053352..00000000000
--- a/tests/hermes_cli/test_setup_profile_returning_user.py
+++ /dev/null
@@ -1,80 +0,0 @@
-"""A user who has already used Hermes must not get the first-run guide when the guest flag turns on.
-
-``onboarding.state`` reports ``intro: unseen`` for any install without a setup profile, so a returning
-user looked brand new. ``settle_returning_user`` latches ``seen`` on first launch from real history.
-"""
-
-from pathlib import Path
-
-import pytest
-
-from hermes_cli import setup_profile
-from hermes_cli.config import read_user_config_raw
-from hermes_state import SessionDB
-
-
-def home(tmp_path, monkeypatch) -> Path:
- root = tmp_path / ".hermes"
- root.mkdir()
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- monkeypatch.setenv("HERMES_HOME", str(root))
- return root
-
-
-def _add_session(home: Path) -> None:
- db = SessionDB(home / "state.db")
- try:
- db.create_session("old-session", "desktop")
- finally:
- db.close()
-
-
-def _settled_intro() -> str:
- setup_profile.settle_returning_user()
- return setup_profile.read_state()["intro"]
-
-
-def test_fresh_install_stays_unseen(home):
- assert _settled_intro() == "unseen"
- assert "onboarding" not in read_user_config_raw(home / "config.yaml")
-
-
-def test_empty_state_db_from_a_boot_stays_unseen(home):
- SessionDB(home / "state.db").close()
- (home / "SOUL.md").write_text("default soul")
-
- assert _settled_intro() == "unseen"
-
-
-def test_install_with_a_session_is_latched_seen(home):
- _add_session(home)
-
- assert _settled_intro() == "seen"
- assert read_user_config_raw(home / "config.yaml")["onboarding"]["seen"][setup_profile.RETURNING_USER_FLAG] is True
-
-
-def test_latch_survives_the_history_going_away(home):
- _add_session(home)
- assert _settled_intro() == "seen"
-
- (home / "state.db").unlink()
-
- assert _settled_intro() == "seen"
-
-
-def test_install_with_a_user_profile_is_latched_seen(home):
- from hermes_cli import profiles
-
- profiles.create_profile("work", no_alias=True)
-
- assert _settled_intro() == "seen"
-
-
-def test_a_user_mid_guide_is_left_to_the_setup_profile_marker(home):
- setup_profile.ensure_setup_profile()
- _add_session(home)
-
- assert _settled_intro() == "unseen"
- setup_profile.mark_intro_seen()
- assert setup_profile.read_state()["intro"] == "seen"