Skip to content

The agent that grows with you

Merge remote-tracking branch 'origin/main' into ethie/pm-clean

ethernet82a5affdd3a5
diff --cc hermes_cli/backup.py
index 97235f8246a,b948f573587..452c0f1d03f
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@@ -427,13 -461,641 +427,200 @@@ def verify_sqlite_integrity
return _done("header check passed", valid=True, size=size)
-def _foreign_db_holder_pids(db_path: Path) -> Optional[List[int]]:
- """PIDs of OTHER processes holding *db_path* or its WAL/SHM open (Linux ``/proc`` scan).
-
- An already-unlinked ``(deleted)`` sidecar — the #90950 split-brain fingerprint — still
- counts as held. None off-Linux or when /proc fails.
- """
- if not sys.platform.startswith("linux"):
- return None
-
- def _canonical(path: str) -> str:
- return os.path.normcase(os.path.abspath(path.removesuffix(" (deleted)")))
-
- def _holds_watched(fds: List[str], fd_dir: str) -> bool:
- for fd in fds:
- try:
- target = os.readlink(f"{fd_dir}/{fd}")
- except OSError:
- continue
- if _canonical(target) in watched:
- return True
- return False
-
- canonical_db = _canonical(os.fspath(db_path))
- watched = {canonical_db, canonical_db + "-wal", canonical_db + "-shm"}
- pids: List[int] = []
- try:
- own_pid = os.getpid()
- for pid_str in os.listdir("/proc"):
- if not pid_str.isdigit() or int(pid_str) == own_pid:
- continue
- fd_dir = f"/proc/{pid_str}/fd"
- try:
- fds = os.listdir(fd_dir)
- except OSError:
- continue
- if _holds_watched(fds, fd_dir):
- pids.append(int(pid_str))
- except OSError:
- return None
- return pids
-
-
-def _safe_restore_db(src: Path, dst: Path) -> bool:
- """Restore snapshot *src* into live *dst* through the backup() API; unlink+move fallback.
-
- Writing pages into the live file preserves its inode and WAL state, so other holders (gateway,
- dashboard, another CLI) see the restored data instead of stale pages from a replaced inode.
- The fallback runs ONLY when no other process or in-process connection holds the file
- (replacing the inode under a live holder is the #90950 split-brain); otherwise it fails closed
- (``False``) and the caller reports the file as skipped.
- """
- try:
- dst_conn = sqlite3.connect(str(dst))
- # Checkpoint first so the backup starts clean rather than writing on top of a deep WAL.
- with suppress(Exception):
- dst_conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
- with closing(sqlite3.connect(f"file:{src}?mode=ro", uri=True)) as src_conn:
- src_conn.backup(dst_conn)
- dst_conn.close()
- with suppress(Exception):
- dst.chmod(src.stat().st_mode)
- return True
- except Exception as exc:
- logger.warning("SQLite safe restore failed for %s -> %s: %s", src, dst, exc)
- return _unlink_move_restore_db(src, dst)
-
-
-def _unlink_move_restore_db(src: Path, dst: Path) -> bool:
- """Fallback restore: unlink+move. Only safe when no process holds the DB open.
-
- Replacing the inode under a live holder is the #90950 corruption class (the holder keeps
- writing through a deleted-inode fd and loses its WAL index), so fail closed. The foreign-pid
- scan excludes THIS process, so ``offline_file_access`` also fails CLOSED on any live
- in-process connection to *dst* and holds the connection-lifecycle lock across the swap.
- """
- from hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_access
- try:
- holders = _foreign_db_holder_pids(dst)
- if holders:
- logger.error("Refusing unlink+move restore of %s: process(es) %s still "
- "hold the database or its WAL open. Stop them and retry.", dst, holders)
- return False
- with offline_file_access(dst, what="unlink+move restore of"):
- tmp = dst.parent / f".{dst.name}.snap_restore"
- shutil.copy2(src, tmp)
- dst.unlink(missing_ok=True)
- # The snapshot owns no WAL, so any -wal/-shm here belongs to the DB just unlinked (a
- # killed gateway leaves them — exactly when a restore runs); SQLite would replay that
- # foreign WAL over the restored file: "malformed" or resurrected post-snapshot rows.
- for _sidecar_suffix in ("-wal", "-shm", "-journal"):
- dst.with_name(dst.name + _sidecar_suffix).unlink(missing_ok=True)
- shutil.move(str(tmp), str(dst))
- return True
- except LiveConnectionError as exc2:
- logger.error("Refusing unlink+move restore of %s: %s Close the in-process "
- "database handles (or restart Hermes) and retry.", dst, exc2)
- return False
- except Exception as exc2:
- logger.error("Fallback restore also failed for %s -> %s: %s", src, dst, exc2)
- return False
-
-
+ def _zip_sqlite_snapshot(zf: zipfile.ZipFile, abs_path: Path, rel_path: Path, out_path: Path) -> Optional[int]:
+ """Add a WAL-safe snapshot of *abs_path* to *zf*; return its byte size, or None on failure.
+
+ Staged beside the output zip: /tmp may be a small tmpfs that cannot hold large databases.
+ """
+ with tempfile.NamedTemporaryFile(suffix=".db", delete=False, dir=str(out_path.parent)) as tmp:
+ tmp_db = Path(tmp.name)
+ try:
+ if not _safe_copy_db(abs_path, tmp_db):
+ return None
+ zf.write(tmp_db, arcname=str(rel_path))
+ return tmp_db.stat().st_size
+ finally:
+ tmp_db.unlink(missing_ok=True)
+
+
+ def _write_zip_entries(
+ zf: zipfile.ZipFile, files_to_add: List[Tuple[Path, Path]], out_path: Path,
+ *, on_db_failure, on_error, on_progress, track_bytes: bool) -> int:
+ """Add every ``(abs_path, rel_path)`` to *zf*, WAL-safe for ``*.db``; return bytes archived.
+
+ ``on_db_failure(rel_path)`` runs when a SQLite snapshot fails (may raise to abort);
+ ``on_error(rel_path, exc)`` records a read failure; ``on_progress(i)`` fires every 500 files;
+ ``track_bytes`` stats plain files for the size total.
+ """
+ total_bytes = 0
+ for i, (abs_path, rel_path) in enumerate(files_to_add, 1):
+ try:
+ if abs_path.suffix == ".db":
+ size = _zip_sqlite_snapshot(zf, abs_path, rel_path, out_path)
+ if size is None:
+ on_db_failure(rel_path)
+ continue
+ total_bytes += size
+ else:
+ zf.write(abs_path, arcname=str(rel_path))
+ if track_bytes:
+ total_bytes += abs_path.stat().st_size
+ except (PermissionError, OSError, ValueError) as exc:
+ on_error(rel_path, exc)
+ continue
+ if i % 500 == 0:
+ on_progress(i)
+ return total_bytes
+
+
+ def _print_capped(header: str, lines: List[str], indent: str) -> None:
+ """Print *header*, then at most 10 of *lines* (each prefixed by *indent*) and a "... and N more" tail."""
+ print(header)
+ for line in lines[:10]:
+ print(f"{indent}{line}")
+ if len(lines) > 10:
+ print(f"{indent}... and {len(lines) - 10} more")
+
+
# --- Backup ---
_RUN_BACKUP_PREFIX = "hermes-backup-"
+ def _resolve_backup_output_path(output: Optional[str]) -> Path:
+ """Turn ``--output`` (file, directory, or None) into a ``.zip`` path whose parent exists;
+ an unwritable path exits with a one-line error, not a traceback."""
+ out_path = None
+ default_name = f"{_RUN_BACKUP_PREFIX}{datetime.now().strftime('%Y-%m-%d-%H%M%S')}.zip"
+ try:
+ if output:
+ out_path = Path(output).expanduser().resolve()
+ if out_path.is_dir():
+ out_path = out_path / default_name
+ else:
+ out_path = Path.home() / default_name
+ if out_path.suffix.lower() != ".zip":
+ out_path = out_path.with_suffix(out_path.suffix + ".zip")
+ out_path.parent.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ print(f"Error: cannot write backup to {output or out_path}: {exc}")
+ raise SystemExit(1) from exc
+ return out_path
+
+
+ def _collect_external_entries() -> tuple[list[tuple[Path, str]], list[str]]:
+ """``([(abs_path, arcname)], [skipped])`` for the memory provider's external state, arc-named
+ ``_external/<home-relative>``; paths outside home are skipped (security + portability)."""
+ home_dir = Path.home().resolve()
+ external_to_add: list[tuple[Path, str]] = []
+ skipped_external: list[str] = []
+ for base in _collect_memory_provider_external_paths():
+ try:
+ base.resolve().relative_to(home_dir)
+ except (ValueError, OSError):
+ skipped_external.append(str(base))
+ continue
+ for fpath in _iter_external_files(base):
+ with suppress(ValueError, OSError):
+ rel_to_home = fpath.resolve().relative_to(home_dir)
+ external_to_add.append((fpath, _EXTERNAL_PREFIX + rel_to_home.as_posix()))
+ return external_to_add, skipped_external
+
+
+ def run_backup(args) -> bool:
+ """Create a zip backup of the Hermes home directory.
+
+ True when every selected file landed in the archive (or there was nothing to back up); False
+ when the zip was written but is incomplete — it is kept so the rest can still be restored, and
+ the caller turns False into exit status 1 so a cron/systemd timer never publishes a "successful"
+ archive that is missing state.db. Hard failures keep raising ``SystemExit``.
+ """
+ hermes_root = get_default_hermes_root()
+
+ if not hermes_root.is_dir():
+ print(f"Error: Hermes home directory not found at {hermes_root}")
+ sys.exit(1)
+
+ try:
+ with _backup_operation_lock(hermes_root):
+ return _run_backup_locked(args, hermes_root)
+ except BackupInProgressError as exc:
+ print(f"Error: {exc}")
+ raise SystemExit(2) from exc
+
+
+ def _run_backup_locked(args, hermes_root: Path) -> bool:
+ """Write a full backup while the cross-process backup slot is held."""
+ out_path = _resolve_backup_output_path(args.output)
+ scan_started = time.monotonic()
+ logger.info("backup phase=scan status=started")
+ print(f"Scanning {display_hermes_home()} ...")
+ skipped_dirs: set = set()
+ files_to_add: list[tuple[Path, Path]] = list(_iter_backup_files(hermes_root, out_path, skipped_dirs))
+ external_to_add, skipped_external = _collect_external_entries()
+ if not files_to_add and not external_to_add:
+ logger.info("backup phase=scan status=empty duration_ms=%.1f", (time.monotonic() - scan_started) * 1000)
+ print("No files to back up.")
+ return True
+
+ file_count = len(files_to_add) + len(external_to_add)
+ logger.info("backup phase=scan status=complete duration_ms=%.1f files=%d",
+ (time.monotonic() - scan_started) * 1000, file_count)
+ logger.info("backup phase=archive status=started files=%d", file_count)
+ print(f"Backing up {file_count} files ...")
+ errors = []
+ t0 = time.monotonic()
+
+ def _progress(i: int) -> None:
+ print(f" {i}/{file_count} files ...")
+ logger.info("backup phase=archive status=progress completed=%d total=%d", i, file_count)
+
+ with _atomic_output_path(out_path) as archive_path, zipfile.ZipFile(
+ archive_path, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as zf:
+ total_bytes = _write_zip_entries(
+ zf, files_to_add, out_path, on_progress=_progress, track_bytes=True,
+ on_db_failure=lambda rel: errors.append(f"{rel}: SQLite safe copy failed"),
+ on_error=lambda rel, exc: errors.append(f"{rel}: {exc}"))
+ # External memory-provider state never includes ``.db`` files in practice, so a
+ # straight zf.write is fine.
+ for abs_path, arcname in external_to_add:
+ try:
+ zf.write(abs_path, arcname=arcname)
+ total_bytes += abs_path.stat().st_size
+ except (PermissionError, OSError, ValueError) as exc:
+ errors.append(f"{arcname}: {exc}")
+ elapsed = time.monotonic() - t0
+ zip_size = out_path.stat().st_size
+ logger.info("backup phase=archive status=complete duration_ms=%.1f files=%d errors=%d bytes=%d",
+ elapsed * 1000, file_count, len(errors), zip_size)
+ print(f"\nBackup {'incomplete' if errors else 'complete'}: {out_path}\n"
+ f" Files: {file_count}\n"
+ f" Original: {_format_size(total_bytes)}\n"
+ f" Compressed: {_format_size(zip_size)}\n"
+ f" Time: {elapsed:.1f}s")
+ if external_to_add:
+ print(f"\n Included {len(external_to_add)} memory-provider file(s) stored outside {display_hermes_home()}.")
+ if skipped_external:
+ print(f"\n Skipped {len(skipped_external)} memory-provider path(s) outside your home directory "
+ "(not portable):\n" + "\n".join(f" {p}" for p in sorted(skipped_external)[:10]))
+ if skipped_dirs:
+ print("\n Excluded directories:\n" + "\n".join(f" {d}/" for d in sorted(skipped_dirs)))
+ if errors:
+ _print_capped(f"\n Archive kept, but {len(errors)} file(s) could not be added:", errors, " ")
+ else:
+ print(f"\nRestore with: hermes import {out_path.name}")
+ # Prune only after a complete archive: a timer hitting the same unreadable file every run must
+ # not rotate the last good backups out in favour of incomplete ones.
+ keep = getattr(args, "keep", 0) # 0 / absent: never prune (non-CLI callers)
+ if keep and not errors and out_path.name.startswith(_RUN_BACKUP_PREFIX):
+ pruned = _prune_prefixed_zips(out_path.parent, _RUN_BACKUP_PREFIX, keep, "backup")
+ if pruned:
+ print(f" Pruned {pruned} older {_RUN_BACKUP_PREFIX}*.zip (keeping {keep}).")
+ return not errors
+
+
# --- Import ---
-def _validate_backup_zip(zf: zipfile.ZipFile) -> tuple[bool, str]:
- """Check that a zip looks like a Hermes backup."""
- names = zf.namelist()
- if not names:
- return False, "zip archive is empty"
- # Telltale files a hermes home has — at the root or one level deep (zipped directory).
- if not any(Path(n).name in {"config.yaml", ".env", "state.db"} for n in names):
- return False, "zip does not appear to be a Hermes backup (no config.yaml, .env, or state databases found)"
- return True, ""
-
-
-def _detect_prefix(zf: zipfile.ZipFile) -> str:
- """Detect if the zip has a common directory prefix wrapping all entries."""
- names = [n for n in zf.namelist() if not n.endswith("/")]
- first_parts = {Path(n).parts[0] for n in names if len(Path(n).parts) > 1}
- if len(first_parts) == 1 and first_parts <= {".hermes", "hermes"}:
- return first_parts.pop() + "/"
- return ""
-
-
-def _extract_member_atomically(
- zf: zipfile.ZipFile, member: str, target: Path, new_file_mode: Optional[int] = None) -> None:
- """Restore one zip member onto *target* with no truncation window.
-
- ``open(target, "wb")`` would truncate the user's file before any replacement bytes exist.
- ``atomic_replace`` (not bare ``os.replace``) resolves a symlinked target first, so a
- dotfiles-linked ``config.yaml`` keeps the link (#16743), and falls back to copy/fsync/unlink
- on ``EXDEV``/``EBUSY`` for cross-device and bind-mount installs.
- """
- # Mode is None when the target does not exist: the umask-derived create-mode applies.
- mode = _preserve_file_mode(target)
- owner = _preserve_file_owner(target)
- if mode is None:
- mode = new_file_mode
- else:
- # Deliberately NOT a faithful copy: setuid/setgid are dropped. The bytes come from the
- # archive, so carrying elevated bits would hand the zip's author the identity an existing
- # setuid file runs as — and ``_external/`` publishes members anywhere under ``$HOME``.
- mode &= ~(stat.S_ISUID | stat.S_ISGID)
- # Truncate the stem: mkstemp adds ~16 chars and a member near NAME_MAX would otherwise fail.
- fd, tmp_name = tempfile.mkstemp(dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".partial")
- try:
- with os.fdopen(fd, "wb") as dst:
- if mode is not None:
- # Apply the mode BEFORE the replace so the target never transits through mkstemp's
- # 0600 and the EXDEV/EBUSY ``copystat`` fallback copies the intended bits.
- if hasattr(os, "fchmod"): # Unix-only; Windows takes the path-based chmod
- os.fchmod(dst.fileno(), mode)
- else:
- os.chmod(tmp_name, mode)
- # Stream: a multi-gigabyte state.db member must not be held in memory in one piece.
- with zf.open(member) as src:
- shutil.copyfileobj(src, dst)
- dst.flush()
- os.fsync(dst.fileno())
- real_path = Path(atomic_replace(tmp_name, target))
- # Owner first, mode second (as ``atomic_yaml_write``): chown drops setuid/setgid and
- # ``mode`` no longer carries them, so neither step can re-elevate the restored file.
- _restore_file_owner(real_path, owner)
- _restore_file_mode(real_path, mode)
- except BaseException:
- with suppress(OSError):
- os.unlink(tmp_name)
- raise
-
-
-def _count_session_rows(path: Path) -> Optional[Tuple[int, int]]:
- """``(sessions, messages)`` in session database *path*; read-only, best effort.
-
- ``None`` means "unknown" (missing, not a Hermes session store, unreadable) — never "zero":
- acting on an unreadable database would mask the very loss this count exists to surface.
- Same contract as :func:`_count_cron_jobs`.
- """
- if not path.is_file():
- return None
- try:
- conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
- except sqlite3.Error:
- return None
- try:
- sessions = conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]
- messages = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]
- return int(sessions), int(messages)
- except (sqlite3.Error, TypeError, ValueError):
- return None
- finally:
- conn.close()
-
-
-def _import_db_member(
- zf: zipfile.ZipFile, member: str, target: Path, new_file_mode: Optional[int] = None) -> None:
- """Publish a SQLite ``.db`` member onto *target* without replacing its inode.
-
- A rename-publish over a live database is the #65942 / #90950 corruption class: a gateway,
- dashboard, or WebUI holding it open keeps serving the unlinked inode and writing sessions no
- other process will see, and a sidecar WAL beside the new file describes the old database —
- nothing fails, the sessions are simply gone (#100960). Route the member through the same
- ``_safe_restore_db`` page copy ``/snapshot restore`` uses, so the live inode is preserved and
- every open connection converges. A target that does not exist yet has no holders, so it takes
- the ordinary atomic publish. Raises ``OSError`` when the database could not be replaced
- safely, so the caller reports a skipped file instead of a silent success.
- """
- if not target.exists():
- _extract_member_atomically(zf, member, target, new_file_mode)
- return
- # The database keeps its own mode/ownership: the bytes come from the archive, the file does not.
- mode = _preserve_file_mode(target)
- owner = _preserve_file_owner(target)
- fd, tmp_name = tempfile.mkstemp(dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".dbimport")
- try:
- with os.fdopen(fd, "wb") as dst:
- with zf.open(member) as src: # stream: never hold a multi-GB state.db in memory
- shutil.copyfileobj(src, dst)
- dst.flush()
- os.fsync(dst.fileno())
- if not _safe_restore_db(Path(tmp_name), target):
- raise OSError(
- "live-safe restore refused or failed; the existing database was "
- "left untouched. Stop the gateway/dashboard processes holding it "
- "open and re-run the import."
- )
- _restore_file_owner(target, owner)
- _restore_file_mode(target, mode)
- finally:
- with suppress(OSError):
- os.unlink(tmp_name)
-
-
-def _confirm_import_overwrite(hermes_root: Path) -> bool:
- """Prompt before importing over an existing installation; True when import may proceed."""
- if not any((hermes_root / m).exists() for m in ("config.yaml", ".env")):
- return True
- print("\nWarning: Target directory already has Hermes configuration.\n"
- "Importing will overwrite existing files with backup contents.\n")
- try:
- answer = input("Continue? [y/N] ").strip().lower()
- except (EOFError, KeyboardInterrupt):
- print("\nAborted.")
- sys.exit(1)
- if answer in {"y", "yes"}:
- return True
- print("Aborted.")
- return False
-
-
-def _import_members(
- zf: zipfile.ZipFile, members: List[str], prefix: str, hermes_root: Path, file_count: int
-) -> tuple[int, int, list[str], list[str], list[tuple[str, tuple[int, int], tuple[int, int]]]]:
- """Publish every member; return ``(restored, restored_external, errors, skipped_runtime, db_shrunk)``.
-
- ``db_shrunk`` holds ``(rel, live_counts, imported_counts)`` for every session database the
- import replaced with one holding fewer rows — allowed, but never silent (#100960).
- """
- errors: list[str] = []
- skipped_runtime: list[str] = []
- db_shrunk: list[tuple[str, tuple[int, int], tuple[int, int]]] = []
- restored = restored_external = 0
- home_dir = Path.home().resolve()
- new_file_mode = default_new_file_mode() # once: every member is published via mkstemp (0600)
- for member in members:
- # ``_external/`` members restore to their home-relative location (~/.honcho/config.json),
- # NOT under HERMES_HOME; provider configs commonly hold credentials, so tighten to 0600.
- external = member.startswith(_EXTERNAL_PREFIX)
- if external:
- rel = member[len(_EXTERNAL_PREFIX):]
- target = home_dir / rel
- root = home_dir
- tighten = target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES
- else:
- rel = member[len(prefix):] if prefix and member.startswith(prefix) else member
- if rel and Path(rel).name in _IMPORT_SKIP_NAMES: # see ``_IMPORT_SKIP_NAMES``
- skipped_runtime.append(rel)
- continue
- # A ``.db`` member is page-restored into the live file; an archived WAL/SHM/journal
- # describes a different database image and installed beside it (over a live sidecar)
- # would replay a foreign WAL on next open. Current backups never ship these
- # (_EXCLUDED_SUFFIXES); older or hand-built archives might.
- if rel.endswith(_SQLITE_SIDECAR_SUFFIXES):
- skipped_runtime.append(rel)
- continue
- target = hermes_root / rel
- root = hermes_root.resolve()
- tighten = target.name in _SECRET_FILE_NAMES
- if not rel:
- continue
-
- label = member if external else rel
- if not _is_within(target, root):
- errors.append(f"{label}: path traversal blocked")
- else:
- try:
- target.parent.mkdir(parents=True, exist_ok=True)
- if target.suffix == ".db":
- # Count before the write: afterwards the dropped rows are gone.
- before = _count_session_rows(target)
- _import_db_member(zf, member, target, new_file_mode)
- after = _count_session_rows(target)
- if before and after and after[1] < before[1]:
- db_shrunk.append((rel, before, after))
- else:
- _extract_member_atomically(zf, member, target, new_file_mode)
- if tighten:
- try:
- os.chmod(target, 0o600)
- except OSError:
- if not external: # external configs are tightened best-effort only
- raise
- restored += 1
- restored_external += external
- except (PermissionError, OSError) as exc:
- errors.append(f"{label}: {exc}")
-
- if restored % 500 == 0:
- print(f" {restored}/{file_count} files ...")
-
- return restored, restored_external, errors, skipped_runtime, db_shrunk
-
-
-def run_import(args) -> None:
- """Restore a Hermes backup from a zip file."""
- zip_path = Path(args.zipfile).expanduser().resolve()
- if not zip_path.is_file():
- print(f"Error: File not found: {zip_path}")
- sys.exit(1)
- if not zipfile.is_zipfile(zip_path):
- print(f"Error: Not a valid zip file: {zip_path}")
- sys.exit(1)
- # The restore target is the home the command operates under (the printed "Target:");
- # ``get_default_hermes_root()`` would silently retarget a profile restore at the live root.
- hermes_root = get_hermes_home()
- with zipfile.ZipFile(zip_path, "r") as zf:
- ok, reason = _validate_backup_zip(zf)
- if not ok:
- print(f"Error: {reason}")
- sys.exit(1)
- prefix = _detect_prefix(zf)
- members = [n for n in zf.namelist() if not n.endswith("/")]
- file_count = len(members)
- print(f"Backup contains {file_count} files\nTarget: {display_hermes_home()}")
- if prefix:
- print(f"Detected archive prefix: {prefix!r} (will be stripped)")
- if not args.force and not _confirm_import_overwrite(hermes_root):
- return
- print(f"\nImporting {file_count} files ...")
- hermes_root.mkdir(parents=True, exist_ok=True)
- t0 = time.monotonic()
- restored, restored_external, errors, skipped_runtime, db_shrunk = _import_members(
- zf, members, prefix, hermes_root, file_count)
- elapsed = time.monotonic() - t0
- print(f"\nImport complete: {restored} files restored in {elapsed:.1f}s\n Target: {display_hermes_home()}")
- if restored_external:
- print(f"\n Restored {restored_external} memory-provider file(s) to "
- f"their original location(s) outside {display_hermes_home()}.")
- if errors:
- _print_capped(f"\n Warnings ({len(errors)} files skipped):", errors, " ")
- if db_shrunk:
- # The backup predates work that is now overwritten — say so (#100960: twelve sessions
- # disappeared with nothing logged anywhere).
- print("\n ⚠ Session data replaced by older backup contents:")
- for rel, before, after in db_shrunk:
- print(f" {rel}: {before[0]} session(s) / {before[1]} message(s)"
- f" -> {after[0]} / {after[1]}")
- print(f" Anything recorded after the backup was taken is not in it. {_snapshot_recovery_hint()}")
- if skipped_runtime:
- _print_capped(f"\n Preserved {len(skipped_runtime)} runtime state "
- f"file(s) (kept this machine's, not the backup's):",
- sorted(skipped_runtime), " ")
- restored_profiles = _restore_profile_wrappers(hermes_root)
- print()
- if not (hermes_root / "hermes-agent").is_dir():
- print("Note: The hermes-agent codebase was not included in the backup.\n"
- " If this is a fresh install, run: hermes update")
- if restored_profiles:
- print("\nTo re-enable gateway services for profiles:")
- for pname in restored_profiles:
- print(f" hermes -p {pname} gateway install")
- _revive_gateway_after_import(hermes_root)
- print("Done. Your Hermes configuration has been restored.")
-
-
-def _restore_profile_wrappers(hermes_root: Path) -> List[str]:
- """Re-create shell wrapper scripts for restored named profiles; return the profile names seen."""
- profiles_dir = hermes_root / "profiles"
- restored_profiles: list[tuple[str, bool]] = []
- if not profiles_dir.is_dir():
- return []
- try:
- from hermes_cli.profiles import (
- create_wrapper_script, check_alias_collision, _is_wrapper_dir_in_path, _get_wrapper_dir)
- for entry in sorted(profiles_dir.iterdir()):
- if not entry.is_dir() or not any((entry / m).exists() for m in ("config.yaml", ".env")):
- continue # only profiles with config get wrappers
- profile_name = entry.name
- collision = check_alias_collision(profile_name)
- if collision:
- print(f" Skipped alias '{profile_name}': {collision}")
- restored_profiles.append(
- (profile_name, not collision and create_wrapper_script(profile_name) is not None))
- if restored_profiles:
- created = [n for n, ok in restored_profiles if ok]
- skipped = [n for n, ok in restored_profiles if not ok]
- if created:
- print(f"\n Profile aliases restored: {', '.join(created)}")
- if skipped:
- print(f" Profile aliases skipped: {', '.join(skipped)}")
- if not _is_wrapper_dir_in_path():
- print(f"\n Note: {_get_wrapper_dir()} is not in your PATH.\n"
- " Add to your shell config (~/.bashrc or ~/.zshrc):\n"
- ' export PATH="$HOME/.local/bin:$PATH"')
- except ImportError: # hermes_cli.profiles unavailable (fresh install)
- if any(profiles_dir.iterdir()):
- print("\n Profiles detected but aliases could not be created.\n"
- " Run: hermes profile list (after installing hermes)")
- return [n for n, _ in restored_profiles]
-
-
-def _revive_gateway_after_import(hermes_root: Path) -> None:
- """Install/start the gateway service after a restore, best-effort and prompt-free.
-
- Bot tokens and cron jobs are inert without a gateway (a platform-less gateway is supported, so
- this is safe for any backup); failures print a manual fallback, never fail the import. Only
- revived when the restore landed in the default home or no other install exists: a sandbox or
- profile restore must not install a second gateway on the default service name.
- """
- native_default = _get_platform_default_hermes_home()
- if hermes_root != native_default and any(
- (native_default / marker).exists() for marker in ("config.yaml", ".env", "state.db")):
- print("\nRestored into a non-default home; leaving the gateway service alone to avoid clashing "
- f"with the install at {native_default}.\n"
- "To start a gateway for this home, run: hermes gateway install")
- return
- try:
- from hermes_cli.gateway import ensure_gateway_service, _is_service_running
- if not _is_service_running():
- print()
- ensure_gateway_service(context="import")
- except Exception:
- print("\nStart the gateway to activate cron jobs and messaging:\n hermes gateway install")
-
# --- Quick state snapshots (used by /snapshot slash command and hermes backup --quick) ---
@@@ -467,711 -1129,114 +654,525 @@@ def _quick_snapshot_root(hermes_home: O
return home / _QUICK_SNAPSHOTS_DIR
-def create_quick_snapshot(
- label: Optional[str] = None, hermes_home: Optional[Path] = None, keep: Optional[int] = None,
- max_file_size: Optional[int] = None) -> Optional[str]:
- """Create one atomic quick snapshot while holding the shared backup slot."""
- home = hermes_home or get_hermes_home()
- with _backup_operation_lock(home):
- return _create_quick_snapshot_locked(label, home, keep, max_file_size)
+def _newest_first(root: Path, keep_entry) -> List[Path]:
+ """Entries of *root* passing ``keep_entry``, newest (by name) first; ``[]`` if *root* is missing."""
+ if not root.exists():
+ return []
+ return sorted(filter(keep_entry, root.iterdir()), key=lambda p: p.name, reverse=True)
-def _quick_snapshot_candidates(home: Path):
- """Yield ``(src, rel_posix, in_dir)`` for every regular file a quick snapshot captures; heavy
- regenerable per-board subtrees (workspaces, attachments) are skipped."""
- for rel in _QUICK_STATE_FILES:
- src = home / rel
- if src.is_dir():
- for sub in filter(Path.is_file, src.rglob("*")):
- sub_rel = sub.relative_to(home).as_posix()
- if "/workspaces/" in f"/{sub_rel}/" or "/attachments/" in f"/{sub_rel}/":
- continue
- yield sub, sub_rel, True
- elif src.is_file():
- yield src, rel, False
+# Kept in sync with ``_QUICK_STATE_FILES`` and ``cron/jobs.py``'s ``JOBS_FILE``.
+_CRON_JOBS_REL = "cron/jobs.json"
-def _copy_quick_snapshot_files(
- home: Path, staging_dir: Path, max_file_size: Optional[int]
-) -> tuple[Dict[str, int], list[str], list[str]]:
- """Copy every quick-snapshot candidate into *staging_dir*.
+# Config paths the update flow must never change (#64160): model routing and the MoA section are
+# consumed machine-wide, so an update/repair cycle that rewrites them silently redirects paid
+# inference. Dotted paths into raw config.yaml; a single-element tuple protects a whole section.
+_PROTECTED_CONFIG_PATHS: Tuple[Tuple[str, ...], ...] = (
+ ("model", "provider"), ("model", "default"), ("model", "base_url"), ("model", "api_key"),
+ ("moa",))
- Returns ``(manifest {rel: size}, failed_dbs, oversized_skipped)``. The last two are snapshot
- incompleteness (#68805): the caller must suppress pruning so the older snapshot that may hold
- the only recoverable DB survives.
- """
- manifest: Dict[str, int] = {}
- failed_dbs: list[str] = []
- oversized_skipped: list[str] = []
- for src, rel, in_dir in _quick_snapshot_candidates(home):
- if max_file_size is not None:
- try:
- size = src.stat().st_size
- except OSError:
- size = None
- if size is not None and size > max_file_size:
- print(f" ⚠ Snapshot: skipping {rel} "
- f"({_format_size(size)} exceeds {_format_size(max_file_size)} limit)")
- logger.warning("Quick snapshot skipped %s: %d bytes exceeds %d byte limit", rel, size, max_file_size)
- if src.suffix == ".db":
- oversized_skipped.append(rel)
- continue
- dst = staging_dir / rel
- dst.parent.mkdir(parents=True, exist_ok=True)
+
+def _prune_oldest(newest_first: List[Path], keep: int, remove, what: str) -> int:
+ """``remove(path)`` every entry past the first *keep*; return how many succeeded."""
+ deleted = 0
+ for p in newest_first[keep:]:
try:
- # SQLite DBs go through the WAL-safe backup() path (the gateway may hold the WAL open).
- if src.suffix == ".db":
- if not _safe_copy_db(src, dst):
- failed_dbs.append(rel)
- print(f" ⚠ Snapshot: SQLite safe copy FAILED for {rel} — file may be locked or corrupted")
- if is_zeroed_sqlite_file(src):
- nuls = " of NULs?" if in_dir else ""
- print(f" ⚠ Snapshot: {rel} looks ZEROED "
- f"(no SQLite header; {src.stat().st_size} bytes{nuls})")
- continue
- else:
- shutil.copy2(src, dst)
- manifest[rel] = dst.stat().st_size
- except (OSError, PermissionError) as exc:
- logger.warning("Could not snapshot %s: %s", rel, exc)
- return manifest, failed_dbs, oversized_skipped
+ remove(p)
+ deleted += 1
+ except OSError as exc:
+ logger.warning("Failed to prune %s %s: %s", what, p.name, exc)
+ return deleted
-def _secure_quick_snapshot_tree(root: Path, snapshot_dir: Path) -> None:
- """Make a staged quick snapshot owner-only before it is published.
+# --- Shared full-zip backup helper ---
- The staging directory is private from creation, so copied source modes can
- be normalized safely before the final atomic rename exposes the snapshot.
- Permission failures are intentionally fatal: publishing a readable
- recovery bundle is worse than reporting a failed snapshot.
- """
- if os.name == "nt":
- return
- os.chmod(root, 0o700)
- os.chmod(snapshot_dir, 0o700)
- for path in snapshot_dir.rglob("*"):
- if path.is_dir():
- os.chmod(path, 0o700)
- elif path.is_file():
- os.chmod(path, 0o600)
+# --- Pre-update / pre-migration auto-backups ---
-def _create_quick_snapshot_locked(
- label: Optional[str], home: Path, keep: Optional[int], max_file_size: Optional[int]
-) -> Optional[str]:
- """Copy the quick-snapshot set to a timestamped dir under state-snapshots/ and prune old ones.
+_PRE_UPDATE_BACKUPS_DIR = "backups"
+_PRE_UPDATE_PREFIX = "pre-update-"
+_PRE_UPDATE_DEFAULT_KEEP = 5
+_PRE_MIGRATION_PREFIX = "pre-migration-"
+_PRE_MIGRATION_DEFAULT_KEEP = 5
+
+
+def _prune_prefixed_zips(backup_dir: Path, prefix: str, keep: int, what: str) -> int:
+ """Remove oldest ``<prefix>*.zip`` in *backup_dir* beyond *keep*; return count deleted.
- ``max_file_size`` skips (with a warning) larger files: the pre-update snapshot uses it so a
- multi-GB ``state.db`` never stalls ``hermes update`` while the small files are always captured.
+ Only prefix-matched files are touched, so hand-made zips or other backup kinds survive.
"""
- root = _quick_snapshot_root(home)
- ts = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
- base_snap_id = f"{ts}-{label}" if label else ts
- snap_id, suffix = base_snap_id, 2
- while (root / snap_id).exists():
- snap_id = f"{base_snap_id}-{suffix}"
- suffix += 1
- staging_dir = root / f".{snap_id}.{os.getpid()}.partial"
- shutil.rmtree(staging_dir, ignore_errors=True)
- root.mkdir(parents=True, exist_ok=True, mode=0o700)
- if os.name != "nt":
+ backups = _newest_first(backup_dir, lambda p: p.is_file() and p.name.startswith(prefix)
+ and p.suffix.lower() == ".zip")
+ return _prune_oldest(backups, keep, Path.unlink, what)
+
+
+def _create_prefixed_full_backup(
+ hermes_home: Optional[Path], prefix: str, keep: int, what: str, prune_what: str) -> Optional[Path]:
+ """Write ``<HERMES_HOME>/backups/<prefix><timestamp>.zip`` and prune older same-prefix zips.
+ Returns the path, or ``None`` if nothing to back up or the write failed. Never raises."""
+ hermes_root = hermes_home or get_default_hermes_root()
+ if not hermes_root.is_dir():
+ return None
+ backup_dir = hermes_root / _PRE_UPDATE_BACKUPS_DIR
+ try:
+ backup_dir.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ logger.warning("Could not create %s backup dir %s: %s", what, backup_dir, exc)
+ return None
+ out_path = backup_dir / f"{prefix}{datetime.now().strftime('%Y-%m-%d-%H%M%S')}.zip"
+ if _write_full_zip_backup(out_path, hermes_root) is None:
+ return None
+ _prune_prefixed_zips(backup_dir, prefix, keep, prune_what)
+ return out_path
+
+
+def create_pre_update_backup(
+ hermes_home: Optional[Path] = None, keep: int = _PRE_UPDATE_DEFAULT_KEEP) -> Optional[Path]:
+ """Full zip backup to ``backups/pre-update-<timestamp>.zip``, auto-pruned; ``None`` if nothing
+ was found or the backup failed. Never raises — ``hermes update`` continues anyway."""
+ return _create_prefixed_full_backup(hermes_home, _PRE_UPDATE_PREFIX, max(keep, 1), "pre-update", "backup")
+
+
+def create_pre_migration_backup(
+ hermes_home: Optional[Path] = None, keep: int = _PRE_MIGRATION_DEFAULT_KEEP) -> Optional[Path]:
+ """Full zip backup to ``backups/pre-migration-<timestamp>.zip`` before ``hermes claw migrate``
+ (same dir as update backups so listings/``hermes import`` find it); ``None`` if nothing was
+ found or the write failed. Never raises."""
+ return _create_prefixed_full_backup(
+ hermes_home, _PRE_MIGRATION_PREFIX, max(keep, 0), "pre-migration", "pre-migration backup")
+
+
+# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
+# Names external plugins imported from this module before the Sep 2026 decomposition.
+# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
+# The whole block is removed by reverting the commit that added it.
+
+def copy_db_and_verify(src: Path, dst: Path) -> bool:
+ """Like :func:`_safe_copy_db` but verifies the destination after copy.
+
+ Returns True only when the copy succeeded AND the destination is valid
+ SQLite (header + integrity check). Verification honours the default
+ size ceiling — a multi-GB destination gets the header + schema probe
+ rather than a full ``PRAGMA integrity_check`` that would page through
+ the whole file.
+ """
+ if not _safe_copy_db(src, dst):
+ return False
+ integrity = verify_sqlite_integrity(dst, run_pragma=True)
+ if not integrity.get("valid"):
+ try:
+ dst.unlink(missing_ok=True)
+ except OSError:
+ pass
+ logger.warning("Backup of %s failed integrity verification: %s", src, integrity.get("message"))
+ return False
+ return True
+
+
+# ---- END PLUGIN-COMPAT ----
+
+
+# ---------------------------------------------------------------------------
+# Backup
+# ---------------------------------------------------------------------------
+
- def run_backup(args) -> None:
- """Create a zip backup of the Hermes home directory."""
- hermes_root = get_default_hermes_root()
-
- if not hermes_root.is_dir():
- print(f"Error: Hermes home directory not found at {hermes_root}")
- sys.exit(1)
-
- try:
- with _backup_operation_lock(hermes_root):
- _run_backup_locked(args, hermes_root)
- except BackupInProgressError as exc:
- print(f"Error: {exc}")
- raise SystemExit(2) from exc
-
-
- def _run_backup_locked(args, hermes_root: Path) -> None:
- """Write a full backup while the cross-process backup slot is held."""
-
- # Determine output path
- out_path = None
- try:
- if args.output:
- out_path = Path(args.output).expanduser().resolve()
- # If user gave a directory, put the zip inside it
- if out_path.is_dir():
- stamp = datetime.now().strftime("%Y-%m-%d-%H%M%S")
- out_path = out_path / f"{_RUN_BACKUP_PREFIX}{stamp}.zip"
- else:
- stamp = datetime.now().strftime("%Y-%m-%d-%H%M%S")
- out_path = Path.home() / f"{_RUN_BACKUP_PREFIX}{stamp}.zip"
-
- # Ensure the suffix is .zip
- if out_path.suffix.lower() != ".zip":
- out_path = out_path.with_suffix(out_path.suffix + ".zip")
-
- # Ensure parent directory exists
- out_path.parent.mkdir(parents=True, exist_ok=True)
- except OSError as exc:
- # A bad/unwritable output path (permission denied, unreadable parent,
- # etc.) should give a clean one-line error, not a raw traceback
- # (round-3 QA SUB-01). is_dir() and mkdir() both hit the filesystem.
- print(f"Error: cannot write backup to {args.output or out_path}: {exc}")
- raise SystemExit(1) from exc
-
- # Collect files
- scan_started = time.monotonic()
- logger.info("backup phase=scan status=started")
- print(f"Scanning {display_hermes_home()} ...")
- skipped_dirs: set = set()
- files_to_add: list[tuple[Path, Path]] = list(
- _iter_backup_files(hermes_root, out_path, skipped_dirs)
- )
-
- # External memory-provider state (e.g. ~/.honcho, ~/.hindsight) lives
- # outside HERMES_HOME, so the walk above never sees it. Ask the active
- # provider for its declared paths and stage them under the reserved
- # ``_external/`` arc prefix, encoded relative to the user's home dir.
- # Only paths under home are captured (security + portability); anything
- # else is skipped with a note.
- home_dir = Path.home().resolve()
- external_to_add: list[tuple[Path, str]] = [] # (absolute, arcname)
- skipped_external: list[str] = []
- for base in _collect_memory_provider_external_paths():
- try:
- base_resolved = base.resolve()
- base_resolved.relative_to(home_dir)
- except (ValueError, OSError):
- skipped_external.append(str(base))
- continue
- for fpath in _iter_external_files(base):
- try:
- rel_to_home = fpath.resolve().relative_to(home_dir)
- except (ValueError, OSError):
- continue
- arcname = _EXTERNAL_PREFIX + rel_to_home.as_posix()
- external_to_add.append((fpath, arcname))
-
- if not files_to_add and not external_to_add:
- logger.info(
- "backup phase=scan status=empty duration_ms=%.1f",
- (time.monotonic() - scan_started) * 1000,
- )
- print("No files to back up.")
- return
-
- # Create the zip
- file_count = len(files_to_add) + len(external_to_add)
- logger.info(
- "backup phase=scan status=complete duration_ms=%.1f files=%d",
- (time.monotonic() - scan_started) * 1000,
- file_count,
- )
- logger.info("backup phase=archive status=started files=%d", file_count)
- print(f"Backing up {file_count} files ...")
-
- total_bytes = 0
- errors = []
- t0 = time.monotonic()
-
- with _atomic_output_path(out_path) as archive_path, zipfile.ZipFile(
- archive_path, "w", zipfile.ZIP_DEFLATED, compresslevel=6
- ) as zf:
- for i, (abs_path, rel_path) in enumerate(files_to_add, 1):
- try:
- total_bytes += _write_backup_file(zf, abs_path, str(rel_path), out_path.parent)
- except (OSError, ValueError, _SQLiteSnapshotError) as exc:
- errors.append(f" {rel_path}: {exc}")
- continue
-
- # Progress every 500 files
- if i % 500 == 0:
- print(f" {i}/{file_count} files ...")
- logger.info(
- "backup phase=archive status=progress completed=%d total=%d",
- i,
- file_count,
- )
-
- # External memory-provider state, stored under the ``_external/`` arc
- # prefix. These never include ``.db`` files in practice (config/env
- # blobs), so a straight zf.write is fine.
- for abs_path, arcname in external_to_add:
- try:
- zf.write(abs_path, arcname=arcname)
- total_bytes += abs_path.stat().st_size
- except (PermissionError, OSError, ValueError) as exc:
- errors.append(f" {arcname}: {exc}")
- continue
-
- elapsed = time.monotonic() - t0
- zip_size = out_path.stat().st_size
- logger.info(
- "backup phase=archive status=complete duration_ms=%.1f files=%d errors=%d bytes=%d",
- elapsed * 1000,
- file_count,
- len(errors),
- zip_size,
- )
-
- # Summary
- print()
- if errors:
- print(f"Backup incomplete: {out_path}")
- else:
- print(f"Backup complete: {out_path}")
- print(f" Files: {file_count}")
- print(f" Original: {_format_size(total_bytes)}")
- print(f" Compressed: {_format_size(zip_size)}")
- print(f" Time: {elapsed:.1f}s")
-
- if external_to_add:
- print(
- f"\n Included {len(external_to_add)} memory-provider file(s) "
- f"stored outside {display_hermes_home()}."
- )
-
- if skipped_external:
- print(
- f"\n Skipped {len(skipped_external)} memory-provider path(s) "
- f"outside your home directory (not portable):"
- )
- for p in sorted(skipped_external)[:10]:
- print(f" {p}")
-
- if skipped_dirs:
- print("\n Excluded directories:")
- for d in sorted(skipped_dirs):
- print(f" {d}/")
-
- if errors:
- print(f"\n Warnings ({len(errors)} files skipped):")
- for e in errors[:10]:
- print(e)
- if len(errors) > 10:
- print(f" ... and {len(errors) - 10} more")
-
- if not errors:
- print(f"\nRestore with: hermes import {out_path.name}")
- keep = getattr(args, "keep", 0)
- if keep and out_path.name.startswith(_RUN_BACKUP_PREFIX):
- pruned = _prune_prefixed_zips(out_path.parent, _RUN_BACKUP_PREFIX, keep, "backup")
- if pruned:
- print(f" Pruned {pruned} older {_RUN_BACKUP_PREFIX}*.zip (keeping {keep}).")
-
-
+# ---------------------------------------------------------------------------
+# Import
+# ---------------------------------------------------------------------------
+
+def run_import(args) -> None:
+ """Restore a Hermes backup from a zip file."""
+ zip_path = Path(args.zipfile).expanduser().resolve()
+
+ if not zip_path.is_file():
+ print(f"Error: File not found: {zip_path}")
+ sys.exit(1)
+
+ if not zipfile.is_zipfile(zip_path):
+ print(f"Error: Not a valid zip file: {zip_path}")
+ sys.exit(1)
+
+ # The restore target must be the home the command operates under — the
+ # same path printed as "Target:" via display_hermes_home(). Resolving
+ # through get_default_hermes_root() instead maps a profile home
+ # (<root>/profiles/<name>) back to <root>, silently retargeting the
+ # restore at the live root while the profile directory stays empty.
+ hermes_root = get_hermes_home()
+
+ with zipfile.ZipFile(zip_path, "r") as zf:
+ # Validate
+ ok, reason = _validate_backup_zip(zf)
+ if not ok:
+ print(f"Error: {reason}")
+ sys.exit(1)
+
+ prefix = _detect_prefix(zf)
+ members = [n for n in zf.namelist() if not n.endswith("/")]
+ file_count = len(members)
+
+ print(f"Backup contains {file_count} files")
+ print(f"Target: {display_hermes_home()}")
+
+ if prefix:
+ print(f"Detected archive prefix: {prefix!r} (will be stripped)")
+
+ # Check for existing installation
+ has_config = (hermes_root / "config.yaml").exists()
+ has_env = (hermes_root / ".env").exists()
+
+ if (has_config or has_env) and not args.force:
+ print()
+ print("Warning: Target directory already has Hermes configuration.")
+ print("Importing will overwrite existing files with backup contents.")
+ print()
+ try:
+ answer = input("Continue? [y/N] ").strip().lower()
+ except (EOFError, KeyboardInterrupt):
+ print("\nAborted.")
+ sys.exit(1)
+ if answer not in {"y", "yes"}:
+ print("Aborted.")
+ return
+
+ # Extract
+ print(f"\nImporting {file_count} files ...")
+ hermes_root.mkdir(parents=True, exist_ok=True)
+
+ errors = []
+ restored = 0
+ restored_external = 0
+ skipped_runtime: list[str] = []
+ # (rel, live_counts, imported_counts) for every session database the
+ # import replaced with one holding fewer rows. A restore is allowed to
+ # do that — it just must not do it silently (issue #100960).
+ db_shrunk: list[tuple[str, tuple[int, int], tuple[int, int]]] = []
+ home_dir = Path.home().resolve()
+ # Resolved once: every member is published via a temp file, and mkstemp
+ # would otherwise create newly restored files as 0600.
+ new_file_mode = _default_new_file_mode()
+ t0 = time.monotonic()
+
+ for member in members:
+ # External memory-provider state captured under the reserved
+ # ``_external/`` arc prefix restores to its original home-relative
+ # location (e.g. ~/.honcho/config.json), NOT under HERMES_HOME.
+ if member.startswith(_EXTERNAL_PREFIX):
+ ext_rel = member[len(_EXTERNAL_PREFIX):]
+ if not ext_rel:
+ continue
+ target = home_dir / ext_rel
+ # Security: the resolved target must stay under the home dir.
+ try:
+ target.resolve().relative_to(home_dir)
+ except ValueError:
+ errors.append(f" {member}: path traversal blocked")
+ continue
+ try:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ _extract_member_atomically(zf, member, target, new_file_mode)
+ # External provider configs commonly hold credentials.
+ if target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES:
+ try:
+ os.chmod(target, 0o600)
+ except OSError:
+ pass
+ restored += 1
+ restored_external += 1
+ except (PermissionError, OSError) as exc:
+ errors.append(f" {member}: {exc}")
+ if restored % 500 == 0:
+ print(f" {restored}/{file_count} files ...")
+ continue
+
+ # Strip prefix if detected
+ if prefix and member.startswith(prefix):
+ rel = member[len(prefix):]
+ else:
+ rel = member
+
+ if not rel:
+ continue
+
+ try:
+ parts = tuple(normalize_archive_parts(rel))
+ except ValueError:
+ errors.append(f" {rel}: path traversal blocked")
+ continue
+
+ # Never overwrite volatile gateway/process runtime state. These are
+ # namespaced to the machine/container the backup was taken on;
+ # clobbering them (especially gateway_state.json) breaks the gateway
+ # reconciler on the target and disconnects hosted instances from the
+ # Nous portal. Matched by basename so both the root profile and
+ # named profiles (profiles/<name>/gateway_state.json) are covered.
+ if parts[-1] in _IMPORT_SKIP_NAMES:
+ skipped_runtime.append(rel)
+ continue
+
+ # Older archives may contain PM selections pointing at another machine.
+ # Match their home-root paths; a plugin's own facts.json is user data.
+ if profile_root_entry(parts) in PM_RUNTIME_ROOT_DIRS:
+ skipped_runtime.append(rel)
+ continue
+
+ # A ``.db`` member is page-restored into the live file below; a
+ # WAL/SHM/journal member from the archive describes a different
+ # database image, and installing it beside the restored file (over
+ # a live sidecar, via os.replace) would replay a foreign WAL on
+ # the next open. Current backups never ship these
+ # (_EXCLUDED_SUFFIXES); older or hand-built archives might.
+ if rel.endswith(_SQLITE_SIDECAR_SUFFIXES):
+ skipped_runtime.append(rel)
+ continue
+
+ target = hermes_root.joinpath(*parts)
+
+ # Security: reject absolute paths and traversals
+ try:
+ target.resolve().relative_to(hermes_root.resolve())
+ except ValueError:
+ errors.append(f" {rel}: path traversal blocked")
+ continue
+
+ try:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ if target.suffix == ".db":
+ # Count before the write: afterwards the rows this import
+ # drops are gone and there is nothing left to compare.
+ before = _count_session_rows(target)
+ _import_db_member(zf, member, target, new_file_mode)
+ after = _count_session_rows(target)
+ if before and after and after[1] < before[1]:
+ db_shrunk.append((rel, before, after))
+ else:
+ _extract_member_atomically(zf, member, target, new_file_mode)
+ if target.name in _SECRET_FILE_NAMES:
+ os.chmod(target, 0o600)
+ restored += 1
+ except (PermissionError, OSError) as exc:
+ errors.append(f" {rel}: {exc}")
+
+ if restored % 500 == 0:
+ print(f" {restored}/{file_count} files ...")
+
+ elapsed = time.monotonic() - t0
+
+ # Summary
+ print()
+ print(f"Import complete: {restored} files restored in {elapsed:.1f}s")
+ print(f" Target: {display_hermes_home()}")
+
+ if restored_external:
+ print(
+ f"\n Restored {restored_external} memory-provider file(s) to "
+ f"their original location(s) outside {display_hermes_home()}."
+ )
+
+ if errors:
+ print(f"\n Warnings ({len(errors)} files skipped):")
+ for e in errors[:10]:
+ print(e)
+ if len(errors) > 10:
+ print(f" ... and {len(errors) - 10} more")
+
+ if db_shrunk:
+ # The backup predates work that is now overwritten. Say so: the
+ # reported incident was twelve sessions disappearing with nothing
+ # logged anywhere (issue #100960).
+ print("\n ⚠ Session data replaced by older backup contents:")
+ for rel, before, after in db_shrunk:
+ print(
+ f" {rel}: {before[0]} session(s) / {before[1]} message(s)"
+ f" -> {after[0]} / {after[1]}"
+ )
+ print(
+ " Anything recorded after the backup was taken is not in it. "
+ f"{_snapshot_recovery_hint()}"
+ )
+
+ if skipped_runtime:
+ print(
+ f"\n Preserved {len(skipped_runtime)} runtime state "
+ f"file(s) (kept this machine's, not the backup's):"
+ )
+ for rel in sorted(skipped_runtime)[:10]:
+ print(f" {rel}")
+ if len(skipped_runtime) > 10:
+ print(f" ... and {len(skipped_runtime) - 10} more")
+
+ # Post-import: restore profile wrapper scripts
+ profiles_dir = hermes_root / "profiles"
+ restored_profiles = []
+ if profiles_dir.is_dir():
+ try:
+ from hermes_cli.profiles import (
+ create_wrapper_script, check_alias_collision,
+ _is_wrapper_dir_in_path, _get_wrapper_dir,
+ )
+ for entry in sorted(profiles_dir.iterdir()):
+ if not entry.is_dir():
+ continue
+ profile_name = entry.name
+ # Only create wrappers for directories with config
+ if not (entry / "config.yaml").exists() and not (entry / ".env").exists():
+ continue
+ collision = check_alias_collision(profile_name)
+ if collision:
+ print(f" Skipped alias '{profile_name}': {collision}")
+ restored_profiles.append((profile_name, False))
+ else:
+ wrapper = create_wrapper_script(profile_name)
+ restored_profiles.append((profile_name, wrapper is not None))
+
+ if restored_profiles:
+ created = [n for n, ok in restored_profiles if ok]
+ skipped = [n for n, ok in restored_profiles if not ok]
+ if created:
+ print(f"\n Profile aliases restored: {', '.join(created)}")
+ if skipped:
+ print(f" Profile aliases skipped: {', '.join(skipped)}")
+ if not _is_wrapper_dir_in_path():
+ print(f"\n Note: {_get_wrapper_dir()} is not in your PATH.")
+ print(' Add to your shell config (~/.bashrc or ~/.zshrc):')
+ print(' export PATH="$HOME/.local/bin:$PATH"')
+ except ImportError:
+ # hermes_cli.profiles might not be available (fresh install)
+ if any(profiles_dir.iterdir()):
+ print("\n Profiles detected but aliases could not be created.")
+ print(" Run: hermes profile list (after installing hermes)")
+
+ # Guidance
+ print()
+ if not (hermes_root / "hermes-agent").is_dir():
+ print("Note: The hermes-agent codebase was not included in the backup.")
+ print(" If this is a fresh install, run: hermes update")
+
+ if restored_profiles:
+ gw_profiles = [n for n, _ in restored_profiles]
+ print("\nTo re-enable gateway services for profiles:")
+ for pname in gw_profiles:
+ print(f" hermes -p {pname} gateway install")
+
+ # Bring the restored install to life: the backup may contain bot
+ # tokens and registered cron jobs, but they're inert without a
+ # gateway process. Install/start the service automatically (a
+ # platform-less gateway is a supported mode, so this is safe even
+ # for backups with no messaging config). Best-effort and prompt-free;
+ # failures print a manual fallback and never fail the import.
+ native_default = _get_platform_default_hermes_home()
+ default_has_install = any(
+ (native_default / marker).exists()
+ for marker in ("config.yaml", ".env", "state.db")
+ )
+ # A restore into a sandbox or profile home must not silently install
+ # a second gateway pointed at it — on the default service name that
+ # would shadow or hijack the machine's primary install. Only revive
+ # the service automatically when the restore landed in the default
+ # home, or when no other install exists on this machine.
+ if hermes_root != native_default and default_has_install:
+ print(
+ "\nRestored into a non-default home; leaving the gateway service "
+ "alone to avoid clashing with the install at "
+ f"{native_default}."
+ )
+ print("To start a gateway for this home, run: hermes gateway install")
+ else:
+ try:
+ from hermes_cli.gateway import ensure_gateway_service, _is_service_running
+
+ if not _is_service_running():
+ print()
+ ensure_gateway_service(context="import")
+ except Exception:
+ print("\nStart the gateway to activate cron jobs and messaging:")
+ print(" hermes gateway install")
+
+ print("Done. Your Hermes configuration has been restored.")
+
+
+# ---------------------------------------------------------------------------
+# Quick state snapshots (used by /snapshot slash command and hermes backup --quick)
+# ---------------------------------------------------------------------------
+
+def create_quick_snapshot(
+ label: Optional[str] = None,
+ hermes_home: Optional[Path] = None,
+ keep: Optional[int] = None,
+ max_file_size: Optional[int] = None,
+) -> Optional[str]:
+ """Create one atomic quick snapshot while holding the shared backup slot."""
+ home = hermes_home or get_hermes_home()
+ with _backup_operation_lock(home):
+ return _create_quick_snapshot_locked(
+ label=label,
+ hermes_home=home,
+ keep=keep,
+ max_file_size=max_file_size,
+ )
+
+
+def _create_quick_snapshot_locked(
+ label: Optional[str] = None,
+ hermes_home: Optional[Path] = None,
+ keep: Optional[int] = None,
+ max_file_size: Optional[int] = None,
+) -> Optional[str]:
+ """Create a quick state snapshot of critical files.
+
+ Copies STATE_FILES to a timestamped directory under state-snapshots/.
+ Auto-prunes old snapshots beyond the keep limit.
+
+ Args:
+ max_file_size: When set, individual files larger than this many bytes
+ are skipped (with a printed warning) instead of copied. Used by
+ the pre-update safety snapshot so a multi-GB ``state.db`` can
+ never stall ``hermes update`` or silently eat disk — the small
+ pairing/cron/config files the snapshot exists to protect are
+ always captured. ``None`` (default) copies everything, which
+ preserves manual ``/snapshot`` and ``hermes backup --quick``
+ behavior.
+
+ Returns:
+ Snapshot ID (timestamp-based), or None if no files found.
+ """
+ home = hermes_home or get_hermes_home()
+ root = _quick_snapshot_root(home)
+
+ def _too_large(path: Path, rel_name: str) -> bool:
+ """True (and warn) when ``path`` exceeds the max_file_size cap."""
+ if max_file_size is None:
+ return False
+ try:
+ size = path.stat().st_size
+ except OSError:
+ return False
+ if size <= max_file_size:
+ return False
+ print(
+ f" ⚠ Snapshot: skipping {rel_name} "
+ f"({_format_size(size)} exceeds {_format_size(max_file_size)} limit)"
+ )
+ logger.warning(
+ "Quick snapshot skipped %s: %d bytes exceeds %d byte limit",
+ rel_name,
+ size,
+ max_file_size,
+ )
+ return True
+
+ ts = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
+ base_snap_id = f"{ts}-{label}" if label else ts
+ snap_id = base_snap_id
+ suffix = 2
+ while (root / snap_id).exists():
+ snap_id = f"{base_snap_id}-{suffix}"
+ suffix += 1
+ snap_dir = root / snap_id
+ staging_dir = root / f".{snap_id}.{os.getpid()}.partial"
+ shutil.rmtree(staging_dir, ignore_errors=True)
+ root.mkdir(parents=True, exist_ok=True, mode=0o700)
+ if os.name != "nt":
os.chmod(root, 0o700)
staging_dir.mkdir(mode=0o700, exist_ok=False)
logger.info("quick snapshot phase=copy status=started id=%s", snap_id)
@@@ -1878,28 -1602,11 +1879,12 @@@ def run_quick_backup(args) -> None
print("No state files found to snapshot.")
-# --- Shared full-zip backup helper ---
+# ---------------------------------------------------------------------------
+# Shared full-zip backup helper
+# ---------------------------------------------------------------------------
- def _write_backup_file(zf: zipfile.ZipFile, source: Path, arcname: str, staging_dir: Path) -> int:
- """Serialize one file, staging SQLite beside the ZIP rather than in small tmpfs."""
- if source.suffix != ".db":
- zf.write(source, arcname=arcname)
- return source.stat().st_size
- with tempfile.NamedTemporaryFile(suffix=".db", delete=False, dir=str(staging_dir)) as tmp:
- snapshot = Path(tmp.name)
- try:
- if not _safe_copy_db(source, snapshot):
- raise _SQLiteSnapshotError("SQLite safe copy failed")
- zf.write(snapshot, arcname=arcname)
- return snapshot.stat().st_size
- finally:
- snapshot.unlink(missing_ok=True)
-
-
def _write_full_zip_backup(out_path: Path, hermes_root: Path) -> Optional[Path]:
- """Full zip snapshot of ``hermes_root`` to ``out_path`` under the backup slot (same rules as
- :func:`run_backup`); None when nothing to back up, another backup running, or write error."""
+ """Single-flight wrapper for automatic full zip backups."""
try:
with _backup_operation_lock(hermes_root):
return _write_full_zip_backup_locked(out_path, hermes_root)
diff --cc hermes_cli/gateway.py
index 50bfbd375f3,dcdec3f6b9b..c9939f0a31e
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@@ -4447,21 -4426,9 +4493,22 @@@ def launchd_restart()
print("⚠ launchd did not revive the gateway after its graceful exit — forcing restart")
else:
print(f"⚠ Gateway drain timed out after {wait_budget:.0f}s — forcing launchd restart")
+ if not refresh_ok and get_launchd_plist_path().exists() and not launchd_plist_is_current():
+ # The refresh attempted a reload and launchd never re-registered
+ # the (rewritten) job: kickstart would hang on the same wall. The
+ # bootout already happened inside the refresh — bootstrap is the
+ # bounded revival path. (False alone is ambiguous: a missing or
+ # already-current plist also returns False, and both must keep
+ # the ordinary kickstart flow.)
+ print("↻ launchd job was not re-registered by the plist refresh; reloading")
+ plist_path = str(get_launchd_plist_path())
+ subprocess.run(["launchctl", "bootstrap", _launchd_domain(), plist_path], check=True, timeout=30)
+ subprocess.run(["launchctl", "kickstart", target], check=True, timeout=30)
+ _launchd_ok("✓ Service restarted")
+ return
# Captured: an unloaded job (3/113/125) is the expected case below, which
# prints its own ↻ line — and e.stderr feeds the update_cmd failure diagnostic.
+ _wait_for_api_server_port_free()
subprocess.run(["launchctl", "kickstart", "-k", target], check=True, timeout=90, **_CAPTURE_TEXT)
_launchd_ok("✓ Service restarted")
except subprocess.CalledProcessError as e:
@@@ -6467,8 -6411,9 +6514,9 @@@ def _cmd_start(args)
if killed:
print(f"✓ Killed {killed} stale gateway process(es) across all profiles")
_wait_for_gateway_exit(timeout=10.0, force_after=5.0)
+ _wait_for_api_server_port_free()
- if is_termux():
+ if _service_mgmt_blocked():
_no_backend_exit("start", "termux")
backend = _service_backend()
if backend is not None:
diff --cc tests/hermes_cli/test_gateway_restart_loop.py
index d1e0177bc63,ca2e000cf3e..fcfb2c269ec
--- a/tests/hermes_cli/test_gateway_restart_loop.py
+++ b/tests/hermes_cli/test_gateway_restart_loop.py
@@@ -906,7 -944,7 +952,7 @@@ class TestLifecycleGuardModule
contains_gateway_lifecycle_command_or_referenced_script,
)
script = tmp_path / "restart.sh"
- script.write_text("#!/usr/bin/env bash\nhermes gateway restart\n")
- script.write_text("#!/bin/bash\nhermes gateway restart\n", encoding="utf-8")
++ script.write_text("#!/usr/bin/env bash\nhermes gateway restart\n", encoding="utf-8")
assert (
contains_gateway_lifecycle_command_or_referenced_script(f". {script}")
is True
@@@ -938,7 -974,7 +984,7 @@@
contains_gateway_lifecycle_command_or_referenced_script,
)
script = tmp_path / "restart.sh"
- script.write_text("#!/usr/bin/env bash\nhermes gateway restart\n")
- script.write_text("#!/bin/bash\nhermes gateway restart\n", encoding="utf-8")
++ script.write_text("#!/usr/bin/env bash\nhermes gateway restart\n", encoding="utf-8")
assert (
contains_gateway_lifecycle_command_or_referenced_script(f"source {script}")
is True
@@@ -951,7 -987,7 +997,7 @@@
contains_gateway_lifecycle_command_or_referenced_script,
)
script = tmp_path / "activate.sh"
- script.write_text("#!/usr/bin/env bash\nexport PATH=/usr/bin:$PATH\n")
- script.write_text("#!/bin/bash\nexport PATH=/usr/bin:$PATH\n", encoding="utf-8")
++ script.write_text("#!/usr/bin/env bash\nexport PATH=/usr/bin:$PATH\n", encoding="utf-8")
assert (
contains_gateway_lifecycle_command_or_referenced_script(f". {script}")
is False
diff --cc website/docs/developer-guide/web-search-provider-plugin.md
index 5d297f1a968,2070c68740e..a254b8561ce
--- a/website/docs/developer-guide/web-search-provider-plugin.md
+++ b/website/docs/developer-guide/web-search-provider-plugin.md
@@@ -233,14 -233,7 +233,14 @@@ Errors surface as the tool result; the
## Lazy-installing optional dependencies
-If your provider wraps a third-party SDK (like DDGS does with the `ddgs` package), don't `import` it at module top level. Use `tools.lazy_deps.ensure(...)` inside `is_available()` or `search()` — Hermes will install the package on first use, gated by `security.allow_lazy_installs`. See [Build a Hermes Plugin → Lazy-install](./plugins/index.md#lazy-install-optional-python-dependencies) for the security model.
+Keep availability checks read-only. For an SDK covered by a Hermes extra,
+use `pm.available("extra-name")` in `is_available()`. Request
+`pm.ensure_import("extra-name")` from the operation that needs it. Report
+`InstallError`, including a required restart, to the caller.
+
+Declare a third-party plugin's own dependencies in its manifest or
+`pyproject.toml` rather than inventing a Hermes extra. See
- [Build a Hermes Plugin → Lazy-install](/developer-guide/plugins#lazy-install-optional-python-dependencies).
++[Build a Hermes Plugin → Lazy-install](./plugins/index.md#lazy-install-optional-python-dependencies).
## Reference implementations
diff --cc website/docs/getting-started/updating.md
index 0acf24d78b5,9173aabb348..72fbe2c2f76
--- a/website/docs/getting-started/updating.md
+++ b/website/docs/getting-started/updating.md
@@@ -280,33 -180,59 +282,33 @@@ updates
pre_update_backup: full
```
-`updates.pre_update_backup` is a single knob with three modes: `quick` (default — the lightweight state snapshot described above), `full` (the quick snapshot plus a complete `HERMES_HOME` zip; can add minutes on large homes), and `off` (no pre-update backup at all — `--no-backup` does the same for a single run). Legacy boolean values still work: `true` means `full`, `false` means `off`.
+`updates.pre_update_backup` has three modes:
+
+- `quick` saves the selected state files described above. This is the default.
+- `full` adds a zip archive with the [backup exclusions](/reference/faq#hermes-backup-vs-hermes-profile-export). Large data directories can take several minutes.
+- `off` disables pre-update backups. `--no-backup` selects this mode for one run.
+
+Legacy boolean values remain supported: `true` means `full`, and `false` means `off`.
:::tip Moving to a new machine instead?
- Update backups protect an in-place update. If you're migrating your whole setup to different hardware, use `hermes backup` + `hermes import` instead — see [Exporting Hermes to another machine](/reference/faq#exporting-hermes-to-another-machine) and [`hermes backup` vs `hermes profile export`](/reference/faq#hermes-backup-vs-hermes-profile-export).
+ Update backups protect an in-place update. If you're migrating your whole setup to different hardware, use `hermes backup` + `hermes import` instead — see [Exporting Hermes to another machine](../reference/faq.md#exporting-hermes-to-another-machine) and [`hermes backup` vs `hermes profile export`](../reference/faq.md#hermes-backup-vs-hermes-profile-export).
:::
-### Windows: another `hermes.exe` is running
-
-On Windows, `hermes update` will refuse to run if it detects another `hermes.exe` process holding the venv's entry-point executable open — most commonly the Hermes Desktop app's spawned backend, an open `hermes` REPL in another terminal, or a running gateway:
-
-```
-$ hermes update
-✗ Another hermes.exe is running:
- PID 12345 hermes.exe
-
- Updating now would fail to overwrite ...\venv\Scripts\hermes.exe because
- Windows blocks REPLACE on a running executable.
-
- Close Hermes Desktop, exit any open `hermes` REPLs, and
- stop the gateway (`hermes gateway stop`) before retrying.
- Override with `hermes update --force` if you've already
- confirmed those processes will not write to the venv.
-```
-
-Close the listed processes and re-run. If you're sure the concurrent process won't interfere (rare — usually only useful when an antivirus shim is mis-attributed), pass `--force` to skip the check. In that case the updater will still retry the `.exe` rename with exponential backoff and, on stubborn locks, schedule the replacement for next reboot via `MoveFileEx(MOVEFILE_DELAY_UNTIL_REBOOT)` so the update can complete.
-
-A second, separate guard refuses to touch the venv while any process is running from its Python interpreter (the Desktop app's backend, a gateway, a Python REPL). Those processes keep native extension files (`.pyd`) locked, and a dependency sync that dies partway on an access-denied error strands the install between versions. This guard is **not** bypassed by `--force`; if you're certain the detected holders are false positives, use the explicit `hermes update --force-venv`.
-
-Both guards, the Desktop update preflight, and the dependency repair steps look for the environment at `venv` first and then at the uv-default `.venv`, so a source checkout set up with `uv venv` / `uv sync` updates the same way an installer-created `venv` does. When both directories exist, `venv` is the one that gets updated.
-
-#### Windows venv recreation is transactional
-
-When the Windows installer must recreate an existing `venv`, it first moves the old directory to a unique `venv.stale.*` name, then creates and verifies the replacement. The old tree is deleted only after the dependency install completes and the baseline imports pass in the new tree — until then it is the rollback source (recorded in `venv.pending-backup`).
+### Windows process ownership and dependency changes
-If the move cannot be completed, the installer stops and leaves the live `venv` untouched. If `uv` fails or reports success without creating the interpreter, any partial replacement is moved to `venv.failed.*` and the previous venv is restored. This keeps the health and blocker checks usable after a failed install.
+Windows can hold executable and native-extension files open while processes run.
+PM therefore prepares dependency generations separately instead of replacing
+imported libraries in place. A running process keeps its current imports until
+it restarts.
-A `venv.stale.*` or `venv.failed.*` directory can remain when another process still owns a file handle. Close Hermes Desktop, gateways, and Python processes using the install, then retry the install/update; parked directories are cleaned up best-effort after a successful recreation.
+Follow any blocker diagnostic for the specific process and installation. Do
+not kill every process named Python or Hermes. Source updates and MSIX package
+replacement have different owners and shutdown requirements.
-Expected output looks like:
-
-```
-$ hermes update
-Updating Hermes Agent...
-📥 Pulling latest code...
-Already up to date. (or: Updating abc1234..def5678)
-📦 Updating dependencies...
-✅ Dependencies updated
-🔍 Checking for new config options...
-✅ Config is up to date (or: Found 2 new options — running migration...)
-🔄 Restarting gateways...
-✅ Gateway restarted
-✅ Hermes Agent updated successfully!
-```
+The parser retains `--force` and `--force-venv` for Windows compatibility. They
+are not normal update instructions or a guarantee that an OS file lock can be
+bypassed. Inspect `hermes update --plan`, the update log, and `hermes pm status`
+before retrying a failed update.
### Recommended Post-Update Validation
@@@ -408,22 -363,10 +410,22 @@@ See [Nix Setup](./nix-setup.md) for mor
hermes uninstall
```
-The uninstaller gives you the option to keep your configuration files (`~/.hermes/`) for a future reinstall.
+For source installs, review `hermes uninstall --dry-run` before removal.
+The default removal can preserve configuration and user data. `--full` also
+removes data. `--data` removes user data without deleting package-owned code.
+These modes are destructive; make a backup first.
+
+For MSIX/Store, use Windows Settings → Apps → Installed apps. For macOS,
+quit Hermes and move its app bundle to Trash. Docker, Nix, and Termux use the
+same manager that installed them. Their package files are not removed by the
+source uninstaller. Data deletion is separate from package removal.
:::tip Moving to a new machine rather than leaving?
-Take your setup with you before removing anything: `hermes backup` captures the entire `~/.hermes` directory including credentials, while `hermes profile export` packs a single profile with credentials excluded by design (so an export alone is not a full backup). See [`hermes backup` vs `hermes profile export`](../reference/faq.md#hermes-backup-vs-hermes-profile-export).
+Run `hermes backup` before you remove the installation. The full archive includes
+credentials but excludes downloaded runtimes, dependency environments, caches,
+and browser profiles. Review its skipped-file report before you delete source data.
+`hermes profile export` packs one profile without credentials.
- See [`hermes backup` vs `hermes profile export`](/reference/faq#hermes-backup-vs-hermes-profile-export).
++See [`hermes backup` vs `hermes profile export`](../reference/faq.md#hermes-backup-vs-hermes-profile-export).
:::
### Manual Uninstall
diff --cc website/docs/guides/manage-hermes-cloud-with-mcp.md
index 3ead907c771,c4eaab64014..4bb6aa292fa
--- a/website/docs/guides/manage-hermes-cloud-with-mcp.md
+++ b/website/docs/guides/manage-hermes-cloud-with-mcp.md
@@@ -6,13 -6,9 +6,13 @@@ description: "Connect Hermes Agent to t
# Manage Hermes Cloud with MCP
+Python dependency commands on this page use a
+[PM-prepared source checkout](/reference/package-management#developer-workflow).
+After a dependency change, reactivate the checkout and restart Hermes.
+
- [Hermes Cloud](https://portal.nousresearch.com/cloud) runs hosted Hermes Agent instances for you. Normally you manage them from the `/agents` page in the [Nous Portal](/integrations/nous-portal). This guide connects your **local** Hermes Agent to the Portal's MCP server so you can manage those cloud instances by just asking — "list my cloud agents", "restart the stopped one", "what's it costing me" — without leaving your terminal.
+ [Hermes Cloud](https://portal.nousresearch.com/cloud) runs hosted Hermes Agent instances for you. Normally you manage them from the `/agents` page in the [Nous Portal](../integrations/nous-portal.md). This guide connects your **local** Hermes Agent to the Portal's MCP server so you can manage those cloud instances by just asking — "list my cloud agents", "restart the stopped one", "what's it costing me" — without leaving your terminal.
- It's a standard [MCP](/user-guide/features/mcp) server hosted by Nous Research, gated by the same OAuth login you already use for the Portal. Once connected, Hermes gets two tools it can call on your behalf.
+ It's a standard [MCP](../user-guide/features/mcp.md) server hosted by Nous Research, gated by the same OAuth login you already use for the Portal. Once connected, Hermes gets two tools it can call on your behalf.
## What you can do with it
diff --cc website/docs/guides/use-voice-mode-with-hermes.md
index b034b895c96,b9cca2a4aaf..5918e9e6d0a
--- a/website/docs/guides/use-voice-mode-with-hermes.md
+++ b/website/docs/guides/use-voice-mode-with-hermes.md
@@@ -6,11 -6,7 +6,11 @@@ description: "A practical guide to sett
# Use Voice Mode with Hermes
+Python dependency commands on this page use a
+[PM-prepared source checkout](/reference/package-management#developer-workflow).
+After a dependency change, reactivate the checkout and restart Hermes.
+
- This guide is the practical companion to the [Voice Mode feature reference](/user-guide/features/voice-mode).
+ This guide is the practical companion to the [Voice Mode feature reference](../user-guide/features/voice-mode.md).
If the feature page explains what voice mode can do, this guide shows how to actually use it well.
diff --cc website/docs/index.mdx
index c55ff33f111,430f708451b..daff2570eef
--- a/website/docs/index.mdx
+++ b/website/docs/index.mdx
@@@ -99,10 -97,10 +99,10 @@@ Run in powershell
iex (irm https://hermes-agent.nousresearch.com/install.ps1)
```
- See the full **[Installation Guide](/getting-started/installation)** for what the installer does, installation ownership and data locations, and Windows-specific notes. For the complete platform support matrix, see **[Platform Support](/getting-started/platform-support)**.
-See the full **[Installation Guide](./getting-started/installation.md)** for what the installer does, the per-user vs root layout, and Windows-specific notes. For the complete platform support matrix, see **[Platform Support](./getting-started/platform-support.md)**.
++See the full **[Installation Guide](./getting-started/installation.md)** for what the installer does, installation ownership and data locations, and Windows-specific notes. For the complete platform support matrix, see **[Platform Support](./getting-started/platform-support.md)**.
:::tip Fastest path to a working agent
- After installing, run `hermes setup --portal` — one OAuth covers a model plus all four Tool Gateway tools (web search, image generation, TTS, browser). See [Nous Portal](/integrations/nous-portal).
+ After installing, run `hermes setup --portal` — one OAuth covers a model plus all four Tool Gateway tools (web search, image generation, TTS, browser). See [Nous Portal](./integrations/nous-portal.md).
:::
## What is Hermes Agent?
diff --cc website/docs/reference/cli-commands.md
index 28bc87064af,f9a9089cf81..2116295abe8
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@@ -1779,7 -1784,7 +1788,7 @@@ Start the Hermes **backend server** �
hermes dashboard [options]
```
- Launch the web dashboard to manage configuration, API keys, and sessions. For a headless backend, use [`hermes serve`](#hermes-serve). FastAPI, Uvicorn, and the platform PTY helper are core dependencies. The `web` extra adds exact HTTP-stack constraints and is selected by standard PM setup through `all`. If dependencies are damaged, run `hermes pm repair`. The embedded Chat tab requires a POSIX PTY environment, such as Linux, macOS, or WSL2. See [Web Dashboard](/user-guide/features/web-dashboard).
-Launch the web dashboard — a browser-based UI for managing configuration, API keys, and monitoring sessions. (For a headless backend with no browser UI — e.g. what the desktop app spawns — use [`hermes serve`](#hermes-serve) above.) Requires `cd ~/.hermes/hermes-agent && uv pip install -e ".[web]"` (FastAPI + Uvicorn). The embedded browser Chat tab is always available and additionally needs the `pty` extra (`cd ~/.hermes/hermes-agent && uv pip install -e ".[web,pty]"`) plus a POSIX PTY environment such as Linux, macOS, or WSL2. See [Web Dashboard](../user-guide/features/web-dashboard.md) for full documentation.
++Launch the web dashboard to manage configuration, API keys, and sessions. For a headless backend, use [`hermes serve`](#hermes-serve). FastAPI, Uvicorn, and the platform PTY helper are core dependencies. The `web` extra adds exact HTTP-stack constraints and is selected by standard PM setup through `all`. If dependencies are damaged, run `hermes pm repair`. The embedded Chat tab requires a POSIX PTY environment, such as Linux, macOS, or WSL2. See [Web Dashboard](../user-guide/features/web-dashboard.md).
| Option | Default | Description |
|--------|---------|-------------|
diff --cc website/docs/user-guide/docker.md
index 1c03d46d0f3,def63ea1f0a..317b0800c84
--- a/website/docs/user-guide/docker.md
+++ b/website/docs/user-guide/docker.md
@@@ -515,33 -499,18 +515,34 @@@ docker run -d
## What the Dockerfile does
-The official image is based on `debian:13.4` and includes:
+The image uses Debian 13.4 and includes:
+
+
-- Python 3.13 with dependencies synced from the lockfile via `uv sync --frozen --no-install-project` for the baked extras (`all`, `messaging`, Anthropic/Bedrock/Azure identity, Hindsight, Matrix), followed by a no-dependency editable install of Hermes itself.
-- Node.js 26 + npm (for browser automation, WhatsApp bridge, TUI/Desktop bundles, and workspace build tooling)
-- Playwright with Chromium (`npx playwright install --with-deps chromium --only-shell`)
-- ripgrep, ffmpeg, git, and `xz-utils` as system utilities
-- **`docker-cli`** — so agents running inside the container can drive the host's Docker daemon (bind-mount `/var/run/docker.sock` to opt in) for `docker build`, `docker run`, container inspection, etc.
-- **`openssh-client`** — enables the [SSH terminal backend](./configuration.md#ssh-backend) from inside the container. The SSH backend shells out to the system `ssh` binary; without this, it failed silently in containerized installs.
-- The WhatsApp bridge (`scripts/whatsapp-bridge/`)
-- **[`s6-overlay`](https://github.com/just-containers/s6-overlay) v3** as PID 1 (replaces the older `tini`) — supervises the dashboard and per-profile gateways with auto-restart on crash, reaps zombie subprocesses, and forwards signals.
+- A Python 3.14 environment synchronized from the committed `uv.lock`, followed
+ by a no-dependency editable install of Hermes.
+- The curated extras `all`, `messaging`, `otlp`, `anthropic`, `bedrock`,
+ `azure-identity`, `hindsight`, and `matrix`. This is not `--all-extras`.
+- Node.js 26 and npm from the digest-pinned Node source image.
+- PM-pinned uv, Chromium, and Chromium headless shell in `/opt/hermes/tools`.
+- System Git, ripgrep, FFmpeg, OpenSSH, Docker CLI, and Chromium shared libraries.
+- Prebuilt TUI/dashboard assets and baked Photon sidecar dependencies.
+- s6-overlay for supervision and zombie-process cleanup.
-The image treats `/opt/hermes` as an immutable install tree at runtime. Optional Python extras, Node workspaces, and TUI assets that must be available inside Docker need to be baked during the image build; runtime lazy installs are disabled so supervised gateways and `docker exec hermes …` commands do not try to write dependency artifacts back into the read-only source tree.
+Chromium is staged through PM, not `npx playwright install`. The build records
+its resolved executable in `/etc/hermes/agent-browser-executable-path`.
+`PLAYWRIGHT_BROWSERS_PATH` names `/opt/hermes/tools`, outside the data mount.
+
+The image disables on-demand dependency installation with its internal
+`HERMES_DISABLE_LAZY_INSTALLS` policy. Changing `security.allow_lazy_installs`
+alone does not override that image policy. The old `lazy-packages` overlay is
+not used. Build additional required dependencies into a derived image, or run
+an independent tool in a separate environment/service.
+
+Image provenance lives at `/etc/hermes/image-provenance.json`, outside both the
+source and data mounts. The build stamp lives at `/opt/hermes/install-stamp.json`.
+A local build without a supplied stamp reports an unknown revision rather than
+inventing a commit. `hermes update` refuses image-owned code changes; replace
+the image to update the application.
The container's `ENTRYPOINT` is a small dispatcher (`docker/entrypoint-dispatch.sh`). When the container owns PID 1 (normal Docker / Podman), it exec's s6-overlay's `/init` and you get the full supervision tree described below. When a platform wraps the image entrypoint under its own PID-1 init (Fly.io Machines, `docker run --init`, some Nomad/Kubernetes setups), `/init` would abort with `s6-overlay-suexec: fatal: can only run as pid 1` — so the dispatcher instead runs the stage2 bootstrap directly and exec's the main wrapper without s6. On that fallback path the requested command still runs, but supervised services (dashboard, per-profile gateways) are unavailable.
diff --cc website/docs/user-guide/messaging/teams.md
index e3e1859f0e7,32002637d1b..deba396843f
--- a/website/docs/user-guide/messaging/teams.md
+++ b/website/docs/user-guide/messaging/teams.md
@@@ -6,13 -6,9 +6,13 @@@ description: "Set up Hermes Agent as a
# Microsoft Teams Setup
+Python dependency commands on this page use a
+[PM-prepared source checkout](/reference/package-management#developer-workflow).
+After a dependency change, reactivate the checkout and restart Hermes.
+
Connect Hermes Agent to Microsoft Teams as a bot. Unlike Slack's Socket Mode, Teams delivers messages by calling a **public HTTPS webhook**, so your instance needs a publicly reachable endpoint — either a dev tunnel (local dev) or a real domain (production).
- Need meeting summaries from Microsoft Graph events rather than normal bot conversations? Use the dedicated setup page: [Teams Meetings](/user-guide/messaging/teams-meetings).
+ Need meeting summaries from Microsoft Graph events rather than normal bot conversations? Use the dedicated setup page: [Teams Meetings](./teams-meetings.md).
> Run `hermes gateway setup` and pick **Microsoft Teams** for a guided walk-through.
diff --cc website/docs/user-guide/windows-native.md
index 38856eb1cb7,42d26afea10..5422f76ec60
--- a/website/docs/user-guide/windows-native.md
+++ b/website/docs/user-guide/windows-native.md
@@@ -9,10 -9,10 +9,10 @@@ sidebar_position:
Hermes runs natively on Windows 10 and Windows 11 — no WSL, no Cygwin, no Docker. This page is the deep dive: what works natively, what's WSL-only, what the installer actually does, and the Windows-specific knobs you might need to touch.
- If you just want to install, the one-liner on the [landing page](/) or [Installation page](../getting-started/installation#windows-native) is all you need. Come back here when something surprises you.
+ If you just want to install, the one-liner on the [landing page](../index.mdx) or [Installation page](../getting-started/installation#windows-native) is all you need. Come back here when something surprises you.
:::tip Want WSL instead?
-If you prefer a real POSIX environment (for the dashboard's embedded terminal, `fork` semantics, Linux-style file watchers, etc.), see the **[Windows (WSL2) Guide](./windows-wsl-quickstart.md)**. Both coexist cleanly: native data lives under `%LOCALAPPDATA%\hermes`, WSL data lives under `~/.hermes`.
+If you prefer a POSIX environment for `fork` semantics or Linux-style file watchers, see the **[Windows (WSL2) Guide](./windows-wsl-quickstart.md)**. Both coexist cleanly: native data lives under `%LOCALAPPDATA%\hermes`, WSL data lives under `~/.hermes`.
:::
## Quick install
@@@ -25,85 -25,61 +25,85 @@@ iex (irm https://raw.githubusercontent.
No admin rights required. The installer goes to `%LOCALAPPDATA%\hermes\` and adds `hermes` to your **User PATH** — open a new terminal after it finishes.
-**Installer options** (requires the scriptblock form to pass parameters):
+**Installer options** use a scriptblock:
```powershell
-& ([scriptblock]::Create((irm https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.ps1))) -NoVenv -SkipSetup -Branch main
+& ([scriptblock]::Create((irm https://hermes-agent.nousresearch.com/install.ps1))) -NonInteractive -Branch main
```
-| Parameter | Default | Purpose |
-|---|---|---|
-| `-Branch` | `main` | Clone a specific branch (useful for testing PRs) |
-| `-Commit` | unset | Pin install to a specific commit SHA (overrides `-Branch`) |
-| `-Tag` | unset | Pin install to a specific git tag (e.g. `v0.14.0`) |
-| `-NoVenv` | off | Skip venv creation (advanced — you manage Python yourself) |
-| `-SkipSetup` | off | Skip the post-install `hermes setup` wizard |
-| `-HermesHome` | `%LOCALAPPDATA%\hermes` | Override data directory |
-| `-InstallDir` | `%LOCALAPPDATA%\hermes\hermes-agent` | Override code location |
-
-The installer auto-retries flaky git fetches and strips BOM from any downloaded `install.ps1` payload, so a UTF-8 BOM picked up during HTTP transit no longer breaks the `[scriptblock]::Create((irm ...))` form.
-
-### Desktop installer (alternative)
-
-A thin GUI installer is also available — useful if you'd rather double-click an `.exe` than open PowerShell. Download Hermes Desktop, run the installer, and on first launch the GUI calls `install.ps1` under the hood to provision Python (via `uv`), Node, PortableGit, and the rest of the dependency bootstrap described below. After the first run, the desktop app and the PowerShell-installed `hermes` CLI share the same `%LOCALAPPDATA%\hermes\hermes-agent` install and `%LOCALAPPDATA%\hermes` data directory — switch between the GUI and the CLI freely.
-
-Use the desktop installer when you want a familiar Windows install experience or you're handing Hermes to a non-developer; use the PowerShell one-liner when you're already in a terminal.
-
-### Dependency bootstrap (`dep_ensure`)
-
-On first launch (and on demand when a missing tool is detected), Hermes runs a small Python bootstrapper — `hermes_cli/dep_ensure.py` — that checks for and lazily installs the non-Python dependencies it needs. On Windows, the relevant ones are:
-
-| Dependency | Why Hermes needs it |
+| Parameter | Purpose |
|---|---|
-| **PortableGit** | Provides `bash.exe` for the terminal tool and `git` for in-session clones. Provisioned at install time, not by `dep_ensure`. |
-| **Node.js 26** | Required for the browser tool (`agent-browser`), the TUI's web bridge, and the WhatsApp bridge. |
-| **ffmpeg** | Audio format conversion for TTS / voice messages. |
-| **ripgrep** | Fast file search — falls back to `grep` if unavailable. |
-| **npm packages** | `agent-browser`, Playwright Chromium, and any per-toolset Node deps are installed once at first browser-tool use. |
+| `-Branch NAME` | Select the source branch; default `main`. |
+| `-Commit SHA` | Select a commit after the branch checkout. |
+| `-HermesHome PATH` | Select the data directory. |
+| `-InstallDir PATH` | Select the source checkout directory. |
+| `-NonInteractive` | Skip setup and gateway stages that need input. |
+| `-IncludeDesktop` | Build the desktop app and create shortcuts. |
+| `-ShowResolvedPaths` | Print resolved paths as JSON without installing. |
+| `-Manifest` / `-ProtocolVersion` | Inspect the stage protocol used by the bootstrap GUI. |
+| `-Stage NAME -Json` | Run one stage and emit its result frame. |
+
+The current script does not accept `-NoVenv`, `-SkipSetup`, or `-Tag`.
+To diagnose an unexpected short Windows path, use `-ShowResolvedPaths` first.
+
+### MSIX / App Installer and Microsoft Store
+
+The bundled desktop is separate from the source script. Its MSIX package
+requires **Windows 11 22H2 or later**. Windows 10 source-script support does
+not mean the MSIX package supports Windows 10.
+
+Open the downloaded `.appinstaller` file with Windows App Installer. It installs
+a signed universal bundle and records the update source. The package includes
+Python, Node, supported dependencies, and prebuilt interfaces. It does not clone
+a checkout or build the base runtime on first launch.
+
+The MSIX execution aliases expose `hermes`, `hermes-agent`, and `hermes-acp`.
+If another installation shadows an alias, inspect `Get-Command hermes -All`.
+Windows Settings → Apps → Advanced app settings → App execution aliases
+controls the aliases.
+
+Sideload updates use the app's Update control and Windows App Installer.
+Hermes downloads a local descriptor before teardown and registers automatic
+relaunch. It does not require the `ms-appinstaller:` URL protocol. An unknown
+update-check result is not a claim that the package is current.
+
+The Microsoft Store variant uses its Partner Center package identity and Store
+updates. It does not use the sideload feed. `hermes update` inside either
+bundled runtime does not run Git against package files.
+
+`Hermes-Setup.exe` is a different, bootstrap installer. It provisions a source
+checkout through the scripts. Do not confuse it with the self-contained MSIX
+package. See [Updating & Uninstalling](../getting-started/updating.md).
+
+### Dependency bootstrap
+
+PM owns managed tools. `hermes_cli/dep_ensure.py` maps feature requirements to
+PM packages instead of invoking `install.ps1 -Ensure`. Already installed tools
+come from PM facts; missing optional tools follow the lazy-install policy.
-Each dep has a `shutil.which(...)`-style check; if a binary is missing and the run is interactive, `dep_ensure` offers to install it (deferring to `scripts\install.ps1 -ensure <dep>` for the actual install logic). Non-interactive runs (gateway, cron, headless desktop launches) skip the prompt and surface a clear `this feature needs <dep>` error instead.
+```powershell
+hermes pm doctor
+hermes pm install
+```
-## What the installer actually does
+## What the source installer does
-Top-to-bottom, in order:
+1. Locate Git, or stage the verified Git for Windows pin when Git is absent.
+2. Clone the selected repository branch and apply an optional commit pin.
+3. Bootstrap uv and create the initial Python environment.
+4. Run PM to provision Python 3.14, required tools, and the `all` Python extra.
+5. Mint CLI launchers in the data home's `bin` directory and add it to User PATH.
+6. Prepare configuration and invoke the interactive setup/gateway stages unless skipped.
+7. If requested, build the desktop and create Start Menu/Desktop shortcuts.
+8. Write the bootstrap-completion marker.
-1. **Bootstraps `uv`** — Astral's fast Python manager. Installed to `%USERPROFILE%\.local\bin`.
-2. **Installs Python 3.11** via `uv`. No existing Python needed.
-3. **Installs Node.js 26** (winget if available, else a portable Node tarball unpacked under `%LOCALAPPDATA%\hermes\node`). Used for the browser tool and the WhatsApp bridge.
-4. **Installs portable Git** — if `git` is already on PATH the installer uses it; otherwise it downloads a trimmed, self-contained **PortableGit** (~45 MB, from the official `git-for-windows` release) to `%LOCALAPPDATA%\hermes\git`. No admin, no Windows installer registry, no interference with anything else on the box.
-5. **Clones the repo** to `%LOCALAPPDATA%\hermes\hermes-agent` and creates a virtualenv inside it.
-6. **Tiered `uv pip install`** — tries `.[all]` first, falls back to progressively smaller sets (`[messaging,dashboard,ext]` → `[messaging]` → `.`) if a `git+https` dep flakes on rate-limited GitHub. Prevents "single flake drops you to a bare install" failure mode.
-7. **Auto-installs messaging SDKs** keyed off `.env` — if `TELEGRAM_BOT_TOKEN` / `DISCORD_BOT_TOKEN` / `SLACK_BOT_TOKEN` / `SLACK_APP_TOKEN` / `WHATSAPP_ENABLED` are present, runs `python -m ensurepip --upgrade` and targeted `pip install` calls so each platform's SDK is actually importable.
-8. **Sets `HERMES_GIT_BASH_PATH`** to the resolved `bash.exe` so Hermes finds it deterministically in fresh shells.
-9. **Adds `%LOCALAPPDATA%\hermes\bin` to User PATH and sets `HERMES_HOME=%LOCALAPPDATA%\hermes`** — exposes the `hermes` command (and points it at your data dir) after you open a new terminal. Only the `hermes.exe` / `hermes-acp.exe` launchers are copied into this `bin` directory; the full `venv\Scripts` is deliberately **not** placed on PATH so Hermes never shadows your own `python` command.
-10. **Runs `hermes setup`** — the normal first-run wizard (model, provider, toolsets). Skip with `-SkipSetup`.
+The runtime launcher executes PM's store Python and selects the dependency
+environment before imports. PM can publish a new writable environment without
+replacing libraries already loaded by a running process. There is no tiered
+pip fallback to silently reduce the installed feature set.
:::tip Skip provider hunting on Windows
- On Windows, per-tool API key setup (Firecrawl, FAL, Browser Use, OpenAI TTS) is the highest-friction part of getting a useful agent. A [Nous Portal](/user-guide/features/tool-gateway) subscription covers the model **and** all of those tools through one OAuth login. After the installer finishes, run `hermes setup --portal` to wire everything up.
+ On Windows, per-tool API key setup (Firecrawl, FAL, Browser Use, OpenAI TTS) is the highest-friction part of getting a useful agent. A [Nous Portal](./features/tool-gateway.md) subscription covers the model **and** all of those tools through one OAuth login. After the installer finishes, run `hermes setup --portal` to wire everything up.
:::
## Feature matrix
diff --cc website/docs/user-guide/windows-wsl-quickstart.md
index edcc9131391,9cf804af52c..b6dacc3f8ed
--- a/website/docs/user-guide/windows-wsl-quickstart.md
+++ b/website/docs/user-guide/windows-wsl-quickstart.md
@@@ -352,7 -352,7 +352,7 @@@ WSL2 stores its VM disk as a sparse VHD
## Where to go next
- - **[Installation](/getting-started/installation)** — actual install steps (Linux/WSL2 use the same installer).
- - **[Integrations → Providers → WSL2 Networking](/integrations/providers#wsl2-networking-windows-users)** — the canonical networking deep-dive for local model servers.
- - **[MCP guide → WSL → Windows Chrome](/guides/use-mcp-with-hermes#wsl2-bridge-hermes-in-wsl-to-windows-chrome)** — controlling your signed-in Windows Chrome from Hermes in WSL.
- - **[Tool Gateway](/user-guide/features/tool-gateway)** and **[Web Dashboard](/user-guide/features/web-dashboard)** — the long-lived services you'll most often want to expose from WSL to the rest of your network.
-- **[Installation](../getting-started/installation.md)** — actual install steps (Linux/WSL2/Termux all use the same installer).
++- **[Installation](../getting-started/installation.md)** — actual install steps (Linux/WSL2 use the same installer).
+ - **[Integrations → Providers → WSL2 Networking](../integrations/providers.md#wsl2-networking-windows-users)** — the canonical networking deep-dive for local model servers.
+ - **[MCP guide → WSL → Windows Chrome](../guides/use-mcp-with-hermes.md#wsl2-bridge-hermes-in-wsl-to-windows-chrome)** — controlling your signed-in Windows Chrome from Hermes in WSL.
+ - **[Tool Gateway](./features/tool-gateway.md)** and **[Web Dashboard](./features/web-dashboard.md)** — the long-lived services you'll most often want to expose from WSL to the rest of your network.
diff --cc website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/plugins/index.md
index dc40f6018f5,bacfccdf666..2524a53dde1
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/plugins/index.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/plugins/index.md
@@@ -14,25 -14,25 +14,25 @@@ Hermes 有多种不同的可插拔接�
| 如果你想添加… | 请阅读 |
|---|---|
| 自定义工具、钩子、斜杠命令、技能或 CLI 子命令 | **本指南**(通用插件接口) |
- | **LLM / 推理后端**(新提供商) | [模型提供商插件](/developer-guide/model-provider-plugin) |
- | **网关频道**(Discord/Telegram/IRC/Teams 等) | [添加平台适配器](/developer-guide/adding-platform-adapters) |
- | **记忆后端**(Honcho/Mem0/Supermemory 等) | [记忆提供商插件](/developer-guide/memory-provider-plugin) |
- | **上下文压缩引擎** | [上下文引擎插件](/developer-guide/context-engine-plugin) |
- | **图像生成后端** | [图像生成提供商插件](/developer-guide/image-gen-provider-plugin) |
- | **视频生成后端** | [视频生成提供商插件](/developer-guide/video-gen-provider-plugin) |
- | **网页搜索/提取后端** | [网页搜索提供商插件](/developer-guide/web-search-provider-plugin) |
+ | **LLM / 推理后端**(新提供商) | [模型提供商插件](../model-provider-plugin.md) |
+ | **网关频道**(Discord/Telegram/IRC/Teams 等) | [添加平台适配器](../adding-platform-adapters.md) |
+ | **记忆后端**(Honcho/Mem0/Supermemory 等) | [记忆提供商插件](../memory-provider-plugin.md) |
+ | **上下文压缩引擎** | [上下文引擎插件](../context-engine-plugin.md) |
+ | **图像生成后端** | [图像生成提供商插件](../image-gen-provider-plugin.md) |
+ | **视频生成后端** | [视频生成提供商插件](../video-gen-provider-plugin.md) |
+ | **网页搜索/提取后端** | [网页搜索提供商插件](../web-search-provider-plugin.md) |
-| **云浏览器后端**(Browserbase 类 CDP 会话提供商) | [浏览器提供商插件](../browser-provider-plugin.md) |
-| **密钥管理器后端**(保险库 / 密码管理器 / 系统钥匙串) | [密钥源插件](../secret-source-plugin.md) |
-| **仪表盘 OIDC/认证提供商** | [Web 仪表盘 — 自定义提供商](../../user-guide/features/web-dashboard.md#custom-providers) — `ctx.register_dashboard_auth_provider()` |
-| **TTS 后端**(任意 CLI——Piper、VoxCPM、Kokoro、声音克隆等) | [TTS 自定义命令提供商](../../user-guide/features/tts.md#custom-command-providers)——配置驱动,无需 Python |
-| **STT 后端**(自定义 whisper / ASR CLI) | [语音消息转录](../../user-guide/features/tts.md#voice-message-transcription-stt)——将 `HERMES_LOCAL_STT_COMMAND` 设置为 shell 模板 |
+| **云浏览器后端**(Browserbase 类 CDP 会话提供商) | [浏览器提供商插件](/developer-guide/browser-provider-plugin) |
+| **密钥管理器后端**(保险库 / 密码管理器 / 系统钥匙串) | [密钥源插件](/developer-guide/secret-source-plugin) |
+| **仪表盘 OIDC/认证提供商** | [Web 仪表盘 — 自定义提供商](https://hermes-agent.nousresearch.com/docs/user-guide/features/web-dashboard#custom-providers) — `ctx.register_dashboard_auth_provider()` |
- | **TTS 后端**(任意 CLI——Piper、VoxCPM、Kokoro、声音克隆等) | [TTS 自定义命令提供商](/user-guide/features/tts#自定义命令提供商)——配置驱动,无需 Python |
- | **STT 后端**(自定义 whisper / ASR CLI) | [语音消息转录](/user-guide/features/tts#语音消息转录stt)——将 `HERMES_LOCAL_STT_COMMAND` 设置为 shell 模板 |
- | **通过 MCP 接入外部工具**(文件系统、GitHub、Linear、任意 MCP 服务器) | [MCP](/user-guide/features/mcp)——在 `config.yaml` 中声明 `mcp_servers.<name>` |
- | **网关事件钩子**(在启动、会话事件、命令时触发) | [事件钩子](/user-guide/features/hooks#gateway-event-hooks)——将 `HOOK.yaml` + `handler.py` 放入 `~/.hermes/hooks/<name>/` |
- | **Shell 钩子**(在事件发生时运行 shell 命令) | [Shell 钩子](/user-guide/features/hooks#shell-hooks)——在 `config.yaml` 的 `hooks:` 下声明 |
- | **额外技能来源**(自定义 GitHub 仓库、私有技能索引) | [技能](/user-guide/features/skills)——`hermes skills tap add <repo>` · [发布 tap](/user-guide/features/skills#发布自定义-skill-tap) |
- | 一流的**核心**推理提供商(非插件) | [添加提供商](/developer-guide/adding-providers) |
-
- 查看完整的[可插拔接口表](/user-guide/features/plugins#可插拔接口--各场景对应文档),获取每种扩展接口的汇总视图,包括配置驱动(TTS、STT、MCP、shell 钩子)和放入目录(网关钩子)两种方式。
++| **TTS 后端**(任意 CLI——Piper、VoxCPM、Kokoro、声音克隆等) | [TTS 自定义命令提供商](../../user-guide/features/tts.md#自定义命令提供商)——配置驱动,无需 Python |
++| **STT 后端**(自定义 whisper / ASR CLI) | [语音消息转录](../../user-guide/features/tts.md#语音消息转录stt)——将 `HERMES_LOCAL_STT_COMMAND` 设置为 shell 模板 |
+ | **通过 MCP 接入外部工具**(文件系统、GitHub、Linear、任意 MCP 服务器) | [MCP](../../user-guide/features/mcp.md)——在 `config.yaml` 中声明 `mcp_servers.<name>` |
+ | **网关事件钩子**(在启动、会话事件、命令时触发) | [事件钩子](../../user-guide/features/hooks.md#gateway-event-hooks)——将 `HOOK.yaml` + `handler.py` 放入 `~/.hermes/hooks/<name>/` |
+ | **Shell 钩子**(在事件发生时运行 shell 命令) | [Shell 钩子](../../user-guide/features/hooks.md#shell-hooks)——在 `config.yaml` 的 `hooks:` 下声明 |
-| **额外技能来源**(自定义 GitHub 仓库、私有技能索引) | [技能](../../user-guide/features/skills.md)——`hermes skills tap add <repo>` · [发布 tap](../../user-guide/features/skills.md#publishing-a-custom-skill-tap) |
++| **额外技能来源**(自定义 GitHub 仓库、私有技能索引) | [技能](../../user-guide/features/skills.md)——`hermes skills tap add <repo>` · [发布 tap](../../user-guide/features/skills.md#发布自定义-skill-tap) |
+ | 一流的**核心**推理提供商(非插件) | [添加提供商](../adding-providers.md) |
+
-查看完整的[可插拔接口表](../../user-guide/features/plugins.md#pluggable-interfaces--where-to-go-for-each),获取每种扩展接口的汇总视图,包括配置驱动(TTS、STT、MCP、shell 钩子)和放入目录(网关钩子)两种方式。
++查看完整的[可插拔接口表](../../user-guide/features/plugins.md#可插拔接口--各场景对应文档),获取每种扩展接口的汇总视图,包括配置驱动(TTS、STT、MCP、shell 钩子)和放入目录(网关钩子)两种方式。
:::
## 你将构建什么
@@@ -537,14 -531,14 +537,14 @@@ def register(ctx)
| 钩子 | 触发时机 | 回调签名 | 返回值 |
|------|-----------|-------------------|---------|
- | [`pre_tool_call`](/user-guide/features/hooks#pre_tool_call) | 任意工具执行前 | `tool_name: str, args: dict, task_id: str` | 忽略 |
- | [`post_tool_call`](/user-guide/features/hooks#post_tool_call) | 任意工具返回后 | `tool_name: str, args: dict, result: str, task_id: str, duration_ms: int` | 忽略 |
- | [`pre_llm_call`](/user-guide/features/hooks#pre_llm_call) | 每轮一次,工具调用循环前 | `session_id: str, user_message: str, conversation_history: list, is_first_turn: bool, model: str, platform: str` | [上下文注入](#pre_llm_call-上下文注入) |
- | [`post_llm_call`](/user-guide/features/hooks#post_llm_call) | 每轮一次,工具调用循环后(仅成功轮次) | `session_id: str, user_message: str, assistant_response: str, conversation_history: list, model: str, platform: str` | 忽略 |
- | [`on_session_start`](/user-guide/features/hooks#on_session_start) | 新会话创建(仅第一轮) | `session_id: str, model: str, platform: str` | 忽略 |
- | [`on_session_end`](/user-guide/features/hooks#on_session_end) | 每次 `run_conversation` 调用结束 + CLI 退出 | `session_id: str, completed: bool, interrupted: bool, model: str, platform: str` | 忽略 |
- | [`on_session_finalize`](/user-guide/features/hooks#on_session_finalize) | CLI/网关销毁活跃会话 | `session_id: str \| None, platform: str` | 忽略 |
- | [`on_session_reset`](/user-guide/features/hooks#on_session_reset) | 网关切换新会话键(`/new`、`/reset`) | `session_id: str, platform: str` | 忽略 |
+ | [`pre_tool_call`](../../user-guide/features/hooks.md#pre_tool_call) | 任意工具执行前 | `tool_name: str, args: dict, task_id: str` | 忽略 |
+ | [`post_tool_call`](../../user-guide/features/hooks.md#post_tool_call) | 任意工具返回后 | `tool_name: str, args: dict, result: str, task_id: str, duration_ms: int` | 忽略 |
-| [`pre_llm_call`](../../user-guide/features/hooks.md#pre_llm_call) | 每轮一次,工具调用循环前 | `session_id: str, user_message: str, conversation_history: list, is_first_turn: bool, model: str, platform: str` | [上下文注入](#pre_llm_call-context-injection) |
++| [`pre_llm_call`](../../user-guide/features/hooks.md#pre_llm_call) | 每轮一次,工具调用循环前 | `session_id: str, user_message: str, conversation_history: list, is_first_turn: bool, model: str, platform: str` | [上下文注入](#pre_llm_call-上下文注入) |
+ | [`post_llm_call`](../../user-guide/features/hooks.md#post_llm_call) | 每轮一次,工具调用循环后(仅成功轮次) | `session_id: str, user_message: str, assistant_response: str, conversation_history: list, model: str, platform: str` | 忽略 |
+ | [`on_session_start`](../../user-guide/features/hooks.md#on_session_start) | 新会话创建(仅第一轮) | `session_id: str, model: str, platform: str` | 忽略 |
+ | [`on_session_end`](../../user-guide/features/hooks.md#on_session_end) | 每次 `run_conversation` 调用结束 + CLI 退出 | `session_id: str, completed: bool, interrupted: bool, model: str, platform: str` | 忽略 |
+ | [`on_session_finalize`](../../user-guide/features/hooks.md#on_session_finalize) | CLI/网关销毁活跃会话 | `session_id: str \| None, platform: str` | 忽略 |
+ | [`on_session_reset`](../../user-guide/features/hooks.md#on_session_reset) | 网关切换新会话键(`/new`、`/reset`) | `session_id: str, platform: str` | 忽略 |
大多数钩子是即发即忘的观察者——其返回值被忽略。例外是 `pre_llm_call`,它可以向对话中注入上下文。
@@@ -681,7 -675,7 +681,7 @@@ def register(ctx)
注册后,用户可以运行 `hermes my-plugin status`、`hermes my-plugin config` 等命令。
- **记忆提供商插件**使用基于约定的方式:在插件的 `cli.py` 文件中添加 `register_cli(subparser)` 函数。记忆插件发现系统会自动找到它——无需调用 `ctx.register_cli_command()`。详见[记忆提供商插件指南](/developer-guide/memory-provider-plugin#添加-cli-命令)。
-**记忆提供商插件**使用基于约定的方式:在插件的 `cli.py` 文件中添加 `register_cli(subparser)` 函数。记忆插件发现系统会自动找到它——无需调用 `ctx.register_cli_command()`。详见[记忆提供商插件指南](../memory-provider-plugin.md#adding-cli-commands)。
++**记忆提供商插件**使用基于约定的方式:在插件的 `cli.py` 文件中添加 `register_cli(subparser)` 函数。记忆插件发现系统会自动找到它——无需调用 `ctx.register_cli_command()`。详见[记忆提供商插件指南](../memory-provider-plugin.md#添加-cli-命令)。
**活跃提供商限制:** 记忆插件 CLI 命令仅在其提供商是配置中活跃的 `memory.provider` 时才会出现。如果用户尚未设置你的提供商,你的 CLI 命令不会出现在帮助输出中。
@@@ -966,7 -960,7 +966,7 @@@ description: Custom image generation ba
## 非 Python 扩展接口
- Hermes 也接受完全不是 Python 插件的扩展。这些在[可插拔接口表](/user-guide/features/plugins#可插拔接口--各场景对应文档)中有所展示;以下各节简要介绍每种编写方式。
-Hermes 也接受完全不是 Python 插件的扩展。这些在[可插拔接口表](../../user-guide/features/plugins.md#pluggable-interfaces--where-to-go-for-each)中有所展示;以下各节简要介绍每种编写方式。
++Hermes 也接受完全不是 Python 插件的扩展。这些在[可插拔接口表](../../user-guide/features/plugins.md#可插拔接口--各场景对应文档)中有所展示;以下各节简要介绍每种编写方式。
### MCP 服务器——注册外部工具
@@@ -1039,7 -1033,7 +1039,7 @@@ hermes skills install myorg/skills-repo
发布你自己的 tap 只需一个包含 `skills/<skill-name>/SKILL.md` 目录的 GitHub 仓库——无需服务器或注册表注册。
- **完整指南:** [技能中心](/user-guide/features/skills#skills-hub) · [发布自定义 tap](/user-guide/features/skills#发布自定义-skill-tap)(仓库结构、最小示例、非默认路径、信任级别)。
-**完整指南:** [技能中心](../../user-guide/features/skills.md#skills-hub) · [发布自定义 tap](../../user-guide/features/skills.md#publishing-a-custom-skill-tap)(仓库结构、最小示例、非默认路径、信任级别)。
++**完整指南:** [技能中心](../../user-guide/features/skills.md#skills-hub) · [发布自定义 tap](../../user-guide/features/skills.md#发布自定义-skill-tap)(仓库结构、最小示例、非默认路径、信任级别)。
### 通过命令模板接入 TTS / STT
@@@ -1058,7 -1052,7 +1058,7 @@@ tts
对于 STT,将 `HERMES_LOCAL_STT_COMMAND` 指向一个 shell 模板。支持的占位符:`{input_path}`、`{output_path}`、`{format}`、`{voice}`、`{model}`、`{speed}`(TTS);`{input_path}`、`{output_dir}`、`{language}`、`{model}`(STT)。任何与路径交互的 CLI 都自动成为插件。
- **完整指南:** [TTS 自定义命令提供商](/user-guide/features/tts#自定义命令提供商) · [STT](/user-guide/features/tts#语音消息转录stt)。
-**完整指南:** [TTS 自定义命令提供商](../../user-guide/features/tts.md#custom-command-providers) · [STT](../../user-guide/features/tts.md#voice-message-transcription-stt)。
++**完整指南:** [TTS 自定义命令提供商](../../user-guide/features/tts.md#自定义命令提供商) · [STT](../../user-guide/features/tts.md#语音消息转录stt)。
## 通过 pip 分发
@@@ -1111,7 -1104,7 +1111,7 @@@ services.hermes-agent.extraPlugins =
];
```
- 完整文档(包括 overlay 用法和冲突检查)见 [Nix 设置指南](/getting-started/nix-setup#插件)。
-完整文档(包括 overlay 用法和冲突检查)见 [Nix 设置指南](../../getting-started/nix-setup.md#plugins)。
++完整文档(包括 overlay 用法和冲突检查)见 [Nix 设置指南](../../getting-started/nix-setup.md#插件)。
## 常见错误
diff --cc website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/web-search-provider-plugin.md
index 98a62751be9,af0c527a0d2..807a0eff5cf
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/web-search-provider-plugin.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/web-search-provider-plugin.md
@@@ -141,7 -141,7 +141,7 @@@ requires_env
|---|---|
| `kind: backend` | 将插件路由至后端加载路径 |
| `provides_web_providers` | 该插件注册的提供商 `name` 列表——在 `register()` 运行之前,加载器即可通过此字段在 `hermes tools` 中公示插件 |
- | `requires_env` | 在 `hermes plugins install` 期间进行交互式凭据提示(富格式说明参见[构建 Hermes 插件](/developer-guide/plugins#根据环境变量决定是否启用)) |
-| `requires_env` | 在 `hermes plugins install` 期间进行交互式凭据提示(富格式说明参见[构建 Hermes 插件](./plugins/index.md#gate-on-environment-variables)) |
++| `requires_env` | 在 `hermes plugins install` 期间进行交互式凭据提示(富格式说明参见[构建 Hermes 插件](./plugins/index.md#根据环境变量决定是否启用)) |
## ABC 参考
@@@ -233,11 -233,7 +233,11 @@@ web
## 懒加载可选依赖
-如果你的提供商封装了第三方 SDK(如 DDGS 封装了 `ddgs` 包),请勿在模块顶层 `import`。在 `is_available()` 或 `search()` 内部使用 `tools.lazy_deps.ensure(...)` ——Hermes 将在首次使用时安装该包,并受 `security.allow_lazy_installs` 控制。安全模型详见[构建 Hermes 插件 → 懒加载](./plugins/index.md#lazy-install-optional-python-dependencies)。
+对于 Hermes 已声明的 SDK extra,在 `search()` 或 `extract()` 的实际操作中调用
+`pm.ensure_import("extra-name")`。`is_available()` 必须保持只读,可使用 `pm.available`,
+不能通过它安装依赖。`pm.InstallError` 可以表示依赖不可用或新环境需要重启。
+第三方目录插件在自己的 `pyproject.toml` 或 `plugin.yaml` 中声明依赖,由 PM 统一准备。
- 详见[插件依赖指南](/developer-guide/plugins#lazy-install-optional-python-dependencies)。
++详见[插件依赖指南](./plugins/index.md#lazy-install-optional-python-dependencies)。
## 参考实现
@@@ -255,7 -251,7 +255,7 @@@
my-backend-web = "my_backend_web_package"
```
- `my_backend_web_package` 必须暴露顶层 `register` 函数。完整配置说明参见通用插件指南中的[通过 pip 分发](/developer-guide/plugins#通过-pip-分发)。
-`my_backend_web_package` 必须暴露顶层 `register` 函数。完整配置说明参见通用插件指南中的[通过 pip 分发](./plugins/index.md#distribute-via-pip)。
++`my_backend_web_package` 必须暴露顶层 `register` 函数。完整配置说明参见通用插件指南中的[通过 pip 分发](./plugins/index.md#通过-pip-分发)。
## 相关页面
diff --cc website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/use-voice-mode-with-hermes.md
index 7db376ff86f,e41ab8edcd9..35de72cf8de
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/use-voice-mode-with-hermes.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/use-voice-mode-with-hermes.md
@@@ -6,10 -6,7 +6,10 @@@ description: "在 CLI、Telegram、Disc
# 在 Hermes 中使用语音模式
+本页的 Python 依赖命令使用 [PM 准备的源码环境](/reference/package-management#developer-workflow)。
+依赖变更后,请重新激活该 checkout 并重启 Hermes。
+
- 本指南是[语音模式功能参考](/user-guide/features/voice-mode)的实用配套文档。
+ 本指南是[语音模式功能参考](../user-guide/features/voice-mode.md)的实用配套文档。
功能页面介绍语音模式能做什么,本指南则说明如何真正用好它。
diff --cc website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/index.mdx
index a7471c6d7d2,d4c0b43a4b5..325df05e0a2
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/index.mdx
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/index.mdx
@@@ -63,7 -63,9 +63,7 @@@ curl -fsSL https://hermes-agent.nousres
iex (irm https://hermes-agent.nousresearch.com/install.ps1)
```
- 请参阅完整的 **[安装指南](/getting-started/installation)**,了解安装程序的具体操作、按用户与 root 的目录布局以及 Windows 相关说明。
-**Android(Termux)** — 与 Linux 相同的 curl 一行命令;安装程序会自动检测 Termux。
-
+ 请参阅完整的 **[安装指南](./getting-started/installation.md)**,了解安装程序的具体操作、按用户与 root 的目录布局以及 Windows 相关说明。
## Hermes Agent 是什么?
diff --cc website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/cli-commands.md
index fdfc27ed7dd,bb8cd5319aa..c0c615a276a
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/cli-commands.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/cli-commands.md
@@@ -230,7 -227,7 +230,7 @@@ hermes gateway <subcommand
| `--no-supervise` | 在 `run` 时:在 s6-overlay Docker 镜像内部,跳过 s6 自动监管,退回到 pre-s6 前台语义——gateway 作为容器主进程运行,无自动重启。在 s6 镜像之外为空操作。等同于设置 `HERMES_GATEWAY_NO_SUPERVISE=1`。 |
:::tip WSL 用户
- 使用 `hermes gateway run` 而非 `hermes gateway start`——WSL 的 systemd 支持不稳定。用 tmux 包裹以保持持久运行:`tmux new -s hermes 'hermes gateway run'`。详见 [WSL FAQ](/reference/faq#wsl网关持续断开连接或-hermes-gateway-start-失败)。
-使用 `hermes gateway run` 而非 `hermes gateway start`——WSL 的 systemd 支持不稳定。用 tmux 包裹以保持持久运行:`tmux new -s hermes 'hermes gateway run'`。详见 [WSL FAQ](./faq.md#wsl-gateway-keeps-disconnecting-or-hermes-gateway-start-fails)。
++使用 `hermes gateway run` 而非 `hermes gateway start`——WSL 的 systemd 支持不稳定。用 tmux 包裹以保持持久运行:`tmux new -s hermes 'hermes gateway run'`。详见 [WSL FAQ](./faq.md#wsl网关持续断开连接或-hermes-gateway-start-失败)。
:::
## `hermes lsp`
@@@ -1148,7 -1145,7 +1148,7 @@@ hermes claw migrate --source /home/user
hermes dashboard [options]
```
- 启动 Web 控制台,用于管理配置、API 密钥和会话。FastAPI、Uvicorn 和平台 PTY 辅助库是核心依赖。`web` extra 提供 HTTP 栈的精确约束,标准 PM 安装通过 `all` 选择它。如依赖损坏,请运行 `hermes pm repair`。内嵌 Chat 标签页需要 POSIX PTY 环境,例如 Linux、macOS 或 WSL2。请参阅 [Web 控制台](/user-guide/features/web-dashboard)。
-启动 Web 控制台——基于浏览器的界面,用于管理配置、API 密钥和监控会话。需要 `cd ~/.hermes/hermes-agent && uv pip install -e ".[web]"`(FastAPI + Uvicorn)。内嵌浏览器 Chat 标签页始终可用,但额外需要 `pty` extra(`cd ~/.hermes/hermes-agent && uv pip install -e ".[web,pty]"`)以及 POSIX PTY 环境(如 Linux、macOS 或 WSL2)。完整文档请参阅 [Web 控制台](../user-guide/features/web-dashboard.md)。
++启动 Web 控制台,用于管理配置、API 密钥和会话。FastAPI、Uvicorn 和平台 PTY 辅助库是核心依赖。`web` extra 提供 HTTP 栈的精确约束,标准 PM 安装通过 `all` 选择它。如依赖损坏,请运行 `hermes pm repair`。内嵌 Chat 标签页需要 POSIX PTY 环境,例如 Linux、macOS 或 WSL2。请参阅 [Web 控制台](../user-guide/features/web-dashboard.md)。
| 选项 | 默认值 | 说明 |
|--------|---------|-------------|
diff --cc website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.md
index f6d24ae34a5,ead51dbf032..886f525cc1e
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.md
@@@ -58,7 -58,7 +58,7 @@@ description: "Hermes Agent 使用的所
| `AZURE_CLIENT_SECRET` | `EnvironmentCredential` 使用的服务主体密钥 |
| `AZURE_CLIENT_CERTIFICATE_PATH` | 服务主体证书(`AZURE_CLIENT_SECRET` 的替代方案) |
| `AZURE_FEDERATED_TOKEN_FILE` | AKS Workload Identity / OIDC 流程的联合 token 文件路径 |
- | `AZURE_AUTHORITY_HOST` | 主权云 authority 覆盖(例如 Azure Government 使用 `https://login.microsoftonline.us`)。参见 [Azure Foundry 指南](/guides/azure-foundry#主权云政府云中国云) |
-| `AZURE_AUTHORITY_HOST` | 主权云 authority 覆盖(例如 Azure Government 使用 `https://login.microsoftonline.us`)。参见 [Azure Foundry 指南](../guides/azure-foundry.md#sovereign-clouds-government-china) |
++| `AZURE_AUTHORITY_HOST` | 主权云 authority 覆盖(例如 Azure Government 使用 `https://login.microsoftonline.us`)。参见 [Azure Foundry 指南](../guides/azure-foundry.md#主权云政府云中国云) |
| `IDENTITY_ENDPOINT` / `MSI_ENDPOINT` | App Service、Functions 和 Container Apps 的托管标识端点;VM 通常使用 IMDS 而不设置这些变量 |
| `HF_TOKEN` | Hugging Face Inference Providers token([huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)) |
| `HF_BASE_URL` | 覆盖 Hugging Face base URL(默认:`https://router.huggingface.co/v1`) |
@@@ -414,7 -415,7 +414,7 @@@
| `API_SERVER_PORT` | API 服务器端口(默认:`8642`) |
| `API_SERVER_HOST` | API 服务器主机/绑定地址(默认:`127.0.0.1`)。使用 `0.0.0.0` 开放网络访问——需要 `API_SERVER_KEY` 和严格的 `API_SERVER_CORS_ORIGINS` 白名单。 |
| `API_SERVER_MODEL_NAME` | `/v1/models` 上公告的模型名称。默认为 profile 名称(默认 profile 为 `hermes-agent`)。适用于 Open WebUI 等前端需要每个连接使用不同模型名称的多用户场景。 |
- | `GATEWAY_PROXY_URL` | 将消息转发到的远程 Hermes API 服务器 URL([代理模式](/user-guide/messaging/matrix#代理模式macos-上的-e2ee))。设置后,gateway 仅处理平台 I/O——所有 agent 工作委托给远程服务器。也可通过 `config.yaml` 中的 `gateway.proxy_url` 配置。 |
-| `GATEWAY_PROXY_URL` | 将消息转发到的远程 Hermes API 服务器 URL([代理模式](../user-guide/messaging/matrix.md#proxy-mode-e2ee-on-macos))。设置后,gateway 仅处理平台 I/O——所有 agent 工作委托给远程服务器。也可通过 `config.yaml` 中的 `gateway.proxy_url` 配置。 |
++| `GATEWAY_PROXY_URL` | 将消息转发到的远程 Hermes API 服务器 URL([代理模式](../user-guide/messaging/matrix.md#代理模式macos-上的-e2ee))。设置后,gateway 仅处理平台 I/O——所有 agent 工作委托给远程服务器。也可通过 `config.yaml` 中的 `gateway.proxy_url` 配置。 |
| `GATEWAY_PROXY_KEY` | 代理模式下与远程 API 服务器认证的 Bearer token。必须与远程主机上的 `API_SERVER_KEY` 一致。 |
| `MESSAGING_CWD` | 消息模式下终端命令的工作目录(默认:`~`) |
| `GATEWAY_ALLOWED_USERS` | 跨所有平台允许的逗号分隔用户 ID |
@@@ -446,7 -447,7 +446,7 @@@ Graph 事件(Teams 会议、日历、
### Teams 会议摘要投递
- 仅在启用 [`teams_pipeline` 插件](/user-guide/messaging/msgraph-webhook)时使用。设置也可在 `config.yaml` 的 `platforms.teams.extra` 下配置——两者都设置时环境变量优先。参见 [Microsoft Teams → 会议摘要投递](/user-guide/messaging/teams#会议摘要投递teams-会议-pipeline)。
-仅在启用 [`teams_pipeline` 插件](../user-guide/messaging/msgraph-webhook.md)时使用。设置也可在 `config.yaml` 的 `platforms.teams.extra` 下配置——两者都设置时环境变量优先。参见 [Microsoft Teams → 会议摘要投递](../user-guide/messaging/teams.md#meeting-summary-delivery-teams-meeting-pipeline)。
++仅在启用 [`teams_pipeline` 插件](../user-guide/messaging/msgraph-webhook.md)时使用。设置也可在 `config.yaml` 的 `platforms.teams.extra` 下配置——两者都设置时环境变量优先。参见 [Microsoft Teams → 会议摘要投递](../user-guide/messaging/teams.md#会议摘要投递teams-会议-pipeline)。
| 变量 | 描述 |
|----------|-------------|
diff --cc website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/docker.md
index 2a8f65229d6,3e8fc8c011c..df3aeec6ef8
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/docker.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/docker.md
@@@ -270,36 -258,38 +270,37 @@@ docker run -d
nousresearch/hermes-agent gateway run
```
-## Dockerfile 说明
-
-官方镜像基于 `debian:13.4`,包含:
-
-- Python 3 及所有 Hermes 依赖(`uv pip install -e ".[all]"`)
-- Node.js + npm(用于浏览器自动化和 WhatsApp 桥接)
-- Playwright 与 Chromium(`npx playwright install --with-deps chromium --only-shell`)
-- ripgrep、ffmpeg、git 和 `xz-utils` 作为系统工具
-- **`docker-cli`** — 使容器内运行的 agent 可以驱动宿主机的 Docker 守护进程(绑定挂载 `/var/run/docker.sock` 以启用),用于 `docker build`、`docker run`、容器检查等操作
-- **`openssh-client`** — 从容器内启用 [SSH 终端后端](./configuration.md#ssh-backend)。SSH 后端调用系统 `ssh` 二进制文件;若缺少此组件,在容器化安装中会静默失败
-- WhatsApp 桥接(`scripts/whatsapp-bridge/`)
-- **[`s6-overlay`](https://github.com/just-containers/s6-overlay) v3** 作为 PID 1(替代旧版 `tini`)——监管 dashboard 和各 profile gateway,崩溃后自动重启,回收僵尸子进程,并转发信号
-
-容器的 `ENTRYPOINT` 是 s6-overlay 的 `/init`。启动时:
-1. 以 root 身份运行 `/etc/cont-init.d/01-hermes-setup`(即 `docker/stage2-hook.sh`):可选的 UID/GID 重映射、修复卷所有权、首次启动时初始化 `.env` / `config.yaml` / `SOUL.md`、同步内置技能。
-2. 运行 `/etc/cont-init.d/02-reconcile-profiles`(即 `hermes_cli.container_boot`):遍历 `$HERMES_HOME/profiles/<name>/`,在 `/run/service/gateway-<profile>/` 下重建各 profile 的 gateway s6 服务槽,并仅自动启动上次记录状态为 `running` 的 profile(参见 [Per-profile gateway 监管](#per-profile-gateway-supervision))。
-3. 启动静态的 `main-hermes` 和 `dashboard` s6-rc 服务。
-4. 将容器的 CMD 作为主程序 exec(`/opt/hermes/docker/main-wrapper.sh`),根据用户传给 `docker run` 的参数进行路由:
- - 无参数 → `hermes`(默认)
- - 第一个参数是 PATH 上的可执行文件(如 `sleep`、`bash`)→ 直接 exec
- - 其他情况 → `hermes <args>`(子命令透传)
- 主程序退出时容器退出,并使用其退出码。
-
-:::warning 与 pre-s6 镜像的破坏性变更
-容器 ENTRYPOINT 现在是 `/init`(s6-overlay),而非 `/usr/bin/tini`。所有五种已记录的 `docker run` 调用模式(无参数、`chat -q "…"`、`sleep infinity`、`bash`、`--tui`)的行为与基于 tini 的镜像完全相同。如果你有依赖 tini 特定信号行为或硬编码 `/usr/bin/tini --` 调用的下游封装,请固定到之前的镜像标签。
-:::
+## Dockerfile 说明 {#what-the-dockerfile-does}
-:::warning 权限模型
-除非你在命令链中保留 `/init`(或等效的旧版 `docker/entrypoint.sh` shim,它会转发到 stage2 hook),否则不要覆盖镜像入口点。s6-overlay 的 `/init` 以 root 运行,以便在首次启动时对卷执行 chown,然后通过 `s6-setuidgid` 为每个受监管的服务**以及**主程序降权至 `hermes` 用户。在官方镜像内以 root 启动 `hermes gateway run` 默认会被拒绝,因为这可能在 `/opt/data` 中留下 root 所有的文件,导致后续 dashboard 或 gateway 启动失败。仅在你有意接受该风险时才设置 `HERMES_ALLOW_ROOT_GATEWAY=1`。
-:::
+官方镜像基于 Debian 13.4,包含:
+
++
+- 按提交的 `uv.lock` 同步的 Python 3.14 环境,然后无依赖地安装 Hermes 源码。
+- 选定的 extras:`all`、`messaging`、`otlp`、`anthropic`、`bedrock`、`azure-identity`、`hindsight` 和 `matrix`,不是 `--all-extras`。
+- 从摘要固定的 Node 镜像提供的 Node.js 26 和 npm。
+- PM 固定版本的 uv、Chromium 和 headless shell,位于 `/opt/hermes/tools`。
+- 系统 Git、ripgrep、FFmpeg、OpenSSH、Docker CLI 和 Chromium 所需共享库。
+- 预构建的 TUI/dashboard 和 Photon sidecar 依赖,以及 s6-overlay。
+
+Chromium 由 PM 准备,不使用 `npx playwright install`。
+实际可执行路径记录在 `/etc/hermes/agent-browser-executable-path`。
+`PLAYWRIGHT_BROWSERS_PATH` 指向 `/opt/hermes/tools`,不在数据卷内。
+
+镜像通过内部 `HERMES_DISABLE_LAZY_INSTALLS` 策略关闭按需安装。
+仅修改 `security.allow_lazy_installs` 不能覆盖它。新增所需依赖应烘焙进派生镜像,
+或作为独立工具放在单独环境或服务中。旧 `lazy-packages` overlay 不再使用。
+
+构建来源记录在 `/etc/hermes/image-provenance.json`,构建戳记位于 `/opt/hermes/install-stamp.json`。
+没有戳记的本地构建报告未知版本,不猜测提交。`hermes update` 不修改镜像所有的代码,应用更新需替换镜像。
+
+入口点是 `docker/entrypoint-dispatch.sh`。正常 Docker/Podman 中它占有 PID 1,转交给 s6 的 `/init`。
+若平台已有 PID-1 init,则直接运行 stage2 和主包装器;命令仍可运行,但没有 s6 监管的 dashboard 或各 profile gateway。
+
+PID-1 路径先准备数据卷和配置,重建各 profile 的 gateway 服务槽,然后运行主命令。
+不要绕过这些入口步骤,否则会失去权限处理和服务监管。
+主程序及受监管服务以 `hermes` 用户运行,避免在 `/opt/data` 中留下 root 所有的文件。
-### Per-profile gateway 监管
+### Per-profile gateway 监管 {#per-profile-gateway-supervision}
在容器内,每个通过 `hermes profile create <name>` 创建的 profile 都会自动在 `/run/service/gateway-<name>/` 注册一个受 s6 监管的 gateway 服务。你在宿主机上运行的生命周期命令在此同样适用:
diff --cc website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/plugins.md
index b71ac4476ea,8f15ef9bdd1..0c04734f93d
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/plugins.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/plugins.md
@@@ -122,7 -122,7 +122,7 @@@ def register(ctx)
| 用户 | `~/.hermes/plugins/` | 个人插件 |
| 项目 | `.hermes/plugins/` | 项目专属插件(需要 `HERMES_ENABLE_PROJECT_PLUGINS=true`) |
| pip | `hermes_agent.plugins` entry_points | 分发包 |
- | Nix | `services.hermes-agent.extraPlugins` / `extraPythonPackages` | NixOS 声明式安装 — 参见 [Nix Setup](/getting-started/nix-setup#插件) |
-| Nix | `services.hermes-agent.extraPlugins` / `extraPythonPackages` | NixOS 声明式安装 — 参见 [Nix Setup](../../getting-started/nix-setup.md#plugins) |
++| Nix | `services.hermes-agent.extraPlugins` / `extraPythonPackages` | NixOS 声明式安装 — 参见 [Nix Setup](../../getting-started/nix-setup.md#插件) |
名称冲突时,后面的来源会覆盖前面的,因此与内置插件同名的用户插件会替换它。
@@@ -217,23 -217,23 +217,23 @@@ Memory provider 和 context engine 是
| 想要添加… | 方式 | 编写指南 |
|---|---|---|
- | LLM 可调用的**工具** | Python 插件 — `ctx.register_tool()` | [Build a Hermes Plugin](/developer-guide/plugins) · [Adding Tools](/developer-guide/adding-tools) |
- | **生命周期 hook**(LLM 前后、会话开始/结束、工具过滤) | Python 插件 — `ctx.register_hook()` | [Hooks reference](/user-guide/features/hooks) · [Build a Hermes Plugin](/developer-guide/plugins) |
- | CLI / gateway 的**斜杠命令** | Python 插件 — `ctx.register_command()` | [Build a Hermes Plugin](/developer-guide/plugins) · [Extending the CLI](/developer-guide/extending-the-cli) |
- | `hermes <thing>` 的**子命令** | Python 插件 — `ctx.register_cli_command()` | [Extending the CLI](/developer-guide/extending-the-cli) |
- | 插件附带的**skill** | Python 插件 — `ctx.register_skill()` | [Creating Skills](/developer-guide/creating-skills) |
- | **推理后端**(LLM provider:OpenAI 兼容、Codex、Anthropic-Messages、Bedrock) | Provider 插件 — 在 `plugins/model-providers/<name>/` 中调用 `register_provider(ProviderProfile(...))` | **[Model Provider Plugins](/developer-guide/model-provider-plugin)** · [Adding Providers](/developer-guide/adding-providers) |
- | **Gateway 频道**(Discord / Telegram / IRC / Teams 等) | 平台插件 — 在 `plugins/platforms/<name>/` 中调用 `ctx.register_platform()` | [Adding Platform Adapters](/developer-guide/adding-platform-adapters) |
- | **Memory 后端**(Honcho、Mem0、Supermemory 等) | Memory 插件 — 在 `plugins/memory/<name>/` 中继承 `MemoryProvider` | [Memory Provider Plugins](/developer-guide/memory-provider-plugin) |
- | **上下文压缩策略** | Context-engine 插件 — `ctx.register_context_engine()` | [Context Engine Plugins](/developer-guide/context-engine-plugin) |
- | **图像生成后端**(DALL·E、SDXL 等) | 后端插件 — `ctx.register_image_gen_provider()` | [Image Generation Provider Plugins](/developer-guide/image-gen-provider-plugin) |
- | **视频生成后端**(Veo、Kling、Pixverse、Grok-Imagine、Runway 等) | 后端插件 — `ctx.register_video_gen_provider()` | [Video Generation Provider Plugins](/developer-guide/video-gen-provider-plugin) |
- | **TTS 后端**(任意 CLI — Piper、VoxCPM、Kokoro、xtts、语音克隆脚本等) | 配置驱动(推荐)— 在 `config.yaml` 的 `tts.providers.<name>` 下以 `type: command` 声明。或 Python 后端插件 — 对需要超出 shell 模板的 Python SDK / 流式引擎使用 `ctx.register_tts_provider()`。 | [TTS Setup](/user-guide/features/tts#自定义命令提供商) · [Python plugin guide](/user-guide/features/tts#python-插件提供商) |
- | **STT 后端**(自定义 whisper 二进制、本地 ASR CLI) | 配置驱动 — 将 `HERMES_LOCAL_STT_COMMAND` 环境变量设置为 shell 模板 | [Voice Message Transcription (STT)](/user-guide/features/tts#语音消息转录stt) |
- | **通过 MCP 使用外部工具**(文件系统、GitHub、Linear、Notion、任意 MCP 服务器) | 配置驱动 — 在 `config.yaml` 中以 `command:` / `url:` 声明 `mcp_servers.<name>`。Hermes 自动发现服务器的工具并与内置工具一同注册。 | [MCP](/user-guide/features/mcp) |
- | **额外 skill 来源**(自定义 GitHub 仓库、私有 skill 索引) | CLI — `hermes skills tap add <repo>` | [Skills Hub](/user-guide/features/skills#skills-hub) · [发布自定义 tap](/user-guide/features/skills#发布自定义-skill-tap) |
- | **Gateway 事件 hook**(在 `gateway:startup`、`session:start`、`agent:end`、`command:*` 时触发) | 将 `HOOK.yaml` + `handler.py` 放入 `~/.hermes/hooks/<name>/` | [Event Hooks](/user-guide/features/hooks#gateway-event-hooks) |
- | **Shell hook**(在事件时运行 shell 命令 — 通知、审计日志、桌面提醒) | 配置驱动 — 在 `config.yaml` 的 `hooks:` 下声明 | [Shell Hooks](/user-guide/features/hooks#shell-hooks) |
+ | LLM 可调用的**工具** | Python 插件 — `ctx.register_tool()` | [Build a Hermes Plugin](../../developer-guide/plugins/index.md) · [Adding Tools](../../developer-guide/adding-tools.md) |
+ | **生命周期 hook**(LLM 前后、会话开始/结束、工具过滤) | Python 插件 — `ctx.register_hook()` | [Hooks reference](./hooks.md) · [Build a Hermes Plugin](../../developer-guide/plugins/index.md) |
+ | CLI / gateway 的**斜杠命令** | Python 插件 — `ctx.register_command()` | [Build a Hermes Plugin](../../developer-guide/plugins/index.md) · [Extending the CLI](../../developer-guide/extending-the-cli.md) |
+ | `hermes <thing>` 的**子命令** | Python 插件 — `ctx.register_cli_command()` | [Extending the CLI](../../developer-guide/extending-the-cli.md) |
+ | 插件附带的**skill** | Python 插件 — `ctx.register_skill()` | [Creating Skills](../../developer-guide/creating-skills.md) |
+ | **推理后端**(LLM provider:OpenAI 兼容、Codex、Anthropic-Messages、Bedrock) | Provider 插件 — 在 `plugins/model-providers/<name>/` 中调用 `register_provider(ProviderProfile(...))` | **[Model Provider Plugins](../../developer-guide/model-provider-plugin.md)** · [Adding Providers](../../developer-guide/adding-providers.md) |
+ | **Gateway 频道**(Discord / Telegram / IRC / Teams 等) | 平台插件 — 在 `plugins/platforms/<name>/` 中调用 `ctx.register_platform()` | [Adding Platform Adapters](../../developer-guide/adding-platform-adapters.md) |
+ | **Memory 后端**(Honcho、Mem0、Supermemory 等) | Memory 插件 — 在 `plugins/memory/<name>/` 中继承 `MemoryProvider` | [Memory Provider Plugins](../../developer-guide/memory-provider-plugin.md) |
+ | **上下文压缩策略** | Context-engine 插件 — `ctx.register_context_engine()` | [Context Engine Plugins](../../developer-guide/context-engine-plugin.md) |
+ | **图像生成后端**(DALL·E、SDXL 等) | 后端插件 — `ctx.register_image_gen_provider()` | [Image Generation Provider Plugins](../../developer-guide/image-gen-provider-plugin.md) |
+ | **视频生成后端**(Veo、Kling、Pixverse、Grok-Imagine、Runway 等) | 后端插件 — `ctx.register_video_gen_provider()` | [Video Generation Provider Plugins](../../developer-guide/video-gen-provider-plugin.md) |
-| **TTS 后端**(任意 CLI — Piper、VoxCPM、Kokoro、xtts、语音克隆脚本等) | 配置驱动(推荐)— 在 `config.yaml` 的 `tts.providers.<name>` 下以 `type: command` 声明。或 Python 后端插件 — 对需要超出 shell 模板的 Python SDK / 流式引擎使用 `ctx.register_tts_provider()`。 | [TTS Setup](./tts.md#custom-command-providers) · [Python plugin guide](./tts.md#python-plugin-providers) |
-| **STT 后端**(自定义 whisper 二进制、本地 ASR CLI) | 配置驱动 — 将 `HERMES_LOCAL_STT_COMMAND` 环境变量设置为 shell 模板 | [Voice Message Transcription (STT)](./tts.md#voice-message-transcription-stt) |
++| **TTS 后端**(任意 CLI — Piper、VoxCPM、Kokoro、xtts、语音克隆脚本等) | 配置驱动(推荐)— 在 `config.yaml` 的 `tts.providers.<name>` 下以 `type: command` 声明。或 Python 后端插件 — 对需要超出 shell 模板的 Python SDK / 流式引擎使用 `ctx.register_tts_provider()`。 | [TTS Setup](./tts.md#自定义命令提供商) · [Python plugin guide](./tts.md#python-插件提供商) |
++| **STT 后端**(自定义 whisper 二进制、本地 ASR CLI) | 配置驱动 — 将 `HERMES_LOCAL_STT_COMMAND` 环境变量设置为 shell 模板 | [Voice Message Transcription (STT)](./tts.md#语音消息转录stt) |
+ | **通过 MCP 使用外部工具**(文件系统、GitHub、Linear、Notion、任意 MCP 服务器) | 配置驱动 — 在 `config.yaml` 中以 `command:` / `url:` 声明 `mcp_servers.<name>`。Hermes 自动发现服务器的工具并与内置工具一同注册。 | [MCP](./mcp.md) |
-| **额外 skill 来源**(自定义 GitHub 仓库、私有 skill 索引) | CLI — `hermes skills tap add <repo>` | [Skills Hub](./skills.md#skills-hub) · [发布自定义 tap](./skills.md#publishing-a-custom-skill-tap) |
++| **额外 skill 来源**(自定义 GitHub 仓库、私有 skill 索引) | CLI — `hermes skills tap add <repo>` | [Skills Hub](./skills.md#skills-hub) · [发布自定义 tap](./skills.md#发布自定义-skill-tap) |
+ | **Gateway 事件 hook**(在 `gateway:startup`、`session:start`、`agent:end`、`command:*` 时触发) | 将 `HOOK.yaml` + `handler.py` 放入 `~/.hermes/hooks/<name>/` | [Event Hooks](./hooks.md#gateway-event-hooks) |
+ | **Shell hook**(在事件时运行 shell 命令 — 通知、审计日志、桌面提醒) | 配置驱动 — 在 `config.yaml` 的 `hooks:` 下声明 | [Shell Hooks](./hooks.md#shell-hooks) |
:::note
并非所有扩展都是 Python 插件。某些扩展接口有意使用**配置驱动的 shell 命令**(TTS、STT、shell hook),这样你已有的任意 CLI 无需编写 Python 即可成为插件。其他的是 agent 连接并自动注册工具的**外部服务器**(MCP)。还有一些是拥有自己 manifest 格式的**即插即用目录**(gateway hook)。根据你的集成风格选择合适的接口;上表中的编写指南各自涵盖了占位符、发现机制和示例。
@@@ -241,7 -241,7 +241,7 @@@
## NixOS 声明式插件
- 在 NixOS 上,插件可通过模块选项声明式安装 — 无需 `hermes plugins install`。完整详情请参见 **[Nix Setup 指南](/getting-started/nix-setup#插件)**。
-在 NixOS 上,插件可通过模块选项声明式安装 — 无需 `hermes plugins install`。完整详情请参见 **[Nix Setup 指南](../../getting-started/nix-setup.md#plugins)**。
++在 NixOS 上,插件可通过模块选项声明式安装 — 无需 `hermes plugins install`。完整详情请参见 **[Nix Setup 指南](../../getting-started/nix-setup.md#插件)**。
```nix
services.hermes-agent = {
diff --cc website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/security.md
index ac337d2e4b4,421d458db60..fd1795ab4f4
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/security.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/security.md
@@@ -495,7 -495,7 +495,7 @@@ security
当请求被阻止的 URL 时,工具会返回一条错误,说明该域名已被策略阻止。黑名单在 `web_search`、`web_extract`、`browser_navigate` 及所有支持 URL 的工具中均强制执行。
- 完整详情请参见配置指南中的[网站黑名单](/user-guide/configuration#网站黑名单)。
-完整详情请参见配置指南中的[网站黑名单](./configuration.md#website-blocklist)。
++完整详情请参见配置指南中的[网站黑名单](./configuration.md#网站黑名单)。
### SSRF 防护
diff --cc website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/windows-native.md
index 00696fefc34,d9474632a31..a520cc61683
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/windows-native.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/windows-native.md
@@@ -25,59 -25,61 +25,59 @@@ iex (irm https://hermes-agent.nousresea
无需管理员权限。安装程序会写入 `%LOCALAPPDATA%\hermes\`,并将 `hermes` 添加到你的**用户 PATH**——安装完成后打开新终端即可使用。
-**安装程序选项**(需要使用 scriptblock 形式传递参数):
+**安装程序选项:**
```powershell
-& ([scriptblock]::Create((irm https://hermes-agent.nousresearch.com/install.ps1))) -NoVenv -SkipSetup -Branch main
+& ([scriptblock]::Create((irm https://hermes-agent.nousresearch.com/install.ps1))) -NonInteractive -Branch main
```
-| 参数 | 默认值 | 用途 |
-| ------------- | ------------------------------------ | ----------------------------------------------- |
-| `-Branch` | `main` | 克隆指定分支(用于测试 PR) |
-| `-Commit` | 未设置 | 将安装固定到指定 commit SHA(覆盖 `-Branch`) |
-| `-Tag` | 未设置 | 将安装固定到指定 git tag(如 `v0.14.0`) |
-| `-NoVenv` | 关闭 | 跳过 venv 创建(高级用法——由你自行管理 Python) |
-| `-SkipSetup` | 关闭 | 跳过安装后的 `hermes setup` 向导 |
-| `-HermesHome` | `%LOCALAPPDATA%\hermes` | 覆盖数据目录 |
-| `-InstallDir` | `%LOCALAPPDATA%\hermes\hermes-agent` | 覆盖代码存放位置 |
-
-安装程序会自动重试不稳定的 git 拉取,并剥离下载的 `install.ps1` 内容中的 BOM,因此 HTTP 传输中携带的 UTF-8 BOM 不再会破坏 `[scriptblock]::Create((irm ...))` 形式。
-
-### 桌面安装程序(备选方案)
+| 参数 | 用途 |
+|---|---|
+| `-Branch NAME` | 选择源码分支,默认 `main`。 |
+| `-Commit SHA` | 在分支检出后固定到指定 commit。 |
+| `-HermesHome PATH` | 选择数据目录。 |
+| `-InstallDir PATH` | 选择源码目录。 |
+| `-NonInteractive` | 跳过需要输入的 setup/gateway 阶段。 |
+| `-IncludeDesktop` | 构建桌面应用并创建快捷方式。 |
+| `-ShowResolvedPaths` | 只输出解析后的路径 JSON,不安装。 |
+| `-Manifest` / `-ProtocolVersion` | 查看引导 GUI 使用的阶段协议。 |
+| `-Stage NAME -Json` | 执行单个阶段并输出结果帧。 |
-也提供了一个轻量 GUI 安装程序——如果你更倾向于双击 `.exe` 而非打开 PowerShell,可以使用它。下载 Hermes Desktop,运行安装程序,首次启动时 GUI 会在后台调用 `install.ps1` 来配置 Python(通过 `uv`)、Node、PortableGit 以及下文描述的其余依赖引导流程。首次运行后,桌面应用与 PowerShell 安装的 `hermes` CLI 共享同一个 `%LOCALAPPDATA%\hermes\hermes-agent` 安装目录和 `%USERPROFILE%\.hermes` 数据目录——可以在 GUI 和 CLI 之间自由切换。
+当前脚本不接受 `-NoVenv`、`-SkipSetup` 或 `-Tag`。
-如果你想要熟悉的 Windows 安装体验,或者要将 Hermes 交给非开发者使用,请使用桌面安装程序;如果你已经在终端中,请使用 PowerShell 一行命令。
+### MSIX / App Installer 和 Microsoft Store
-### 依赖引导(`dep_ensure`)
+自包含 MSIX 要求 Windows 11 22H2 或更新版本。
+Windows 10 源码安装支持不代表 MSIX 支持 Windows 10。
+打开 `.appinstaller` 文件,Windows 会安装签名包并记录更新源。
+软件包包含 Python、Node 和基础依赖,首次启动无需克隆或编译源码。
-在首次启动时(以及检测到缺少工具时按需触发),Hermes 会运行一个小型 Python 引导程序——`hermes_cli/dep_ensure.py`——检查并懒加载安装所需的非 Python 依赖。在 Windows 上,相关依赖如下:
+执行别名提供 `hermes`、`hermes-agent` 和 `hermes-acp`。
+用 `Get-Command hermes -All` 检查是否被其他安装覆盖。
+在 Windows 的应用执行别名设置中管理这些入口。
-| 依赖 | Hermes 需要它的原因 |
-| --------------- | ----------------------------------------------------------------------------------------------- |
-| **PortableGit** | 为终端工具提供 `bash.exe`,为会话内克隆提供 `git`。在安装时配置,而非由 `dep_ensure` 负责。 |
-| **Node.js 22** | 浏览器工具(`agent-browser`)、TUI 的 web 桥接以及 WhatsApp 桥接所必需。 |
-| **ffmpeg** | TTS / 语音消息的音频格式转换。 |
-| **ripgrep** | 快速文件搜索——不可用时回退到 `grep`。 |
-| **npm 包** | `agent-browser`、Playwright Chromium 以及各工具集的 Node 依赖,在首次使用浏览器工具时安装一次。 |
+侧载版通过桌面 Update 控件交给 App Installer 更新。
+Hermes 先下载本地描述文件,再停止自己的后端、退出并等待包替换。
+它不依赖 `ms-appinstaller:` URL 协议。商店版本由 Microsoft Store 更新。
-每个依赖都有类似 `shutil.which(...)` 的检查;如果二进制文件缺失且当前为交互式运行,`dep_ensure` 会提示安装(实际安装逻辑委托给 `scripts\install.ps1 -ensure <dep>`)。非交互式运行(gateway、cron、无头桌面启动)会跳过提示,并直接给出清晰的 `this feature needs <dep>` 错误。
+`Hermes-Setup.exe` 是另一种引导安装程序,会下载并配置源码安装。
+不要把它与自包含 MSIX 混为一谈。
-## 安装程序实际做了什么
+## 源码安装程序实际做了什么
-从头到尾,按顺序:
+1. 使用现有 Git;缺少时下载经过验证的 Git for Windows 工具包。
+2. 克隆源码分支,并应用可选的 commit pin。
+3. 引导 uv,再委托 PM 准备 Python 3.14、必要工具和名为 `all` 的 Python extra。
+4. 在数据目录的 `bin` 下生成启动器,并加入用户 PATH。
+5. 准备配置;非交互模式跳过输入阶段。
+6. 按需构建桌面应用,并写入完成标记。
-1. **引导 `uv`** — Astral 的快速 Python 管理器。安装到 `%USERPROFILE%\.local\bin`。
-2. **通过 `uv` 安装 Python 3.11**。无需预先安装 Python。
-3. **安装 Node.js 22**(优先使用 winget,否则将便携式 Node 压缩包解压到 `%LOCALAPPDATA%\hermes\node`)。用于浏览器工具和 WhatsApp 桥接。
-4. **安装便携式 Git** — 如果 `git` 已在 PATH 中,安装程序直接使用;否则从官方 `git-for-windows` 发布版下载精简的自包含 **PortableGit**(约 45 MB)到 `%LOCALAPPDATA%\hermes\git`。无需管理员权限,不写入 Windows 安装程序注册表,不干扰系统上的其他任何内容。
-5. **将仓库克隆**到 `%LOCALAPPDATA%\hermes\hermes-agent` 并在其中创建 virtualenv。
-6. **分层 `uv pip install`** — 先尝试 `.[all]`,如果 `git+https` 依赖在 GitHub 限速时失败,则逐步回退到更小的集合(`[messaging,dashboard,ext]` → `[messaging]` → `.`)。防止"单次失败导致裸安装"的故障模式。
-7. **根据 `.env` 自动安装消息 SDK** — 如果存在 `TELEGRAM_BOT_TOKEN` / `DISCORD_BOT_TOKEN` / `SLACK_BOT_TOKEN` / `SLACK_APP_TOKEN` / `WHATSAPP_ENABLED`,则运行 `python -m ensurepip --upgrade` 并针对性地调用 `pip install`,确保各平台 SDK 可正常导入。
-8. **设置 `HERMES_GIT_BASH_PATH`** 为解析后的 `bash.exe` 路径,使 Hermes 在新 shell 中能确定性地找到它。
-9. **将 `%LOCALAPPDATA%\hermes\bin` 添加到用户 PATH** — 打开新终端后即可使用 `hermes` 命令。
-10. **运行 `hermes setup`** — 正常的首次运行向导(模型、提供商、工具集)。使用 `-SkipSetup` 跳过。
+PM 通过 `pm/lock.json` 管理工具版本,不使用旧的 winget/分层 pip 回退。
+启动器运行工具存储中的 Python,并在导入依赖前选择完整环境。
+`hermes_cli/dep_ensure.py` 将功能需求交给 PM,不再调用 `install.ps1 -Ensure`。
:::tip 在 Windows 上跳过繁琐的提供商配置
- 在 Windows 上,逐个配置工具 API key(Firecrawl、FAL、Browser Use、OpenAI TTS)是获得可用 agent 摩擦最大的部分。[Nous Portal](/user-guide/features/tool-gateway) 订阅通过一次 OAuth 登录即可覆盖模型**以及**所有这些工具。安装程序完成后,运行 `hermes setup --portal` 完成配置。
+ 在 Windows 上,逐个配置工具 API key(Firecrawl、FAL、Browser Use、OpenAI TTS)是获得可用 agent 摩擦最大的部分。[Nous Portal](./features/tool-gateway.md) 订阅通过一次 OAuth 登录即可覆盖模型**以及**所有这些工具。安装程序完成后,运行 `hermes setup --portal` 完成配置。
:::
## 功能矩阵
diff --cc website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/windows-wsl-quickstart.md
index 0a4d8075d98,6304a3c0657..2c45ee6d338
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/windows-wsl-quickstart.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/windows-wsl-quickstart.md
@@@ -326,7 -326,7 +326,7 @@@ WSL2 将虚拟机磁盘存储为 `%LOCA
## 下一步
- - **[安装说明](/getting-started/installation)** —— 实际安装步骤(Linux/WSL2 使用同一安装程序)。
- - **[集成 → Providers → WSL2 网络配置](/integrations/providers#wsl2-networking-windows-users)** —— 本地模型服务器网络配置的权威深度说明。
- - **[MCP 指南 → WSL → Windows Chrome](/guides/use-mcp-with-hermes#wsl2-bridge-hermes-in-wsl-to-windows-chrome)** —— 从 WSL 中的 Hermes 控制你已登录的 Windows Chrome。
- - **[Tool Gateway](/user-guide/features/tool-gateway)** 和 **[Web Dashboard](/user-guide/features/web-dashboard)** —— 你最常需要从 WSL 暴露到网络其他部分的长期运行服务。
-- **[安装说明](../getting-started/installation.md)** —— 实际安装步骤(Linux/WSL2/Termux 均使用同一安装程序)。
++- **[安装说明](../getting-started/installation.md)** —— 实际安装步骤(Linux/WSL2 使用同一安装程序)。
+ - **[集成 → Providers → WSL2 网络配置](../integrations/providers.md#wsl2-networking-windows-users)** —— 本地模型服务器网络配置的权威深度说明。
+ - **[MCP 指南 → WSL → Windows Chrome](../guides/use-mcp-with-hermes.md#wsl2-bridge-hermes-in-wsl-to-windows-chrome)** —— 从 WSL 中的 Hermes 控制你已登录的 Windows Chrome。
+ - **[Tool Gateway](./features/tool-gateway.md)** 和 **[Web Dashboard](./features/web-dashboard.md)** —— 你最常需要从 WSL 暴露到网络其他部分的长期运行服务。