The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): profiles cluster — AST-neutral bracket/string folding
Teknium02226f9ef36c
diff --git a/hermes_cli/profile_cmd.py b/hermes_cli/profile_cmd.pyindex 5429c8e77a2..f233533e187 100644--- a/hermes_cli/profile_cmd.py+++ b/hermes_cli/profile_cmd.py@@ -127,12 +127,10 @@ def _profile_list(args):returnprint(- f"\n {'Profile':<16} {'Model':<28} {'Gateway':<12} "- f"{'Alias':<12} {'Distribution'}"+ f"\n {'Profile':<16} {'Model':<28} {'Gateway':<12} {'Alias':<12} {'Distribution'}")print(- f" {'─' * 15} {'─' * 27} {'─' * 11} "- f"{'─' * 11} {'─' * 20}"+ f" {'─' * 15} {'─' * 27} {'─' * 11} {'─' * 11} {'─' * 20}")for p in profiles:@@ -210,8 +208,7 @@ def _profile_create(args):result = seed_profile_skills(profile_dir)if result and result.get("skipped_opt_out"):print(- "No bundled skills seeded (--no-skills). "- "Delete .no-bundled-skills in the profile to opt back in."+ "No bundled skills seeded (--no-skills). Delete .no-bundled-skills in the profile to opt back in.")elif result:print(f"{len(result.get('copied', []))} bundled skills synced.")@@ -311,9 +308,7 @@ def _profile_describe(args):if text_value:try:_profiles_mod.write_profile_meta(- _describe_target_dir(name),- description=text_value,- description_auto=False,+ _describe_target_dir(name), description=text_value, description_auto=False)print(f"Description updated for '{name}'.")except Exception as exc:diff --git a/hermes_cli/profile_describer.py b/hermes_cli/profile_describer.pyindex 17e36afa161..e94dc5897fe 100644--- a/hermes_cli/profile_describer.py+++ b/hermes_cli/profile_describer.py@@ -111,10 +111,7 @@ def _extract_json_blob(raw: str) -> Optional[dict]:def describe_profile(- profile_name: str,- *,- overwrite: bool = False,- timeout: Optional[int] = None,+ profile_name: str, *, overwrite: bool = False, timeout: Optional[int] = None) -> DescribeOutcome:"""Auto-generate a description for one profile. Expected failures (profile missing, no auxclient, API error, malformed response) return ``ok=False`` so a sweep continues.@@ -137,10 +134,7 @@ def describe_profile(existing = profiles_mod.read_profile_meta(profile_dir)if existing.get("description") and not existing.get("description_auto") and not overwrite:return DescribeOutcome(- canon,- False,- "profile already has a user-authored description "- "(use --overwrite to replace)",+ canon, False, "profile already has a user-authored description (use --overwrite to replace)")all_skills = _collect_skills(profile_dir)@@ -172,8 +166,7 @@ def describe_profile(resp = call_llm(task="profile_describer",messages=[- {"role": "system", "content": _SYSTEM_PROMPT},- {"role": "user", "content": user_msg},+ {"role": "system", "content": _SYSTEM_PROMPT}, {"role": "user", "content": user_msg}],temperature=0.3,max_tokens=400,@@ -205,9 +198,7 @@ def describe_profile(try:profiles_mod.write_profile_meta(- profile_dir,- description=description,- description_auto=True,+ profile_dir, description=description, description_auto=True)except Exception as exc:return DescribeOutcome(canon, False, f"failed to write profile.yaml: {exc}")diff --git a/hermes_cli/profile_distribution.py b/hermes_cli/profile_distribution.pyindex 607b067ba20..d661f4f559c 100644--- a/hermes_cli/profile_distribution.py+++ b/hermes_cli/profile_distribution.py@@ -182,11 +182,7 @@ def write_manifest(profile_dir: Path, manifest: DistributionManifest) -> Path:# shareable descriptor, not a secret — don't leave it at mkstemp's 0600. An existing# file's mode is preserved.atomic_yaml_write(- mf_path,- manifest.to_dict(),- sort_keys=False,- default_flow_style=False,- create_mode=0o644,+ mf_path, manifest.to_dict(), sort_keys=False, default_flow_style=False, create_mode=0o644)return mf_path@@ -217,8 +213,7 @@ def check_hermes_requires(spec: str, current_version: str) -> None:op, target = m.groups() if m else (">=", spec.strip())if not _VERSION_OPS[op](_parse_semver(current_version), _parse_semver(target)):raise DistributionError(- f"This distribution requires Hermes {op}{target}, "- f"but you have {current_version}."+ f"This distribution requires Hermes {op}{target}, but you have {current_version}.")@@ -343,15 +338,11 @@ def _has_cron_jobs(staged: Path) -> bool:def plan_install(- source: str,- workdir: Path,- override_name: Optional[str] = None,+ source: str, workdir: Path, override_name: Optional[str] = None) -> InstallPlan:"""Stage *source* and produce a plan describing what install would do."""from hermes_cli.profiles import (- get_profile_dir,- normalize_profile_name,- validate_profile_name,+ get_profile_dir, normalize_profile_name, validate_profile_name)from hermes_cli import __version__ as hermes_version@@ -360,8 +351,7 @@ def plan_install(manifest = read_manifest(staged)if manifest is None:raise DistributionError(- f"No {MANIFEST_FILENAME} found at the distribution root — "- "this source is not a Hermes distribution."+ f"No {MANIFEST_FILENAME} found at the distribution root — this source is not a Hermes distribution.")check_hermes_requires(manifest.hermes_requires, hermes_version) # fail fast@@ -371,8 +361,7 @@ def plan_install(if canon == "default":raise DistributionError("Cannot install a distribution as 'default' — that is the built-in "- "root profile (~/.hermes). Pass --name <name> to install under a "- "new profile."+ "root profile (~/.hermes). Pass --name <name> to install under a new profile.")manifest.name = canonmanifest.source = provenance@@ -416,10 +405,7 @@ def _owned_entries(staged: Path, manifest: DistributionManifest):def _copy_dist_payload(- staged: Path,- target: Path,- manifest: DistributionManifest,- preserve_config: bool,+ staged: Path, target: Path, manifest: DistributionManifest, preserve_config: bool) -> None:"""Copy distribution-owned files (see ``_owned_entries``) from *staged* into *target*.@@ -469,16 +455,12 @@ def _bootstrap_user_dirs(target: Path) -> None:def install_distribution(- source: str,- name: Optional[str] = None,- force: bool = False,- create_alias: bool = False,+ source: str, name: Optional[str] = None, force: bool = False, create_alias: bool = False) -> InstallPlan:"""Install a distribution from *source* into a new profile; returns the resolved plan.Use :func:`plan_install` first to preview + prompt."""from hermes_cli.profiles import (- check_alias_collision,- create_wrapper_script,+ check_alias_collision, create_wrapper_script)with tempfile.TemporaryDirectory(prefix="hermes_dist_install_") as tmp:@@ -487,8 +469,7 @@ def install_distribution(if plan.existing and not force:raise DistributionError(f"Profile '{plan.manifest.name}' already exists at {plan.target_dir}. "- "Use `hermes profile update` to upgrade in place, "- "or pass --force to overwrite."+ "Use `hermes profile update` to upgrade in place, or pass --force to overwrite.")# Fresh install: config.yaml comes from the distribution.@@ -504,9 +485,7 @@ def install_distribution(def _existing_profile(profile_name: str) -> Tuple[str, Path]:"""Return ``(canonical_name, profile_dir)`` or raise if the profile doesn't exist."""from hermes_cli.profiles import (- get_profile_dir,- normalize_profile_name,- validate_profile_name,+ get_profile_dir, normalize_profile_name, validate_profile_name)canon = normalize_profile_name(profile_name)@@ -518,8 +497,7 @@ def _existing_profile(profile_name: str) -> Tuple[str, Path]:def update_distribution(- profile_name: str,- force_config: bool = False,+ profile_name: str, force_config: bool = False) -> InstallPlan:"""Re-pull from the installed manifest's ``source:`` and apply: dist-owned filesoverwritten, user data never touched, ``config.yaml`` preserved unless ``force_config``."""diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.pyindex b9c9761125b..6026250eb9d 100644--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@ -16,15 +16,10 @@ from typing import Dict, List, Optional, Tuplefrom agent.skill_utils import is_excluded_skill_pathfrom hermes_cli.archive_safe import (- archive_root_dirs,- make_targz,- normalize_archive_parts,- safe_extract_targz,+ archive_root_dirs, make_targz, normalize_archive_parts, safe_extract_targz)from hermes_constants import (- clear_named_profile_deleted,- mark_named_profile_deleted,- named_profile_is_deleted,+ clear_named_profile_deleted, mark_named_profile_deleted, named_profile_is_deleted)logger = logging.getLogger(__name__)@@ -172,8 +167,7 @@ def _is_our_wrapper(path: Path) -> bool:def _missing_profile_error(canon: str) -> FileNotFoundError:return FileNotFoundError(- f"Profile '{canon}' does not exist. "- f"Create it with: hermes profile create {canon}"+ f"Profile '{canon}' does not exist. Create it with: hermes profile create {canon}")@@ -202,8 +196,7 @@ def validate_profile_name(name: str) -> None:return # special alias for ~/.hermesif not _PROFILE_ID_RE.match(name):raise ValueError(- f"Invalid profile name {name!r}. Must match "- f"[a-z0-9][a-z0-9_-]{{0,63}}"+ f"Invalid profile name {name!r}. Must match [a-z0-9][a-z0-9_-]{{0,63}}")if name in _RESERVED_NAMES:raise ValueError(@@ -218,8 +211,7 @@ def validate_alias_name(name: str) -> None:under ``~/.local/bin``, so ``../../.bashrc`` must never escape the wrapper dir."""if not _PROFILE_ID_RE.match(name):raise ValueError(- f"Invalid alias name {name!r}. Must match "- f"[a-z0-9][a-z0-9_-]{{0,63}}"+ f"Invalid alias name {name!r}. Must match [a-z0-9][a-z0-9_-]{{0,63}}")@@ -260,8 +252,7 @@ def profile_matches_home(name: str, home: "Path | None" = None) -> bool:home = get_hermes_home()return (- Path(target).expanduser().resolve(strict=False)- == Path(home).expanduser().resolve(strict=False)+ Path(target).expanduser().resolve(strict=False) == Path(home).expanduser().resolve(strict=False))except Exception:return False@@ -551,8 +542,7 @@ def _seed_model_config(profile_dir: Path) -> None:if not model_cfg:returnconfig_path.write_text(- yaml.safe_dump({"model": model_cfg}, sort_keys=False),- encoding="utf-8",+ yaml.safe_dump({"model": model_cfg}, sort_keys=False), encoding="utf-8")except Exception:pass # creation must not fail over this; `hermes model` sets it later@@ -567,9 +557,7 @@ def _check_gateway_running(profile_dir: Path) -> bool:against the process table, matching ``/api/status``."""try:from gateway.status import (- get_running_pid,- get_runtime_status_running_pid,- read_runtime_status,+ get_running_pid, get_runtime_status_running_pid, read_runtime_status)if get_running_pid(profile_dir / "gateway.pid", cleanup_stale=False) is not None:return True@@ -635,9 +623,7 @@ def _count_skills(profile_dir: Path) -> int:now = time.time()cached = _SKILL_COUNT_CACHE.get(key)if (- cached is not None- and cached[0] == signature- and (now - cached[1]) < _SKILL_COUNT_TTL_SECONDS+ cached is not None and cached[0] == signature and (now - cached[1]) < _SKILL_COUNT_TTL_SECONDS):return cached[2]@@ -771,8 +757,7 @@ def list_profiles() -> List[ProfileInfo]:def profiles_to_serve(- multiplex: bool,- profile_allowlist: Optional[List[str]] = None,+ multiplex: bool, profile_allowlist: Optional[List[str]] = None) -> List[Tuple[str, Path]]:"""``(profile_name, hermes_home)`` pairs a gateway should serve — the single chokepointfor "which profiles does the inbound gateway handle".@@ -808,8 +793,7 @@ def profiles_to_serve(if missing and missing not in _WARNED_MISSING_ALLOWLIST_ENTRIES:_WARNED_MISSING_ALLOWLIST_ENTRIES.add(missing)logger.warning(- "Skipping missing gateway.multiplex_profile_allowlist profile(s): %s",- ", ".join(missing),+ "Skipping missing gateway.multiplex_profile_allowlist profile(s): %s", ", ".join(missing))return serve@@ -862,10 +846,7 @@ def _clone_all_into(source_dir: Path, profile_dir: Path, canon: str) -> None:"""--clone-all: full copytree minus infrastructure/history, then strip runtime filesand cloned single-use OAuth grants."""shutil.copytree(- source_dir,- profile_dir,- symlinks=True,- ignore=_clone_all_copytree_ignore(source_dir),+ source_dir, profile_dir, symlinks=True, ignore=_clone_all_copytree_ignore(source_dir))for stale in _CLONE_ALL_STRIP:(profile_dir / stale).unlink(missing_ok=True)@@ -967,8 +948,7 @@ def create_profile(if no_skills:_seed_file_if_missing(profile_dir / NO_BUNDLED_SKILLS_MARKER,- "This profile opted out of bundled-skill seeding "- "(`hermes profile create --no-skills`).\n"+ "This profile opted out of bundled-skill seeding (`hermes profile create --no-skills`).\n""Delete this file to re-enable sync on the next `hermes update`.\n",)@@ -982,9 +962,7 @@ def create_profile(if description and description.strip():try:write_profile_meta(- profile_dir,- description=description.strip(),- description_auto=False,+ profile_dir, description=description.strip(), description_auto=False)except Exception:pass # non-fatal — user can describe later with `hermes profile describe`@@ -1169,9 +1147,7 @@ def _wait_then_force_kill(pids: List[int], start_times: dict, *, wait: float = 1if _pid_exists(pid):try:terminate_pid(- pid,- force=True,- expected_start_time=start_times.get(pid, get_process_start_time(pid)),+ pid, force=True, expected_start_time=start_times.get(pid, get_process_start_time(pid)))except (ProcessLookupError, PermissionError, OSError):pass@@ -1272,8 +1248,7 @@ def delete_profile(name: str, yes: bool = False) -> Path:if canon == "default":raise ValueError(- "Cannot delete the default profile (~/.hermes).\n"- "To remove everything, use: hermes uninstall"+ "Cannot delete the default profile (~/.hermes).\nTo remove everything, use: hermes uninstall")profile_dir = get_profile_dir(canon)@@ -1436,9 +1411,7 @@ def _stop_gateway_process(profile_dir: Path) -> None:# owner. A poisoned gateway.pid in this dir can point at another profile's live# gateway — killing it starts a mutual SIGTERM restart loop.from gateway.status import (- get_process_start_time,- recorded_gateway_home_conflicts,- terminate_pid,+ get_process_start_time, recorded_gateway_home_conflicts, terminate_pid)if recorded_gateway_home_conflicts(data, expected_home=profile_dir):@@ -1554,8 +1527,7 @@ def _profile_export_directory() -> Path:# path another local user could pre-create (or symlink) first.uid_suffix = f"-{os.getuid()}" if hasattr(os, "getuid") else ""candidates = (- Path.home() / ".hermes-profile-exports",- Path(tempfile.gettempdir()) / f"hermes-profile-exports{uid_suffix}",+ Path.home() / ".hermes-profile-exports", Path(tempfile.gettempdir()) / f"hermes-profile-exports{uid_suffix}")for candidate in candidates:if not _inside_git_checkout(candidate):@@ -1585,8 +1557,7 @@ def get_profile_export_path(name: str, *, timestamp: Optional[str] = None) -> Paif hasattr(os, "getuid") and export_dir.stat().st_uid != os.getuid():raise ValueError(f"Export directory {export_dir} is owned by another user; "- "refusing to write a profile archive there. Provide an explicit "- "output path."+ "refusing to write a profile archive there. Provide an explicit output path.")stamp = timestamp or time.strftime("%Y%m%d-%H%M%S")return export_dir / f"{canon}-{stamp}.tar.gz"@@ -1781,9 +1752,7 @@ def _migrate_honcho_profile_host(old_name: str, new_name: str, new_dir: Path) ->new_host = f"hermes_{new_name}"candidates = [- new_dir / "honcho.json",- _get_default_hermes_home() / "honcho.json",- Path.home() / ".honcho" / "config.json",+ new_dir / "honcho.json", _get_default_hermes_home() / "honcho.json", Path.home() / ".honcho" / "config.json"]seen: set[Path] = set()