{"owner":"NousResearch","repo":"hermes-agent","hasSkills":true,"hasMcp":false,"mcpConfig":null,"found":["AGENTS.md"],"skills":{"AGENTS.md":"# Hermes Agent - Development Guide\n\nInstructions for AI coding assistants and developers working on the hermes-agent codebase.\n\n**Never give up on the right solution.**\n\n## What Hermes Is\n\nHermes is a personal AI agent that runs the same agent core across a CLI, a\nmessaging gateway (Telegram, Discord, Slack, and ~20 other platforms), a TUI,\nand an Electron desktop app. It learns across sessions (memory + skills),\ndelegates to subagents, runs scheduled jobs, and drives a real terminal and\nbrowser. It is extended primarily through **plugins and skills**, not by\ngrowing the core.\n\nTwo properties shape almost every design decision and are the lens for\nreviewing any change:\n\n- **Per-conversation prompt caching is sacred.** A long-lived conversation\n  reuses a cached prefix every turn. Anything that mutates past context,\n  swaps toolsets, or rebuilds the system prompt mid-conversation invalidates\n  that cache and multiplies the user's cost. We do not do it (the one\n  exception is context compression).\n- **The core is a narrow waist; capability lives at the edges.** Every model\n  tool we add is sent on every API call, so the bar for a new *core* tool is\n  high. Most new capability should arrive as a CLI command + skill, a\n  service-gated tool, or a plugin — not as core surface.\n\n## Contribution Rubric — What We Want / What We Don't\n\nThis is the project's intent layer. Use it two ways:\n\n1. **For humans and for your own work** — what gets merged and what gets\n   rejected, so a contribution aims at the target.\n2. **For automated review (the triage sweeper)** — guidance on when a PR is\n   safe to close on the three allowed reasons (`implemented_on_main`,\n   `cannot_reproduce`, `incoherent`) and, just as important, **when NOT to\n   close** one. Taste-based \"we don't want this / out of scope\" closes are NOT\n   an automated decision — those stay with a human maintainer. The sweeper's\n   job here is to recognize design intent and *avoid wrongly closing a\n   legitimate contribution*, not to make the won't-implement call itself.\n\nRead the balance right: Hermes ships a **lot** — most merges are bug fixes to\nreal reported behavior, and the product surface (platforms, channels,\nproviders, models, desktop/TUI features) expands aggressively and on purpose.\nThe restraint below is aimed squarely at the **core agent + the model tool\nschema**, the one place where every addition is paid for on every API call.\n\"Smallest footprint\" governs *how a capability is wired into the core*, NOT\nwhether the product is allowed to grow. We are expansive at the edges and\nconservative at the waist.\n\n### What we want\n\n- **Fix real bugs, well.** The bulk of what lands is `fix(...)` against an\n  actual reported symptom. A good fix reproduces the symptom on current\n  `main`, points to the exact line where it manifests, and fixes the whole bug\n  class — sibling call paths included — not just the one site the reporter hit.\n- **Expand reach at the edges.** New platform adapters, channels, providers,\n  models, and desktop/TUI/dashboard features are welcome and land routinely,\n  including large ones (a new messaging channel, a session-cap feature, a\n  Windows PTY bridge). Breadth in the product is a goal, not a footprint\n  concern — as long as it integrates with the existing setup/config UX\n  (`hermes tools`, `hermes setup`, auto-install) rather than bolting on a raw\n  env var.\n- **Refactor god-files into clean modules.** Extracting a multi-thousand-line\n  cluster out of `cli.py` / `run_agent.py` / `gateway/run.py` into a focused\n  mixin or module is wanted work, even when the diff is huge and mechanical\n  (large `+N/-N` refactors merge regularly). The \"every line traces to the\n  request\" test applies to *feature* PRs; a declared refactor's request IS the\n  extraction.\n- **Keep the core narrow.** New *model tools* are the expensive exception —\n  every tool ships on every API call. Prefer, in order: extend existing code →\n  CLI command + skill → service-gated tool (`check_fn`) → plugin → MCP server\n  in the catalog → new core tool (last resort). See \"The Footprint Ladder.\"\n- **Extend, don't duplicate.** Before adding a module/manager/hook, check\n  whether existing infrastructure already covers the use case. When several PRs\n  integrate the same *category*, design one shared interface instead of merging\n  them one at a time (see the ABC + orchestrator note under the Footprint\n  Ladder).\n- **Behavior contracts over snapshots.** Tests should assert how two pieces of\n  data must relate (invariants), not freeze a current value (model lists,\n  config version literals, enumeration counts). See \"Don't write\n  change-detector tests.\"\n- **E2E validation, not just green unit mocks.** For anything touching\n  resolution chains, config propagation, security boundaries, remote\n  backends, or file/network I/O, exercise the real path with real imports\n  against a temp `HERMES_HOME`. Mocks hide integration bugs.\n- **Cache-, alternation-, and invariant-safe.** Preserve prompt caching, strict\n  message role alternation (never two same-role messages in a row; never a\n  synthetic user message injected mid-loop), and a system prompt that is\n  byte-stable for the life of a conversation.\n- **Contributor credit preserved.** Salvage external work by cherry-picking\n  (rebase-merge) so authorship survives in git history; don't reimplement from\n  scratch when you can build on top.\n\n### What we don't want (rejected even when well-built)\n\n- **Speculative infrastructure.** Hooks, callbacks, or extension points with no\n  concrete consumer. Adding a hook is easy; removing one after plugins depend\n  on it is hard. A hook is NOT speculative if a contributor has a real, stated\n  use case — even if the consumer ships separately.\n- **New `HERMES_*` env vars for non-secret config.** `.env` is for secrets\n  only (API keys, tokens, passwords). All behavioral settings — timeouts,\n  thresholds, feature flags, display prefs — go in `config.yaml`. Bridge to an\n  internal env var if the mechanism needs one, but user-facing docs point to\n  `config.yaml`. Reject PRs that tell users to \"set X in your .env\" unless X\n  is a credential.\n- **A new core tool when terminal + file already do the job, or when a skill\n  would.** If the only barrier is file visibility on a remote backend, fix the\n  mount, not the toolset.\n- **Lazy-reading escape hatches on instructional tools.** No `offset`/`limit`\n  pagination on tools that load content the agent must read fully (skills,\n  prompts, playbooks). Models will read page 1 and skip the rest.\n- **\"Fixes\" that destroy the feature they secure.** A mitigation that kills the\n  feature's purpose is the wrong mitigation. Read the original commit's intent\n  (`git log -p -S`) before restricting behavior; find a fix that preserves the\n  feature.\n- **Outbound telemetry / usage attribution without opt-in gating.** No new\n  analytics, third-party identifier tagging, or attribution tags until a\n  generic user-facing opt-in (config gate + setup prompt + `hermes tools`\n  toggle) exists. Park behind a label, do not merge.\n- **Change-detector tests, cache-breaking mid-conversation, dead code wired in\n  without E2E proof, and plugins that touch core files.** Plugins live in their\n  own directory and work within the ABCs/hooks we provide; if a plugin needs\n  more, widen the generic plugin surface, don't special-case it in core.\n- **Third-party products / other people's projects integrated into the core\n  tree.** Observability backends, vendor SaaS integrations, analytics dashboards,\n  and similar \"someone else's product\" plugins do NOT land under `plugins/` in\n  this repo. They place an ongoing maintenance burden on us to keep them working\n  against a fast-moving core, for a backend we don't own. Ship them as a\n  **standalone plugin repo** users install into `~/.hermes/plugins/` (or via a\n  pip entry point), and promote them in the Nous Research Discord\n  (`#plugins-skills-and-skins`). This is a coupling-and-maintenance decision, not\n  a quality bar — the plugin can be excellent and still be a close. PRs that add\n  such a directory to the tree are closed with a pointer to publish it as its own\n  repo.\n\n### Before you call it a bug — verify the premise (and when NOT to close)\n\nThe most common reason a well-written PR gets closed is not code quality — it\nis that the change is built on a **wrong premise**, or it treats an\n**intentional design as a gap**. These patterns cut both ways: they tell a\nhuman reviewer what to scrutinize, and they tell the automated sweeper when a\nPR is NOT safe to close as `implemented_on_main` / `cannot_reproduce` (when in\ndoubt, leave it open for a human). They are distilled from real closes.\n\n- **\"Intentional design, not a gap.\"** A limitation that looks like an\n  oversight is often deliberate. Before \"fixing\" a missing link or a\n  restriction, ask whether the isolation IS the design. Example: profiles are\n  independent islands on purpose — a PR adding live config inheritance from the\n  default profile was closed because coupling profiles together is exactly what\n  the design prevents (the copy-at-creation `--clone` path already covers the\n  legitimate \"start from my default\" case). Read the original commit's intent\n  (`git log -p -S \"<symbol>\"`) before assuming something is unfinished.\n- **\"The premise doesn't hold against how X actually works.\"** A PR's\n  justification frequently rests on a wrong mental model of an existing\n  mechanism. Trace the real code/runtime before accepting the rationale. Two\n  real closes: a rate-limit \"re-probe during cooldown\" PR (the breaker only\n  trips on a *confirmed-empty* account bucket, so re-probing just hammers a\n  bucket we've already proven empty); a usage-accumulation fix whose new branch\n  **never executes at runtime** because an earlier guard already popped the\n  state it depended on. If you can't point to the exact line where the bug\n  manifests AND show the fix changes that line's behavior, you haven't verified\n  the premise.\n- **\"This fix was wrong — the absence/omission was deliberate.\"** Adding the\n  obvious-looking missing piece can break things the omission was protecting.\n  Example: restoring \"missing\" `__init__.py` files made a test tree importable\n  as a dotted package that shadowed the real plugin, deleting its `register()`\n  at import time. The absence was load-bearing.\n- **\"Overreached / resurrected an approach we'd moved past.\"** Scope creep that\n  supersedes an agreed-on base, or revives a direction the maintainers\n  deliberately closed, gets rejected even when the code works. Keep the change\n  to the narrow piece that was actually agreed; offer the rest as a focused\n  follow-up.\n\nThe throughline: **verify the claim AND the intent against the codebase before\nwriting or merging a fix.** A confirmed reproduction on current `main` plus a\nline-level account of where the fix acts beats a plausible-sounding rationale\nevery time. When in doubt about intent, it is cheaper to ask than to ship a\nfix that fights the design.\n\n### The Footprint Ladder (new capability decision)\n\nEach rung adds more permanent surface than the one above. Choose the highest\n(least-footprint) rung that correctly solves the problem:\n\n1. **Extend existing code** — the capability is a variation of something that\n   already exists. Zero new surface.\n2. **CLI command + skill** — manages config/state/infra expressible as shell\n   commands. The agent runs `hermes <subcommand>` guided by a skill. Zero\n   model-tool footprint. Default choice for subscriptions, scheduled tasks,\n   service setup. Examples: `hermes webhook`, `hermes cron`, `hermes tools`.\n3. **Service-gated tool (`check_fn`)** — needs structured params/returns AND\n   only appears when a prerequisite is configured. Zero footprint otherwise.\n   Examples: Home Assistant tools (gated on token), memory-provider tools.\n4. **Plugin** — third-party/niche/user-specific capability that doesn't ship in\n   core. Lives in `~/.hermes/plugins/` or a pip package, discovered at runtime.\n5. **MCP server (in the catalog)** — if the capability genuinely needs to be a\n   tool (structured I/O the agent invokes) but isn't core-fundamental, prefer\n   building it as an MCP server and adding it to the MCP catalog over growing\n   the core toolset. The agent connects to it through the built-in MCP client;\n   zero permanent core-schema footprint, and it's reusable by any MCP host.\n6. **New core tool** — only when the capability is fundamental, broadly useful\n   to nearly every user, and unreachable via terminal + file (or an MCP server).\n   Examples of correct core tools: terminal, read_file, web_search,\n   browser_navigate.\n\nWhen 3+ open PRs try to integrate the same *category* of thing (memory\nbackends, providers, notifiers), don't merge them one at a time — design an\nABC + orchestrator, wrap the existing built-in as the first provider, and turn\nthe competing PRs into plugins against that interface.\n\n### Surface capability is a property of the SESSION, never of the process env\n\nA tool that only works because of *who is on the other end of the connection* —\nthe desktop app's panes, the in-app browser, message reactions, Projects — must\nresolve its availability from the **session's own source**, not from an env var\non the backend process.\n\nThe client and the backend are separate machines on separate clocks. The\ndesktop app can be driving a backend Electron spawned locally, one over SSH,\none behind a plain URL + token, or Hermes Cloud. Only the first two are spawned\nby us and carry `HERMES_DESKTOP=1`. Every env-keyed GUI gate is therefore a\nsilent no-op on the other half of the topologies, and the failure is invisible:\nthe tool is stripped from the schema before the model ever sees it, on the same\nbackend whose platform hint is telling the model it's *\"chatting inside the\nHermes desktop app.\"*\n\nThe pattern that works:\n\n- **The toolset is the surface gate.** Keep the tools off `_HERMES_CORE_TOOLS`\n  (nobody else should pay their schema) and put them in a named toolset —\n  `desktop_ui`, `project`. The GUI gateway's `_load_enabled_toolsets(platform)`\n  folds that toolset in when the session's platform says GUI. One resolver,\n  every topology.\n- **`check_fn` answers reachability or user opt-in, not surface.** \"Is the\n  renderer bridge wired?\", \"did the user enable reactions?\" — fine. \"Was I\n  spawned by Electron?\" — not fine. `check_fn` results are also TTL-cached\n  process-wide (`tools/registry.py`), so a per-session answer does not belong\n  there at all: one process serves many sessions.\n- **Ask which identity you actually mean.** `HERMES_DESKTOP=1` legitimately\n  marks *\"this backend process was spawned by the app\"* — it gates the cron\n  ticker and web-dist handling correctly. It does NOT mean \"a GUI is watching\",\n  and the embedded terminal pane (`hermes --tui` against that same backend) is\n  the standing counterexample.\n\nSame test both ways: if the capability would still make sense with the client\non another machine, it is session-scoped. Cover it with a test that asserts the\nGUI session gets the tool **with the env var absent** — that's the assertion\nthe original gate could never have passed.\n\n## Development Environment\n\n```bash\n# Prefer .venv; fall back to venv if that's what your checkout has.\nsource .venv/bin/activate   # or: source venv/bin/activate\n```\n\n`scripts/run_tests.sh` probes `.venv` first, then `venv`, then\n`$HOME/.hermes/hermes-agent/venv` (for worktrees that share a venv with the\nmain checkout).\n\n## Project Structure\n\nFile counts shift constantly — don't treat the tree below as exhaustive.\nThe canonical source is the filesystem. The notes call out the load-bearing\nentry points you'll actually edit.\n\n```\nhermes-agent/\n├── run_agent.py          # AIAgent class — core conversation loop (~12k LOC)\n├── model_tools.py        # Tool orchestration, discover_builtin_tools(), handle_function_call()\n├── toolsets.py           # Toolset definitions, _HERMES_CORE_TOOLS list\n├── cli.py                # HermesCLI class — interactive CLI orchestrator (~11k LOC)\n├── hermes_state.py       # SessionDB — SQLite session store (FTS5 search)\n├── hermes_constants.py   # get_hermes_home(), display_hermes_home() — profile-aware paths\n├── hermes_logging.py     # setup_logging() — agent.log / errors.log / gateway.log (profile-aware)\n├── batch_runner.py       # Parallel batch processing\n├── agent/                # Agent internals (provider adapters, memory, caching, compression, etc.)\n├── hermes_cli/           # CLI subcommands, setup wizard, plugins loader, skin engine\n├── tools/                # Tool implementations — auto-discovered via tools/registry.py\n│   └── environments/     # Terminal backends (local, docker, ssh, modal, daytona, singularity)\n├── gateway/              # Messaging gateway — run.py + session.py + platforms/\n│   ├── platforms/        # Adapter per platform (telegram, discord, slack, whatsapp,\n│   │                     #   homeassistant, signal, matrix, mattermost, email, sms,\n│   │                     #   dingtalk, wecom, weixin, feishu, qqbot, bluebubbles,\n│   │                     #   yuanbao, webhook, api_server, ...). See ADDING_A_PLATFORM.md.\n│   └── builtin_hooks/    # Extension point for always-registered gateway hooks (none shipped)\n├── plugins/              # Plugin system (see \"Plugins\" section below)\n│   ├── memory/           # Memory-provider plugins (honcho, mem0, supermemory, ...)\n│   ├── context_engine/   # Context-engine plugins\n│   ├── model-providers/  # Inference backend plugins (openrouter, anthropic, gmi, ...)\n│   ├── kanban/           # Multi-agent board dispatcher + worker plugin\n│   ├── hermes-achievements/  # Gamified achievement tracking\n│   ├── observability/    # Metrics / traces / logs plugin\n│   ├── image_gen/        # Image-generation providers\n│   └── <others>/         # disk-cleanup, google_meet, platforms, spotify,\n│                         #   strike-freedom-cockpit, ...\n├── optional-skills/      # Heavier/niche skills shipped but NOT active by default\n├── skills/               # Built-in skills bundled with the repo\n├── ui-tui/               # Ink (React) terminal UI — `hermes --tui`\n│   └── src/              # entry.tsx, app.tsx, gatewayClient.ts + app/components/hooks/lib\n├── tui_gateway/          # Python JSON-RPC backend for the TUI\n├── acp_adapter/          # ACP server (VS Code / Zed / JetBrains integration)\n├── cron/                 # Scheduler — jobs.py, scheduler.py\n├── scripts/              # run_tests.sh, release.py, auxiliary scripts\n├── website/              # Docusaurus docs site\n└── tests/                # Pytest suite (~17k tests across ~900 files as of May 2026)\n```\n\n**User config:** `~/.hermes/config.yaml` (settings), `~/.hermes/.env` (API keys only).\n**Logs:** `~/.hermes/logs/` — `agent.log` (INFO+), `errors.log` (WARNING+),\n`gateway.log` when running the gateway. Profile-aware via `get_hermes_home()`.\nBrowse with `hermes logs [--follow] [--level ...] [--session ...]`.\n\n## TypeScript Style\n\nApplies to TypeScript across Hermes: desktop, TUI, website, and future TS packages.\n\n- Prefer small nanostores over component state when state is shared, reused, or read by distant UI.\n- Let each feature own its atoms. Chat state belongs near chat, shell state near shell, shared state in `src/store`.\n- Components that render from an atom should use `useStore`. Non-rendering actions should read with `$atom.get()`.\n- Do not pass state through three components when the leaf can subscribe to the atom.\n- Keep persistence beside the atom that owns it.\n- Keep route roots thin. They compose routes and shell; they should not become controllers.\n- No monolithic hooks. A hook should own one narrow job.\n- Prefer colocated action modules over hidden god hooks.\n- If a callback is pure side effect, use the terse void form:\n  `onState={st => void setGatewayState(st)}`.\n- Async UI handlers should make intent explicit:\n  `onClick={() => void save()}`.\n- Prefer interfaces for public props and shared object shapes. Avoid `type X = { ... }` for object props.\n- Extend React primitives for props: `React.ComponentProps<'button'>`, `React.ComponentProps<typeof Dialog>`, `Omit<...>`, `Pick<...>`.\n- Table-driven beats condition ladders when mapping ids, routes, or views.\n- `src/app` owns routes, pages, and page-specific components.\n- `src/store` owns shared atoms.\n- `src/lib` owns shared pure helpers.\n\n## File Dependency Chain\n\n```\ntools/registry.py  (no deps — imported by all tool files)\n       ↑\ntools/*.py  (each calls registry.register() at import time)\n       ↑\nmodel_tools.py  (imports tools/registry + triggers tool discovery)\n       ↑\nrun_agent.py, cli.py, batch_runner.py, environments/\n```\n\n---\n\n## AIAgent Class (run_agent.py)\n\nThe real `AIAgent.__init__` takes ~60 parameters (credentials, routing, callbacks,\nsession context, budget, credential pool, etc.). The signature below is the\nminimum subset you'll usually touch — read `run_agent.py` for the full list.\n\n```python\nclass AIAgent:\n    def __init__(self,\n        base_url: str = None,\n        api_key: str = None,\n        provider: str = None,\n        api_mode: str = None,              # \"chat_completions\" | \"codex_responses\" | ...\n        model: str = \"\",                   # empty → resolved from config/provider later\n        max_iterations: int = 500,         # tool-calling iterations (shared with subagents)\n        enabled_toolsets: list = None,\n        disabled_toolsets: list = None,\n        quiet_mode: bool = False,\n        save_trajectories: bool = False,\n        platform: str = None,              # \"cli\", \"telegram\", etc.\n        session_id: str = None,\n        skip_context_files: bool = False,\n        skip_memory: bool = False,\n        credential_pool=None,\n        # ... plus callbacks, thread/user/chat IDs, iteration_budget, fallback_model,\n        # checkpoints config, prefill_messages, service_tier, reasoning_config, etc.\n    ): ...\n\n    def chat(self, message: str) -> str:\n        \"\"\"Simple interface — returns final response string.\"\"\"\n\n    def run_conversation(self, user_message: str, system_message: str = None,\n                         conversation_history: list = None, task_id: str = None) -> dict:\n        \"\"\"Full interface — returns dict with final_response + messages.\"\"\"\n```\n\n### Agent Loop\n\nThe core loop is inside `run_conversation()` — entirely synchronous, with\ninterrupt checks, budget tracking, and a one-turn grace call:\n\n```python\nwhile (api_call_count < self.max_iterations and self.iteration_budget.remaining > 0) \\\n        or self._budget_grace_call:\n    if self._interrupt_requested: break\n    response = client.chat.completions.create(model=model, messages=messages, tools=tool_schemas)\n    if response.tool_calls:\n        for tool_call in response.tool_calls:\n            result = handle_function_call(tool_call.name, tool_call.args, task_id)\n            messages.append(tool_result_message(result))\n        api_call_count += 1\n    else:\n        return response.content\n```\n\nMessages follow OpenAI format: `{\"role\": \"system/user/assistant/tool\", ...}`.\nReasoning content is stored in `assistant_msg[\"reasoning\"]`.\n\n---\n\n## CLI Architecture (cli.py)\n\n- **Rich** for banner/panels, **prompt_toolkit** for input with autocomplete\n- **KawaiiSpinner** (`agent/display.py`) — animated faces during API calls, `┊` activity feed for tool results\n- `load_cli_config()` in cli.py merges hardcoded defaults + user config YAML\n- **Skin engine** (`hermes_cli/skin_engine.py`) — data-driven CLI theming; initialized from `display.skin` config key at startup; skins customize banner colors, spinner faces/verbs/wings, tool prefix, response box, branding text\n- `process_command()` is a method on `HermesCLI` — dispatches on canonical command name resolved via `resolve_command()` from the central registry\n- Skill slash commands: `agent/skill_commands.py` scans `~/.hermes/skills/`, injects as **user message** (not system prompt) to preserve prompt caching\n\n### Slash Command Registry (`hermes_cli/commands.py`)\n\nAll slash commands are defined in a central `COMMAND_REGISTRY` list of `CommandDef` objects. Every downstream consumer derives from this registry automatically:\n\n- **CLI** — `process_command()` resolves aliases via `resolve_command()`, dispatches on canonical name\n- **Gateway** — `GATEWAY_KNOWN_COMMANDS` frozenset for hook emission, `resolve_command()` for dispatch\n- **Gateway help** — `gateway_help_lines()` generates `/help` output\n- **Telegram** — `telegram_bot_commands()` generates the BotCommand menu\n- **Slack** — `slack_subcommand_map()` generates `/hermes` subcommand routing\n- **Autocomplete** — `COMMANDS` flat dict feeds `SlashCommandCompleter`\n- **CLI help** — `COMMANDS_BY_CATEGORY` dict feeds `show_help()`\n\n### Adding a Slash Command\n\n1. Add a `CommandDef` entry to `COMMAND_REGISTRY` in `hermes_cli/commands.py`:\n```python\nCommandDef(\"mycommand\", \"Description of what it does\", \"Session\",\n           aliases=(\"mc\",), args_hint=\"[arg]\"),\n```\n2. Add handler in `HermesCLI.process_command()` in `cli.py`:\n```python\nelif canonical == \"mycommand\":\n    self._handle_mycommand(cmd_original)\n```\n3. If the command is available in the gateway, add a handler in `gateway/run.py`:\n```python\nif canonical == \"mycommand\":\n    return await self._handle_mycommand(event)\n```\n4. For persistent settings, use `save_config_value()` in `cli.py`\n\n**CommandDef fields:**\n- `name` — canonical name without slash (e.g. `\"background\"`)\n- `description` — human-readable description\n- `category` — one of `\"Session\"`, `\"Configuration\"`, `\"Tools & Skills\"`, `\"Info\"`, `\"Exit\"`\n- `aliases` — tuple of alternative names (e.g. `(\"bg\",)`)\n- `args_hint` — argument placeholder shown in help (e.g. `\"<prompt>\"`, `\"[name]\"`)\n- `cli_only` — only available in the interactive CLI\n- `gateway_only` — only available in messaging platforms\n- `gateway_config_gate` — config dotpath (e.g. `\"display.tool_progress_command\"`); when set on a `cli_only` command, the command becomes available in the gateway if the config value is truthy. `GATEWAY_KNOWN_COMMANDS` always includes config-gated commands so the gateway can dispatch them; help/menus only show them when the gate is open.\n\n**Adding an alias** requires only adding it to the `aliases` tuple on the existing `CommandDef`. No other file changes needed — dispatch, help text, Telegram menu, Slack mapping, and autocomplete all update automatically.\n\n---\n\n## TUI Architecture (ui-tui + tui_gateway)\n\nThe TUI is a full replacement for the classic (prompt_toolkit) CLI, activated via `hermes --tui` or `HERMES_TUI=1`.\n\n### Process Model\n\n```\nhermes --tui\n  └─ Node (Ink)  ──stdio JSON-RPC──  Python (tui_gateway)\n       │                                  └─ AIAgent + tools + sessions\n       └─ renders transcript, composer, prompts, activity\n```\n\nTypeScript owns the screen. Python owns sessions, tools, model calls, and slash command logic.\n\n### Transport\n\nNewline-delimited JSON-RPC over stdio. Requests from Ink, events from Python. See `tui_gateway/server.py` for the full method/event catalog.\n\n### Key Surfaces\n\n| Surface | Ink component | Gateway method |\n|---------|---------------|----------------|\n| Chat streaming | `app.tsx` + `messageLine.tsx` | `prompt.submit` → `message.delta/complete` |\n| Tool activity | `thinking.tsx` | `tool.start/progress/complete` |\n| Approvals | `prompts.tsx` | `approval.respond` ← `approval.request` |\n| Clarify/sudo/secret | `prompts.tsx`, `maskedPrompt.tsx` | `clarify/sudo/secret.respond` |\n| Session picker | `sessionPicker.tsx` | `session.list/resume` |\n| Slash commands | Local handler + fallthrough | `slash.exec` → `_SlashWorker`, `command.dispatch` |\n| Completions | `useCompletion` hook | `complete.slash`, `complete.path` |\n| Theming | `theme.ts` + `branding.tsx` | `gateway.ready` with skin data |\n\n### Slash Command Flow\n\n1. Built-in client commands (`/help`, `/quit`, `/clear`, `/resume`, `/copy`, `/paste`, etc.) handled locally in `app.tsx`\n2. Everything else → `slash.exec` (runs in persistent `_SlashWorker` subprocess) → `command.dispatch` fallback\n\n### Dev Commands\n\n```bash\ncd ui-tui\nnpm install       # first time\nnpm run dev       # watch mode (rebuilds hermes-ink + tsx --watch)\nnpm start         # production\nnpm run build     # full build (hermes-ink + tsc)\nnpm run typecheck # typecheck only (tsc --noEmit)\nnpm run lint      # eslint\nnpm run fmt       # prettier\nnpm test          # vitest\n```\n\n### TUI in the Dashboard (`hermes dashboard` → `/chat`)\n\nThe dashboard embeds the real `hermes --tui` — **not** a rewrite.  See `hermes_cli/pty_bridge.py` + the `@app.websocket(\"/api/pty\")` endpoint in `hermes_cli/web_server.py`.\n\n- Browser loads `web/src/pages/ChatPage.tsx`, which mounts xterm.js's `Terminal` with the WebGL renderer, `@xterm/addon-fit` for container-driven resize, and `@xterm/addon-unicode11` for modern wide-character widths.\n- `/api/pty?token=…` upgrades to a WebSocket; auth uses the same ephemeral `_SESSION_TOKEN` as REST, via query param (browsers can't set `Authorization` on WS upgrade).\n- The server spawns whatever `hermes --tui` would spawn, through `ptyprocess` (POSIX PTY — WSL works, native Windows does not).\n- Frames: raw PTY bytes each direction; resize via `\\x1b[RESIZE:<cols>;<rows>]` intercepted on the server and applied with `TIOCSWINSZ`.\n\n**Do not re-implement the primary chat experience in React.** The main transcript, composer/input flow (including slash-command behavior), and PTY-backed terminal belong to the embedded `hermes --tui` — anything new you add to Ink shows up in the dashboard automatically. If you find yourself rebuilding the transcript or composer for the dashboard, stop and extend Ink instead.\n\n**Structured React UI around the TUI is allowed when it is not a second chat surface.** Sidebar widgets, inspectors, summaries, status panels, and similar supporting views (e.g. `ChatSidebar`, `ModelPickerDialog`, `ToolCall`) are fine when they complement the embedded TUI rather than replacing the transcript / composer / terminal. Keep their state independent of the PTY child's session and surface their failures non-destructively so the terminal pane keeps working unimpaired.\n\n### Electron Desktop Chat App (`apps/desktop/`)\n\nA **separate** chat surface from both the classic CLI and the dashboard's embedded TUI. It is an Electron + React + nanostore renderer (`@assistant-ui/react`) that talks to a `tui_gateway` backend over JSON-RPC (`requestGateway(method, params)`). The WebSocket/JSON-RPC transport lives in the framework-agnostic `apps/shared` package (`@hermes/shared` — `JsonRpcGatewayClient` + WS URL helpers), which the web dashboard (`web/`) also consumes; **desktop has no build/runtime dependency on the dashboard frontend** — it spawns a headless `hermes serve` backend server (the same gateway `dashboard` serves, minus the browser UI entirely: `serve` sets `headless_backend=True`, so `cmd_dashboard` skips `_build_web_ui` AND exports `HERMES_SERVE_HEADLESS=1` so `mount_spa()` disables the SPA even if a stray `web_dist/` exists — only the JSON-RPC/WS/API surface is reachable). `dashboard` and `serve` share `cmd_dashboard`/`start_server` but are independent surfaces — neither launches the other. The one exception is a backward-compat *fallback*: `serve` is newer, so the desktop spawn (`electron/backend-command.ts` + `backendSupportsServe()` in `electron/main.ts`) detects whether the resolved runtime registers `serve` and, only when it does not (an older managed install / PATH `hermes` the app hasn't updated yet), rewrites the argv to the legacy `dashboard --no-open`. Without that, a new app against an un-upgraded runtime would crash on an unknown subcommand and brick every mid-upgrade user. It does NOT embed `hermes --tui` — it has its own composer, transcript, and slash-command pipeline. For scoped Desktop architecture, state, resolver, transport, and testing rules, read `apps/desktop/AGENTS.md`.\n\n**Slash commands in the desktop app are curated client-side, then dispatched to the backend.** The pipeline:\n\n- **Backend already provides everything.** `tui_gateway/server.py` `commands.catalog` (empty-query list) and `complete.slash` (typed-query completions) both include built-in commands, user `quick_commands`, AND skill-derived commands (`scan_skill_commands()` / `get_skill_commands()`). The desktop app does not need a new RPC to see skills.\n- **The renderer curates via `apps/desktop/src/lib/desktop-slash-commands.ts`.** This is the load-bearing file. It holds `DESKTOP_COMMAND_SPECS` (the built-ins and their Desktop surfaces) plus `NO_DESKTOP_SURFACE` block-lists for terminal-only / messaging-only / picker-owned / settings-owned / advanced commands that should NOT clutter the desktop popover.\n  - `isDesktopSlashCommand(name)` — gates **execution**. Returns true for built-ins AND for any non-built-in (skill / quick command), so typed extension commands run.\n  - `isDesktopSlashSuggestion(name)` — gates **discovery/completion**. Used by BOTH completion paths in `app/chat/composer/hooks/use-slash-completions.ts` (empty-query catalog filter + typed-query `complete.slash` filter) and by `filterDesktopCommandsCatalog`.\n  - `isDesktopSlashExtensionCommand(name)` — true when the command is NOT a known Hermes built-in (i.e. a skill or user quick command). Both suggestion and catalog-filter paths allow extensions through so skill commands surface in the palette. (Added when fixing \"skill commands missing from the desktop slash palette\" — the curated allow-list was silently dropping every skill/quick command from completions even though they executed fine when typed.)\n- **Dispatch** lives in `app/session/hooks/use-prompt-actions/slash.ts` (`runSlash`): built-ins that the desktop owns (`/skin`, `/help`, `/new`, …) are handled locally or via `commands.catalog`; everything else goes to `slash.exec`, falling back to `command.dispatch` (which the gateway resolves into skill / alias / exec directives). A skill command resolves to `{type: \"skill\", message}` and is submitted as a normal prompt.\n\n**Rule:** the desktop slash palette's curation is about hiding noise (terminal-only / messaging-only built-ins), NOT about hiding user-activated extensions. Skill commands and `quick_commands` are extensions the backend surfaces — they belong in completions. If you tighten `desktop-slash-commands.ts`, keep `isDesktopSlashExtensionCommand` flowing into both the suggestion and catalog-filter paths. Tests: from `apps/desktop`, run `npx vitest run src/lib/desktop-slash-commands.test.ts` (workspace dependencies are installed at the repo root).\n\n---\n\n## Adding New Tools\n\nBefore adding any tool, settle the footprint question first (see \"The\nFootprint Ladder\" in the Contribution Rubric): most capabilities should NOT\nbe core tools. For custom or local-only tools, do **not** edit Hermes core.\nUse the plugin route instead: create `~/.hermes/plugins/<name>/plugin.yaml`\nand `~/.hermes/plugins/<name>/__init__.py`, then register tools with\n`ctx.register_tool(...)`. Plugin toolsets are discovered automatically and can be\nenabled or disabled without touching `tools/` or `toolsets.py`.\n\nUse the built-in route below only when the user is explicitly contributing a new\ncore Hermes tool that should ship in the base system.\n\nBuilt-in/core tools require changes in **2 files**:\n\n**1. Create `tools/your_tool.py`:**\n```python\nimport json, os\nfrom tools.registry import registry\n\ndef check_requirements() -> bool:\n    return bool(os.getenv(\"EXAMPLE_API_KEY\"))\n\ndef example_tool(param: str, task_id: str = None) -> str:\n    return json.dumps({\"success\": True, \"data\": \"...\"})\n\nregistry.register(\n    name=\"example_tool\",\n    toolset=\"example\",\n    schema={\"name\": \"example_tool\", \"description\": \"...\", \"parameters\": {...}},\n    handler=lambda args, **kw: example_tool(param=args.get(\"param\", \"\"), task_id=kw.get(\"task_id\")),\n    check_fn=check_requirements,\n    requires_env=[\"EXAMPLE_API_KEY\"],\n)\n```\n\n**2. Add to `toolsets.py`** — either `_HERMES_CORE_TOOLS` (all platforms) or a new toolset. **This step is required:** auto-discovery imports the tool and registers its schema, but the tool is only *exposed to an agent* if its name appears in a toolset. `_HERMES_CORE_TOOLS` is not dead code — it's the default bundle every platform's base toolset inherits from.\n\nAuto-discovery: any `tools/*.py` file with a top-level `registry.register()` call is imported automatically — no manual import list to maintain. Wiring into a toolset is still a deliberate, manual step.\n\nThe registry handles schema collection, dispatch, availability checking, and error wrapping. All handlers MUST return a JSON string.\n\n**Path references in tool schemas**: If the schema description mentions file paths (e.g. default output directories), use `display_hermes_home()` to make them profile-aware. The schema is generated at import time, which is after `_apply_profile_override()` sets `HERMES_HOME`.\n\n**State files**: If a tool stores persistent state (caches, logs, checkpoints), use `get_hermes_home()` for the base directory — never `Path.home() / \".hermes\"`. This ensures each profile gets its own state.\n\n**Agent-level tools** (todo, memory): intercepted by `run_agent.py` before `handle_function_call()`. See `tools/todo_tool.py` for the pattern.\n\n---\n\n## Dependency Pinning Policy\n\nAll dependencies must have upper bounds to limit supply-chain attack surface.\nThis policy was established after the litellm compromise (PR #2796, #2810) and\nreinforced after the Mini Shai-Hulud worm campaign (May 2026).\n\n| Source type | Treatment | Example |\n|---|---|---|\n| PyPI package | `>=floor,<next_major` | `\"httpx>=0.28.1,<1\"` |\n| Git URL | Commit SHA | `git+https://...@<40-char-sha>` |\n| GitHub Actions | Commit SHA + comment | `uses: actions/checkout@<sha>  # v4` |\n| CI-only pip | `==exact` | `pyyaml==6.0.2` |\n\n**When adding a new dependency to `pyproject.toml`:**\n1. Pin to `>=current_version,<next_major` for post-1.0 (e.g. `>=1.5.0,<2`).\n2. For pre-1.0 packages, use `<0.(current_minor + 2)` (e.g. `>=0.29,<0.32`).\n3. Never commit a bare `>=X.Y.Z` without a ceiling — CI and reviewers will reject it.\n4. Run `uv lock` to regenerate `uv.lock` with hashes.\n\nReference: #2810 (bounds pass), #9801 (SHA pinning + audit CI).\n\n---\n\n## Adding Configuration\n\n### config.yaml options:\n1. Add to `DEFAULT_CONFIG` in `hermes_cli/config.py`\n2. Bump `_config_version` (check the current value at the top of `DEFAULT_CONFIG`)\n   ONLY if you need to actively migrate/transform existing user config\n   (renaming keys, changing structure). Adding a new key to an existing\n   section is handled automatically by the deep-merge and does NOT require\n   a version bump.\n\n### Top-level `config.yaml` sections (non-exhaustive):\n\n`model`, `agent`, `terminal`, `compression`, `display`, `stt`, `tts`,\n`memory`, `security`, `delegation`, `smart_model_routing`, `checkpoints`,\n`auxiliary`, `curator`, `skills`, `gateway`, `logging`, `cron`, `profiles`,\n`plugins`, `honcho`.\n\n`auxiliary` holds per-task overrides for side-LLM work (curator, vision,\nembedding, title generation, session_search, etc.) — each task can pin\nits own provider/model/base_url/max_tokens/reasoning_effort. See\n`agent/auxiliary_client.py::_resolve_auto` for resolution order.\n\n`curator` holds the background skill-maintenance config —\n`enabled`, `interval_hours`, `min_idle_hours`, `stale_after_days`,\n`archive_after_days`, `backup` (nested).\n\n### .env variables (SECRETS ONLY — API keys, tokens, passwords):\n1. Add to `OPTIONAL_ENV_VARS` in `hermes_cli/config.py` with metadata:\n```python\n\"NEW_API_KEY\": {\n    \"description\": \"What it's for\",\n    \"prompt\": \"Display name\",\n    \"url\": \"https://...\",\n    \"password\": True,\n    \"category\": \"tool\",  # provider, tool, messaging, setting\n},\n```\n\nNon-secret settings (timeouts, thresholds, feature flags, paths, display\npreferences) belong in `config.yaml`, not `.env`. If internal code needs an\nenv var mirror for backward compatibility, bridge it from `config.yaml` to\nthe env var in code (see `gateway_timeout`, `terminal.cwd` → `TERMINAL_CWD`).\n\n### Config loaders (three paths — know which one you're in):\n\n| Loader | Used by | Location |\n|--------|---------|----------|\n| `load_cli_config()` | CLI mode | `cli.py` — merges CLI-specific defaults + user YAML |\n| `load_config()` | `hermes tools`, `hermes setup`, most CLI subcommands | `hermes_cli/config.py` — merges `DEFAULT_CONFIG` + user YAML |\n| Direct YAML load | Gateway runtime | `gateway/run.py` + `gateway/config.py` — reads user YAML raw |\n\nIf you add a new key and the CLI sees it but the gateway doesn't (or vice\nversa), you're on the wrong loader. Check `DEFAULT_CONFIG` coverage.\n\n### Working directory:\n- **CLI** — uses the process's current directory (`os.getcwd()`).\n- **Messaging** — uses `terminal.cwd` from `config.yaml`. The gateway bridges this\n  to the `TERMINAL_CWD` env var for child tools. **`MESSAGING_CWD` has been\n  removed** — the config loader prints a deprecation warning if it's set in\n  `.env`. Same for `TERMINAL_CWD` in `.env`; the canonical setting is\n  `terminal.cwd` in `config.yaml`.\n\n---\n\n## Skin/Theme System\n\nThe skin engine (`hermes_cli/skin_engine.py`) provides data-driven CLI visual customization. Skins are **pure data** — no code changes needed to add a new skin.\n\n### Architecture\n\n```\nhermes_cli/skin_engine.py    # SkinConfig dataclass, built-in skins, YAML loader\n~/.hermes/skins/*.yaml       # User-installed custom skins (drop-in)\n```\n\n- `init_skin_from_config()` — called at CLI startup, reads `display.skin` from config\n- `get_active_skin()` — returns cached `SkinConfig` for the current skin\n- `set_active_skin(name)` — switches skin at runtime (used by `/skin` command)\n- `load_skin(name)` — loads from user skins first, then built-ins, then falls back to default\n- Missing skin values inherit from the `default` skin automatically\n\n### What skins customize\n\n| Element | Skin Key | Used By |\n|---------|----------|---------|\n| Banner panel border | `colors.banner_border` | `banner.py` |\n| Banner panel title | `colors.banner_title` | `banner.py` |\n| Banner section headers | `colors.banner_accent` | `banner.py` |\n| Banner dim text | `colors.banner_dim` | `banner.py` |\n| Banner body text | `colors.banner_text` | `banner.py` |\n| Response box border | `colors.response_border` | `cli.py` |\n| Spinner faces (waiting) | `spinner.waiting_faces` | `display.py` |\n| Spinner faces (thinking) | `spinner.thinking_faces` | `display.py` |\n| Spinner verbs | `spinner.thinking_verbs` | `display.py` |\n| Spinner wings (optional) | `spinner.wings` | `display.py` |\n| Tool output prefix | `tool_prefix` | `display.py` |\n| Per-tool emojis | `tool_emojis` | `display.py` → `get_tool_emoji()` |\n| Agent name | `branding.agent_name` | `banner.py`, `cli.py` |\n| Welcome message | `branding.welcome` | `cli.py` |\n| Response box label | `branding.response_label` | `cli.py` |\n| Prompt symbol | `branding.prompt_symbol` | `cli.py` |\n\n### Built-in skins\n\n- `default` — Classic Hermes gold/kawaii (the current look)\n- `ares` — Crimson/bronze war-god theme with custom spinner wings\n- `mono` — Clean grayscale monochrome\n- `slate` — Cool blue developer-focused theme\n\n### Adding a built-in skin\n\nAdd to `_BUILTIN_SKINS` dict in `hermes_cli/skin_engine.py`:\n\n```python\n\"mytheme\": {\n    \"name\": \"mytheme\",\n    \"description\": \"Short description\",\n    \"colors\": { ... },\n    \"spinner\": { ... },\n    \"branding\": { ... },\n    \"tool_prefix\": \"┊\",\n},\n```\n\n### User skins (YAML)\n\nUsers create `~/.hermes/skins/<name>.yaml`:\n\n```yaml\nname: cyberpunk\ndescription: Neon-soaked terminal theme\n\ncolors:\n  banner_border: \"#FF00FF\"\n  banner_title: \"#00FFFF\"\n  banner_accent: \"#FF1493\"\n\nspinner:\n  thinking_verbs: [\"jacking in\", \"decrypting\", \"uploading\"]\n  wings:\n    - [\"⟨⚡\", \"⚡⟩\"]\n\nbranding:\n  agent_name: \"Cyber Agent\"\n  response_label: \" ⚡ Cyber \"\n\ntool_prefix: \"▏\"\n```\n\nActivate with `/skin cyberpunk` or `display.skin: cyberpunk` in config.yaml.\n\n---\n\n## Plugins\n\nHermes has two plugin surfaces. Both live under `plugins/` in the repo so\nrepo-shipped plugins can be discovered alongside user-installed ones in\n`~/.hermes/plugins/` and pip-installed entry points.\n\n### General plugins (`hermes_cli/plugins.py` + `plugins/<name>/`)\n\n`PluginManager` discovers plugins from `~/.hermes/plugins/`, `./.hermes/plugins/`,\nand pip entry points. Each plugin exposes a `register(ctx)` function that\ncan:\n\n- Register Python-callback lifecycle hooks:\n  `pre_tool_call`, `post_tool_call`, `pre_llm_call`, `post_llm_call`,\n  `on_session_start`, `on_session_end`\n- Register new tools via `ctx.register_tool(...)`\n- Register CLI subcommands via `ctx.register_cli_command(...)` — the\n  plugin's argparse tree is wired into `hermes` at startup so\n  `hermes <pluginname> <subcmd>` works with no change to `main.py`\n\nHooks are invoked from `model_tools.py` (pre/post tool) and `run_agent.py`\n(lifecycle). **Discovery timing pitfall:** `discover_plugins()` only runs\nas a side effect of importing `model_tools.py`. Code paths that read plugin\nstate without importing `model_tools.py` first must call `discover_plugins()`\nexplicitly (it's idempotent).\n\n#### Native plugin compatibility policy\n\nThe canonical contract and deprecation policy live in\n`website/docs/developer-guide/plugins/index.md#native-plugin-compatibility-contract`.\nCompatibility is enforced as a behavior contract, not through a monolithic\n`PLUGIN_API_VERSION`, a manifest-wide native `api:` match, or version literals\non unrelated payloads. Keep documented plugin surfaces additive:\n\n- add hook payload data as keyword fields; signature-inspect callbacks so old\n  narrow signatures receive only fields they declare, while `**kwargs`\n  callbacks receive the complete payload;\n- do not remove or rename `PluginContext` methods; make new parameters optional\n  with defaults and keyword-only where possible;\n- ignore unknown native manifest fields;\n- give new provider methods default implementations, and signature-inspect\n  optional callback kwargs rather than forwarding them unconditionally;\n- use a local schema version only for a capability with a wire or persisted\n  contract, and preserve old state/config/session replay or ship a migration.\n\nDeprecations require a once-per-process warning, a documented replacement and\nmigration note, and at least two subsequent minor releases before removal.\nCompatibility tests must load frozen plugins through the real discovery path\nand assert outcomes. Do not replace these with exact registry/catalog counts,\nsource-reading tests, or assertions that a global version literal changed.\n\n### Memory-provider plugins (`plugins/memory/<name>/`)\n\nSeparate discovery system for pluggable memory backends. Current built-in\nproviders include **honcho, mem0, supermemory, byterover, hindsight,\nholographic, openviking, retaindb**.\n\nDiscovery covers the same four sources as the general `PluginManager` —\nbundled, `$HERMES_HOME/plugins/`, `./.hermes/plugins/` (opt-in via\n`HERMES_ENABLE_PROJECT_PLUGINS`), and `hermes_agent.memory_providers` entry\npoints — but with **bundled-first** precedence, the reverse of the general\nsystem's later-wins order: a memory provider is activated by name, so a\ndropped-in directory must not be able to shadow a shipped one. Discovery\nenumerates without importing; nothing runs until `memory.provider` names it.\n\nEach provider implements the `MemoryProvider` ABC (see `agent/memory_provider.py`)\nand is orchestrated by `agent/memory_manager.py`. Lifecycle hooks include\n`sync_turn(turn_messages)`, `prefetch(query)`, `shutdown()`, and optional\n`post_setup(hermes_home, config)` for setup-wizard integration.\n\n**CLI commands via `plugins/memory/<name>/cli.py`:** if a memory plugin\ndefines `register_cli(subparser)`, `discover_plugin_cli_commands()` finds\nit at argparse setup time and wires it into `hermes <plugin>`. The\nframework only exposes CLI commands for the **currently active** memory\nprovider (read from `memory.provider` in config.yaml), so disabled\nproviders don't clutter `hermes --help`.\n\n**Rule (Teknium, May 2026):** plugins MUST NOT modify core files\n(`run_agent.py`, `cli.py`, `gateway/run.py`, `hermes_cli/main.py`, etc.).\nIf a plugin needs a capability the framework doesn't expose, expand the\ngeneric plugin surface (new hook, new ctx method) — never hardcode\nplugin-specific logic into core. PR #5295 removed 95 lines of hardcoded\nhoncho argparse from `main.py` for exactly this reason.\n\n**No new in-tree memory providers (policy, May 2026):** the set of\nbuilt-in memory providers under `plugins/memory/` is closed. New memory\nbackends must ship as **standalone plugin repos** that users install\ninto `~/.hermes/plugins/` (or via pip entry points) — they implement\nthe same `MemoryProvider` ABC, register through the same discovery\npath, and integrate via `hermes memory setup` / `post_setup()` without\nlanding in this tree. PRs that add a new directory under\n`plugins/memory/` will be closed with a pointer to publish the\nprovider as its own repo. Existing in-tree providers stay; bug fixes\nto them are welcome.\n\n**No new third-party-product plugins in-tree (policy, June 2026):** the\nsame rule applies beyond memory providers. Plugins that integrate\nsomeone else's product or project — observability/metrics backends,\nvendor SaaS connectors, analytics dashboards, paid-service tie-ins —\nmust ship as **standalone plugin repos** that users install into\n`~/.hermes/plugins/` (or via pip entry points). They register through\nthe existing plugin discovery path and use the ABCs/hooks/ctx surface\nwe expose; nothing special is needed in core. The reason is\nmaintenance load: every product we absorb into the tree becomes our\nburden to keep working against a fast-moving core, for a backend we\ndon't own. Promote standalone plugins in the Nous Research Discord\n(`#plugins-skills-and-skins`). PRs that add such a directory under\n`plugins/` are closed with a pointer to publish it as its own repo —\nthis is a coupling decision, not a quality judgment. (The\n`observability/`, `kanban/`, `disk-cleanup/`, etc. directories already\nin the tree are existing precedent, not an invitation to add more\nthird-party-product plugins alongside them.)\n\n### Model-provider plugins (`plugins/model-providers/<name>/`)\n\nEvery inference backend (openrouter, anthropic, gmi, deepseek, nvidia, …)\nships as a plugin here. Each plugin's `__init__.py` calls\n`providers.register_provider(ProviderProfile(...))` at module load.\n`providers/__init__.py._discover_providers()` is a **lazy, separate\ndiscovery system** — scanned on first `get_provider_profile()` or\n`list_providers()` call, NOT by the general PluginManager.\n\nScan order:\n1. Bundled: `<repo>/plugins/model-providers/<name>/`\n2. User: `$HERMES_HOME/plugins/model-providers/<name>/`\n3. Legacy: `<repo>/providers/<name>.py` (back-compat)\n\nUser plugins of the same name override bundled ones — `register_provider()`\nis last-writer-wins. This lets third parties swap out any built-in\nprofile without a repo patch.\n\nThe general PluginManager records `kind: model-provider` manifests but does\nNOT import them (would double-instantiate `ProviderProfile`). Plugins\nwithout an explicit `kind:` get auto-coerced via a source-text heuristic\n(`register_provider` + `ProviderProfile` in `__init__.py`).\n\nFull authoring guide: `website/docs/developer-guide/model-provider-plugin.md`.\n\n### Dashboard / context-engine / image-gen plugin directories\n\n`plugins/context_engine/`, `plugins/image_gen/`, etc. follow the same\npattern (ABC + orchestrator + per-plugin directory). Context engines\nplug into `agent/context_engine.py`; image-gen providers into\n`agent/image_gen_provider.py`. Reference / docs-companion plugins\n(`example-dashboard`, `strike-freedom-cockpit`, `plugin-llm-example`,\n`plugin-llm-async-example`) live in the\n[`hermes-example-plugins`](https://github.com/NousResearch/hermes-example-plugins)\ncompanion repo, not in this tree.\n\n---\n\n## Skills\n\nTwo parallel surfaces:\n\n- **`skills/`** — built-in skills shipped and loadable by default.\n  Organized by category directories (e.g. `skills/github/`, `skills/mlops/`).\n- **`optional-skills/`** — heavier or niche skills shipped with the repo but\n  NOT active by default. Installed explicitly via\n  `hermes skills install official/<category>/<skill>`. Adapter lives in\n  `tools/skills_hub.py` (`OptionalSkillSource`). Categories include\n  `autonomous-ai-agents`, `blockchain`, `communication`, `creative`,\n  `devops`, `email`, `health`, `mcp`, `migration`, `mlops`, `productivity`,\n  `research`, `security`, `web-development`.\n\nWhen reviewing skill PRs, check which directory they target — heavy-dep or\nniche skills belong in `optional-skills/`.\n\n### SKILL.md frontmatter\n\nStandard fields: `name`, `description`, `version`, `author`, `license`,\n`platforms` (OS-gating list: `[macos]`, `[linux, macos]`, ...),\n`metadata.hermes.tags`, `metadata.hermes.category`,\n`metadata.hermes.related_skills`, `metadata.hermes.config` (config.yaml\nsettings the skill needs — stored under `skills.config.<key>`, prompted\nduring setup, injected at load time).\n\nTop-level `tags:` and `category:` are also accepted and mirrored from\n`metadata.hermes.*` by the loader.\n\n### Skill authoring standards (HARDLINE)\n\nEvery new or modernized skill — bundled, optional, or contributed —\nmust meet these standards before merge. Reviewers reject PRs that\nviolate them.\n\n1. **`description` ≤ 60 characters, one sentence, ends with a period.**\n   Long descriptions bloat skill listings and dilute the model's\n   attention when many skills are loaded. State the capability, not\n   the implementation. No marketing words (\"powerful\",\n   \"comprehensive\", \"seamless\", \"advanced\"). Don't repeat the skill\n   name. Verify with:\n   ```python\n   import re, pathlib\n   m = re.search(r'^description: (.*)$',\n                 pathlib.Path('skills/<cat>/<name>/SKILL.md').read_text(),\n                 re.MULTILINE)\n   assert len(m.group(1)) <= 60, len(m.group(1))\n   ```\n\n2. **Tools referenced in SKILL.md prose must be native Hermes tools or\n   MCP servers the skill explicitly expects.** When the skill needs a\n   capability, point at the proper tool by name in backticks\n   (`` `terminal` ``, `` `web_extract` ``, `` `read_file` ``,\n   `` `patch` ``, `` `search_files` ``, `` `vision_analyze` ``,\n   `` `browser_navigate` ``, `` `delegate_task` ``, etc.). Do NOT\n   name shell utilities the agent already has wrapped — `grep` →\n   `search_files`, `cat`/`head`/`tail` → `read_file`, `sed`/`awk` →\n   `patch`, `find`/`ls` → `search_files target='files'`. If the skill\n   depends on an MCP server, name the MCP server and document the\n   expected setup in `## Prerequisites`. Anything else (third-party\n   CLIs, shell pipelines, etc.) is fair game inside script files but\n   should not be the headline interaction surface in the prose.\n\n3. **`platforms:` gating audited against actual script imports.**\n   Skills that use POSIX-only primitives (`fcntl`, `termios`,\n   `os.setsid`, `os.kill(pid, 0)` for liveness, `/proc`, `/tmp`\n   hardcoded, `signal.SIGKILL`, bash heredocs, `osascript`, `apt`,\n   `systemctl`) must declare their supported platforms. Default\n   posture: try to fix it cross-platform first — `tempfile.gettempdir`,\n   `pathlib.Path`, `psutil.pid_exists`, Python-level filtering instead\n   of `grep`. Gate to a narrower set only when the dependency is\n   genuinely platform-bound.\n\n4. **`author` credits the human contributor first.** For external\n   contributions, the contributor's real name + GitHub handle goes\n   first; \"Hermes Agent\" is the secondary collaborator. If the\n   contributor's commit shows \"Hermes Agent\" as author (because they\n   used Hermes to draft the skill), replace it with their actual name\n   — credit the human, not the tool.\n\n5. **SKILL.md body uses the modern section order.** `# <Skill> Skill`\n   title, 2-3 sentence intro stating what it does and doesn't do,\n   `## When to Use`, `## Prerequisites`, `## How to Run`,\n   `## Quick Reference`, `## Procedure`, `## Pitfalls`,\n   `## Verification`. Target ~200 lines for a complex skill,\n   ~100 lines for a simple one. Cut redundant intro fluff, marketing\n   prose, and re-explanations of env vars already in\n   `## Prerequisites`.\n\n6. **Scripts go in `scripts/`, references in `references/`,\n   templates in `templates/`.** Don't expect the model to inline-write\n   parsers, XML walkers, or non-trivial logic every call — ship a\n   helper script. Reference it from SKILL.md by path relative to the\n   skill directory.\n\n7. **Tests live at `tests/skills/test_<skill>_skill.py`** and use only\n   stdlib + pytest + `unittest.mock`. No live network calls. Run via\n   `scripts/run_tests.sh tests/skills/test_<skill>_skill.py -q`.\n\n8. **`.env.example` additions are isolated to a clearly delimited\n   block.** Don't touch the surrounding file — contributor-supplied\n   `.env.example` versions are usually stale and edits outside the\n   skill's own block must be dropped during salvage.\n\nThe full salvage / modernization checklist for external skill PRs\nlives in the `hermes-agent-dev` skill at\n`references/new-skill-pr-salvage.md` — load it before polishing\ncontributor skill PRs.\n\n---\n\n## Toolsets\n\nAll toolsets are defined in `toolsets.py` as a single `TOOLSETS` dict.\nEach platform's adapter picks a base toolset (e.g. Telegram uses\n`\"messaging\"`); `_HERMES_CORE_TOOLS` is the default bundle most\nplatforms inherit from.\n\nCurrent toolset keys: `browser`, `clarify`, `code_execution`, `cronjob`,\n`debugging`, `delegation`, `discord`, `discord_admin`, `feishu_doc`,\n`feishu_drive`, `file`, `homeassistant`, `image_gen`, `kanban`, `memory`,\n`messaging`, `moa`, `rl`, `safe`, `search`, `session_search`, `skills`,\n`spotify`, `terminal`, `todo`, `tts`, `video`, `vision`, `web`, `yuanbao`.\n\nEnable/disable per platform via `hermes tools` (the curses UI) or the\n`tools.<platform>.enabled` / `tools.<platform>.disabled` lists in\n`config.yaml`.\n\n---\n\n## Delegation (`delegate_task`)\n\n`tools/delegate_tool.py` spawns a subagent with an isolated\ncontext + terminal session. By default the parent waits for the\nchild's summary before continuing its own loop. With `background=true`,\nHermes returns a delegation id immediately and the result re-enters the\nconversation later through the async-delegation completion queue.\n\nTwo shapes:\n\n- **Single:** pass `goal` (+ optional `context`, `toolsets`).\n- **Batch (parallel):** pass `tasks: [...]` — each gets its own subagent\n  running concurrently. Concurrency is capped by\n  `delegation.max_concurrent_children` (default 3).\n\nRoles:\n\n- `role=\"leaf\"` (default) — focused worker. Cannot call `delegate_task`,\n  `clarify`, `memory`, `send_message`, `cronjob`. Retains `execute_code`\n  (programmatic tool calling).\n- `role=\"orchestrator\"` — retains `delegate_task` so it can spawn its\n  own workers. Gated by `delegation.orchestrator_enabled` (default true)\n  and bounded by `delegation.max_spawn_depth` (default 2).\n\nKey config knobs (under `delegation:` in `config.yaml`):\n`max_concurrent_children`, `max_spawn_depth`, `child_timeout_seconds`,\n`orchestrator_enabled`, `subagent_auto_approve`, `inherit_mcp_toolsets`,\n`max_iterations`.\n\nDurability rule: background `delegate_task` is detached from the current\nturn but still process-local. For work that must survive process restart, use\n`cronjob` or `terminal(background=True, notify_on_complete=True)` instead.\n\n---\n\n## Curator (skill lifecycle)\n\nBackground skill-maintenance system that tracks usage on agent-created\nskills and auto-archives stale ones. Users never lose skills; archives\ngo to `~/.hermes/skills/.archive/` and are restorable.\n\n- **Core:** `agent/curator.py` (review loop, auto-transitions, LLM review\n  prompt) + `agent/curator_backup.py` (pre-run tar.gz snapshots).\n- **CLI:** `hermes_cli/curator.py` wires `hermes curator <verb>` where\n  verbs are: `status`, `run`, `pause`, `resume`, `pin`, `unpin`,\n  `archive`, `restore`, `prune`, `backup`, `rollback`.\n- **Telemetry:** `tools/skill_usage.py` owns the sidecar\n  `~/.hermes/skills/.usage.json` — per-skill `use_count`, `view_count`,\n  `patch_count`, `last_activity_at`, `state` (active / stale /\n  archived), `pinned`.\n\nInvariants:\n- Curator only touches skills with `created_by: \"agent\"` provenance —\n  bundled + hub-installed skills are off-limits.\n- Never deletes; max destructive action is archive.\n- Pinned skills are exempt from every auto-transition and from the\n  LLM review pass.\n- `skill_manage(action=\"delete\")` refuses pinned skills; patch/edit/\n  write_file/remove_file go through so the agent can keep improving\n  pinned skills.\n\nConfig section (`curator:` in `config.yaml`):\n`enabled`, `interval_hours`, `min_idle_hours`, `stale_after_days`,\n`archive_after_days`, `backup.*`.\n\nFull user-facing docs: `website/docs/user-guide/features/curator.md`.\n\n---\n\n## Cron (scheduled jobs)\n\n`cron/jobs.py` (job store) + `cron/scheduler.py` (tick loop). Agents\nschedule jobs via the `cronjob` tool; users via `hermes cron <verb>`\n(`list`, `add`, `edit`, `pause`, `resume`, `run`, `remove`) or the\n`/cron` slash command.\n\nSupported schedule formats:\n- Duration: `\"30m\"`, `\"2h\"`, `\"1d\"`\n- \"every\" phrase: `\"every 2h\"`, `\"every monday 9am\"`\n- 5-field cron expression: `\"0 9 * * *\"`\n- ISO timestamp (one-shot): `\"2026-06-01T09:00:00Z\"`\n\nPer-job fields include `skills` (load specific skills), `model` /\n`provider` overrides, `script` (pre-run data-collection script whose\nstdout is injected into the prompt; `no_agent=True` turns the script\ninto the entire job), `context_from` (chain job A's last output into\njob B's prompt), `workdir` (run in a specific directory with its\n`AGENTS.md`/`CLAUDE.md` loaded), and multi-platform delivery.\n\nHardening invariants:\n- **3-minute hard interrupt** on cron sessions — runaway agent loops\n  cannot monopolize the scheduler.\n- Catchup window: half the job's period, clamped to 120s–2h.\n- Grace window: 120s for one-shot jobs whose fire time was missed.\n- File lock at `~/.hermes/cron/.tick.lock` prevents duplicate ticks\n  across processes.\n- Cron sessions pass `skip_memory=True` by default; memory providers\n  intentionally do not run during cron.\n\nCron deliveries are **not** mirrored into the target gateway session —\nthey land in their own cron session with a header/footer frame so the\nmain conversation's message-role alternation stays intact.\n\n---\n\n## Kanban (multi-agent work queue)\n\nDurable SQLite-backed board that lets multiple profiles / workers\ncollaborate on shared tasks. Users drive it via `hermes kanban <verb>`;\nworkers spawned by the dispatcher drive it via a dedicated `kanban_*`\ntoolset so their schema footprint is zero when they're not inside a\nkanban task.\n\n- **CLI:** `hermes_cli/kanban.py` wires `hermes kanban` with verbs\n  `init`, `create`, `list` (alias `ls`), `show`, `assign`, `link`,\n  `unlink`, `comment`, `attach`, `attachments`, `attach-rm`, `complete`,\n  `request-review`, `request-changes`, `reopen-review`, `block`, `unblock`, `archive`,\n  `tail`, plus less-commonly-used `watch`, `stats`, `runs`, `log`,\n  `assignees`, `heartbeat`, `notify-*`, `dispatch`, `daemon`, `gc`.\n- **Worker/orchestrator toolset:** `tools/kanban_tools.py` exposes\n  `kanban_show`, `kanban_complete`, `kanban_request_review`,\n  `kanban_request_changes`, `kanban_block`,\n  `kanban_heartbeat`, `kanban_comment`, `kanban_create`, `kanban_link`,\n  `kanban_attach`, `kanban_attach_url`, `kanban_attachments`; profiles that\n  explicitly enable the `kanban` toolset outside a dispatcher-spawned\n  task also get `kanban_list` and `kanban_unblock` for board routing.\n- **Dispatcher:** long-lived loop that (default every 60s) reclaims\n  stale claims, promotes ready tasks, atomically claims, and spawns\n  assigned profiles. Runs **inside the gateway** by default via\n  `kanban.dispatch_in_gateway: true`.\n- **Plugin assets:** `plugins/kanban/dashboard/` (web UI) +\n  `plugins/kanban/systemd/` (`hermes-kanban-dispatcher.service` for\n  standalone dispatcher deployment).\n\nIsolation model:\n- **Board** is the hard boundary — workers are spawned with\n  `HERMES_KANBAN_BOARD` pinned in their env so they can't see other\n  boards.\n- **Tenant** is a soft namespace *within* a board — one specialist\n  fleet can serve multiple businesses with workspace-path + memory-key\n  isolation.\n- After `kanban.failure_limit` consecutive non-success attempts on the\n  same task (default: 2), the dispatcher auto-blocks it to prevent spin\n  loops.\n\nFull user-facing docs: `website/docs/user-guide/features/kanban.md`.\n\n---\n\n## Important Policies\n\n### Prompt Caching Must Not Break\n\nHermes-Agent ensures caching remains valid throughout a conversation. **Do NOT implement changes that would:**\n- Alter past context mid-conversation\n- Change toolsets mid-conversation\n- Reload memories or rebuild system prompts mid-conversation\n\nCache-breaking forces dramatically higher costs. The ONLY time we alter context is during context compression.\n\nSlash commands that mutate system-prompt state (skills, tools, memory, etc.)\nmust be **cache-aware**: default to deferred invalidation (change takes\neffect next session), with an opt-in `--now` flag for immediate\ninvalidation. See `/skills install --now` for the canonical pattern.\n\n### Background Process Notifications (Gateway)\n\nWhen `terminal(background=true, notify_on_complete=true)` is used, the gateway runs a watcher that\ndetects process completion and triggers a new agent turn. Control verbosity of background process\nmessages with `display.background_process_notifications`\nin config.yaml (or `HERMES_BACKGROUND_NOTIFICATIONS` env var):\n\n- `concise` — one-line status message on completion; failures append a short output tail (default)\n- `all` — running-output updates + final raw-output message\n- `result` — only the final raw-output completion message\n- `error` — only the final raw-output message when exit code != 0\n- `off` — no watcher messages at all\n\n---\n\n## Profiles: Multi-Instance Support\n\nHermes supports **profiles** — multiple fully isolated instances, each with its own\n`HERMES_HOME` directory (config, API keys, memory, sessions, skills, gateway, etc.).\n\nThe core mechanism: `_apply_profile_override()` in `hermes_cli/main.py` sets\n`HERMES_HOME` before any module imports. All `get_hermes_home()` references\nautomatically scope to the active profile.\n\n### Rules for profile-safe code\n\n1. **Use `get_hermes_home()` for all HERMES_HOME paths.** Import from `hermes_constants`.\n   NEVER hardcode `~/.hermes` or `Path.home() / \".hermes\"` in code that reads/writes state.\n   ```python\n   # GOOD\n   from hermes_constants import get_hermes_home\n   config_path = get_hermes_home() / \"config.yaml\"\n\n   # BAD — breaks profiles\n   config_path = Path.home() / \".hermes\" / \"config.yaml\"\n   ```\n\n2. **Use `display_hermes_home()` for user-facing messages.** Import from `hermes_constants`.\n   This returns `~/.hermes` for default or `~/.hermes/profiles/<name>` for profiles.\n   ```python\n   # GOOD\n   from hermes_constants import display_hermes_home\n   print(f\"Config saved to {display_hermes_home()}/config.yaml\")\n\n   # BAD — shows wrong path for profiles\n   print(\"Config saved to ~/.hermes/config.yaml\")\n   ```\n\n3. **Module-level constants are fine** — they cache `get_hermes_home()` at import time,\n   which is AFTER `_apply_profile_override()` sets the env var. Just use `get_hermes_home()`,\n   not `Path.home() / \".hermes\"`.\n\n4. **Tests that mock `Path.home()` must also set `HERMES_HOME`** — since code now uses\n   `get_hermes_home()` (reads env var), not `Path.home() / \".hermes\"`:\n   ```python\n   with patch.object(Path, \"home\", return_value=tmp_path), \\\n        patch.dict(os.environ, {\"HERMES_HOME\": str(tmp_path / \".hermes\")}):\n       ...\n   ```\n\n5. **Gateway platform adapters should use token locks** — if the adapter connects with\n   a unique credential (bot token, API key), call `acquire_scoped_lock()` from\n   `gateway.status` in the `connect()`/`start()` method and `release_scoped_lock()` in\n   `disconnect()`/`stop()`. This prevents two profiles from using the same credential.\n   See `plugins/platforms/irc/adapter.py` for the canonical pattern.\n\n6. **Profile operations are HOME-anchored, not HERMES_HOME-anchored** — `_get_profiles_root()`\n   returns `Path.home() / \".hermes\" / \"profiles\"`, NOT `get_hermes_home() / \"profiles\"`.\n   This is intentional — it lets `hermes -p coder profile list` see all profiles regardless\n   of which one is active.\n\n## Known Pitfalls\n\n### DO NOT hardcode `~/.hermes` paths\nUse `get_hermes_home()` from `hermes_constants` for code paths. Use `display_hermes_home()`\nfor user-facing print/log messages. Hardcoding `~/.hermes` breaks profiles — each profile\nhas its own `HERMES_HOME` directory. This was the source of 5 bugs fixed in PR #3575.\n\n### All CLI menu-pickers MUST use curses.\nInteractive menus must use `hermes_cli/curses_ui.py`. See `hermes_cli/tools_config.py` for an example.\n\n### DO NOT use `\\033[K` (ANSI erase-to-EOL) in spinner/display code\nLeaks as literal `?[K` text under `prompt_toolkit`'s `patch_stdout`. Use space-padding: `f\"\\r{line}{' ' * pad}\"`.\n\n### `_last_resolved_tool_names` is a process-global in `model_tools.py`\n`_run_single_child()` in `delegate_tool.py` saves and restores this global around subagent execution. If you add new code that reads this global, be aware it may be temporarily stale during child agent runs.\n\n### DO NOT hardcode cross-tool references in schema descriptions\nTool schema descriptions must not mention tools from other toolsets by name (e.g., `browser_navigate` saying \"prefer web_search\"). Those tools may be unavailable (missing API keys, disabled toolset), causing the model to hallucinate calls to non-existent tools. If a cross-reference is needed, add it dynamically in `get_tool_definitions()` in `model_tools.py` — see the `browser_navigate` / `execute_code` post-processing blocks for the pattern.\n\n### The gateway has TWO message guards — both must bypass approval/control commands\nWhen an agent is running, messages pass through two sequential guards:\n(1) **base adapter** (`gateway/platforms/base.py`) queues messages in\n`_pending_messages` when `session_key in self._active_sessions`, and\n(2) **gateway runner** (`gateway/run.py`) intercepts `/stop`, `/new`,\n`/queue`, `/status`, `/approve`, `/deny` before they reach\n`running_agent.interrupt()`. Any new command that must reach the runner\nwhile the agent is blocked (e.g. approval prompts) MUST bypass BOTH\nguards and be dispatched inline, not via `_process_message_background()`\n(which races session lifecycle).\n\n### Squash merges from stale branches silently revert recent fixes\nBefore squash-merging a PR, ensure the branch is up to date with `main`\n(`git fetch origin main && git reset --hard origin/main` in the worktree,\nthen re-apply the PR's commits). A stale branch's version of an unrelated\nfile will silently overwrite recent fixes on main when squashed. Verify\nwith `git diff HEAD~1..HEAD` after merging — unexpected deletions are a\nred flag.\n\n### Don't wire in dead code without E2E validation\nUnused code that was never shipped was dead for a reason. Before wiring an\nunused module into a live code path, E2E test the real resolution chain\nwith actual imports (not mocks) against a temp `HERMES_HOME`.\n\n### Tests must not write to `~/.hermes/`\nThe `_isolate_hermes_home` autouse fixture in `tests/conftest.py` redirects `HERMES_HOME` to a temp dir. Never hardcode `~/.hermes/` paths in tests.\n\n**Profile tests**: When testing profile features, also mock `Path.home()` so that\n`_get_profiles_root()` and `_get_default_hermes_home()` resolve within the temp dir.\nUse the pattern from `tests/hermes_cli/test_profiles.py`:\n```python\n@pytest.fixture\ndef profile_env(tmp_path, monkeypatch):\n    home = tmp_path / \".hermes\"\n    home.mkdir()\n    monkeypatch.setattr(Path, \"home\", lambda: tmp_path)\n    monkeypatch.setenv(\"HERMES_HOME\", str(home))\n    return home\n```\n\n---\n\n## Testing\n\n### Python\n**ALWAYS use `scripts/run_tests.sh`** — do not call `pytest` directly. The script enforces\nhermetic environment parity with CI (unset credential vars, TZ=UTC, LANG=C.UTF-8,\nper-file subprocess isolation via `scripts/run_tests_parallel.py` — no xdist,\nworker count auto-scaled from CPU count). Direct `pytest`\non a 16+ core developer machine with API keys set diverges from CI in ways\nthat have caused multiple \"works locally, fails in CI\" incidents (and the reverse).\n\n```bash\nscripts/run_tests.sh                                  # full suite, CI-parity\nscripts/run_tests.sh tests/gateway/                   # one directory\nscripts/run_tests.sh tests/agent/test_foo.py -k test_x  # one test (file + -k; the runner is file-granular)\nscripts/run_tests.sh -v --tb=long                     # pass-through pytest flags\n```\n\n**Flake policy:** the runner auto-retries a failing test FILE once in a fresh\nsubprocess (`--file-retries`, default 1; `HERMES_TEST_FILE_RETRIES=0` to\ndisable). Pass-on-retry counts as green but is printed in a `⚠ FLAKY` summary\nsection with both attempts' output. A FLAKY report is a bug to fix, not noise\nto ignore — timing-sensitive tests must not assume a quiet runner (loose\nwall-clock bounds ≥ 2s, event-based sync, no `assert not _wait_until(...)`\nnegative-timing races).\n\n#### Subprocess-per-test-file isolation\n\nEvery test file runs in a freshly-spawned Python subprocess via `run_tests_parallel.py`. This means module-level dicts/sets and\nContextVars from one test file cannot leak into the next.\n\n#### Why the wrapper\n\n|                     | Without wrapper                             | With wrapper                              |\n| ------------------- | ------------------------------------------- | ----------------------------------------- |\n| Provider API keys   | Whatever is in your env (auto-detects pool) | All env vars except a specific few unset. |\n| HOME / `~/.hermes/` | Your real config+auth.json                  | Temp dir per test                         |\n| Timezone            | Local TZ (PDT etc.)                         | UTC                                       |\n| Locale              | Whatever is set                             | C.UTF-8                                   |\n\n### Where to place what tests\n\nThe CI change classifier (`scripts/ci/classify_changes.py`) runs specific jobs based on what files changed. A Python test that asserts\nabout the contents of `package.json`, `package-lock.json`, `.ts`/`.tsx`\nsource, or any other JS-side artifact will not run on a PR that only touches\nthose files. This means a regression can go green on a PR and red on `main` (where the\nclassifier fails open and runs everything).\n\nAny test that reads or asserts about `package.json`,\n`package-lock.json`, `tsconfig.json`, `.ts`/`.tsx`/`.js`/`.mjs`/`.cjs`\nsource files configuration belongs in the JS (vitest) test suite, not in `tests/*.py`.\n\n### Don't fake the host OS\n\nHermes supports Linux, macOS and native Windows, and plenty of its behaviour\ngenuinely differs per host. Those differences are tested by running on the\nhost, not by patching `sys.platform`.\n\n```python\n@pytest.mark.linux_only\n@pytest.mark.macos_only\n@pytest.mark.windows_only\n```\n\nThings that are host-independent can stay unmarked:\n\n- **Pure functions that take a platform as data** —\n  `hidden_windows_child_options(opts, is_windows=True)` is input→output, not a\n  fake host. (Contrast: setting a module-level `IS_WINDOWS` flag and then\n  calling `windows_detach_flags()` *is* a fake.)\n- **Declaration/packaging invariants** — \"pyproject declares `tzdata` with a\n  `sys_platform == 'win32'` marker\" asserts about a file, not about runtime.\n\nThe line: **if the test needs the interpreter to believe it is on another OS\nin order to pass, it belongs on that OS.**\nWhen one test body walks several platforms in sequence, split it.\nKeep the host-native arm on the Linux lane and move the other arm into its own marked test.\n\n**Use the marker, never a bare `skipif`.** `scripts/ci/list_os_marked_tests.py`\ndecides which files the macOS/Windows lanes import by grepping for the marker\n*name*, and the lane then filters with `-m <marker>`. A test gated with\n`@pytest.mark.skipif(sys.platform != \"win32\")` therefore skips on Linux AND is\nnever imported on the Windows lane — it runs on no host at all, silently. The\nsame trap catches a file-local alias (`windows_only = pytest.mark.skipif(...)`):\nthe grep matches the name, so the file *is* listed, but `-m windows_only`\ndeselects every test in it and the lane reports green over zero coverage.\nEqually, don't `pytest.skip()` the non-host rows of a `@parametrize` over\nplatforms — split it into one marked test per OS, or only the host's row ever\nexecutes.\n\n### Don't write change-detector tests\n\nA test is a **change-detector** if it fails whenever data that is **expected\nto change** gets updated — model catalogs, config version numbers,\nenumeration counts, hardcoded lists of provider models. These tests add no\nbehavioral coverage; they just guarantee that routine source updates break\nCI and cost engineering time to \"fix.\"\n\n**Do not write:**\n\n```python\n# catalog snapshot — breaks every model release\nassert \"gemini-2.5-pro\" in _PROVIDER_MODELS[\"gemini\"]\nassert \"MiniMax-M2.7\" in models\n\n# config version literal — breaks every schema bump\nassert DEFAULT_CONFIG[\"_config_version\"] == 21\n\n# enumeration count — breaks every time a skill/provider is added\nassert len(_PROVIDER_MODELS[\"huggingface\"]) == 8\n```\n\n**Do write:**\n\n```python\n# behavior: does the catalog plumbing work at all?\nassert \"gemini\" in _PROVIDER_MODELS\nassert len(_PROVIDER_MODELS[\"gemini\"]) >= 1\n\n# behavior: does migration bump the user's version to current latest?\nassert raw[\"_config_version\"] == DEFAULT_CONFIG[\"_config_version\"]\n\n# invariant: no plan-only model leaks into the legacy list\nassert not (set(moonshot_models) & coding_plan_only_models)\n\n# invariant: every model in the catalog has a context-length entry\nfor m in _PROVIDER_MODELS[\"huggingface\"]:\n    assert m.lower() in DEFAULT_CONTEXT_LENGTHS_LOWER\n```\n\nThe rule: if the test reads like a snapshot of current data, delete it. If\nit reads like a contract about how two pieces of data must relate, keep it.\nWhen a PR adds a new provider/model and you want a test, make the test\nassert the relationship (e.g. \"catalog entries all have context lengths\"),\nnot the specific names.\n\nReviewers should reject new change-detector tests; authors should convert\nthem into invariants before re-requesting review.\n\n### Never read source code in tests\n\nA test that reads a source file's text is testing *the shape of the\nsource code*, not its behavior. This is a hard antipattern, banned outright.\nAny test that reads a .py, .ts, .tsx, etc., file is suspect.\n\n**Why it's actively harmful, not just weak:**\n\n- It passes when the implementation is subtly broken (the regex matches a\n  call site that exists but is wired wrong) and fails when a correct\n  refactor changes formatting, variable names, or control flow with\n  identical runtime behavior. Both directions of failure are wrong.\n- It can't be run against a built/bundled/minified artifact, so it silently\n  stops testing anything the moment code moves, gets renamed, or a\n  dependency reformats it.\n- It actively blocks refactors: reviewers see \"keeps a pattern intact\" tests\n  fail during pure structural cleanup with no behavior change, and either\n  hand-wave the failure (dangerous) or waste time updating regexes that add\n  nothing (waste).\n- It gives false confidence. a green suite full of source-regex tests\n  looks like coverage but has never once executed the code path it claims\n  to guard.\n\n**Do not write:**\n\n```ts\nconst source = fs.readFileSync(path.join(__dirname, 'main.ts'), 'utf8')\n\ntest('backend spawn hides the Windows console', () => {\n  assert.match(source, /spawn\\(\\s*backend\\.command,\\s*backend\\.args[\\s\\S]{0,300}hiddenWindowsChildOptions/)\n})\n```\n\n**Do write — extract the logic into a small pure/DI-testable function and\ncall it for real:**\n\n```ts\n// backend-spawn.ts\nexport function hiddenWindowsChildOptions(options: SpawnOptionsLike = {}, isWindows = process.platform === 'win32') {\n  if (!isWindows || 'windowsHide' in options) return options\n  return { ...options, windowsHide: true }\n}\n\n// backend-spawn.test.ts\ntest('windowsHide defaults to true on Windows, is left alone elsewhere', () => {\n  assert.equal(hiddenWindowsChildOptions({}, true).windowsHide, true)\n  assert.equal(hiddenWindowsChildOptions({}, false).windowsHide, undefined)\n  assert.equal(hiddenWindowsChildOptions({ windowsHide: false }, true).windowsHide, false)\n})\n```\n\nIf the logic lives inline in a god-file (`main.ts`, `cli.py`,\n`gateway/run.py`) and extracting it feels disruptive: that's the actual\nsignal to do the extraction, not to regex around it.\n"},"files":{"AGENTS.md":"# Hermes Agent - Development Guide\n\nInstructions for AI coding assistants and developers working on the hermes-agent codebase.\n\n**Never give up on the right solution.**\n\n## What Hermes Is\n\nHermes is a personal AI agent that runs the same agent core across a CLI, a\nmessaging gateway (Telegram, Discord, Slack, and ~20 other platforms), a TUI,\nand an Electron desktop app. It learns across sessions (memory + skills),\ndelegates to subagents, runs scheduled jobs, and drives a real terminal and\nbrowser. It is extended primarily through **plugins and skills**, not by\ngrowing the core.\n\nTwo properties shape almost every design decision and are the lens for\nreviewing any change:\n\n- **Per-conversation prompt caching is sacred.** A long-lived conversation\n  reuses a cached prefix every turn. Anything that mutates past context,\n  swaps toolsets, or rebuilds the system prompt mid-conversation invalidates\n  that cache and multiplies the user's cost. We do not do it (the one\n  exception is context compression).\n- **The core is a narrow waist; capability lives at the edges.** Every model\n  tool we add is sent on every API call, so the bar for a new *core* tool is\n  high. Most new capability should arrive as a CLI command + skill, a\n  service-gated tool, or a plugin — not as core surface.\n\n## Contribution Rubric — What We Want / What We Don't\n\nThis is the project's intent layer. Use it two ways:\n\n1. **For humans and for your own work** — what gets merged and what gets\n   rejected, so a contribution aims at the target.\n2. **For automated review (the triage sweeper)** — guidance on when a PR is\n   safe to close on the three allowed reasons (`implemented_on_main`,\n   `cannot_reproduce`, `incoherent`) and, just as important, **when NOT to\n   close** one. Taste-based \"we don't want this / out of scope\" closes are NOT\n   an automated decision — those stay with a human maintainer. The sweeper's\n   job here is to recognize design intent and *avoid wrongly closing a\n   legitimate contribution*, not to make the won't-implement call itself.\n\nRead the balance right: Hermes ships a **lot** — most merges are bug fixes to\nreal reported behavior, and the product surface (platforms, channels,\nproviders, models, desktop/TUI features) expands aggressively and on purpose.\nThe restraint below is aimed squarely at the **core agent + the model tool\nschema**, the one place where every addition is paid for on every API call.\n\"Smallest footprint\" governs *how a capability is wired into the core*, NOT\nwhether the product is allowed to grow. We are expansive at the edges and\nconservative at the waist.\n\n### What we want\n\n- **Fix real bugs, well.** The bulk of what lands is `fix(...)` against an\n  actual reported symptom. A good fix reproduces the symptom on current\n  `main`, points to the exact line where it manifests, and fixes the whole bug\n  class — sibling call paths included — not just the one site the reporter hit.\n- **Expand reach at the edges.** New platform adapters, channels, providers,\n  models, and desktop/TUI/dashboard features are welcome and land routinely,\n  including large ones (a new messaging channel, a session-cap feature, a\n  Windows PTY bridge). Breadth in the product is a goal, not a footprint\n  concern — as long as it integrates with the existing setup/config UX\n  (`hermes tools`, `hermes setup`, auto-install) rather than bolting on a raw\n  env var.\n- **Refactor god-files into clean modules.** Extracting a multi-thousand-line\n  cluster out of `cli.py` / `run_agent.py` / `gateway/run.py` into a focused\n  mixin or module is wanted work, even when the diff is huge and mechanical\n  (large `+N/-N` refactors merge regularly). The \"every line traces to the\n  request\" test applies to *feature* PRs; a declared refactor's request IS the\n  extraction.\n- **Keep the core narrow.** New *model tools* are the expensive exception —\n  every tool ships on every API call. Prefer, in order: extend existing code →\n  CLI command + skill → service-gated tool (`check_fn`) → plugin → MCP server\n  in the catalog → new core tool (last resort). See \"The Footprint Ladder.\"\n- **Extend, don't duplicate.** Before adding a module/manager/hook, check\n  whether existing infrastructure already covers the use case. When several PRs\n  integrate the same *category*, design one shared interface instead of merging\n  them one at a time (see the ABC + orchestrator note under the Footprint\n  Ladder).\n- **Behavior contracts over snapshots.** Tests should assert how two pieces of\n  data must relate (invariants), not freeze a current value (model lists,\n  config version literals, enumeration counts). See \"Don't write\n  change-detector tests.\"\n- **E2E validation, not just green unit mocks.** For anything touching\n  resolution chains, config propagation, security boundaries, remote\n  backends, or file/network I/O, exercise the real path with real imports\n  against a temp `HERMES_HOME`. Mocks hide integration bugs.\n- **Cache-, alternation-, and invariant-safe.** Preserve prompt caching, strict\n  message role alternation (never two same-role messages in a row; never a\n  synthetic user message injected mid-loop), and a system prompt that is\n  byte-stable for the life of a conversation.\n- **Contributor credit preserved.** Salvage external work by cherry-picking\n  (rebase-merge) so authorship survives in git history; don't reimplement from\n  scratch when you can build on top.\n\n### What we don't want (rejected even when well-built)\n\n- **Speculative infrastructure.** Hooks, callbacks, or extension points with no\n  concrete consumer. Adding a hook is easy; removing one after plugins depend\n  on it is hard. A hook is NOT speculative if a contributor has a real, stated\n  use case — even if the consumer ships separately.\n- **New `HERMES_*` env vars for non-secret config.** `.env` is for secrets\n  only (API keys, tokens, passwords). All behavioral settings — timeouts,\n  thresholds, feature flags, display prefs — go in `config.yaml`. Bridge to an\n  internal env var if the mechanism needs one, but user-facing docs point to\n  `config.yaml`. Reject PRs that tell users to \"set X in your .env\" unless X\n  is a credential.\n- **A new core tool when terminal + file already do the job, or when a skill\n  would.** If the only barrier is file visibility on a remote backend, fix the\n  mount, not the toolset.\n- **Lazy-reading escape hatches on instructional tools.** No `offset`/`limit`\n  pagination on tools that load content the agent must read fully (skills,\n  prompts, playbooks). Models will read page 1 and skip the rest.\n- **\"Fixes\" that destroy the feature they secure.** A mitigation that kills the\n  feature's purpose is the wrong mitigation. Read the original commit's intent\n  (`git log -p -S`) before restricting behavior; find a fix that preserves the\n  feature.\n- **Outbound telemetry / usage attribution without opt-in gating.** No new\n  analytics, third-party identifier tagging, or attribution tags until a\n  generic user-facing opt-in (config gate + setup prompt + `hermes tools`\n  toggle) exists. Park behind a label, do not merge.\n- **Change-detector tests, cache-breaking mid-conversation, dead code wired in\n  without E2E proof, and plugins that touch core files.** Plugins live in their\n  own directory and work within the ABCs/hooks we provide; if a plugin needs\n  more, widen the generic plugin surface, don't special-case it in core.\n- **Third-party products / other people's projects integrated into the core\n  tree.** Observability backends, vendor SaaS integrations, analytics dashboards,\n  and similar \"someone else's product\" plugins do NOT land under `plugins/` in\n  this repo. They place an ongoing maintenance burden on us to keep them working\n  against a fast-moving core, for a backend we don't own. Ship them as a\n  **standalone plugin repo** users install into `~/.hermes/plugins/` (or via a\n  pip entry point), and promote them in the Nous Research Discord\n  (`#plugins-skills-and-skins`). This is a coupling-and-maintenance decision, not\n  a quality bar — the plugin can be excellent and still be a close. PRs that add\n  such a directory to the tree are closed with a pointer to publish it as its own\n  repo.\n\n### Before you call it a bug — verify the premise (and when NOT to close)\n\nThe most common reason a well-written PR gets closed is not code quality — it\nis that the change is built on a **wrong premise**, or it treats an\n**intentional design as a gap**. These patterns cut both ways: they tell a\nhuman reviewer what to scrutinize, and they tell the automated sweeper when a\nPR is NOT safe to close as `implemented_on_main` / `cannot_reproduce` (when in\ndoubt, leave it open for a human). They are distilled from real closes.\n\n- **\"Intentional design, not a gap.\"** A limitation that looks like an\n  oversight is often deliberate. Before \"fixing\" a missing link or a\n  restriction, ask whether the isolation IS the design. Example: profiles are\n  independent islands on purpose — a PR adding live config inheritance from the\n  default profile was closed because coupling profiles together is exactly what\n  the design prevents (the copy-at-creation `--clone` path already covers the\n  legitimate \"start from my default\" case). Read the original commit's intent\n  (`git log -p -S \"<symbol>\"`) before assuming something is unfinished.\n- **\"The premise doesn't hold against how X actually works.\"** A PR's\n  justification frequently rests on a wrong mental model of an existing\n  mechanism. Trace the real code/runtime before accepting the rationale. Two\n  real closes: a rate-limit \"re-probe during cooldown\" PR (the breaker only\n  trips on a *confirmed-empty* account bucket, so re-probing just hammers a\n  bucket we've already proven empty); a usage-accumulation fix whose new branch\n  **never executes at runtime** because an earlier guard already popped the\n  state it depended on. If you can't point to the exact line where the bug\n  manifests AND show the fix changes that line's behavior, you haven't verified\n  the premise.\n- **\"This fix was wrong — the absence/omission was deliberate.\"** Adding the\n  obvious-looking missing piece can break things the omission was protecting.\n  Example: restoring \"missing\" `__init__.py` files made a test tree importable\n  as a dotted package that shadowed the real plugin, deleting its `register()`\n  at import time. The absence was load-bearing.\n- **\"Overreached / resurrected an approach we'd moved past.\"** Scope creep that\n  supersedes an agreed-on base, or revives a direction the maintainers\n  deliberately closed, gets rejected even when the code works. Keep the change\n  to the narrow piece that was actually agreed; offer the rest as a focused\n  follow-up.\n\nThe throughline: **verify the claim AND the intent against the codebase before\nwriting or merging a fix.** A confirmed reproduction on current `main` plus a\nline-level account of where the fix acts beats a plausible-sounding rationale\nevery time. When in doubt about intent, it is cheaper to ask than to ship a\nfix that fights the design.\n\n### The Footprint Ladder (new capability decision)\n\nEach rung adds more permanent surface than the one above. Choose the highest\n(least-footprint) rung that correctly solves the problem:\n\n1. **Extend existing code** — the capability is a variation of something that\n   already exists. Zero new surface.\n2. **CLI command + skill** — manages config/state/infra expressible as shell\n   commands. The agent runs `hermes <subcommand>` guided by a skill. Zero\n   model-tool footprint. Default choice for subscriptions, scheduled tasks,\n   service setup. Examples: `hermes webhook`, `hermes cron`, `hermes tools`.\n3. **Service-gated tool (`check_fn`)** — needs structured params/returns AND\n   only appears when a prerequisite is configured. Zero footprint otherwise.\n   Examples: Home Assistant tools (gated on token), memory-provider tools.\n4. **Plugin** — third-party/niche/user-specific capability that doesn't ship in\n   core. Lives in `~/.hermes/plugins/` or a pip package, discovered at runtime.\n5. **MCP server (in the catalog)** — if the capability genuinely needs to be a\n   tool (structured I/O the agent invokes) but isn't core-fundamental, prefer\n   building it as an MCP server and adding it to the MCP catalog over growing\n   the core toolset. The agent connects to it through the built-in MCP client;\n   zero permanent core-schema footprint, and it's reusable by any MCP host.\n6. **New core tool** — only when the capability is fundamental, broadly useful\n   to nearly every user, and unreachable via terminal + file (or an MCP server).\n   Examples of correct core tools: terminal, read_file, web_search,\n   browser_navigate.\n\nWhen 3+ open PRs try to integrate the same *category* of thing (memory\nbackends, providers, notifiers), don't merge them one at a time — design an\nABC + orchestrator, wrap the existing built-in as the first provider, and turn\nthe competing PRs into plugins against that interface.\n\n### Surface capability is a property of the SESSION, never of the process env\n\nA tool that only works because of *who is on the other end of the connection* —\nthe desktop app's panes, the in-app browser, message reactions, Projects — must\nresolve its availability from the **session's own source**, not from an env var\non the backend process.\n\nThe client and the backend are separate machines on separate clocks. The\ndesktop app can be driving a backend Electron spawned locally, one over SSH,\none behind a plain URL + token, or Hermes Cloud. Only the first two are spawned\nby us and carry `HERMES_DESKTOP=1`. Every env-keyed GUI gate is therefore a\nsilent no-op on the other half of the topologies, and the failure is invisible:\nthe tool is stripped from the schema before the model ever sees it, on the same\nbackend whose platform hint is telling the model it's *\"chatting inside the\nHermes desktop app.\"*\n\nThe pattern that works:\n\n- **The toolset is the surface gate.** Keep the tools off `_HERMES_CORE_TOOLS`\n  (nobody else should pay their schema) and put them in a named toolset —\n  `desktop_ui`, `project`. The GUI gateway's `_load_enabled_toolsets(platform)`\n  folds that toolset in when the session's platform says GUI. One resolver,\n  every topology.\n- **`check_fn` answers reachability or user opt-in, not surface.** \"Is the\n  renderer bridge wired?\", \"did the user enable reactions?\" — fine. \"Was I\n  spawned by Electron?\" — not fine. `check_fn` results are also TTL-cached\n  process-wide (`tools/registry.py`), so a per-session answer does not belong\n  there at all: one process serves many sessions.\n- **Ask which identity you actually mean.** `HERMES_DESKTOP=1` legitimately\n  marks *\"this backend process was spawned by the app\"* — it gates the cron\n  ticker and web-dist handling correctly. It does NOT mean \"a GUI is watching\",\n  and the embedded terminal pane (`hermes --tui` against that same backend) is\n  the standing counterexample.\n\nSame test both ways: if the capability would still make sense with the client\non another machine, it is session-scoped. Cover it with a test that asserts the\nGUI session gets the tool **with the env var absent** — that's the assertion\nthe original gate could never have passed.\n\n## Development Environment\n\n```bash\n# Prefer .venv; fall back to venv if that's what your checkout has.\nsource .venv/bin/activate   # or: source venv/bin/activate\n```\n\n`scripts/run_tests.sh` probes `.venv` first, then `venv`, then\n`$HOME/.hermes/hermes-agent/venv` (for worktrees that share a venv with the\nmain checkout).\n\n## Project Structure\n\nFile counts shift constantly — don't treat the tree below as exhaustive.\nThe canonical source is the filesystem. The notes call out the load-bearing\nentry points you'll actually edit.\n\n```\nhermes-agent/\n├── run_agent.py          # AIAgent class — core conversation loop (~12k LOC)\n├── model_tools.py        # Tool orchestration, discover_builtin_tools(), handle_function_call()\n├── toolsets.py           # Toolset definitions, _HERMES_CORE_TOOLS list\n├── cli.py                # HermesCLI class — interactive CLI orchestrator (~11k LOC)\n├── hermes_state.py       # SessionDB — SQLite session store (FTS5 search)\n├── hermes_constants.py   # get_hermes_home(), display_hermes_home() — profile-aware paths\n├── hermes_logging.py     # setup_logging() — agent.log / errors.log / gateway.log (profile-aware)\n├── batch_runner.py       # Parallel batch processing\n├── agent/                # Agent internals (provider adapters, memory, caching, compression, etc.)\n├── hermes_cli/           # CLI subcommands, setup wizard, plugins loader, skin engine\n├── tools/                # Tool implementations — auto-discovered via tools/registry.py\n│   └── environments/     # Terminal backends (local, docker, ssh, modal, daytona, singularity)\n├── gateway/              # Messaging gateway — run.py + session.py + platforms/\n│   ├── platforms/        # Adapter per platform (telegram, discord, slack, whatsapp,\n│   │                     #   homeassistant, signal, matrix, mattermost, email, sms,\n│   │                     #   dingtalk, wecom, weixin, feishu, qqbot, bluebubbles,\n│   │                     #   yuanbao, webhook, api_server, ...). See ADDING_A_PLATFORM.md.\n│   └── builtin_hooks/    # Extension point for always-registered gateway hooks (none shipped)\n├── plugins/              # Plugin system (see \"Plugins\" section below)\n│   ├── memory/           # Memory-provider plugins (honcho, mem0, supermemory, ...)\n│   ├── context_engine/   # Context-engine plugins\n│   ├── model-providers/  # Inference backend plugins (openrouter, anthropic, gmi, ...)\n│   ├── kanban/           # Multi-agent board dispatcher + worker plugin\n│   ├── hermes-achievements/  # Gamified achievement tracking\n│   ├── observability/    # Metrics / traces / logs plugin\n│   ├── image_gen/        # Image-generation providers\n│   └── <others>/         # disk-cleanup, google_meet, platforms, spotify,\n│                         #   strike-freedom-cockpit, ...\n├── optional-skills/      # Heavier/niche skills shipped but NOT active by default\n├── skills/               # Built-in skills bundled with the repo\n├── ui-tui/               # Ink (React) terminal UI — `hermes --tui`\n│   └── src/              # entry.tsx, app.tsx, gatewayClient.ts + app/components/hooks/lib\n├── tui_gateway/          # Python JSON-RPC backend for the TUI\n├── acp_adapter/          # ACP server (VS Code / Zed / JetBrains integration)\n├── cron/                 # Scheduler — jobs.py, scheduler.py\n├── scripts/              # run_tests.sh, release.py, auxiliary scripts\n├── website/              # Docusaurus docs site\n└── tests/                # Pytest suite (~17k tests across ~900 files as of May 2026)\n```\n\n**User config:** `~/.hermes/config.yaml` (settings), `~/.hermes/.env` (API keys only).\n**Logs:** `~/.hermes/logs/` — `agent.log` (INFO+), `errors.log` (WARNING+),\n`gateway.log` when running the gateway. Profile-aware via `get_hermes_home()`.\nBrowse with `hermes logs [--follow] [--level ...] [--session ...]`.\n\n## TypeScript Style\n\nApplies to TypeScript across Hermes: desktop, TUI, website, and future TS packages.\n\n- Prefer small nanostores over component state when state is shared, reused, or read by distant UI.\n- Let each feature own its atoms. Chat state belongs near chat, shell state near shell, shared state in `src/store`.\n- Components that render from an atom should use `useStore`. Non-rendering actions should read with `$atom.get()`.\n- Do not pass state through three components when the leaf can subscribe to the atom.\n- Keep persistence beside the atom that owns it.\n- Keep route roots thin. They compose routes and shell; they should not become controllers.\n- No monolithic hooks. A hook should own one narrow job.\n- Prefer colocated action modules over hidden god hooks.\n- If a callback is pure side effect, use the terse void form:\n  `onState={st => void setGatewayState(st)}`.\n- Async UI handlers should make intent explicit:\n  `onClick={() => void save()}`.\n- Prefer interfaces for public props and shared object shapes. Avoid `type X = { ... }` for object props.\n- Extend React primitives for props: `React.ComponentProps<'button'>`, `React.ComponentProps<typeof Dialog>`, `Omit<...>`, `Pick<...>`.\n- Table-driven beats condition ladders when mapping ids, routes, or views.\n- `src/app` owns routes, pages, and page-specific components.\n- `src/store` owns shared atoms.\n- `src/lib` owns shared pure helpers.\n\n## File Dependency Chain\n\n```\ntools/registry.py  (no deps — imported by all tool files)\n       ↑\ntools/*.py  (each calls registry.register() at import time)\n       ↑\nmodel_tools.py  (imports tools/registry + triggers tool discovery)\n       ↑\nrun_agent.py, cli.py, batch_runner.py, environments/\n```\n\n---\n\n## AIAgent Class (run_agent.py)\n\nThe real `AIAgent.__init__` takes ~60 parameters (credentials, routing, callbacks,\nsession context, budget, credential pool, etc.). The signature below is the\nminimum subset you'll usually touch — read `run_agent.py` for the full list.\n\n```python\nclass AIAgent:\n    def __init__(self,\n        base_url: str = None,\n        api_key: str = None,\n        provider: str = None,\n        api_mode: str = None,              # \"chat_completions\" | \"codex_responses\" | ...\n        model: str = \"\",                   # empty → resolved from config/provider later\n        max_iterations: int = 500,         # tool-calling iterations (shared with subagents)\n        enabled_toolsets: list = None,\n        disabled_toolsets: list = None,\n        quiet_mode: bool = False,\n        save_trajectories: bool = False,\n        platform: str = None,              # \"cli\", \"telegram\", etc.\n        session_id: str = None,\n        skip_context_files: bool = False,\n        skip_memory: bool = False,\n        credential_pool=None,\n        # ... plus callbacks, thread/user/chat IDs, iteration_budget, fallback_model,\n        # checkpoints config, prefill_messages, service_tier, reasoning_config, etc.\n    ): ...\n\n    def chat(self, message: str) -> str:\n        \"\"\"Simple interface — returns final response string.\"\"\"\n\n    def run_conversation(self, user_message: str, system_message: str = None,\n                         conversation_history: list = None, task_id: str = None) -> dict:\n        \"\"\"Full interface — returns dict with final_response + messages.\"\"\"\n```\n\n### Agent Loop\n\nThe core loop is inside `run_conversation()` — entirely synchronous, with\ninterrupt checks, budget tracking, and a one-turn grace call:\n\n```python\nwhile (api_call_count < self.max_iterations and self.iteration_budget.remaining > 0) \\\n        or self._budget_grace_call:\n    if self._interrupt_requested: break\n    response = client.chat.completions.create(model=model, messages=messages, tools=tool_schemas)\n    if response.tool_calls:\n        for tool_call in response.tool_calls:\n            result = handle_function_call(tool_call.name, tool_call.args, task_id)\n            messages.append(tool_result_message(result))\n        api_call_count += 1\n    else:\n        return response.content\n```\n\nMessages follow OpenAI format: `{\"role\": \"system/user/assistant/tool\", ...}`.\nReasoning content is stored in `assistant_msg[\"reasoning\"]`.\n\n---\n\n## CLI Architecture (cli.py)\n\n- **Rich** for banner/panels, **prompt_toolkit** for input with autocomplete\n- **KawaiiSpinner** (`agent/display.py`) — animated faces during API calls, `┊` activity feed for tool results\n- `load_cli_config()` in cli.py merges hardcoded defaults + user config YAML\n- **Skin engine** (`hermes_cli/skin_engine.py`) — data-driven CLI theming; initialized from `display.skin` config key at startup; skins customize banner colors, spinner faces/verbs/wings, tool prefix, response box, branding text\n- `process_command()` is a method on `HermesCLI` — dispatches on canonical command name resolved via `resolve_command()` from the central registry\n- Skill slash commands: `agent/skill_commands.py` scans `~/.hermes/skills/`, injects as **user message** (not system prompt) to preserve prompt caching\n\n### Slash Command Registry (`hermes_cli/commands.py`)\n\nAll slash commands are defined in a central `COMMAND_REGISTRY` list of `CommandDef` objects. Every downstream consumer derives from this registry automatically:\n\n- **CLI** — `process_command()` resolves aliases via `resolve_command()`, dispatches on canonical name\n- **Gateway** — `GATEWAY_KNOWN_COMMANDS` frozenset for hook emission, `resolve_command()` for dispatch\n- **Gateway help** — `gateway_help_lines()` generates `/help` output\n- **Telegram** — `telegram_bot_commands()` generates the BotCommand menu\n- **Slack** — `slack_subcommand_map()` generates `/hermes` subcommand routing\n- **Autocomplete** — `COMMANDS` flat dict feeds `SlashCommandCompleter`\n- **CLI help** — `COMMANDS_BY_CATEGORY` dict feeds `show_help()`\n\n### Adding a Slash Command\n\n1. Add a `CommandDef` entry to `COMMAND_REGISTRY` in `hermes_cli/commands.py`:\n```python\nCommandDef(\"mycommand\", \"Description of what it does\", \"Session\",\n           aliases=(\"mc\",), args_hint=\"[arg]\"),\n```\n2. Add handler in `HermesCLI.process_command()` in `cli.py`:\n```python\nelif canonical == \"mycommand\":\n    self._handle_mycommand(cmd_original)\n```\n3. If the command is available in the gateway, add a handler in `gateway/run.py`:\n```python\nif canonical == \"mycommand\":\n    return await self._handle_mycommand(event)\n```\n4. For persistent settings, use `save_config_value()` in `cli.py`\n\n**CommandDef fields:**\n- `name` — canonical name without slash (e.g. `\"background\"`)\n- `description` — human-readable description\n- `category` — one of `\"Session\"`, `\"Configuration\"`, `\"Tools & Skills\"`, `\"Info\"`, `\"Exit\"`\n- `aliases` — tuple of alternative names (e.g. `(\"bg\",)`)\n- `args_hint` — argument placeholder shown in help (e.g. `\"<prompt>\"`, `\"[name]\"`)\n- `cli_only` — only available in the interactive CLI\n- `gateway_only` — only available in messaging platforms\n- `gateway_config_gate` — config dotpath (e.g. `\"display.tool_progress_command\"`); when set on a `cli_only` command, the command becomes available in the gateway if the config value is truthy. `GATEWAY_KNOWN_COMMANDS` always includes config-gated commands so the gateway can dispatch them; help/menus only show them when the gate is open.\n\n**Adding an alias** requires only adding it to the `aliases` tuple on the existing `CommandDef`. No other file changes needed — dispatch, help text, Telegram menu, Slack mapping, and autocomplete all update automatically.\n\n---\n\n## TUI Architecture (ui-tui + tui_gateway)\n\nThe TUI is a full replacement for the classic (prompt_toolkit) CLI, activated via `hermes --tui` or `HERMES_TUI=1`.\n\n### Process Model\n\n```\nhermes --tui\n  └─ Node (Ink)  ──stdio JSON-RPC──  Python (tui_gateway)\n       │                                  └─ AIAgent + tools + sessions\n       └─ renders transcript, composer, prompts, activity\n```\n\nTypeScript owns the screen. Python owns sessions, tools, model calls, and slash command logic.\n\n### Transport\n\nNewline-delimited JSON-RPC over stdio. Requests from Ink, events from Python. See `tui_gateway/server.py` for the full method/event catalog.\n\n### Key Surfaces\n\n| Surface | Ink component | Gateway method |\n|---------|---------------|----------------|\n| Chat streaming | `app.tsx` + `messageLine.tsx` | `prompt.submit` → `message.delta/complete` |\n| Tool activity | `thinking.tsx` | `tool.start/progress/complete` |\n| Approvals | `prompts.tsx` | `approval.respond` ← `approval.request` |\n| Clarify/sudo/secret | `prompts.tsx`, `maskedPrompt.tsx` | `clarify/sudo/secret.respond` |\n| Session picker | `sessionPicker.tsx` | `session.list/resume` |\n| Slash commands | Local handler + fallthrough | `slash.exec` → `_SlashWorker`, `command.dispatch` |\n| Completions | `useCompletion` hook | `complete.slash`, `complete.path` |\n| Theming | `theme.ts` + `branding.tsx` | `gateway.ready` with skin data |\n\n### Slash Command Flow\n\n1. Built-in client commands (`/help`, `/quit`, `/clear`, `/resume`, `/copy`, `/paste`, etc.) handled locally in `app.tsx`\n2. Everything else → `slash.exec` (runs in persistent `_SlashWorker` subprocess) → `command.dispatch` fallback\n\n### Dev Commands\n\n```bash\ncd ui-tui\nnpm install       # first time\nnpm run dev       # watch mode (rebuilds hermes-ink + tsx --watch)\nnpm start         # production\nnpm run build     # full build (hermes-ink + tsc)\nnpm run typecheck # typecheck only (tsc --noEmit)\nnpm run lint      # eslint\nnpm run fmt       # prettier\nnpm test          # vitest\n```\n\n### TUI in the Dashboard (`hermes dashboard` → `/chat`)\n\nThe dashboard embeds the real `hermes --tui` — **not** a rewrite.  See `hermes_cli/pty_bridge.py` + the `@app.websocket(\"/api/pty\")` endpoint in `hermes_cli/web_server.py`.\n\n- Browser loads `web/src/pages/ChatPage.tsx`, which mounts xterm.js's `Terminal` with the WebGL renderer, `@xterm/addon-fit` for container-driven resize, and `@xterm/addon-unicode11` for modern wide-character widths.\n- `/api/pty?token=…` upgrades to a WebSocket; auth uses the same ephemeral `_SESSION_TOKEN` as REST, via query param (browsers can't set `Authorization` on WS upgrade).\n- The server spawns whatever `hermes --tui` would spawn, through `ptyprocess` (POSIX PTY — WSL works, native Windows does not).\n- Frames: raw PTY bytes each direction; resize via `\\x1b[RESIZE:<cols>;<rows>]` intercepted on the server and applied with `TIOCSWINSZ`.\n\n**Do not re-implement the primary chat experience in React.** The main transcript, composer/input flow (including slash-command behavior), and PTY-backed terminal belong to the embedded `hermes --tui` — anything new you add to Ink shows up in the dashboard automatically. If you find yourself rebuilding the transcript or composer for the dashboard, stop and extend Ink instead.\n\n**Structured React UI around the TUI is allowed when it is not a second chat surface.** Sidebar widgets, inspectors, summaries, status panels, and similar supporting views (e.g. `ChatSidebar`, `ModelPickerDialog`, `ToolCall`) are fine when they complement the embedded TUI rather than replacing the transcript / composer / terminal. Keep their state independent of the PTY child's session and surface their failures non-destructively so the terminal pane keeps working unimpaired.\n\n### Electron Desktop Chat App (`apps/desktop/`)\n\nA **separate** chat surface from both the classic CLI and the dashboard's embedded TUI. It is an Electron + React + nanostore renderer (`@assistant-ui/react`) that talks to a `tui_gateway` backend over JSON-RPC (`requestGateway(method, params)`). The WebSocket/JSON-RPC transport lives in the framework-agnostic `apps/shared` package (`@hermes/shared` — `JsonRpcGatewayClient` + WS URL helpers), which the web dashboard (`web/`) also consumes; **desktop has no build/runtime dependency on the dashboard frontend** — it spawns a headless `hermes serve` backend server (the same gateway `dashboard` serves, minus the browser UI entirely: `serve` sets `headless_backend=True`, so `cmd_dashboard` skips `_build_web_ui` AND exports `HERMES_SERVE_HEADLESS=1` so `mount_spa()` disables the SPA even if a stray `web_dist/` exists — only the JSON-RPC/WS/API surface is reachable). `dashboard` and `serve` share `cmd_dashboard`/`start_server` but are independent surfaces — neither launches the other. The one exception is a backward-compat *fallback*: `serve` is newer, so the desktop spawn (`electron/backend-command.ts` + `backendSupportsServe()` in `electron/main.ts`) detects whether the resolved runtime registers `serve` and, only when it does not (an older managed install / PATH `hermes` the app hasn't updated yet), rewrites the argv to the legacy `dashboard --no-open`. Without that, a new app against an un-upgraded runtime would crash on an unknown subcommand and brick every mid-upgrade user. It does NOT embed `hermes --tui` — it has its own composer, transcript, and slash-command pipeline. For scoped Desktop architecture, state, resolver, transport, and testing rules, read `apps/desktop/AGENTS.md`.\n\n**Slash commands in the desktop app are curated client-side, then dispatched to the backend.** The pipeline:\n\n- **Backend already provides everything.** `tui_gateway/server.py` `commands.catalog` (empty-query list) and `complete.slash` (typed-query completions) both include built-in commands, user `quick_commands`, AND skill-derived commands (`scan_skill_commands()` / `get_skill_commands()`). The desktop app does not need a new RPC to see skills.\n- **The renderer curates via `apps/desktop/src/lib/desktop-slash-commands.ts`.** This is the load-bearing file. It holds `DESKTOP_COMMAND_SPECS` (the built-ins and their Desktop surfaces) plus `NO_DESKTOP_SURFACE` block-lists for terminal-only / messaging-only / picker-owned / settings-owned / advanced commands that should NOT clutter the desktop popover.\n  - `isDesktopSlashCommand(name)` — gates **execution**. Returns true for built-ins AND for any non-built-in (skill / quick command), so typed extension commands run.\n  - `isDesktopSlashSuggestion(name)` — gates **discovery/completion**. Used by BOTH completion paths in `app/chat/composer/hooks/use-slash-completions.ts` (empty-query catalog filter + typed-query `complete.slash` filter) and by `filterDesktopCommandsCatalog`.\n  - `isDesktopSlashExtensionCommand(name)` — true when the command is NOT a known Hermes built-in (i.e. a skill or user quick command). Both suggestion and catalog-filter paths allow extensions through so skill commands surface in the palette. (Added when fixing \"skill commands missing from the desktop slash palette\" — the curated allow-list was silently dropping every skill/quick command from completions even though they executed fine when typed.)\n- **Dispatch** lives in `app/session/hooks/use-prompt-actions/slash.ts` (`runSlash`): built-ins that the desktop owns (`/skin`, `/help`, `/new`, …) are handled locally or via `commands.catalog`; everything else goes to `slash.exec`, falling back to `command.dispatch` (which the gateway resolves into skill / alias / exec directives). A skill command resolves to `{type: \"skill\", message}` and is submitted as a normal prompt.\n\n**Rule:** the desktop slash palette's curation is about hiding noise (terminal-only / messaging-only built-ins), NOT about hiding user-activated extensions. Skill commands and `quick_commands` are extensions the backend surfaces — they belong in completions. If you tighten `desktop-slash-commands.ts`, keep `isDesktopSlashExtensionCommand` flowing into both the suggestion and catalog-filter paths. Tests: from `apps/desktop`, run `npx vitest run src/lib/desktop-slash-commands.test.ts` (workspace dependencies are installed at the repo root).\n\n---\n\n## Adding New Tools\n\nBefore adding any tool, settle the footprint question first (see \"The\nFootprint Ladder\" in the Contribution Rubric): most capabilities should NOT\nbe core tools. For custom or local-only tools, do **not** edit Hermes core.\nUse the plugin route instead: create `~/.hermes/plugins/<name>/plugin.yaml`\nand `~/.hermes/plugins/<name>/__init__.py`, then register tools with\n`ctx.register_tool(...)`. Plugin toolsets are discovered automatically and can be\nenabled or disabled without touching `tools/` or `toolsets.py`.\n\nUse the built-in route below only when the user is explicitly contributing a new\ncore Hermes tool that should ship in the base system.\n\nBuilt-in/core tools require changes in **2 files**:\n\n**1. Create `tools/your_tool.py`:**\n```python\nimport json, os\nfrom tools.registry import registry\n\ndef check_requirements() -> bool:\n    return bool(os.getenv(\"EXAMPLE_API_KEY\"))\n\ndef example_tool(param: str, task_id: str = None) -> str:\n    return json.dumps({\"success\": True, \"data\": \"...\"})\n\nregistry.register(\n    name=\"example_tool\",\n    toolset=\"example\",\n    schema={\"name\": \"example_tool\", \"description\": \"...\", \"parameters\": {...}},\n    handler=lambda args, **kw: example_tool(param=args.get(\"param\", \"\"), task_id=kw.get(\"task_id\")),\n    check_fn=check_requirements,\n    requires_env=[\"EXAMPLE_API_KEY\"],\n)\n```\n\n**2. Add to `toolsets.py`** — either `_HERMES_CORE_TOOLS` (all platforms) or a new toolset. **This step is required:** auto-discovery imports the tool and registers its schema, but the tool is only *exposed to an agent* if its name appears in a toolset. `_HERMES_CORE_TOOLS` is not dead code — it's the default bundle every platform's base toolset inherits from.\n\nAuto-discovery: any `tools/*.py` file with a top-level `registry.register()` call is imported automatically — no manual import list to maintain. Wiring into a toolset is still a deliberate, manual step.\n\nThe registry handles schema collection, dispatch, availability checking, and error wrapping. All handlers MUST return a JSON string.\n\n**Path references in tool schemas**: If the schema description mentions file paths (e.g. default output directories), use `display_hermes_home()` to make them profile-aware. The schema is generated at import time, which is after `_apply_profile_override()` sets `HERMES_HOME`.\n\n**State files**: If a tool stores persistent state (caches, logs, checkpoints), use `get_hermes_home()` for the base directory — never `Path.home() / \".hermes\"`. This ensures each profile gets its own state.\n\n**Agent-level tools** (todo, memory): intercepted by `run_agent.py` before `handle_function_call()`. See `tools/todo_tool.py` for the pattern.\n\n---\n\n## Dependency Pinning Policy\n\nAll dependencies must have upper bounds to limit supply-chain attack surface.\nThis policy was established after the litellm compromise (PR #2796, #2810) and\nreinforced after the Mini Shai-Hulud worm campaign (May 2026).\n\n| Source type | Treatment | Example |\n|---|---|---|\n| PyPI package | `>=floor,<next_major` | `\"httpx>=0.28.1,<1\"` |\n| Git URL | Commit SHA | `git+https://...@<40-char-sha>` |\n| GitHub Actions | Commit SHA + comment | `uses: actions/checkout@<sha>  # v4` |\n| CI-only pip | `==exact` | `pyyaml==6.0.2` |\n\n**When adding a new dependency to `pyproject.toml`:**\n1. Pin to `>=current_version,<next_major` for post-1.0 (e.g. `>=1.5.0,<2`).\n2. For pre-1.0 packages, use `<0.(current_minor + 2)` (e.g. `>=0.29,<0.32`).\n3. Never commit a bare `>=X.Y.Z` without a ceiling — CI and reviewers will reject it.\n4. Run `uv lock` to regenerate `uv.lock` with hashes.\n\nReference: #2810 (bounds pass), #9801 (SHA pinning + audit CI).\n\n---\n\n## Adding Configuration\n\n### config.yaml options:\n1. Add to `DEFAULT_CONFIG` in `hermes_cli/config.py`\n2. Bump `_config_version` (check the current value at the top of `DEFAULT_CONFIG`)\n   ONLY if you need to actively migrate/transform existing user config\n   (renaming keys, changing structure). Adding a new key to an existing\n   section is handled automatically by the deep-merge and does NOT require\n   a version bump.\n\n### Top-level `config.yaml` sections (non-exhaustive):\n\n`model`, `agent`, `terminal`, `compression`, `display`, `stt`, `tts`,\n`memory`, `security`, `delegation`, `smart_model_routing`, `checkpoints`,\n`auxiliary`, `curator`, `skills`, `gateway`, `logging`, `cron`, `profiles`,\n`plugins`, `honcho`.\n\n`auxiliary` holds per-task overrides for side-LLM work (curator, vision,\nembedding, title generation, session_search, etc.) — each task can pin\nits own provider/model/base_url/max_tokens/reasoning_effort. See\n`agent/auxiliary_client.py::_resolve_auto` for resolution order.\n\n`curator` holds the background skill-maintenance config —\n`enabled`, `interval_hours`, `min_idle_hours`, `stale_after_days`,\n`archive_after_days`, `backup` (nested).\n\n### .env variables (SECRETS ONLY — API keys, tokens, passwords):\n1. Add to `OPTIONAL_ENV_VARS` in `hermes_cli/config.py` with metadata:\n```python\n\"NEW_API_KEY\": {\n    \"description\": \"What it's for\",\n    \"prompt\": \"Display name\",\n    \"url\": \"https://...\",\n    \"password\": True,\n    \"category\": \"tool\",  # provider, tool, messaging, setting\n},\n```\n\nNon-secret settings (timeouts, thresholds, feature flags, paths, display\npreferences) belong in `config.yaml`, not `.env`. If internal code needs an\nenv var mirror for backward compatibility, bridge it from `config.yaml` to\nthe env var in code (see `gateway_timeout`, `terminal.cwd` → `TERMINAL_CWD`).\n\n### Config loaders (three paths — know which one you're in):\n\n| Loader | Used by | Location |\n|--------|---------|----------|\n| `load_cli_config()` | CLI mode | `cli.py` — merges CLI-specific defaults + user YAML |\n| `load_config()` | `hermes tools`, `hermes setup`, most CLI subcommands | `hermes_cli/config.py` — merges `DEFAULT_CONFIG` + user YAML |\n| Direct YAML load | Gateway runtime | `gateway/run.py` + `gateway/config.py` — reads user YAML raw |\n\nIf you add a new key and the CLI sees it but the gateway doesn't (or vice\nversa), you're on the wrong loader. Check `DEFAULT_CONFIG` coverage.\n\n### Working directory:\n- **CLI** — uses the process's current directory (`os.getcwd()`).\n- **Messaging** — uses `terminal.cwd` from `config.yaml`. The gateway bridges this\n  to the `TERMINAL_CWD` env var for child tools. **`MESSAGING_CWD` has been\n  removed** — the config loader prints a deprecation warning if it's set in\n  `.env`. Same for `TERMINAL_CWD` in `.env`; the canonical setting is\n  `terminal.cwd` in `config.yaml`.\n\n---\n\n## Skin/Theme System\n\nThe skin engine (`hermes_cli/skin_engine.py`) provides data-driven CLI visual customization. Skins are **pure data** — no code changes needed to add a new skin.\n\n### Architecture\n\n```\nhermes_cli/skin_engine.py    # SkinConfig dataclass, built-in skins, YAML loader\n~/.hermes/skins/*.yaml       # User-installed custom skins (drop-in)\n```\n\n- `init_skin_from_config()` — called at CLI startup, reads `display.skin` from config\n- `get_active_skin()` — returns cached `SkinConfig` for the current skin\n- `set_active_skin(name)` — switches skin at runtime (used by `/skin` command)\n- `load_skin(name)` — loads from user skins first, then built-ins, then falls back to default\n- Missing skin values inherit from the `default` skin automatically\n\n### What skins customize\n\n| Element | Skin Key | Used By |\n|---------|----------|---------|\n| Banner panel border | `colors.banner_border` | `banner.py` |\n| Banner panel title | `colors.banner_title` | `banner.py` |\n| Banner section headers | `colors.banner_accent` | `banner.py` |\n| Banner dim text | `colors.banner_dim` | `banner.py` |\n| Banner body text | `colors.banner_text` | `banner.py` |\n| Response box border | `colors.response_border` | `cli.py` |\n| Spinner faces (waiting) | `spinner.waiting_faces` | `display.py` |\n| Spinner faces (thinking) | `spinner.thinking_faces` | `display.py` |\n| Spinner verbs | `spinner.thinking_verbs` | `display.py` |\n| Spinner wings (optional) | `spinner.wings` | `display.py` |\n| Tool output prefix | `tool_prefix` | `display.py` |\n| Per-tool emojis | `tool_emojis` | `display.py` → `get_tool_emoji()` |\n| Agent name | `branding.agent_name` | `banner.py`, `cli.py` |\n| Welcome message | `branding.welcome` | `cli.py` |\n| Response box label | `branding.response_label` | `cli.py` |\n| Prompt symbol | `branding.prompt_symbol` | `cli.py` |\n\n### Built-in skins\n\n- `default` — Classic Hermes gold/kawaii (the current look)\n- `ares` — Crimson/bronze war-god theme with custom spinner wings\n- `mono` — Clean grayscale monochrome\n- `slate` — Cool blue developer-focused theme\n\n### Adding a built-in skin\n\nAdd to `_BUILTIN_SKINS` dict in `hermes_cli/skin_engine.py`:\n\n```python\n\"mytheme\": {\n    \"name\": \"mytheme\",\n    \"description\": \"Short description\",\n    \"colors\": { ... },\n    \"spinner\": { ... },\n    \"branding\": { ... },\n    \"tool_prefix\": \"┊\",\n},\n```\n\n### User skins (YAML)\n\nUsers create `~/.hermes/skins/<name>.yaml`:\n\n```yaml\nname: cyberpunk\ndescription: Neon-soaked terminal theme\n\ncolors:\n  banner_border: \"#FF00FF\"\n  banner_title: \"#00FFFF\"\n  banner_accent: \"#FF1493\"\n\nspinner:\n  thinking_verbs: [\"jacking in\", \"decrypting\", \"uploading\"]\n  wings:\n    - [\"⟨⚡\", \"⚡⟩\"]\n\nbranding:\n  agent_name: \"Cyber Agent\"\n  response_label: \" ⚡ Cyber \"\n\ntool_prefix: \"▏\"\n```\n\nActivate with `/skin cyberpunk` or `display.skin: cyberpunk` in config.yaml.\n\n---\n\n## Plugins\n\nHermes has two plugin surfaces. Both live under `plugins/` in the repo so\nrepo-shipped plugins can be discovered alongside user-installed ones in\n`~/.hermes/plugins/` and pip-installed entry points.\n\n### General plugins (`hermes_cli/plugins.py` + `plugins/<name>/`)\n\n`PluginManager` discovers plugins from `~/.hermes/plugins/`, `./.hermes/plugins/`,\nand pip entry points. Each plugin exposes a `register(ctx)` function that\ncan:\n\n- Register Python-callback lifecycle hooks:\n  `pre_tool_call`, `post_tool_call`, `pre_llm_call`, `post_llm_call`,\n  `on_session_start`, `on_session_end`\n- Register new tools via `ctx.register_tool(...)`\n- Register CLI subcommands via `ctx.register_cli_command(...)` — the\n  plugin's argparse tree is wired into `hermes` at startup so\n  `hermes <pluginname> <subcmd>` works with no change to `main.py`\n\nHooks are invoked from `model_tools.py` (pre/post tool) and `run_agent.py`\n(lifecycle). **Discovery timing pitfall:** `discover_plugins()` only runs\nas a side effect of importing `model_tools.py`. Code paths that read plugin\nstate without importing `model_tools.py` first must call `discover_plugins()`\nexplicitly (it's idempotent).\n\n#### Native plugin compatibility policy\n\nThe canonical contract and deprecation policy live in\n`website/docs/developer-guide/plugins/index.md#native-plugin-compatibility-contract`.\nCompatibility is enforced as a behavior contract, not through a monolithic\n`PLUGIN_API_VERSION`, a manifest-wide native `api:` match, or version literals\non unrelated payloads. Keep documented plugin surfaces additive:\n\n- add hook payload data as keyword fields; signature-inspect callbacks so old\n  narrow signatures receive only fields they declare, while `**kwargs`\n  callbacks receive the complete payload;\n- do not remove or rename `PluginContext` methods; make new parameters optional\n  with defaults and keyword-only where possible;\n- ignore unknown native manifest fields;\n- give new provider methods default implementations, and signature-inspect\n  optional callback kwargs rather than forwarding them unconditionally;\n- use a local schema version only for a capability with a wire or persisted\n  contract, and preserve old state/config/session replay or ship a migration.\n\nDeprecations require a once-per-process warning, a documented replacement and\nmigration note, and at least two subsequent minor releases before removal.\nCompatibility tests must load frozen plugins through the real discovery path\nand assert outcomes. Do not replace these with exact registry/catalog counts,\nsource-reading tests, or assertions that a global version literal changed.\n\n### Memory-provider plugins (`plugins/memory/<name>/`)\n\nSeparate discovery system for pluggable memory backends. Current built-in\nproviders include **honcho, mem0, supermemory, byterover, hindsight,\nholographic, openviking, retaindb**.\n\nDiscovery covers the same four sources as the general `PluginManager` —\nbundled, `$HERMES_HOME/plugins/`, `./.hermes/plugins/` (opt-in via\n`HERMES_ENABLE_PROJECT_PLUGINS`), and `hermes_agent.memory_providers` entry\npoints — but with **bundled-first** precedence, the reverse of the general\nsystem's later-wins order: a memory provider is activated by name, so a\ndropped-in directory must not be able to shadow a shipped one. Discovery\nenumerates without importing; nothing runs until `memory.provider` names it.\n\nEach provider implements the `MemoryProvider` ABC (see `agent/memory_provider.py`)\nand is orchestrated by `agent/memory_manager.py`. Lifecycle hooks include\n`sync_turn(turn_messages)`, `prefetch(query)`, `shutdown()`, and optional\n`post_setup(hermes_home, config)` for setup-wizard integration.\n\n**CLI commands via `plugins/memory/<name>/cli.py`:** if a memory plugin\ndefines `register_cli(subparser)`, `discover_plugin_cli_commands()` finds\nit at argparse setup time and wires it into `hermes <plugin>`. The\nframework only exposes CLI commands for the **currently active** memory\nprovider (read from `memory.provider` in config.yaml), so disabled\nproviders don't clutter `hermes --help`.\n\n**Rule (Teknium, May 2026):** plugins MUST NOT modify core files\n(`run_agent.py`, `cli.py`, `gateway/run.py`, `hermes_cli/main.py`, etc.).\nIf a plugin needs a capability the framework doesn't expose, expand the\ngeneric plugin surface (new hook, new ctx method) — never hardcode\nplugin-specific logic into core. PR #5295 removed 95 lines of hardcoded\nhoncho argparse from `main.py` for exactly this reason.\n\n**No new in-tree memory providers (policy, May 2026):** the set of\nbuilt-in memory providers under `plugins/memory/` is closed. New memory\nbackends must ship as **standalone plugin repos** that users install\ninto `~/.hermes/plugins/` (or via pip entry points) — they implement\nthe same `MemoryProvider` ABC, register through the same discovery\npath, and integrate via `hermes memory setup` / `post_setup()` without\nlanding in this tree. PRs that add a new directory under\n`plugins/memory/` will be closed with a pointer to publish the\nprovider as its own repo. Existing in-tree providers stay; bug fixes\nto them are welcome.\n\n**No new third-party-product plugins in-tree (policy, June 2026):** the\nsame rule applies beyond memory providers. Plugins that integrate\nsomeone else's product or project — observability/metrics backends,\nvendor SaaS connectors, analytics dashboards, paid-service tie-ins —\nmust ship as **standalone plugin repos** that users install into\n`~/.hermes/plugins/` (or via pip entry points). They register through\nthe existing plugin discovery path and use the ABCs/hooks/ctx surface\nwe expose; nothing special is needed in core. The reason is\nmaintenance load: every product we absorb into the tree becomes our\nburden to keep working against a fast-moving core, for a backend we\ndon't own. Promote standalone plugins in the Nous Research Discord\n(`#plugins-skills-and-skins`). PRs that add such a directory under\n`plugins/` are closed with a pointer to publish it as its own repo —\nthis is a coupling decision, not a quality judgment. (The\n`observability/`, `kanban/`, `disk-cleanup/`, etc. directories already\nin the tree are existing precedent, not an invitation to add more\nthird-party-product plugins alongside them.)\n\n### Model-provider plugins (`plugins/model-providers/<name>/`)\n\nEvery inference backend (openrouter, anthropic, gmi, deepseek, nvidia, …)\nships as a plugin here. Each plugin's `__init__.py` calls\n`providers.register_provider(ProviderProfile(...))` at module load.\n`providers/__init__.py._discover_providers()` is a **lazy, separate\ndiscovery system** — scanned on first `get_provider_profile()` or\n`list_providers()` call, NOT by the general PluginManager.\n\nScan order:\n1. Bundled: `<repo>/plugins/model-providers/<name>/`\n2. User: `$HERMES_HOME/plugins/model-providers/<name>/`\n3. Legacy: `<repo>/providers/<name>.py` (back-compat)\n\nUser plugins of the same name override bundled ones — `register_provider()`\nis last-writer-wins. This lets third parties swap out any built-in\nprofile without a repo patch.\n\nThe general PluginManager records `kind: model-provider` manifests but does\nNOT import them (would double-instantiate `ProviderProfile`). Plugins\nwithout an explicit `kind:` get auto-coerced via a source-text heuristic\n(`register_provider` + `ProviderProfile` in `__init__.py`).\n\nFull authoring guide: `website/docs/developer-guide/model-provider-plugin.md`.\n\n### Dashboard / context-engine / image-gen plugin directories\n\n`plugins/context_engine/`, `plugins/image_gen/`, etc. follow the same\npattern (ABC + orchestrator + per-plugin directory). Context engines\nplug into `agent/context_engine.py`; image-gen providers into\n`agent/image_gen_provider.py`. Reference / docs-companion plugins\n(`example-dashboard`, `strike-freedom-cockpit`, `plugin-llm-example`,\n`plugin-llm-async-example`) live in the\n[`hermes-example-plugins`](https://github.com/NousResearch/hermes-example-plugins)\ncompanion repo, not in this tree.\n\n---\n\n## Skills\n\nTwo parallel surfaces:\n\n- **`skills/`** — built-in skills shipped and loadable by default.\n  Organized by category directories (e.g. `skills/github/`, `skills/mlops/`).\n- **`optional-skills/`** — heavier or niche skills shipped with the repo but\n  NOT active by default. Installed explicitly via\n  `hermes skills install official/<category>/<skill>`. Adapter lives in\n  `tools/skills_hub.py` (`OptionalSkillSource`). Categories include\n  `autonomous-ai-agents`, `blockchain`, `communication`, `creative`,\n  `devops`, `email`, `health`, `mcp`, `migration`, `mlops`, `productivity`,\n  `research`, `security`, `web-development`.\n\nWhen reviewing skill PRs, check which directory they target — heavy-dep or\nniche skills belong in `optional-skills/`.\n\n### SKILL.md frontmatter\n\nStandard fields: `name`, `description`, `version`, `author`, `license`,\n`platforms` (OS-gating list: `[macos]`, `[linux, macos]`, ...),\n`metadata.hermes.tags`, `metadata.hermes.category`,\n`metadata.hermes.related_skills`, `metadata.hermes.config` (config.yaml\nsettings the skill needs — stored under `skills.config.<key>`, prompted\nduring setup, injected at load time).\n\nTop-level `tags:` and `category:` are also accepted and mirrored from\n`metadata.hermes.*` by the loader.\n\n### Skill authoring standards (HARDLINE)\n\nEvery new or modernized skill — bundled, optional, or contributed —\nmust meet these standards before merge. Reviewers reject PRs that\nviolate them.\n\n1. **`description` ≤ 60 characters, one sentence, ends with a period.**\n   Long descriptions bloat skill listings and dilute the model's\n   attention when many skills are loaded. State the capability, not\n   the implementation. No marketing words (\"powerful\",\n   \"comprehensive\", \"seamless\", \"advanced\"). Don't repeat the skill\n   name. Verify with:\n   ```python\n   import re, pathlib\n   m = re.search(r'^description: (.*)$',\n                 pathlib.Path('skills/<cat>/<name>/SKILL.md').read_text(),\n                 re.MULTILINE)\n   assert len(m.group(1)) <= 60, len(m.group(1))\n   ```\n\n2. **Tools referenced in SKILL.md prose must be native Hermes tools or\n   MCP servers the skill explicitly expects.** When the skill needs a\n   capability, point at the proper tool by name in backticks\n   (`` `terminal` ``, `` `web_extract` ``, `` `read_file` ``,\n   `` `patch` ``, `` `search_files` ``, `` `vision_analyze` ``,\n   `` `browser_navigate` ``, `` `delegate_task` ``, etc.). Do NOT\n   name shell utilities the agent already has wrapped — `grep` →\n   `search_files`, `cat`/`head`/`tail` → `read_file`, `sed`/`awk` →\n   `patch`, `find`/`ls` → `search_files target='files'`. If the skill\n   depends on an MCP server, name the MCP server and document the\n   expected setup in `## Prerequisites`. Anything else (third-party\n   CLIs, shell pipelines, etc.) is fair game inside script files but\n   should not be the headline interaction surface in the prose.\n\n3. **`platforms:` gating audited against actual script imports.**\n   Skills that use POSIX-only primitives (`fcntl`, `termios`,\n   `os.setsid`, `os.kill(pid, 0)` for liveness, `/proc`, `/tmp`\n   hardcoded, `signal.SIGKILL`, bash heredocs, `osascript`, `apt`,\n   `systemctl`) must declare their supported platforms. Default\n   posture: try to fix it cross-platform first — `tempfile.gettempdir`,\n   `pathlib.Path`, `psutil.pid_exists`, Python-level filtering instead\n   of `grep`. Gate to a narrower set only when the dependency is\n   genuinely platform-bound.\n\n4. **`author` credits the human contributor first.** For external\n   contributions, the contributor's real name + GitHub handle goes\n   first; \"Hermes Agent\" is the secondary collaborator. If the\n   contributor's commit shows \"Hermes Agent\" as author (because they\n   used Hermes to draft the skill), replace it with their actual name\n   — credit the human, not the tool.\n\n5. **SKILL.md body uses the modern section order.** `# <Skill> Skill`\n   title, 2-3 sentence intro stating what it does and doesn't do,\n   `## When to Use`, `## Prerequisites`, `## How to Run`,\n   `## Quick Reference`, `## Procedure`, `## Pitfalls`,\n   `## Verification`. Target ~200 lines for a complex skill,\n   ~100 lines for a simple one. Cut redundant intro fluff, marketing\n   prose, and re-explanations of env vars already in\n   `## Prerequisites`.\n\n6. **Scripts go in `scripts/`, references in `references/`,\n   templates in `templates/`.** Don't expect the model to inline-write\n   parsers, XML walkers, or non-trivial logic every call — ship a\n   helper script. Reference it from SKILL.md by path relative to the\n   skill directory.\n\n7. **Tests live at `tests/skills/test_<skill>_skill.py`** and use only\n   stdlib + pytest + `unittest.mock`. No live network calls. Run via\n   `scripts/run_tests.sh tests/skills/test_<skill>_skill.py -q`.\n\n8. **`.env.example` additions are isolated to a clearly delimited\n   block.** Don't touch the surrounding file — contributor-supplied\n   `.env.example` versions are usually stale and edits outside the\n   skill's own block must be dropped during salvage.\n\nThe full salvage / modernization checklist for external skill PRs\nlives in the `hermes-agent-dev` skill at\n`references/new-skill-pr-salvage.md` — load it before polishing\ncontributor skill PRs.\n\n---\n\n## Toolsets\n\nAll toolsets are defined in `toolsets.py` as a single `TOOLSETS` dict.\nEach platform's adapter picks a base toolset (e.g. Telegram uses\n`\"messaging\"`); `_HERMES_CORE_TOOLS` is the default bundle most\nplatforms inherit from.\n\nCurrent toolset keys: `browser`, `clarify`, `code_execution`, `cronjob`,\n`debugging`, `delegation`, `discord`, `discord_admin`, `feishu_doc`,\n`feishu_drive`, `file`, `homeassistant`, `image_gen`, `kanban`, `memory`,\n`messaging`, `moa`, `rl`, `safe`, `search`, `session_search`, `skills`,\n`spotify`, `terminal`, `todo`, `tts`, `video`, `vision`, `web`, `yuanbao`.\n\nEnable/disable per platform via `hermes tools` (the curses UI) or the\n`tools.<platform>.enabled` / `tools.<platform>.disabled` lists in\n`config.yaml`.\n\n---\n\n## Delegation (`delegate_task`)\n\n`tools/delegate_tool.py` spawns a subagent with an isolated\ncontext + terminal session. By default the parent waits for the\nchild's summary before continuing its own loop. With `background=true`,\nHermes returns a delegation id immediately and the result re-enters the\nconversation later through the async-delegation completion queue.\n\nTwo shapes:\n\n- **Single:** pass `goal` (+ optional `context`, `toolsets`).\n- **Batch (parallel):** pass `tasks: [...]` — each gets its own subagent\n  running concurrently. Concurrency is capped by\n  `delegation.max_concurrent_children` (default 3).\n\nRoles:\n\n- `role=\"leaf\"` (default) — focused worker. Cannot call `delegate_task`,\n  `clarify`, `memory`, `send_message`, `cronjob`. Retains `execute_code`\n  (programmatic tool calling).\n- `role=\"orchestrator\"` — retains `delegate_task` so it can spawn its\n  own workers. Gated by `delegation.orchestrator_enabled` (default true)\n  and bounded by `delegation.max_spawn_depth` (default 2).\n\nKey config knobs (under `delegation:` in `config.yaml`):\n`max_concurrent_children`, `max_spawn_depth`, `child_timeout_seconds`,\n`orchestrator_enabled`, `subagent_auto_approve`, `inherit_mcp_toolsets`,\n`max_iterations`.\n\nDurability rule: background `delegate_task` is detached from the current\nturn but still process-local. For work that must survive process restart, use\n`cronjob` or `terminal(background=True, notify_on_complete=True)` instead.\n\n---\n\n## Curator (skill lifecycle)\n\nBackground skill-maintenance system that tracks usage on agent-created\nskills and auto-archives stale ones. Users never lose skills; archives\ngo to `~/.hermes/skills/.archive/` and are restorable.\n\n- **Core:** `agent/curator.py` (review loop, auto-transitions, LLM review\n  prompt) + `agent/curator_backup.py` (pre-run tar.gz snapshots).\n- **CLI:** `hermes_cli/curator.py` wires `hermes curator <verb>` where\n  verbs are: `status`, `run`, `pause`, `resume`, `pin`, `unpin`,\n  `archive`, `restore`, `prune`, `backup`, `rollback`.\n- **Telemetry:** `tools/skill_usage.py` owns the sidecar\n  `~/.hermes/skills/.usage.json` — per-skill `use_count`, `view_count`,\n  `patch_count`, `last_activity_at`, `state` (active / stale /\n  archived), `pinned`.\n\nInvariants:\n- Curator only touches skills with `created_by: \"agent\"` provenance —\n  bundled + hub-installed skills are off-limits.\n- Never deletes; max destructive action is archive.\n- Pinned skills are exempt from every auto-transition and from the\n  LLM review pass.\n- `skill_manage(action=\"delete\")` refuses pinned skills; patch/edit/\n  write_file/remove_file go through so the agent can keep improving\n  pinned skills.\n\nConfig section (`curator:` in `config.yaml`):\n`enabled`, `interval_hours`, `min_idle_hours`, `stale_after_days`,\n`archive_after_days`, `backup.*`.\n\nFull user-facing docs: `website/docs/user-guide/features/curator.md`.\n\n---\n\n## Cron (scheduled jobs)\n\n`cron/jobs.py` (job store) + `cron/scheduler.py` (tick loop). Agents\nschedule jobs via the `cronjob` tool; users via `hermes cron <verb>`\n(`list`, `add`, `edit`, `pause`, `resume`, `run`, `remove`) or the\n`/cron` slash command.\n\nSupported schedule formats:\n- Duration: `\"30m\"`, `\"2h\"`, `\"1d\"`\n- \"every\" phrase: `\"every 2h\"`, `\"every monday 9am\"`\n- 5-field cron expression: `\"0 9 * * *\"`\n- ISO timestamp (one-shot): `\"2026-06-01T09:00:00Z\"`\n\nPer-job fields include `skills` (load specific skills), `model` /\n`provider` overrides, `script` (pre-run data-collection script whose\nstdout is injected into the prompt; `no_agent=True` turns the script\ninto the entire job), `context_from` (chain job A's last output into\njob B's prompt), `workdir` (run in a specific directory with its\n`AGENTS.md`/`CLAUDE.md` loaded), and multi-platform delivery.\n\nHardening invariants:\n- **3-minute hard interrupt** on cron sessions — runaway agent loops\n  cannot monopolize the scheduler.\n- Catchup window: half the job's period, clamped to 120s–2h.\n- Grace window: 120s for one-shot jobs whose fire time was missed.\n- File lock at `~/.hermes/cron/.tick.lock` prevents duplicate ticks\n  across processes.\n- Cron sessions pass `skip_memory=True` by default; memory providers\n  intentionally do not run during cron.\n\nCron deliveries are **not** mirrored into the target gateway session —\nthey land in their own cron session with a header/footer frame so the\nmain conversation's message-role alternation stays intact.\n\n---\n\n## Kanban (multi-agent work queue)\n\nDurable SQLite-backed board that lets multiple profiles / workers\ncollaborate on shared tasks. Users drive it via `hermes kanban <verb>`;\nworkers spawned by the dispatcher drive it via a dedicated `kanban_*`\ntoolset so their schema footprint is zero when they're not inside a\nkanban task.\n\n- **CLI:** `hermes_cli/kanban.py` wires `hermes kanban` with verbs\n  `init`, `create`, `list` (alias `ls`), `show`, `assign`, `link`,\n  `unlink`, `comment`, `attach`, `attachments`, `attach-rm`, `complete`,\n  `request-review`, `request-changes`, `reopen-review`, `block`, `unblock`, `archive`,\n  `tail`, plus less-commonly-used `watch`, `stats`, `runs`, `log`,\n  `assignees`, `heartbeat`, `notify-*`, `dispatch`, `daemon`, `gc`.\n- **Worker/orchestrator toolset:** `tools/kanban_tools.py` exposes\n  `kanban_show`, `kanban_complete`, `kanban_request_review`,\n  `kanban_request_changes`, `kanban_block`,\n  `kanban_heartbeat`, `kanban_comment`, `kanban_create`, `kanban_link`,\n  `kanban_attach`, `kanban_attach_url`, `kanban_attachments`; profiles that\n  explicitly enable the `kanban` toolset outside a dispatcher-spawned\n  task also get `kanban_list` and `kanban_unblock` for board routing.\n- **Dispatcher:** long-lived loop that (default every 60s) reclaims\n  stale claims, promotes ready tasks, atomically claims, and spawns\n  assigned profiles. Runs **inside the gateway** by default via\n  `kanban.dispatch_in_gateway: true`.\n- **Plugin assets:** `plugins/kanban/dashboard/` (web UI) +\n  `plugins/kanban/systemd/` (`hermes-kanban-dispatcher.service` for\n  standalone dispatcher deployment).\n\nIsolation model:\n- **Board** is the hard boundary — workers are spawned with\n  `HERMES_KANBAN_BOARD` pinned in their env so they can't see other\n  boards.\n- **Tenant** is a soft namespace *within* a board — one specialist\n  fleet can serve multiple businesses with workspace-path + memory-key\n  isolation.\n- After `kanban.failure_limit` consecutive non-success attempts on the\n  same task (default: 2), the dispatcher auto-blocks it to prevent spin\n  loops.\n\nFull user-facing docs: `website/docs/user-guide/features/kanban.md`.\n\n---\n\n## Important Policies\n\n### Prompt Caching Must Not Break\n\nHermes-Agent ensures caching remains valid throughout a conversation. **Do NOT implement changes that would:**\n- Alter past context mid-conversation\n- Change toolsets mid-conversation\n- Reload memories or rebuild system prompts mid-conversation\n\nCache-breaking forces dramatically higher costs. The ONLY time we alter context is during context compression.\n\nSlash commands that mutate system-prompt state (skills, tools, memory, etc.)\nmust be **cache-aware**: default to deferred invalidation (change takes\neffect next session), with an opt-in `--now` flag for immediate\ninvalidation. See `/skills install --now` for the canonical pattern.\n\n### Background Process Notifications (Gateway)\n\nWhen `terminal(background=true, notify_on_complete=true)` is used, the gateway runs a watcher that\ndetects process completion and triggers a new agent turn. Control verbosity of background process\nmessages with `display.background_process_notifications`\nin config.yaml (or `HERMES_BACKGROUND_NOTIFICATIONS` env var):\n\n- `concise` — one-line status message on completion; failures append a short output tail (default)\n- `all` — running-output updates + final raw-output message\n- `result` — only the final raw-output completion message\n- `error` — only the final raw-output message when exit code != 0\n- `off` — no watcher messages at all\n\n---\n\n## Profiles: Multi-Instance Support\n\nHermes supports **profiles** — multiple fully isolated instances, each with its own\n`HERMES_HOME` directory (config, API keys, memory, sessions, skills, gateway, etc.).\n\nThe core mechanism: `_apply_profile_override()` in `hermes_cli/main.py` sets\n`HERMES_HOME` before any module imports. All `get_hermes_home()` references\nautomatically scope to the active profile.\n\n### Rules for profile-safe code\n\n1. **Use `get_hermes_home()` for all HERMES_HOME paths.** Import from `hermes_constants`.\n   NEVER hardcode `~/.hermes` or `Path.home() / \".hermes\"` in code that reads/writes state.\n   ```python\n   # GOOD\n   from hermes_constants import get_hermes_home\n   config_path = get_hermes_home() / \"config.yaml\"\n\n   # BAD — breaks profiles\n   config_path = Path.home() / \".hermes\" / \"config.yaml\"\n   ```\n\n2. **Use `display_hermes_home()` for user-facing messages.** Import from `hermes_constants`.\n   This returns `~/.hermes` for default or `~/.hermes/profiles/<name>` for profiles.\n   ```python\n   # GOOD\n   from hermes_constants import display_hermes_home\n   print(f\"Config saved to {display_hermes_home()}/config.yaml\")\n\n   # BAD — shows wrong path for profiles\n   print(\"Config saved to ~/.hermes/config.yaml\")\n   ```\n\n3. **Module-level constants are fine** — they cache `get_hermes_home()` at import time,\n   which is AFTER `_apply_profile_override()` sets the env var. Just use `get_hermes_home()`,\n   not `Path.home() / \".hermes\"`.\n\n4. **Tests that mock `Path.home()` must also set `HERMES_HOME`** — since code now uses\n   `get_hermes_home()` (reads env var), not `Path.home() / \".hermes\"`:\n   ```python\n   with patch.object(Path, \"home\", return_value=tmp_path), \\\n        patch.dict(os.environ, {\"HERMES_HOME\": str(tmp_path / \".hermes\")}):\n       ...\n   ```\n\n5. **Gateway platform adapters should use token locks** — if the adapter connects with\n   a unique credential (bot token, API key), call `acquire_scoped_lock()` from\n   `gateway.status` in the `connect()`/`start()` method and `release_scoped_lock()` in\n   `disconnect()`/`stop()`. This prevents two profiles from using the same credential.\n   See `plugins/platforms/irc/adapter.py` for the canonical pattern.\n\n6. **Profile operations are HOME-anchored, not HERMES_HOME-anchored** — `_get_profiles_root()`\n   returns `Path.home() / \".hermes\" / \"profiles\"`, NOT `get_hermes_home() / \"profiles\"`.\n   This is intentional — it lets `hermes -p coder profile list` see all profiles regardless\n   of which one is active.\n\n## Known Pitfalls\n\n### DO NOT hardcode `~/.hermes` paths\nUse `get_hermes_home()` from `hermes_constants` for code paths. Use `display_hermes_home()`\nfor user-facing print/log messages. Hardcoding `~/.hermes` breaks profiles — each profile\nhas its own `HERMES_HOME` directory. This was the source of 5 bugs fixed in PR #3575.\n\n### All CLI menu-pickers MUST use curses.\nInteractive menus must use `hermes_cli/curses_ui.py`. See `hermes_cli/tools_config.py` for an example.\n\n### DO NOT use `\\033[K` (ANSI erase-to-EOL) in spinner/display code\nLeaks as literal `?[K` text under `prompt_toolkit`'s `patch_stdout`. Use space-padding: `f\"\\r{line}{' ' * pad}\"`.\n\n### `_last_resolved_tool_names` is a process-global in `model_tools.py`\n`_run_single_child()` in `delegate_tool.py` saves and restores this global around subagent execution. If you add new code that reads this global, be aware it may be temporarily stale during child agent runs.\n\n### DO NOT hardcode cross-tool references in schema descriptions\nTool schema descriptions must not mention tools from other toolsets by name (e.g., `browser_navigate` saying \"prefer web_search\"). Those tools may be unavailable (missing API keys, disabled toolset), causing the model to hallucinate calls to non-existent tools. If a cross-reference is needed, add it dynamically in `get_tool_definitions()` in `model_tools.py` — see the `browser_navigate` / `execute_code` post-processing blocks for the pattern.\n\n### The gateway has TWO message guards — both must bypass approval/control commands\nWhen an agent is running, messages pass through two sequential guards:\n(1) **base adapter** (`gateway/platforms/base.py`) queues messages in\n`_pending_messages` when `session_key in self._active_sessions`, and\n(2) **gateway runner** (`gateway/run.py`) intercepts `/stop`, `/new`,\n`/queue`, `/status`, `/approve`, `/deny` before they reach\n`running_agent.interrupt()`. Any new command that must reach the runner\nwhile the agent is blocked (e.g. approval prompts) MUST bypass BOTH\nguards and be dispatched inline, not via `_process_message_background()`\n(which races session lifecycle).\n\n### Squash merges from stale branches silently revert recent fixes\nBefore squash-merging a PR, ensure the branch is up to date with `main`\n(`git fetch origin main && git reset --hard origin/main` in the worktree,\nthen re-apply the PR's commits). A stale branch's version of an unrelated\nfile will silently overwrite recent fixes on main when squashed. Verify\nwith `git diff HEAD~1..HEAD` after merging — unexpected deletions are a\nred flag.\n\n### Don't wire in dead code without E2E validation\nUnused code that was never shipped was dead for a reason. Before wiring an\nunused module into a live code path, E2E test the real resolution chain\nwith actual imports (not mocks) against a temp `HERMES_HOME`.\n\n### Tests must not write to `~/.hermes/`\nThe `_isolate_hermes_home` autouse fixture in `tests/conftest.py` redirects `HERMES_HOME` to a temp dir. Never hardcode `~/.hermes/` paths in tests.\n\n**Profile tests**: When testing profile features, also mock `Path.home()` so that\n`_get_profiles_root()` and `_get_default_hermes_home()` resolve within the temp dir.\nUse the pattern from `tests/hermes_cli/test_profiles.py`:\n```python\n@pytest.fixture\ndef profile_env(tmp_path, monkeypatch):\n    home = tmp_path / \".hermes\"\n    home.mkdir()\n    monkeypatch.setattr(Path, \"home\", lambda: tmp_path)\n    monkeypatch.setenv(\"HERMES_HOME\", str(home))\n    return home\n```\n\n---\n\n## Testing\n\n### Python\n**ALWAYS use `scripts/run_tests.sh`** — do not call `pytest` directly. The script enforces\nhermetic environment parity with CI (unset credential vars, TZ=UTC, LANG=C.UTF-8,\nper-file subprocess isolation via `scripts/run_tests_parallel.py` — no xdist,\nworker count auto-scaled from CPU count). Direct `pytest`\non a 16+ core developer machine with API keys set diverges from CI in ways\nthat have caused multiple \"works locally, fails in CI\" incidents (and the reverse).\n\n```bash\nscripts/run_tests.sh                                  # full suite, CI-parity\nscripts/run_tests.sh tests/gateway/                   # one directory\nscripts/run_tests.sh tests/agent/test_foo.py -k test_x  # one test (file + -k; the runner is file-granular)\nscripts/run_tests.sh -v --tb=long                     # pass-through pytest flags\n```\n\n**Flake policy:** the runner auto-retries a failing test FILE once in a fresh\nsubprocess (`--file-retries`, default 1; `HERMES_TEST_FILE_RETRIES=0` to\ndisable). Pass-on-retry counts as green but is printed in a `⚠ FLAKY` summary\nsection with both attempts' output. A FLAKY report is a bug to fix, not noise\nto ignore — timing-sensitive tests must not assume a quiet runner (loose\nwall-clock bounds ≥ 2s, event-based sync, no `assert not _wait_until(...)`\nnegative-timing races).\n\n#### Subprocess-per-test-file isolation\n\nEvery test file runs in a freshly-spawned Python subprocess via `run_tests_parallel.py`. This means module-level dicts/sets and\nContextVars from one test file cannot leak into the next.\n\n#### Why the wrapper\n\n|                     | Without wrapper                             | With wrapper                              |\n| ------------------- | ------------------------------------------- | ----------------------------------------- |\n| Provider API keys   | Whatever is in your env (auto-detects pool) | All env vars except a specific few unset. |\n| HOME / `~/.hermes/` | Your real config+auth.json                  | Temp dir per test                         |\n| Timezone            | Local TZ (PDT etc.)                         | UTC                                       |\n| Locale              | Whatever is set                             | C.UTF-8                                   |\n\n### Where to place what tests\n\nThe CI change classifier (`scripts/ci/classify_changes.py`) runs specific jobs based on what files changed. A Python test that asserts\nabout the contents of `package.json`, `package-lock.json`, `.ts`/`.tsx`\nsource, or any other JS-side artifact will not run on a PR that only touches\nthose files. This means a regression can go green on a PR and red on `main` (where the\nclassifier fails open and runs everything).\n\nAny test that reads or asserts about `package.json`,\n`package-lock.json`, `tsconfig.json`, `.ts`/`.tsx`/`.js`/`.mjs`/`.cjs`\nsource files configuration belongs in the JS (vitest) test suite, not in `tests/*.py`.\n\n### Don't fake the host OS\n\nHermes supports Linux, macOS and native Windows, and plenty of its behaviour\ngenuinely differs per host. Those differences are tested by running on the\nhost, not by patching `sys.platform`.\n\n```python\n@pytest.mark.linux_only\n@pytest.mark.macos_only\n@pytest.mark.windows_only\n```\n\nThings that are host-independent can stay unmarked:\n\n- **Pure functions that take a platform as data** —\n  `hidden_windows_child_options(opts, is_windows=True)` is input→output, not a\n  fake host. (Contrast: setting a module-level `IS_WINDOWS` flag and then\n  calling `windows_detach_flags()` *is* a fake.)\n- **Declaration/packaging invariants** — \"pyproject declares `tzdata` with a\n  `sys_platform == 'win32'` marker\" asserts about a file, not about runtime.\n\nThe line: **if the test needs the interpreter to believe it is on another OS\nin order to pass, it belongs on that OS.**\nWhen one test body walks several platforms in sequence, split it.\nKeep the host-native arm on the Linux lane and move the other arm into its own marked test.\n\n**Use the marker, never a bare `skipif`.** `scripts/ci/list_os_marked_tests.py`\ndecides which files the macOS/Windows lanes import by grepping for the marker\n*name*, and the lane then filters with `-m <marker>`. A test gated with\n`@pytest.mark.skipif(sys.platform != \"win32\")` therefore skips on Linux AND is\nnever imported on the Windows lane — it runs on no host at all, silently. The\nsame trap catches a file-local alias (`windows_only = pytest.mark.skipif(...)`):\nthe grep matches the name, so the file *is* listed, but `-m windows_only`\ndeselects every test in it and the lane reports green over zero coverage.\nEqually, don't `pytest.skip()` the non-host rows of a `@parametrize` over\nplatforms — split it into one marked test per OS, or only the host's row ever\nexecutes.\n\n### Don't write change-detector tests\n\nA test is a **change-detector** if it fails whenever data that is **expected\nto change** gets updated — model catalogs, config version numbers,\nenumeration counts, hardcoded lists of provider models. These tests add no\nbehavioral coverage; they just guarantee that routine source updates break\nCI and cost engineering time to \"fix.\"\n\n**Do not write:**\n\n```python\n# catalog snapshot — breaks every model release\nassert \"gemini-2.5-pro\" in _PROVIDER_MODELS[\"gemini\"]\nassert \"MiniMax-M2.7\" in models\n\n# config version literal — breaks every schema bump\nassert DEFAULT_CONFIG[\"_config_version\"] == 21\n\n# enumeration count — breaks every time a skill/provider is added\nassert len(_PROVIDER_MODELS[\"huggingface\"]) == 8\n```\n\n**Do write:**\n\n```python\n# behavior: does the catalog plumbing work at all?\nassert \"gemini\" in _PROVIDER_MODELS\nassert len(_PROVIDER_MODELS[\"gemini\"]) >= 1\n\n# behavior: does migration bump the user's version to current latest?\nassert raw[\"_config_version\"] == DEFAULT_CONFIG[\"_config_version\"]\n\n# invariant: no plan-only model leaks into the legacy list\nassert not (set(moonshot_models) & coding_plan_only_models)\n\n# invariant: every model in the catalog has a context-length entry\nfor m in _PROVIDER_MODELS[\"huggingface\"]:\n    assert m.lower() in DEFAULT_CONTEXT_LENGTHS_LOWER\n```\n\nThe rule: if the test reads like a snapshot of current data, delete it. If\nit reads like a contract about how two pieces of data must relate, keep it.\nWhen a PR adds a new provider/model and you want a test, make the test\nassert the relationship (e.g. \"catalog entries all have context lengths\"),\nnot the specific names.\n\nReviewers should reject new change-detector tests; authors should convert\nthem into invariants before re-requesting review.\n\n### Never read source code in tests\n\nA test that reads a source file's text is testing *the shape of the\nsource code*, not its behavior. This is a hard antipattern, banned outright.\nAny test that reads a .py, .ts, .tsx, etc., file is suspect.\n\n**Why it's actively harmful, not just weak:**\n\n- It passes when the implementation is subtly broken (the regex matches a\n  call site that exists but is wired wrong) and fails when a correct\n  refactor changes formatting, variable names, or control flow with\n  identical runtime behavior. Both directions of failure are wrong.\n- It can't be run against a built/bundled/minified artifact, so it silently\n  stops testing anything the moment code moves, gets renamed, or a\n  dependency reformats it.\n- It actively blocks refactors: reviewers see \"keeps a pattern intact\" tests\n  fail during pure structural cleanup with no behavior change, and either\n  hand-wave the failure (dangerous) or waste time updating regexes that add\n  nothing (waste).\n- It gives false confidence. a green suite full of source-regex tests\n  looks like coverage but has never once executed the code path it claims\n  to guard.\n\n**Do not write:**\n\n```ts\nconst source = fs.readFileSync(path.join(__dirname, 'main.ts'), 'utf8')\n\ntest('backend spawn hides the Windows console', () => {\n  assert.match(source, /spawn\\(\\s*backend\\.command,\\s*backend\\.args[\\s\\S]{0,300}hiddenWindowsChildOptions/)\n})\n```\n\n**Do write — extract the logic into a small pure/DI-testable function and\ncall it for real:**\n\n```ts\n// backend-spawn.ts\nexport function hiddenWindowsChildOptions(options: SpawnOptionsLike = {}, isWindows = process.platform === 'win32') {\n  if (!isWindows || 'windowsHide' in options) return options\n  return { ...options, windowsHide: true }\n}\n\n// backend-spawn.test.ts\ntest('windowsHide defaults to true on Windows, is left alone elsewhere', () => {\n  assert.equal(hiddenWindowsChildOptions({}, true).windowsHide, true)\n  assert.equal(hiddenWindowsChildOptions({}, false).windowsHide, undefined)\n  assert.equal(hiddenWindowsChildOptions({ windowsHide: false }, true).windowsHide, false)\n})\n```\n\nIf the logic lives inline in a god-file (`main.ts`, `cli.py`,\n`gateway/run.py`) and extracting it feels disruptive: that's the actual\nsignal to do the extraction, not to regex around it.\n"},"items":[{"name":"AGENTS.md","path":"AGENTS.md","title":"AGENTS.md","content":"# Hermes Agent - Development Guide\n\nInstructions for AI coding assistants and developers working on the hermes-agent codebase.\n\n**Never give up on the right solution.**\n\n## What Hermes Is\n\nHermes is a personal AI agent that runs the same agent core across a CLI, a\nmessaging gateway (Telegram, Discord, Slack, and ~20 other platforms), a TUI,\nand an Electron desktop app. It learns across sessions (memory + skills),\ndelegates to subagents, runs scheduled jobs, and drives a real terminal and\nbrowser. It is extended primarily through **plugins and skills**, not by\ngrowing the core.\n\nTwo properties shape almost every design decision and are the lens for\nreviewing any change:\n\n- **Per-conversation prompt caching is sacred.** A long-lived conversation\n  reuses a cached prefix every turn. Anything that mutates past context,\n  swaps toolsets, or rebuilds the system prompt mid-conversation invalidates\n  that cache and multiplies the user's cost. We do not do it (the one\n  exception is context compression).\n- **The core is a narrow waist; capability lives at the edges.** Every model\n  tool we add is sent on every API call, so the bar for a new *core* tool is\n  high. Most new capability should arrive as a CLI command + skill, a\n  service-gated tool, or a plugin — not as core surface.\n\n## Contribution Rubric — What We Want / What We Don't\n\nThis is the project's intent layer. Use it two ways:\n\n1. **For humans and for your own work** — what gets merged and what gets\n   rejected, so a contribution aims at the target.\n2. **For automated review (the triage sweeper)** — guidance on when a PR is\n   safe to close on the three allowed reasons (`implemented_on_main`,\n   `cannot_reproduce`, `incoherent`) and, just as important, **when NOT to\n   close** one. Taste-based \"we don't want this / out of scope\" closes are NOT\n   an automated decision — those stay with a human maintainer. The sweeper's\n   job here is to recognize design intent and *avoid wrongly closing a\n   legitimate contribution*, not to make the won't-implement call itself.\n\nRead the balance right: Hermes ships a **lot** — most merges are bug fixes to\nreal reported behavior, and the product surface (platforms, channels,\nproviders, models, desktop/TUI features) expands aggressively and on purpose.\nThe restraint below is aimed squarely at the **core agent + the model tool\nschema**, the one place where every addition is paid for on every API call.\n\"Smallest footprint\" governs *how a capability is wired into the core*, NOT\nwhether the product is allowed to grow. We are expansive at the edges and\nconservative at the waist.\n\n### What we want\n\n- **Fix real bugs, well.** The bulk of what lands is `fix(...)` against an\n  actual reported symptom. A good fix reproduces the symptom on current\n  `main`, points to the exact line where it manifests, and fixes the whole bug\n  class — sibling call paths included — not just the one site the reporter hit.\n- **Expand reach at the edges.** New platform adapters, channels, providers,\n  models, and desktop/TUI/dashboard features are welcome and land routinely,\n  including large ones (a new messaging channel, a session-cap feature, a\n  Windows PTY bridge). Breadth in the product is a goal, not a footprint\n  concern — as long as it integrates with the existing setup/config UX\n  (`hermes tools`, `hermes setup`, auto-install) rather than bolting on a raw\n  env var.\n- **Refactor god-files into clean modules.** Extracting a multi-thousand-line\n  cluster out of `cli.py` / `run_agent.py` / `gateway/run.py` into a focused\n  mixin or module is wanted work, even when the diff is huge and mechanical\n  (large `+N/-N` refactors merge regularly). The \"every line traces to the\n  request\" test applies to *feature* PRs; a declared refactor's request IS the\n  extraction.\n- **Keep the core narrow.** New *model tools* are the expensive exception —\n  every tool ships on every API call. Prefer, in order: extend existing code →\n  CLI command + skill → service-gated tool (`check_fn`) → plugin → MCP server\n  in the catalog → new core tool (last resort). See \"The Footprint Ladder.\"\n- **Extend, don't duplicate.** Before adding a module/manager/hook, check\n  whether existing infrastructure already covers the use case. When several PRs\n  integrate the same *category*, design one shared interface instead of merging\n  them one at a time (see the ABC + orchestrator note under the Footprint\n  Ladder).\n- **Behavior contracts over snapshots.** Tests should assert how two pieces of\n  data must relate (invariants), not freeze a current value (model lists,\n  config version literals, enumeration counts). See \"Don't write\n  change-detector tests.\"\n- **E2E validation, not just green unit mocks.** For anything touching\n  resolution chains, config propagation, security boundaries, remote\n  backends, or file/network I/O, exercise the real path with real imports\n  against a temp `HERMES_HOME`. Mocks hide integration bugs.\n- **Cache-, alternation-, and invariant-safe.** Preserve prompt caching, strict\n  message role alternation (never two same-role messages in a row; never a\n  synthetic user message injected mid-loop), and a system prompt that is\n  byte-stable for the life of a conversation.\n- **Contributor credit preserved.** Salvage external work by cherry-picking\n  (rebase-merge) so authorship survives in git history; don't reimplement from\n  scratch when you can build on top.\n\n### What we don't want (rejected even when well-built)\n\n- **Speculative infrastructure.** Hooks, callbacks, or extension points with no\n  concrete consumer. Adding a hook is easy; removing one after plugins depend\n  on it is hard. A hook is NOT speculative if a contributor has a real, stated\n  use case — even if the consumer ships separately.\n- **New `HERMES_*` env vars for non-secret config.** `.env` is for secrets\n  only (API keys, tokens, passwords). All behavioral settings — timeouts,\n  thresholds, feature flags, display prefs — go in `config.yaml`. Bridge to an\n  internal env var if the mechanism needs one, but user-facing docs point to\n  `config.yaml`. Reject PRs that tell users to \"set X in your .env\" unless X\n  is a credential.\n- **A new core tool when terminal + file already do the job, or when a skill\n  would.** If the only barrier is file visibility on a remote backend, fix the\n  mount, not the toolset.\n- **Lazy-reading escape hatches on instructional tools.** No `offset`/`limit`\n  pagination on tools that load content the agent must read fully (skills,\n  prompts, playbooks). Models will read page 1 and skip the rest.\n- **\"Fixes\" that destroy the feature they secure.** A mitigation that kills the\n  feature's purpose is the wrong mitigation. Read the original commit's intent\n  (`git log -p -S`) before restricting behavior; find a fix that preserves the\n  feature.\n- **Outbound telemetry / usage attribution without opt-in gating.** No new\n  analytics, third-party identifier tagging, or attribution tags until a\n  generic user-facing opt-in (config gate + setup prompt + `hermes tools`\n  toggle) exists. Park behind a label, do not merge.\n- **Change-detector tests, cache-breaking mid-conversation, dead code wired in\n  without E2E proof, and plugins that touch core files.** Plugins live in their\n  own directory and work within the ABCs/hooks we provide; if a plugin needs\n  more, widen the generic plugin surface, don't special-case it in core.\n- **Third-party products / other people's projects integrated into the core\n  tree.** Observability backends, vendor SaaS integrations, analytics dashboards,\n  and similar \"someone else's product\" plugins do NOT land under `plugins/` in\n  this repo. They place an ongoing maintenance burden on us to keep them working\n  against a fast-moving core, for a backend we don't own. Ship them as a\n  **standalone plugin repo** users install into `~/.hermes/plugins/` (or via a\n  pip entry point), and promote them in the Nous Research Discord\n  (`#plugins-skills-and-skins`). This is a coupling-and-maintenance decision, not\n  a quality bar — the plugin can be excellent and still be a close. PRs that add\n  such a directory to the tree are closed with a pointer to publish it as its own\n  repo.\n\n### Before you call it a bug — verify the premise (and when NOT to close)\n\nThe most common reason a well-written PR gets closed is not code quality — it\nis that the change is built on a **wrong premise**, or it treats an\n**intentional design as a gap**. These patterns cut both ways: they tell a\nhuman reviewer what to scrutinize, and they tell the automated sweeper when a\nPR is NOT safe to close as `implemented_on_main` / `cannot_reproduce` (when in\ndoubt, leave it open for a human). They are distilled from real closes.\n\n- **\"Intentional design, not a gap.\"** A limitation that looks like an\n  oversight is often deliberate. Before \"fixing\" a missing link or a\n  restriction, ask whether the isolation IS the design. Example: profiles are\n  independent islands on purpose — a PR adding live config inheritance from the\n  default profile was closed because coupling profiles together is exactly what\n  the design prevents (the copy-at-creation `--clone` path already covers the\n  legitimate \"start from my default\" case). Read the original commit's intent\n  (`git log -p -S \"<symbol>\"`) before assuming something is unfinished.\n- **\"The premise doesn't hold against how X actually works.\"** A PR's\n  justification frequently rests on a wrong mental model of an existing\n  mechanism. Trace the real code/runtime before accepting the rationale. Two\n  real closes: a rate-limit \"re-probe during cooldown\" PR (the breaker only\n  trips on a *confirmed-empty* account bucket, so re-probing just hammers a\n  bucket we've already proven empty); a usage-accumulation fix whose new branch\n  **never executes at runtime** because an earlier guard already popped the\n  state it depended on. If you can't point to the exact line where the bug\n  manifests AND show the fix changes that line's behavior, you haven't verified\n  the premise.\n- **\"This fix was wrong — the absence/omission was deliberate.\"** Adding the\n  obvious-looking missing piece can break things the omission was protecting.\n  Example: restoring \"missing\" `__init__.py` files made a test tree importable\n  as a dotted package that shadowed the real plugin, deleting its `register()`\n  at import time. The absence was load-bearing.\n- **\"Overreached / resurrected an approach we'd moved past.\"** Scope creep that\n  supersedes an agreed-on base, or revives a direction the maintainers\n  deliberately closed, gets rejected even when the code works. Keep the change\n  to the narrow piece that was actually agreed; offer the rest as a focused\n  follow-up.\n\nThe throughline: **verify the claim AND the intent against the codebase before\nwriting or merging a fix.** A confirmed reproduction on current `main` plus a\nline-level account of where the fix acts beats a plausible-sounding rationale\nevery time. When in doubt about intent, it is cheaper to ask than to ship a\nfix that fights the design.\n\n### The Footprint Ladder (new capability decision)\n\nEach rung adds more permanent surface than the one above. Choose the highest\n(least-footprint) rung that correctly solves the problem:\n\n1. **Extend existing code** — the capability is a variation of something that\n   already exists. Zero new surface.\n2. **CLI command + skill** — manages config/state/infra expressible as shell\n   commands. The agent runs `hermes <subcommand>` guided by a skill. Zero\n   model-tool footprint. Default choice for subscriptions, scheduled tasks,\n   service setup. Examples: `hermes webhook`, `hermes cron`, `hermes tools`.\n3. **Service-gated tool (`check_fn`)** — needs structured params/returns AND\n   only appears when a prerequisite is configured. Zero footprint otherwise.\n   Examples: Home Assistant tools (gated on token), memory-provider tools.\n4. **Plugin** — third-party/niche/user-specific capability that doesn't ship in\n   core. Lives in `~/.hermes/plugins/` or a pip package, discovered at runtime.\n5. **MCP server (in the catalog)** — if the capability genuinely needs to be a\n   tool (structured I/O the agent invokes) but isn't core-fundamental, prefer\n   building it as an MCP server and adding it to the MCP catalog over growing\n   the core toolset. The agent connects to it through the built-in MCP client;\n   zero permanent core-schema footprint, and it's reusable by any MCP host.\n6. **New core tool** — only when the capability is fundamental, broadly useful\n   to nearly every user, and unreachable via terminal + file (or an MCP server).\n   Examples of correct core tools: terminal, read_file, web_search,\n   browser_navigate.\n\nWhen 3+ open PRs try to integrate the same *category* of thing (memory\nbackends, providers, notifiers), don't merge them one at a time — design an\nABC + orchestrator, wrap the existing built-in as the first provider, and turn\nthe competing PRs into plugins against that interface.\n\n### Surface capability is a property of the SESSION, never of the process env\n\nA tool that only works because of *who is on the other end of the connection* —\nthe desktop app's panes, the in-app browser, message reactions, Projects — must\nresolve its availability from the **session's own source**, not from an env var\non the backend process.\n\nThe client and the backend are separate machines on separate clocks. The\ndesktop app can be driving a backend Electron spawned locally, one over SSH,\none behind a plain URL + token, or Hermes Cloud. Only the first two are spawned\nby us and carry `HERMES_DESKTOP=1`. Every env-keyed GUI gate is therefore a\nsilent no-op on the other half of the topologies, and the failure is invisible:\nthe tool is stripped from the schema before the model ever sees it, on the same\nbackend whose platform hint is telling the model it's *\"chatting inside the\nHermes desktop app.\"*\n\nThe pattern that works:\n\n- **The toolset is the surface gate.** Keep the tools off `_HERMES_CORE_TOOLS`\n  (nobody else should pay their schema) and put them in a named toolset —\n  `desktop_ui`, `project`. The GUI gateway's `_load_enabled_toolsets(platform)`\n  folds that toolset in when the session's platform says GUI. One resolver,\n  every topology.\n- **`check_fn` answers reachability or user opt-in, not surface.** \"Is the\n  renderer bridge wired?\", \"did the user enable reactions?\" — fine. \"Was I\n  spawned by Electron?\" — not fine. `check_fn` results are also TTL-cached\n  process-wide (`tools/registry.py`), so a per-session answer does not belong\n  there at all: one process serves many sessions.\n- **Ask which identity you actually mean.** `HERMES_DESKTOP=1` legitimately\n  marks *\"this backend process was spawned by the app\"* — it gates the cron\n  ticker and web-dist handling correctly. It does NOT mean \"a GUI is watching\",\n  and the embedded terminal pane (`hermes --tui` against that same backend) is\n  the standing counterexample.\n\nSame test both ways: if the capability would still make sense with the client\non another machine, it is session-scoped. Cover it with a test that asserts the\nGUI session gets the tool **with the env var absent** — that's the assertion\nthe original gate could never have passed.\n\n## Development Environment\n\n```bash\n# Prefer .venv; fall back to venv if that's what your checkout has.\nsource .venv/bin/activate   # or: source venv/bin/activate\n```\n\n`scripts/run_tests.sh` probes `.venv` first, then `venv`, then\n`$HOME/.hermes/hermes-agent/venv` (for worktrees that share a venv with the\nmain checkout).\n\n## Project Structure\n\nFile counts shift constantly — don't treat the tree below as exhaustive.\nThe canonical source is the filesystem. The notes call out the load-bearing\nentry points you'll actually edit.\n\n```\nhermes-agent/\n├── run_agent.py          # AIAgent class — core conversation loop (~12k LOC)\n├── model_tools.py        # Tool orchestration, discover_builtin_tools(), handle_function_call()\n├── toolsets.py           # Toolset definitions, _HERMES_CORE_TOOLS list\n├── cli.py                # HermesCLI class — interactive CLI orchestrator (~11k LOC)\n├── hermes_state.py       # SessionDB — SQLite session store (FTS5 search)\n├── hermes_constants.py   # get_hermes_home(), display_hermes_home() — profile-aware paths\n├── hermes_logging.py     # setup_logging() — agent.log / errors.log / gateway.log (profile-aware)\n├── batch_runner.py       # Parallel batch processing\n├── agent/                # Agent internals (provider adapters, memory, caching, compression, etc.)\n├── hermes_cli/           # CLI subcommands, setup wizard, plugins loader, skin engine\n├── tools/                # Tool implementations — auto-discovered via tools/registry.py\n│   └── environments/     # Terminal backends (local, docker, ssh, modal, daytona, singularity)\n├── gateway/              # Messaging gateway — run.py + session.py + platforms/\n│   ├── platforms/        # Adapter per platform (telegram, discord, slack, whatsapp,\n│   │                     #   homeassistant, signal, matrix, mattermost, email, sms,\n│   │                     #   dingtalk, wecom, weixin, feishu, qqbot, bluebubbles,\n│   │                     #   yuanbao, webhook, api_server, ...). See ADDING_A_PLATFORM.md.\n│   └── builtin_hooks/    # Extension point for always-registered gateway hooks (none shipped)\n├── plugins/              # Plugin system (see \"Plugins\" section below)\n│   ├── memory/           # Memory-provider plugins (honcho, mem0, supermemory, ...)\n│   ├── context_engine/   # Context-engine plugins\n│   ├── model-providers/  # Inference backend plugins (openrouter, anthropic, gmi, ...)\n│   ├── kanban/           # Multi-agent board dispatcher + worker plugin\n│   ├── hermes-achievements/  # Gamified achievement tracking\n│   ├── observability/    # Metrics / traces / logs plugin\n│   ├── image_gen/        # Image-generation providers\n│   └── <others>/         # disk-cleanup, google_meet, platforms, spotify,\n│                         #   strike-freedom-cockpit, ...\n├── optional-skills/      # Heavier/niche skills shipped but NOT active by default\n├── skills/               # Built-in skills bundled with the repo\n├── ui-tui/               # Ink (React) terminal UI — `hermes --tui`\n│   └── src/              # entry.tsx, app.tsx, gatewayClient.ts + app/components/hooks/lib\n├── tui_gateway/          # Python JSON-RPC backend for the TUI\n├── acp_adapter/          # ACP server (VS Code / Zed / JetBrains integration)\n├── cron/                 # Scheduler — jobs.py, scheduler.py\n├── scripts/              # run_tests.sh, release.py, auxiliary scripts\n├── website/              # Docusaurus docs site\n└── tests/                # Pytest suite (~17k tests across ~900 files as of May 2026)\n```\n\n**User config:** `~/.hermes/config.yaml` (settings), `~/.hermes/.env` (API keys only).\n**Logs:** `~/.hermes/logs/` — `agent.log` (INFO+), `errors.log` (WARNING+),\n`gateway.log` when running the gateway. Profile-aware via `get_hermes_home()`.\nBrowse with `hermes logs [--follow] [--level ...] [--session ...]`.\n\n## TypeScript Style\n\nApplies to TypeScript across Hermes: desktop, TUI, website, and future TS packages.\n\n- Prefer small nanostores over component state when state is shared, reused, or read by distant UI.\n- Let each feature own its atoms. Chat state belongs near chat, shell state near shell, shared state in `src/store`.\n- Components that render from an atom should use `useStore`. Non-rendering actions should read with `$atom.get()`.\n- Do not pass state through three components when the leaf can subscribe to the atom.\n- Keep persistence beside the atom that owns it.\n- Keep route roots thin. They compose routes and shell; they should not become controllers.\n- No monolithic hooks. A hook should own one narrow job.\n- Prefer colocated action modules over hidden god hooks.\n- If a callback is pure side effect, use the terse void form:\n  `onState={st => void setGatewayState(st)}`.\n- Async UI handlers should make intent explicit:\n  `onClick={() => void save()}`.\n- Prefer interfaces for public props and shared object shapes. Avoid `type X = { ... }` for object props.\n- Extend React primitives for props: `React.ComponentProps<'button'>`, `React.ComponentProps<typeof Dialog>`, `Omit<...>`, `Pick<...>`.\n- Table-driven beats condition ladders when mapping ids, routes, or views.\n- `src/app` owns routes, pages, and page-specific components.\n- `src/store` owns shared atoms.\n- `src/lib` owns shared pure helpers.\n\n## File Dependency Chain\n\n```\ntools/registry.py  (no deps — imported by all tool files)\n       ↑\ntools/*.py  (each calls registry.register() at import time)\n       ↑\nmodel_tools.py  (imports tools/registry + triggers tool discovery)\n       ↑\nrun_agent.py, cli.py, batch_runner.py, environments/\n```\n\n---\n\n## AIAgent Class (run_agent.py)\n\nThe real `AIAgent.__init__` takes ~60 parameters (credentials, routing, callbacks,\nsession context, budget, credential pool, etc.). The signature below is the\nminimum subset you'll usually touch — read `run_agent.py` for the full list.\n\n```python\nclass AIAgent:\n    def __init__(self,\n        base_url: str = None,\n        api_key: str = None,\n        provider: str = None,\n        api_mode: str = None,              # \"chat_completions\" | \"codex_responses\" | ...\n        model: str = \"\",                   # empty → resolved from config/provider later\n        max_iterations: int = 500,         # tool-calling iterations (shared with subagents)\n        enabled_toolsets: list = None,\n        disabled_toolsets: list = None,\n        quiet_mode: bool = False,\n        save_trajectories: bool = False,\n        platform: str = None,              # \"cli\", \"telegram\", etc.\n        session_id: str = None,\n        skip_context_files: bool = False,\n        skip_memory: bool = False,\n        credential_pool=None,\n        # ... plus callbacks, thread/user/chat IDs, iteration_budget, fallback_model,\n        # checkpoints config, prefill_messages, service_tier, reasoning_config, etc.\n    ): ...\n\n    def chat(self, message: str) -> str:\n        \"\"\"Simple interface — returns final response string.\"\"\"\n\n    def run_conversation(self, user_message: str, system_message: str = None,\n                         conversation_history: list = None, task_id: str = None) -> dict:\n        \"\"\"Full interface — returns dict with final_response + messages.\"\"\"\n```\n\n### Agent Loop\n\nThe core loop is inside `run_conversation()` — entirely synchronous, with\ninterrupt checks, budget tracking, and a one-turn grace call:\n\n```python\nwhile (api_call_count < self.max_iterations and self.iteration_budget.remaining > 0) \\\n        or self._budget_grace_call:\n    if self._interrupt_requested: break\n    response = client.chat.completions.create(model=model, messages=messages, tools=tool_schemas)\n    if response.tool_calls:\n        for tool_call in response.tool_calls:\n            result = handle_function_call(tool_call.name, tool_call.args, task_id)\n            messages.append(tool_result_message(result))\n        api_call_count += 1\n    else:\n        return response.content\n```\n\nMessages follow OpenAI format: `{\"role\": \"system/user/assistant/tool\", ...}`.\nReasoning content is stored in `assistant_msg[\"reasoning\"]`.\n\n---\n\n## CLI Architecture (cli.py)\n\n- **Rich** for banner/panels, **prompt_toolkit** for input with autocomplete\n- **KawaiiSpinner** (`agent/display.py`) — animated faces during API calls, `┊` activity feed for tool results\n- `load_cli_config()` in cli.py merges hardcoded defaults + user config YAML\n- **Skin engine** (`hermes_cli/skin_engine.py`) — data-driven CLI theming; initialized from `display.skin` config key at startup; skins customize banner colors, spinner faces/verbs/wings, tool prefix, response box, branding text\n- `process_command()` is a method on `HermesCLI` — dispatches on canonical command name resolved via `resolve_command()` from the central registry\n- Skill slash commands: `agent/skill_commands.py` scans `~/.hermes/skills/`, injects as **user message** (not system prompt) to preserve prompt caching\n\n### Slash Command Registry (`hermes_cli/commands.py`)\n\nAll slash commands are defined in a central `COMMAND_REGISTRY` list of `CommandDef` objects. Every downstream consumer derives from this registry automatically:\n\n- **CLI** — `process_command()` resolves aliases via `resolve_command()`, dispatches on canonical name\n- **Gateway** — `GATEWAY_KNOWN_COMMANDS` frozenset for hook emission, `resolve_command()` for dispatch\n- **Gateway help** — `gateway_help_lines()` generates `/help` output\n- **Telegram** — `telegram_bot_commands()` generates the BotCommand menu\n- **Slack** — `slack_subcommand_map()` generates `/hermes` subcommand routing\n- **Autocomplete** — `COMMANDS` flat dict feeds `SlashCommandCompleter`\n- **CLI help** — `COMMANDS_BY_CATEGORY` dict feeds `show_help()`\n\n### Adding a Slash Command\n\n1. Add a `CommandDef` entry to `COMMAND_REGISTRY` in `hermes_cli/commands.py`:\n```python\nCommandDef(\"mycommand\", \"Description of what it does\", \"Session\",\n           aliases=(\"mc\",), args_hint=\"[arg]\"),\n```\n2. Add handler in `HermesCLI.process_command()` in `cli.py`:\n```python\nelif canonical == \"mycommand\":\n    self._handle_mycommand(cmd_original)\n```\n3. If the command is available in the gateway, add a handler in `gateway/run.py`:\n```python\nif canonical == \"mycommand\":\n    return await self._handle_mycommand(event)\n```\n4. For persistent settings, use `save_config_value()` in `cli.py`\n\n**CommandDef fields:**\n- `name` — canonical name without slash (e.g. `\"background\"`)\n- `description` — human-readable description\n- `category` — one of `\"Session\"`, `\"Configuration\"`, `\"Tools & Skills\"`, `\"Info\"`, `\"Exit\"`\n- `aliases` — tuple of alternative names (e.g. `(\"bg\",)`)\n- `args_hint` — argument placeholder shown in help (e.g. `\"<prompt>\"`, `\"[name]\"`)\n- `cli_only` — only available in the interactive CLI\n- `gateway_only` — only available in messaging platforms\n- `gateway_config_gate` — config dotpath (e.g. `\"display.tool_progress_command\"`); when set on a `cli_only` command, the command becomes available in the gateway if the config value is truthy. `GATEWAY_KNOWN_COMMANDS` always includes config-gated commands so the gateway can dispatch them; help/menus only show them when the gate is open.\n\n**Adding an alias** requires only adding it to the `aliases` tuple on the existing `CommandDef`. No other file changes needed — dispatch, help text, Telegram menu, Slack mapping, and autocomplete all update automatically.\n\n---\n\n## TUI Architecture (ui-tui + tui_gateway)\n\nThe TUI is a full replacement for the classic (prompt_toolkit) CLI, activated via `hermes --tui` or `HERMES_TUI=1`.\n\n### Process Model\n\n```\nhermes --tui\n  └─ Node (Ink)  ──stdio JSON-RPC──  Python (tui_gateway)\n       │                                  └─ AIAgent + tools + sessions\n       └─ renders transcript, composer, prompts, activity\n```\n\nTypeScript owns the screen. Python owns sessions, tools, model calls, and slash command logic.\n\n### Transport\n\nNewline-delimited JSON-RPC over stdio. Requests from Ink, events from Python. See `tui_gateway/server.py` for the full method/event catalog.\n\n### Key Surfaces\n\n| Surface | Ink component | Gateway method |\n|---------|---------------|----------------|\n| Chat streaming | `app.tsx` + `messageLine.tsx` | `prompt.submit` → `message.delta/complete` |\n| Tool activity | `thinking.tsx` | `tool.start/progress/complete` |\n| Approvals | `prompts.tsx` | `approval.respond` ← `approval.request` |\n| Clarify/sudo/secret | `prompts.tsx`, `maskedPrompt.tsx` | `clarify/sudo/secret.respond` |\n| Session picker | `sessionPicker.tsx` | `session.list/resume` |\n| Slash commands | Local handler + fallthrough | `slash.exec` → `_SlashWorker`, `command.dispatch` |\n| Completions | `useCompletion` hook | `complete.slash`, `complete.path` |\n| Theming | `theme.ts` + `branding.tsx` | `gateway.ready` with skin data |\n\n### Slash Command Flow\n\n1. Built-in client commands (`/help`, `/quit`, `/clear`, `/resume`, `/copy`, `/paste`, etc.) handled locally in `app.tsx`\n2. Everything else → `slash.exec` (runs in persistent `_SlashWorker` subprocess) → `command.dispatch` fallback\n\n### Dev Commands\n\n```bash\ncd ui-tui\nnpm install       # first time\nnpm run dev       # watch mode (rebuilds hermes-ink + tsx --watch)\nnpm start         # production\nnpm run build     # full build (hermes-ink + tsc)\nnpm run typecheck # typecheck only (tsc --noEmit)\nnpm run lint      # eslint\nnpm run fmt       # prettier\nnpm test          # vitest\n```\n\n### TUI in the Dashboard (`hermes dashboard` → `/chat`)\n\nThe dashboard embeds the real `hermes --tui` — **not** a rewrite.  See `hermes_cli/pty_bridge.py` + the `@app.websocket(\"/api/pty\")` endpoint in `hermes_cli/web_server.py`.\n\n- Browser loads `web/src/pages/ChatPage.tsx`, which mounts xterm.js's `Terminal` with the WebGL renderer, `@xterm/addon-fit` for container-driven resize, and `@xterm/addon-unicode11` for modern wide-character widths.\n- `/api/pty?token=…` upgrades to a WebSocket; auth uses the same ephemeral `_SESSION_TOKEN` as REST, via query param (browsers can't set `Authorization` on WS upgrade).\n- The server spawns whatever `hermes --tui` would spawn, through `ptyprocess` (POSIX PTY — WSL works, native Windows does not).\n- Frames: raw PTY bytes each direction; resize via `\\x1b[RESIZE:<cols>;<rows>]` intercepted on the server and applied with `TIOCSWINSZ`.\n\n**Do not re-implement the primary chat experience in React.** The main transcript, composer/input flow (including slash-command behavior), and PTY-backed terminal belong to the embedded `hermes --tui` — anything new you add to Ink shows up in the dashboard automatically. If you find yourself rebuilding the transcript or composer for the dashboard, stop and extend Ink instead.\n\n**Structured React UI around the TUI is allowed when it is not a second chat surface.** Sidebar widgets, inspectors, summaries, status panels, and similar supporting views (e.g. `ChatSidebar`, `ModelPickerDialog`, `ToolCall`) are fine when they complement the embedded TUI rather than replacing the transcript / composer / terminal. Keep their state independent of the PTY child's session and surface their failures non-destructively so the terminal pane keeps working unimpaired.\n\n### Electron Desktop Chat App (`apps/desktop/`)\n\nA **separate** chat surface from both the classic CLI and the dashboard's embedded TUI. It is an Electron + React + nanostore renderer (`@assistant-ui/react`) that talks to a `tui_gateway` backend over JSON-RPC (`requestGateway(method, params)`). The WebSocket/JSON-RPC transport lives in the framework-agnostic `apps/shared` package (`@hermes/shared` — `JsonRpcGatewayClient` + WS URL helpers), which the web dashboard (`web/`) also consumes; **desktop has no build/runtime dependency on the dashboard frontend** — it spawns a headless `hermes serve` backend server (the same gateway `dashboard` serves, minus the browser UI entirely: `serve` sets `headless_backend=True`, so `cmd_dashboard` skips `_build_web_ui` AND exports `HERMES_SERVE_HEADLESS=1` so `mount_spa()` disables the SPA even if a stray `web_dist/` exists — only the JSON-RPC/WS/API surface is reachable). `dashboard` and `serve` share `cmd_dashboard`/`start_server` but are independent surfaces — neither launches the other. The one exception is a backward-compat *fallback*: `serve` is newer, so the desktop spawn (`electron/backend-command.ts` + `backendSupportsServe()` in `electron/main.ts`) detects whether the resolved runtime registers `serve` and, only when it does not (an older managed install / PATH `hermes` the app hasn't updated yet), rewrites the argv to the legacy `dashboard --no-open`. Without that, a new app against an un-upgraded runtime would crash on an unknown subcommand and brick every mid-upgrade user. It does NOT embed `hermes --tui` — it has its own composer, transcript, and slash-command pipeline. For scoped Desktop architecture, state, resolver, transport, and testing rules, read `apps/desktop/AGENTS.md`.\n\n**Slash commands in the desktop app are curated client-side, then dispatched to the backend.** The pipeline:\n\n- **Backend already provides everything.** `tui_gateway/server.py` `commands.catalog` (empty-query list) and `complete.slash` (typed-query completions) both include built-in commands, user `quick_commands`, AND skill-derived commands (`scan_skill_commands()` / `get_skill_commands()`). The desktop app does not need a new RPC to see skills.\n- **The renderer curates via `apps/desktop/src/lib/desktop-slash-commands.ts`.** This is the load-bearing file. It holds `DESKTOP_COMMAND_SPECS` (the built-ins and their Desktop surfaces) plus `NO_DESKTOP_SURFACE` block-lists for terminal-only / messaging-only / picker-owned / settings-owned / advanced commands that should NOT clutter the desktop popover.\n  - `isDesktopSlashCommand(name)` — gates **execution**. Returns true for built-ins AND for any non-built-in (skill / quick command), so typed extension commands run.\n  - `isDesktopSlashSuggestion(name)` — gates **discovery/completion**. Used by BOTH completion paths in `app/chat/composer/hooks/use-slash-completions.ts` (empty-query catalog filter + typed-query `complete.slash` filter) and by `filterDesktopCommandsCatalog`.\n  - `isDesktopSlashExtensionCommand(name)` — true when the command is NOT a known Hermes built-in (i.e. a skill or user quick command). Both suggestion and catalog-filter paths allow extensions through so skill commands surface in the palette. (Added when fixing \"skill commands missing from the desktop slash palette\" — the curated allow-list was silently dropping every skill/quick command from completions even though they executed fine when typed.)\n- **Dispatch** lives in `app/session/hooks/use-prompt-actions/slash.ts` (`runSlash`): built-ins that the desktop owns (`/skin`, `/help`, `/new`, …) are handled locally or via `commands.catalog`; everything else goes to `slash.exec`, falling back to `command.dispatch` (which the gateway resolves into skill / alias / exec directives). A skill command resolves to `{type: \"skill\", message}` and is submitted as a normal prompt.\n\n**Rule:** the desktop slash palette's curation is about hiding noise (terminal-only / messaging-only built-ins), NOT about hiding user-activated extensions. Skill commands and `quick_commands` are extensions the backend surfaces — they belong in completions. If you tighten `desktop-slash-commands.ts`, keep `isDesktopSlashExtensionCommand` flowing into both the suggestion and catalog-filter paths. Tests: from `apps/desktop`, run `npx vitest run src/lib/desktop-slash-commands.test.ts` (workspace dependencies are installed at the repo root).\n\n---\n\n## Adding New Tools\n\nBefore adding any tool, settle the footprint question first (see \"The\nFootprint Ladder\" in the Contribution Rubric): most capabilities should NOT\nbe core tools. For custom or local-only tools, do **not** edit Hermes core.\nUse the plugin route instead: create `~/.hermes/plugins/<name>/plugin.yaml`\nand `~/.hermes/plugins/<name>/__init__.py`, then register tools with\n`ctx.register_tool(...)`. Plugin toolsets are discovered automatically and can be\nenabled or disabled without touching `tools/` or `toolsets.py`.\n\nUse the built-in route below only when the user is explicitly contributing a new\ncore Hermes tool that should ship in the base system.\n\nBuilt-in/core tools require changes in **2 files**:\n\n**1. Create `tools/your_tool.py`:**\n```python\nimport json, os\nfrom tools.registry import registry\n\ndef check_requirements() -> bool:\n    return bool(os.getenv(\"EXAMPLE_API_KEY\"))\n\ndef example_tool(param: str, task_id: str = None) -> str:\n    return json.dumps({\"success\": True, \"data\": \"...\"})\n\nregistry.register(\n    name=\"example_tool\",\n    toolset=\"example\",\n    schema={\"name\": \"example_tool\", \"description\": \"...\", \"parameters\": {...}},\n    handler=lambda args, **kw: example_tool(param=args.get(\"param\", \"\"), task_id=kw.get(\"task_id\")),\n    check_fn=check_requirements,\n    requires_env=[\"EXAMPLE_API_KEY\"],\n)\n```\n\n**2. Add to `toolsets.py`** — either `_HERMES_CORE_TOOLS` (all platforms) or a new toolset. **This step is required:** auto-discovery imports the tool and registers its schema, but the tool is only *exposed to an agent* if its name appears in a toolset. `_HERMES_CORE_TOOLS` is not dead code — it's the default bundle every platform's base toolset inherits from.\n\nAuto-discovery: any `tools/*.py` file with a top-level `registry.register()` call is imported automatically — no manual import list to maintain. Wiring into a toolset is still a deliberate, manual step.\n\nThe registry handles schema collection, dispatch, availability checking, and error wrapping. All handlers MUST return a JSON string.\n\n**Path references in tool schemas**: If the schema description mentions file paths (e.g. default output directories), use `display_hermes_home()` to make them profile-aware. The schema is generated at import time, which is after `_apply_profile_override()` sets `HERMES_HOME`.\n\n**State files**: If a tool stores persistent state (caches, logs, checkpoints), use `get_hermes_home()` for the base directory — never `Path.home() / \".hermes\"`. This ensures each profile gets its own state.\n\n**Agent-level tools** (todo, memory): intercepted by `run_agent.py` before `handle_function_call()`. See `tools/todo_tool.py` for the pattern.\n\n---\n\n## Dependency Pinning Policy\n\nAll dependencies must have upper bounds to limit supply-chain attack surface.\nThis policy was established after the litellm compromise (PR #2796, #2810) and\nreinforced after the Mini Shai-Hulud worm campaign (May 2026).\n\n| Source type | Treatment | Example |\n|---|---|---|\n| PyPI package | `>=floor,<next_major` | `\"httpx>=0.28.1,<1\"` |\n| Git URL | Commit SHA | `git+https://...@<40-char-sha>` |\n| GitHub Actions | Commit SHA + comment | `uses: actions/checkout@<sha>  # v4` |\n| CI-only pip | `==exact` | `pyyaml==6.0.2` |\n\n**When adding a new dependency to `pyproject.toml`:**\n1. Pin to `>=current_version,<next_major` for post-1.0 (e.g. `>=1.5.0,<2`).\n2. For pre-1.0 packages, use `<0.(current_minor + 2)` (e.g. `>=0.29,<0.32`).\n3. Never commit a bare `>=X.Y.Z` without a ceiling — CI and reviewers will reject it.\n4. Run `uv lock` to regenerate `uv.lock` with hashes.\n\nReference: #2810 (bounds pass), #9801 (SHA pinning + audit CI).\n\n---\n\n## Adding Configuration\n\n### config.yaml options:\n1. Add to `DEFAULT_CONFIG` in `hermes_cli/config.py`\n2. Bump `_config_version` (check the current value at the top of `DEFAULT_CONFIG`)\n   ONLY if you need to actively migrate/transform existing user config\n   (renaming keys, changing structure). Adding a new key to an existing\n   section is handled automatically by the deep-merge and does NOT require\n   a version bump.\n\n### Top-level `config.yaml` sections (non-exhaustive):\n\n`model`, `agent`, `terminal`, `compression`, `display`, `stt`, `tts`,\n`memory`, `security`, `delegation`, `smart_model_routing`, `checkpoints`,\n`auxiliary`, `curator`, `skills`, `gateway`, `logging`, `cron`, `profiles`,\n`plugins`, `honcho`.\n\n`auxiliary` holds per-task overrides for side-LLM work (curator, vision,\nembedding, title generation, session_search, etc.) — each task can pin\nits own provider/model/base_url/max_tokens/reasoning_effort. See\n`agent/auxiliary_client.py::_resolve_auto` for resolution order.\n\n`curator` holds the background skill-maintenance config —\n`enabled`, `interval_hours`, `min_idle_hours`, `stale_after_days`,\n`archive_after_days`, `backup` (nested).\n\n### .env variables (SECRETS ONLY — API keys, tokens, passwords):\n1. Add to `OPTIONAL_ENV_VARS` in `hermes_cli/config.py` with metadata:\n```python\n\"NEW_API_KEY\": {\n    \"description\": \"What it's for\",\n    \"prompt\": \"Display name\",\n    \"url\": \"https://...\",\n    \"password\": True,\n    \"category\": \"tool\",  # provider, tool, messaging, setting\n},\n```\n\nNon-secret settings (timeouts, thresholds, feature flags, paths, display\npreferences) belong in `config.yaml`, not `.env`. If internal code needs an\nenv var mirror for backward compatibility, bridge it from `config.yaml` to\nthe env var in code (see `gateway_timeout`, `terminal.cwd` → `TERMINAL_CWD`).\n\n### Config loaders (three paths — know which one you're in):\n\n| Loader | Used by | Location |\n|--------|---------|----------|\n| `load_cli_config()` | CLI mode | `cli.py` — merges CLI-specific defaults + user YAML |\n| `load_config()` | `hermes tools`, `hermes setup`, most CLI subcommands | `hermes_cli/config.py` — merges `DEFAULT_CONFIG` + user YAML |\n| Direct YAML load | Gateway runtime | `gateway/run.py` + `gateway/config.py` — reads user YAML raw |\n\nIf you add a new key and the CLI sees it but the gateway doesn't (or vice\nversa), you're on the wrong loader. Check `DEFAULT_CONFIG` coverage.\n\n### Working directory:\n- **CLI** — uses the process's current directory (`os.getcwd()`).\n- **Messaging** — uses `terminal.cwd` from `config.yaml`. The gateway bridges this\n  to the `TERMINAL_CWD` env var for child tools. **`MESSAGING_CWD` has been\n  removed** — the config loader prints a deprecation warning if it's set in\n  `.env`. Same for `TERMINAL_CWD` in `.env`; the canonical setting is\n  `terminal.cwd` in `config.yaml`.\n\n---\n\n## Skin/Theme System\n\nThe skin engine (`hermes_cli/skin_engine.py`) provides data-driven CLI visual customization. Skins are **pure data** — no code changes needed to add a new skin.\n\n### Architecture\n\n```\nhermes_cli/skin_engine.py    # SkinConfig dataclass, built-in skins, YAML loader\n~/.hermes/skins/*.yaml       # User-installed custom skins (drop-in)\n```\n\n- `init_skin_from_config()` — called at CLI startup, reads `display.skin` from config\n- `get_active_skin()` — returns cached `SkinConfig` for the current skin\n- `set_active_skin(name)` — switches skin at runtime (used by `/skin` command)\n- `load_skin(name)` — loads from user skins first, then built-ins, then falls back to default\n- Missing skin values inherit from the `default` skin automatically\n\n### What skins customize\n\n| Element | Skin Key | Used By |\n|---------|----------|---------|\n| Banner panel border | `colors.banner_border` | `banner.py` |\n| Banner panel title | `colors.banner_title` | `banner.py` |\n| Banner section headers | `colors.banner_accent` | `banner.py` |\n| Banner dim text | `colors.banner_dim` | `banner.py` |\n| Banner body text | `colors.banner_text` | `banner.py` |\n| Response box border | `colors.response_border` | `cli.py` |\n| Spinner faces (waiting) | `spinner.waiting_faces` | `display.py` |\n| Spinner faces (thinking) | `spinner.thinking_faces` | `display.py` |\n| Spinner verbs | `spinner.thinking_verbs` | `display.py` |\n| Spinner wings (optional) | `spinner.wings` | `display.py` |\n| Tool output prefix | `tool_prefix` | `display.py` |\n| Per-tool emojis | `tool_emojis` | `display.py` → `get_tool_emoji()` |\n| Agent name | `branding.agent_name` | `banner.py`, `cli.py` |\n| Welcome message | `branding.welcome` | `cli.py` |\n| Response box label | `branding.response_label` | `cli.py` |\n| Prompt symbol | `branding.prompt_symbol` | `cli.py` |\n\n### Built-in skins\n\n- `default` — Classic Hermes gold/kawaii (the current look)\n- `ares` — Crimson/bronze war-god theme with custom spinner wings\n- `mono` — Clean grayscale monochrome\n- `slate` — Cool blue developer-focused theme\n\n### Adding a built-in skin\n\nAdd to `_BUILTIN_SKINS` dict in `hermes_cli/skin_engine.py`:\n\n```python\n\"mytheme\": {\n    \"name\": \"mytheme\",\n    \"description\": \"Short description\",\n    \"colors\": { ... },\n    \"spinner\": { ... },\n    \"branding\": { ... },\n    \"tool_prefix\": \"┊\",\n},\n```\n\n### User skins (YAML)\n\nUsers create `~/.hermes/skins/<name>.yaml`:\n\n```yaml\nname: cyberpunk\ndescription: Neon-soaked terminal theme\n\ncolors:\n  banner_border: \"#FF00FF\"\n  banner_title: \"#00FFFF\"\n  banner_accent: \"#FF1493\"\n\nspinner:\n  thinking_verbs: [\"jacking in\", \"decrypting\", \"uploading\"]\n  wings:\n    - [\"⟨⚡\", \"⚡⟩\"]\n\nbranding:\n  agent_name: \"Cyber Agent\"\n  response_label: \" ⚡ Cyber \"\n\ntool_prefix: \"▏\"\n```\n\nActivate with `/skin cyberpunk` or `display.skin: cyberpunk` in config.yaml.\n\n---\n\n## Plugins\n\nHermes has two plugin surfaces. Both live under `plugins/` in the repo so\nrepo-shipped plugins can be discovered alongside user-installed ones in\n`~/.hermes/plugins/` and pip-installed entry points.\n\n### General plugins (`hermes_cli/plugins.py` + `plugins/<name>/`)\n\n`PluginManager` discovers plugins from `~/.hermes/plugins/`, `./.hermes/plugins/`,\nand pip entry points. Each plugin exposes a `register(ctx)` function that\ncan:\n\n- Register Python-callback lifecycle hooks:\n  `pre_tool_call`, `post_tool_call`, `pre_llm_call`, `post_llm_call`,\n  `on_session_start`, `on_session_end`\n- Register new tools via `ctx.register_tool(...)`\n- Register CLI subcommands via `ctx.register_cli_command(...)` — the\n  plugin's argparse tree is wired into `hermes` at startup so\n  `hermes <pluginname> <subcmd>` works with no change to `main.py`\n\nHooks are invoked from `model_tools.py` (pre/post tool) and `run_agent.py`\n(lifecycle). **Discovery timing pitfall:** `discover_plugins()` only runs\nas a side effect of importing `model_tools.py`. Code paths that read plugin\nstate without importing `model_tools.py` first must call `discover_plugins()`\nexplicitly (it's idempotent).\n\n#### Native plugin compatibility policy\n\nThe canonical contract and deprecation policy live in\n`website/docs/developer-guide/plugins/index.md#native-plugin-compatibility-contract`.\nCompatibility is enforced as a behavior contract, not through a monolithic\n`PLUGIN_API_VERSION`, a manifest-wide native `api:` match, or version literals\non unrelated payloads. Keep documented plugin surfaces additive:\n\n- add hook payload data as keyword fields; signature-inspect callbacks so old\n  narrow signatures receive only fields they declare, while `**kwargs`\n  callbacks receive the complete payload;\n- do not remove or rename `PluginContext` methods; make new parameters optional\n  with defaults and keyword-only where possible;\n- ignore unknown native manifest fields;\n- give new provider methods default implementations, and signature-inspect\n  optional callback kwargs rather than forwarding them unconditionally;\n- use a local schema version only for a capability with a wire or persisted\n  contract, and preserve old state/config/session replay or ship a migration.\n\nDeprecations require a once-per-process warning, a documented replacement and\nmigration note, and at least two subsequent minor releases before removal.\nCompatibility tests must load frozen plugins through the real discovery path\nand assert outcomes. Do not replace these with exact registry/catalog counts,\nsource-reading tests, or assertions that a global version literal changed.\n\n### Memory-provider plugins (`plugins/memory/<name>/`)\n\nSeparate discovery system for pluggable memory backends. Current built-in\nproviders include **honcho, mem0, supermemory, byterover, hindsight,\nholographic, openviking, retaindb**.\n\nDiscovery covers the same four sources as the general `PluginManager` —\nbundled, `$HERMES_HOME/plugins/`, `./.hermes/plugins/` (opt-in via\n`HERMES_ENABLE_PROJECT_PLUGINS`), and `hermes_agent.memory_providers` entry\npoints — but with **bundled-first** precedence, the reverse of the general\nsystem's later-wins order: a memory provider is activated by name, so a\ndropped-in directory must not be able to shadow a shipped one. Discovery\nenumerates without importing; nothing runs until `memory.provider` names it.\n\nEach provider implements the `MemoryProvider` ABC (see `agent/memory_provider.py`)\nand is orchestrated by `agent/memory_manager.py`. Lifecycle hooks include\n`sync_turn(turn_messages)`, `prefetch(query)`, `shutdown()`, and optional\n`post_setup(hermes_home, config)` for setup-wizard integration.\n\n**CLI commands via `plugins/memory/<name>/cli.py`:** if a memory plugin\ndefines `register_cli(subparser)`, `discover_plugin_cli_commands()` finds\nit at argparse setup time and wires it into `hermes <plugin>`. The\nframework only exposes CLI commands for the **currently active** memory\nprovider (read from `memory.provider` in config.yaml), so disabled\nproviders don't clutter `hermes --help`.\n\n**Rule (Teknium, May 2026):** plugins MUST NOT modify core files\n(`run_agent.py`, `cli.py`, `gateway/run.py`, `hermes_cli/main.py`, etc.).\nIf a plugin needs a capability the framework doesn't expose, expand the\ngeneric plugin surface (new hook, new ctx method) — never hardcode\nplugin-specific logic into core. PR #5295 removed 95 lines of hardcoded\nhoncho argparse from `main.py` for exactly this reason.\n\n**No new in-tree memory providers (policy, May 2026):** the set of\nbuilt-in memory providers under `plugins/memory/` is closed. New memory\nbackends must ship as **standalone plugin repos** that users install\ninto `~/.hermes/plugins/` (or via pip entry points) — they implement\nthe same `MemoryProvider` ABC, register through the same discovery\npath, and integrate via `hermes memory setup` / `post_setup()` without\nlanding in this tree. PRs that add a new directory under\n`plugins/memory/` will be closed with a pointer to publish the\nprovider as its own repo. Existing in-tree providers stay; bug fixes\nto them are welcome.\n\n**No new third-party-product plugins in-tree (policy, June 2026):** the\nsame rule applies beyond memory providers. Plugins that integrate\nsomeone else's product or project — observability/metrics backends,\nvendor SaaS connectors, analytics dashboards, paid-service tie-ins —\nmust ship as **standalone plugin repos** that users install into\n`~/.hermes/plugins/` (or via pip entry points). They register through\nthe existing plugin discovery path and use the ABCs/hooks/ctx surface\nwe expose; nothing special is needed in core. The reason is\nmaintenance load: every product we absorb into the tree becomes our\nburden to keep working against a fast-moving core, for a backend we\ndon't own. Promote standalone plugins in the Nous Research Discord\n(`#plugins-skills-and-skins`). PRs that add such a directory under\n`plugins/` are closed with a pointer to publish it as its own repo —\nthis is a coupling decision, not a quality judgment. (The\n`observability/`, `kanban/`, `disk-cleanup/`, etc. directories already\nin the tree are existing precedent, not an invitation to add more\nthird-party-product plugins alongside them.)\n\n### Model-provider plugins (`plugins/model-providers/<name>/`)\n\nEvery inference backend (openrouter, anthropic, gmi, deepseek, nvidia, …)\nships as a plugin here. Each plugin's `__init__.py` calls\n`providers.register_provider(ProviderProfile(...))` at module load.\n`providers/__init__.py._discover_providers()` is a **lazy, separate\ndiscovery system** — scanned on first `get_provider_profile()` or\n`list_providers()` call, NOT by the general PluginManager.\n\nScan order:\n1. Bundled: `<repo>/plugins/model-providers/<name>/`\n2. User: `$HERMES_HOME/plugins/model-providers/<name>/`\n3. Legacy: `<repo>/providers/<name>.py` (back-compat)\n\nUser plugins of the same name override bundled ones — `register_provider()`\nis last-writer-wins. This lets third parties swap out any built-in\nprofile without a repo patch.\n\nThe general PluginManager records `kind: model-provider` manifests but does\nNOT import them (would double-instantiate `ProviderProfile`). Plugins\nwithout an explicit `kind:` get auto-coerced via a source-text heuristic\n(`register_provider` + `ProviderProfile` in `__init__.py`).\n\nFull authoring guide: `website/docs/developer-guide/model-provider-plugin.md`.\n\n### Dashboard / context-engine / image-gen plugin directories\n\n`plugins/context_engine/`, `plugins/image_gen/`, etc. follow the same\npattern (ABC + orchestrator + per-plugin directory). Context engines\nplug into `agent/context_engine.py`; image-gen providers into\n`agent/image_gen_provider.py`. Reference / docs-companion plugins\n(`example-dashboard`, `strike-freedom-cockpit`, `plugin-llm-example`,\n`plugin-llm-async-example`) live in the\n[`hermes-example-plugins`](https://github.com/NousResearch/hermes-example-plugins)\ncompanion repo, not in this tree.\n\n---\n\n## Skills\n\nTwo parallel surfaces:\n\n- **`skills/`** — built-in skills shipped and loadable by default.\n  Organized by category directories (e.g. `skills/github/`, `skills/mlops/`).\n- **`optional-skills/`** — heavier or niche skills shipped with the repo but\n  NOT active by default. Installed explicitly via\n  `hermes skills install official/<category>/<skill>`. Adapter lives in\n  `tools/skills_hub.py` (`OptionalSkillSource`). Categories include\n  `autonomous-ai-agents`, `blockchain`, `communication`, `creative`,\n  `devops`, `email`, `health`, `mcp`, `migration`, `mlops`, `productivity`,\n  `research`, `security`, `web-development`.\n\nWhen reviewing skill PRs, check which directory they target — heavy-dep or\nniche skills belong in `optional-skills/`.\n\n### SKILL.md frontmatter\n\nStandard fields: `name`, `description`, `version`, `author`, `license`,\n`platforms` (OS-gating list: `[macos]`, `[linux, macos]`, ...),\n`metadata.hermes.tags`, `metadata.hermes.category`,\n`metadata.hermes.related_skills`, `metadata.hermes.config` (config.yaml\nsettings the skill needs — stored under `skills.config.<key>`, prompted\nduring setup, injected at load time).\n\nTop-level `tags:` and `category:` are also accepted and mirrored from\n`metadata.hermes.*` by the loader.\n\n### Skill authoring standards (HARDLINE)\n\nEvery new or modernized skill — bundled, optional, or contributed —\nmust meet these standards before merge. Reviewers reject PRs that\nviolate them.\n\n1. **`description` ≤ 60 characters, one sentence, ends with a period.**\n   Long descriptions bloat skill listings and dilute the model's\n   attention when many skills are loaded. State the capability, not\n   the implementation. No marketing words (\"powerful\",\n   \"comprehensive\", \"seamless\", \"advanced\"). Don't repeat the skill\n   name. Verify with:\n   ```python\n   import re, pathlib\n   m = re.search(r'^description: (.*)$',\n                 pathlib.Path('skills/<cat>/<name>/SKILL.md').read_text(),\n                 re.MULTILINE)\n   assert len(m.group(1)) <= 60, len(m.group(1))\n   ```\n\n2. **Tools referenced in SKILL.md prose must be native Hermes tools or\n   MCP servers the skill explicitly expects.** When the skill needs a\n   capability, point at the proper tool by name in backticks\n   (`` `terminal` ``, `` `web_extract` ``, `` `read_file` ``,\n   `` `patch` ``, `` `search_files` ``, `` `vision_analyze` ``,\n   `` `browser_navigate` ``, `` `delegate_task` ``, etc.). Do NOT\n   name shell utilities the agent already has wrapped — `grep` →\n   `search_files`, `cat`/`head`/`tail` → `read_file`, `sed`/`awk` →\n   `patch`, `find`/`ls` → `search_files target='files'`. If the skill\n   depends on an MCP server, name the MCP server and document the\n   expected setup in `## Prerequisites`. Anything else (third-party\n   CLIs, shell pipelines, etc.) is fair game inside script files but\n   should not be the headline interaction surface in the prose.\n\n3. **`platforms:` gating audited against actual script imports.**\n   Skills that use POSIX-only primitives (`fcntl`, `termios`,\n   `os.setsid`, `os.kill(pid, 0)` for liveness, `/proc`, `/tmp`\n   hardcoded, `signal.SIGKILL`, bash heredocs, `osascript`, `apt`,\n   `systemctl`) must declare their supported platforms. Default\n   posture: try to fix it cross-platform first — `tempfile.gettempdir`,\n   `pathlib.Path`, `psutil.pid_exists`, Python-level filtering instead\n   of `grep`. Gate to a narrower set only when the dependency is\n   genuinely platform-bound.\n\n4. **`author` credits the human contributor first.** For external\n   contributions, the contributor's real name + GitHub handle goes\n   first; \"Hermes Agent\" is the secondary collaborator. If the\n   contributor's commit shows \"Hermes Agent\" as author (because they\n   used Hermes to draft the skill), replace it with their actual name\n   — credit the human, not the tool.\n\n5. **SKILL.md body uses the modern section order.** `# <Skill> Skill`\n   title, 2-3 sentence intro stating what it does and doesn't do,\n   `## When to Use`, `## Prerequisites`, `## How to Run`,\n   `## Quick Reference`, `## Procedure`, `## Pitfalls`,\n   `## Verification`. Target ~200 lines for a complex skill,\n   ~100 lines for a simple one. Cut redundant intro fluff, marketing\n   prose, and re-explanations of env vars already in\n   `## Prerequisites`.\n\n6. **Scripts go in `scripts/`, references in `references/`,\n   templates in `templates/`.** Don't expect the model to inline-write\n   parsers, XML walkers, or non-trivial logic every call — ship a\n   helper script. Reference it from SKILL.md by path relative to the\n   skill directory.\n\n7. **Tests live at `tests/skills/test_<skill>_skill.py`** and use only\n   stdlib + pytest + `unittest.mock`. No live network calls. Run via\n   `scripts/run_tests.sh tests/skills/test_<skill>_skill.py -q`.\n\n8. **`.env.example` additions are isolated to a clearly delimited\n   block.** Don't touch the surrounding file — contributor-supplied\n   `.env.example` versions are usually stale and edits outside the\n   skill's own block must be dropped during salvage.\n\nThe full salvage / modernization checklist for external skill PRs\nlives in the `hermes-agent-dev` skill at\n`references/new-skill-pr-salvage.md` — load it before polishing\ncontributor skill PRs.\n\n---\n\n## Toolsets\n\nAll toolsets are defined in `toolsets.py` as a single `TOOLSETS` dict.\nEach platform's adapter picks a base toolset (e.g. Telegram uses\n`\"messaging\"`); `_HERMES_CORE_TOOLS` is the default bundle most\nplatforms inherit from.\n\nCurrent toolset keys: `browser`, `clarify`, `code_execution`, `cronjob`,\n`debugging`, `delegation`, `discord`, `discord_admin`, `feishu_doc`,\n`feishu_drive`, `file`, `homeassistant`, `image_gen`, `kanban`, `memory`,\n`messaging`, `moa`, `rl`, `safe`, `search`, `session_search`, `skills`,\n`spotify`, `terminal`, `todo`, `tts`, `video`, `vision`, `web`, `yuanbao`.\n\nEnable/disable per platform via `hermes tools` (the curses UI) or the\n`tools.<platform>.enabled` / `tools.<platform>.disabled` lists in\n`config.yaml`.\n\n---\n\n## Delegation (`delegate_task`)\n\n`tools/delegate_tool.py` spawns a subagent with an isolated\ncontext + terminal session. By default the parent waits for the\nchild's summary before continuing its own loop. With `background=true`,\nHermes returns a delegation id immediately and the result re-enters the\nconversation later through the async-delegation completion queue.\n\nTwo shapes:\n\n- **Single:** pass `goal` (+ optional `context`, `toolsets`).\n- **Batch (parallel):** pass `tasks: [...]` — each gets its own subagent\n  running concurrently. Concurrency is capped by\n  `delegation.max_concurrent_children` (default 3).\n\nRoles:\n\n- `role=\"leaf\"` (default) — focused worker. Cannot call `delegate_task`,\n  `clarify`, `memory`, `send_message`, `cronjob`. Retains `execute_code`\n  (programmatic tool calling).\n- `role=\"orchestrator\"` — retains `delegate_task` so it can spawn its\n  own workers. Gated by `delegation.orchestrator_enabled` (default true)\n  and bounded by `delegation.max_spawn_depth` (default 2).\n\nKey config knobs (under `delegation:` in `config.yaml`):\n`max_concurrent_children`, `max_spawn_depth`, `child_timeout_seconds`,\n`orchestrator_enabled`, `subagent_auto_approve`, `inherit_mcp_toolsets`,\n`max_iterations`.\n\nDurability rule: background `delegate_task` is detached from the current\nturn but still process-local. For work that must survive process restart, use\n`cronjob` or `terminal(background=True, notify_on_complete=True)` instead.\n\n---\n\n## Curator (skill lifecycle)\n\nBackground skill-maintenance system that tracks usage on agent-created\nskills and auto-archives stale ones. Users never lose skills; archives\ngo to `~/.hermes/skills/.archive/` and are restorable.\n\n- **Core:** `agent/curator.py` (review loop, auto-transitions, LLM review\n  prompt) + `agent/curator_backup.py` (pre-run tar.gz snapshots).\n- **CLI:** `hermes_cli/curator.py` wires `hermes curator <verb>` where\n  verbs are: `status`, `run`, `pause`, `resume`, `pin`, `unpin`,\n  `archive`, `restore`, `prune`, `backup`, `rollback`.\n- **Telemetry:** `tools/skill_usage.py` owns the sidecar\n  `~/.hermes/skills/.usage.json` — per-skill `use_count`, `view_count`,\n  `patch_count`, `last_activity_at`, `state` (active / stale /\n  archived), `pinned`.\n\nInvariants:\n- Curator only touches skills with `created_by: \"agent\"` provenance —\n  bundled + hub-installed skills are off-limits.\n- Never deletes; max destructive action is archive.\n- Pinned skills are exempt from every auto-transition and from the\n  LLM review pass.\n- `skill_manage(action=\"delete\")` refuses pinned skills; patch/edit/\n  write_file/remove_file go through so the agent can keep improving\n  pinned skills.\n\nConfig section (`curator:` in `config.yaml`):\n`enabled`, `interval_hours`, `min_idle_hours`, `stale_after_days`,\n`archive_after_days`, `backup.*`.\n\nFull user-facing docs: `website/docs/user-guide/features/curator.md`.\n\n---\n\n## Cron (scheduled jobs)\n\n`cron/jobs.py` (job store) + `cron/scheduler.py` (tick loop). Agents\nschedule jobs via the `cronjob` tool; users via `hermes cron <verb>`\n(`list`, `add`, `edit`, `pause`, `resume`, `run`, `remove`) or the\n`/cron` slash command.\n\nSupported schedule formats:\n- Duration: `\"30m\"`, `\"2h\"`, `\"1d\"`\n- \"every\" phrase: `\"every 2h\"`, `\"every monday 9am\"`\n- 5-field cron expression: `\"0 9 * * *\"`\n- ISO timestamp (one-shot): `\"2026-06-01T09:00:00Z\"`\n\nPer-job fields include `skills` (load specific skills), `model` /\n`provider` overrides, `script` (pre-run data-collection script whose\nstdout is injected into the prompt; `no_agent=True` turns the script\ninto the entire job), `context_from` (chain job A's last output into\njob B's prompt), `workdir` (run in a specific directory with its\n`AGENTS.md`/`CLAUDE.md` loaded), and multi-platform delivery.\n\nHardening invariants:\n- **3-minute hard interrupt** on cron sessions — runaway agent loops\n  cannot monopolize the scheduler.\n- Catchup window: half the job's period, clamped to 120s–2h.\n- Grace window: 120s for one-shot jobs whose fire time was missed.\n- File lock at `~/.hermes/cron/.tick.lock` prevents duplicate ticks\n  across processes.\n- Cron sessions pass `skip_memory=True` by default; memory providers\n  intentionally do not run during cron.\n\nCron deliveries are **not** mirrored into the target gateway session —\nthey land in their own cron session with a header/footer frame so the\nmain conversation's message-role alternation stays intact.\n\n---\n\n## Kanban (multi-agent work queue)\n\nDurable SQLite-backed board that lets multiple profiles / workers\ncollaborate on shared tasks. Users drive it via `hermes kanban <verb>`;\nworkers spawned by the dispatcher drive it via a dedicated `kanban_*`\ntoolset so their schema footprint is zero when they're not inside a\nkanban task.\n\n- **CLI:** `hermes_cli/kanban.py` wires `hermes kanban` with verbs\n  `init`, `create`, `list` (alias `ls`), `show`, `assign`, `link`,\n  `unlink`, `comment`, `attach`, `attachments`, `attach-rm`, `complete`,\n  `request-review`, `request-changes`, `reopen-review`, `block`, `unblock`, `archive`,\n  `tail`, plus less-commonly-used `watch`, `stats`, `runs`, `log`,\n  `assignees`, `heartbeat`, `notify-*`, `dispatch`, `daemon`, `gc`.\n- **Worker/orchestrator toolset:** `tools/kanban_tools.py` exposes\n  `kanban_show`, `kanban_complete`, `kanban_request_review`,\n  `kanban_request_changes`, `kanban_block`,\n  `kanban_heartbeat`, `kanban_comment`, `kanban_create`, `kanban_link`,\n  `kanban_attach`, `kanban_attach_url`, `kanban_attachments`; profiles that\n  explicitly enable the `kanban` toolset outside a dispatcher-spawned\n  task also get `kanban_list` and `kanban_unblock` for board routing.\n- **Dispatcher:** long-lived loop that (default every 60s) reclaims\n  stale claims, promotes ready tasks, atomically claims, and spawns\n  assigned profiles. Runs **inside the gateway** by default via\n  `kanban.dispatch_in_gateway: true`.\n- **Plugin assets:** `plugins/kanban/dashboard/` (web UI) +\n  `plugins/kanban/systemd/` (`hermes-kanban-dispatcher.service` for\n  standalone dispatcher deployment).\n\nIsolation model:\n- **Board** is the hard boundary — workers are spawned with\n  `HERMES_KANBAN_BOARD` pinned in their env so they can't see other\n  boards.\n- **Tenant** is a soft namespace *within* a board — one specialist\n  fleet can serve multiple businesses with workspace-path + memory-key\n  isolation.\n- After `kanban.failure_limit` consecutive non-success attempts on the\n  same task (default: 2), the dispatcher auto-blocks it to prevent spin\n  loops.\n\nFull user-facing docs: `website/docs/user-guide/features/kanban.md`.\n\n---\n\n## Important Policies\n\n### Prompt Caching Must Not Break\n\nHermes-Agent ensures caching remains valid throughout a conversation. **Do NOT implement changes that would:**\n- Alter past context mid-conversation\n- Change toolsets mid-conversation\n- Reload memories or rebuild system prompts mid-conversation\n\nCache-breaking forces dramatically higher costs. The ONLY time we alter context is during context compression.\n\nSlash commands that mutate system-prompt state (skills, tools, memory, etc.)\nmust be **cache-aware**: default to deferred invalidation (change takes\neffect next session), with an opt-in `--now` flag for immediate\ninvalidation. See `/skills install --now` for the canonical pattern.\n\n### Background Process Notifications (Gateway)\n\nWhen `terminal(background=true, notify_on_complete=true)` is used, the gateway runs a watcher that\ndetects process completion and triggers a new agent turn. Control verbosity of background process\nmessages with `display.background_process_notifications`\nin config.yaml (or `HERMES_BACKGROUND_NOTIFICATIONS` env var):\n\n- `concise` — one-line status message on completion; failures append a short output tail (default)\n- `all` — running-output updates + final raw-output message\n- `result` — only the final raw-output completion message\n- `error` — only the final raw-output message when exit code != 0\n- `off` — no watcher messages at all\n\n---\n\n## Profiles: Multi-Instance Support\n\nHermes supports **profiles** — multiple fully isolated instances, each with its own\n`HERMES_HOME` directory (config, API keys, memory, sessions, skills, gateway, etc.).\n\nThe core mechanism: `_apply_profile_override()` in `hermes_cli/main.py` sets\n`HERMES_HOME` before any module imports. All `get_hermes_home()` references\nautomatically scope to the active profile.\n\n### Rules for profile-safe code\n\n1. **Use `get_hermes_home()` for all HERMES_HOME paths.** Import from `hermes_constants`.\n   NEVER hardcode `~/.hermes` or `Path.home() / \".hermes\"` in code that reads/writes state.\n   ```python\n   # GOOD\n   from hermes_constants import get_hermes_home\n   config_path = get_hermes_home() / \"config.yaml\"\n\n   # BAD — breaks profiles\n   config_path = Path.home() / \".hermes\" / \"config.yaml\"\n   ```\n\n2. **Use `display_hermes_home()` for user-facing messages.** Import from `hermes_constants`.\n   This returns `~/.hermes` for default or `~/.hermes/profiles/<name>` for profiles.\n   ```python\n   # GOOD\n   from hermes_constants import display_hermes_home\n   print(f\"Config saved to {display_hermes_home()}/config.yaml\")\n\n   # BAD — shows wrong path for profiles\n   print(\"Config saved to ~/.hermes/config.yaml\")\n   ```\n\n3. **Module-level constants are fine** — they cache `get_hermes_home()` at import time,\n   which is AFTER `_apply_profile_override()` sets the env var. Just use `get_hermes_home()`,\n   not `Path.home() / \".hermes\"`.\n\n4. **Tests that mock `Path.home()` must also set `HERMES_HOME`** — since code now uses\n   `get_hermes_home()` (reads env var), not `Path.home() / \".hermes\"`:\n   ```python\n   with patch.object(Path, \"home\", return_value=tmp_path), \\\n        patch.dict(os.environ, {\"HERMES_HOME\": str(tmp_path / \".hermes\")}):\n       ...\n   ```\n\n5. **Gateway platform adapters should use token locks** — if the adapter connects with\n   a unique credential (bot token, API key), call `acquire_scoped_lock()` from\n   `gateway.status` in the `connect()`/`start()` method and `release_scoped_lock()` in\n   `disconnect()`/`stop()`. This prevents two profiles from using the same credential.\n   See `plugins/platforms/irc/adapter.py` for the canonical pattern.\n\n6. **Profile operations are HOME-anchored, not HERMES_HOME-anchored** — `_get_profiles_root()`\n   returns `Path.home() / \".hermes\" / \"profiles\"`, NOT `get_hermes_home() / \"profiles\"`.\n   This is intentional — it lets `hermes -p coder profile list` see all profiles regardless\n   of which one is active.\n\n## Known Pitfalls\n\n### DO NOT hardcode `~/.hermes` paths\nUse `get_hermes_home()` from `hermes_constants` for code paths. Use `display_hermes_home()`\nfor user-facing print/log messages. Hardcoding `~/.hermes` breaks profiles — each profile\nhas its own `HERMES_HOME` directory. This was the source of 5 bugs fixed in PR #3575.\n\n### All CLI menu-pickers MUST use curses.\nInteractive menus must use `hermes_cli/curses_ui.py`. See `hermes_cli/tools_config.py` for an example.\n\n### DO NOT use `\\033[K` (ANSI erase-to-EOL) in spinner/display code\nLeaks as literal `?[K` text under `prompt_toolkit`'s `patch_stdout`. Use space-padding: `f\"\\r{line}{' ' * pad}\"`.\n\n### `_last_resolved_tool_names` is a process-global in `model_tools.py`\n`_run_single_child()` in `delegate_tool.py` saves and restores this global around subagent execution. If you add new code that reads this global, be aware it may be temporarily stale during child agent runs.\n\n### DO NOT hardcode cross-tool references in schema descriptions\nTool schema descriptions must not mention tools from other toolsets by name (e.g., `browser_navigate` saying \"prefer web_search\"). Those tools may be unavailable (missing API keys, disabled toolset), causing the model to hallucinate calls to non-existent tools. If a cross-reference is needed, add it dynamically in `get_tool_definitions()` in `model_tools.py` — see the `browser_navigate` / `execute_code` post-processing blocks for the pattern.\n\n### The gateway has TWO message guards — both must bypass approval/control commands\nWhen an agent is running, messages pass through two sequential guards:\n(1) **base adapter** (`gateway/platforms/base.py`) queues messages in\n`_pending_messages` when `session_key in self._active_sessions`, and\n(2) **gateway runner** (`gateway/run.py`) intercepts `/stop`, `/new`,\n`/queue`, `/status`, `/approve`, `/deny` before they reach\n`running_agent.interrupt()`. Any new command that must reach the runner\nwhile the agent is blocked (e.g. approval prompts) MUST bypass BOTH\nguards and be dispatched inline, not via `_process_message_background()`\n(which races session lifecycle).\n\n### Squash merges from stale branches silently revert recent fixes\nBefore squash-merging a PR, ensure the branch is up to date with `main`\n(`git fetch origin main && git reset --hard origin/main` in the worktree,\nthen re-apply the PR's commits). A stale branch's version of an unrelated\nfile will silently overwrite recent fixes on main when squashed. Verify\nwith `git diff HEAD~1..HEAD` after merging — unexpected deletions are a\nred flag.\n\n### Don't wire in dead code without E2E validation\nUnused code that was never shipped was dead for a reason. Before wiring an\nunused module into a live code path, E2E test the real resolution chain\nwith actual imports (not mocks) against a temp `HERMES_HOME`.\n\n### Tests must not write to `~/.hermes/`\nThe `_isolate_hermes_home` autouse fixture in `tests/conftest.py` redirects `HERMES_HOME` to a temp dir. Never hardcode `~/.hermes/` paths in tests.\n\n**Profile tests**: When testing profile features, also mock `Path.home()` so that\n`_get_profiles_root()` and `_get_default_hermes_home()` resolve within the temp dir.\nUse the pattern from `tests/hermes_cli/test_profiles.py`:\n```python\n@pytest.fixture\ndef profile_env(tmp_path, monkeypatch):\n    home = tmp_path / \".hermes\"\n    home.mkdir()\n    monkeypatch.setattr(Path, \"home\", lambda: tmp_path)\n    monkeypatch.setenv(\"HERMES_HOME\", str(home))\n    return home\n```\n\n---\n\n## Testing\n\n### Python\n**ALWAYS use `scripts/run_tests.sh`** — do not call `pytest` directly. The script enforces\nhermetic environment parity with CI (unset credential vars, TZ=UTC, LANG=C.UTF-8,\nper-file subprocess isolation via `scripts/run_tests_parallel.py` — no xdist,\nworker count auto-scaled from CPU count). Direct `pytest`\non a 16+ core developer machine with API keys set diverges from CI in ways\nthat have caused multiple \"works locally, fails in CI\" incidents (and the reverse).\n\n```bash\nscripts/run_tests.sh                                  # full suite, CI-parity\nscripts/run_tests.sh tests/gateway/                   # one directory\nscripts/run_tests.sh tests/agent/test_foo.py -k test_x  # one test (file + -k; the runner is file-granular)\nscripts/run_tests.sh -v --tb=long                     # pass-through pytest flags\n```\n\n**Flake policy:** the runner auto-retries a failing test FILE once in a fresh\nsubprocess (`--file-retries`, default 1; `HERMES_TEST_FILE_RETRIES=0` to\ndisable). Pass-on-retry counts as green but is printed in a `⚠ FLAKY` summary\nsection with both attempts' output. A FLAKY report is a bug to fix, not noise\nto ignore — timing-sensitive tests must not assume a quiet runner (loose\nwall-clock bounds ≥ 2s, event-based sync, no `assert not _wait_until(...)`\nnegative-timing races).\n\n#### Subprocess-per-test-file isolation\n\nEvery test file runs in a freshly-spawned Python subprocess via `run_tests_parallel.py`. This means module-level dicts/sets and\nContextVars from one test file cannot leak into the next.\n\n#### Why the wrapper\n\n|                     | Without wrapper                             | With wrapper                              |\n| ------------------- | ------------------------------------------- | ----------------------------------------- |\n| Provider API keys   | Whatever is in your env (auto-detects pool) | All env vars except a specific few unset. |\n| HOME / `~/.hermes/` | Your real config+auth.json                  | Temp dir per test                         |\n| Timezone            | Local TZ (PDT etc.)                         | UTC                                       |\n| Locale              | Whatever is set                             | C.UTF-8                                   |\n\n### Where to place what tests\n\nThe CI change classifier (`scripts/ci/classify_changes.py`) runs specific jobs based on what files changed. A Python test that asserts\nabout the contents of `package.json`, `package-lock.json`, `.ts`/`.tsx`\nsource, or any other JS-side artifact will not run on a PR that only touches\nthose files. This means a regression can go green on a PR and red on `main` (where the\nclassifier fails open and runs everything).\n\nAny test that reads or asserts about `package.json`,\n`package-lock.json`, `tsconfig.json`, `.ts`/`.tsx`/`.js`/`.mjs`/`.cjs`\nsource files configuration belongs in the JS (vitest) test suite, not in `tests/*.py`.\n\n### Don't fake the host OS\n\nHermes supports Linux, macOS and native Windows, and plenty of its behaviour\ngenuinely differs per host. Those differences are tested by running on the\nhost, not by patching `sys.platform`.\n\n```python\n@pytest.mark.linux_only\n@pytest.mark.macos_only\n@pytest.mark.windows_only\n```\n\nThings that are host-independent can stay unmarked:\n\n- **Pure functions that take a platform as data** —\n  `hidden_windows_child_options(opts, is_windows=True)` is input→output, not a\n  fake host. (Contrast: setting a module-level `IS_WINDOWS` flag and then\n  calling `windows_detach_flags()` *is* a fake.)\n- **Declaration/packaging invariants** — \"pyproject declares `tzdata` with a\n  `sys_platform == 'win32'` marker\" asserts about a file, not about runtime.\n\nThe line: **if the test needs the interpreter to believe it is on another OS\nin order to pass, it belongs on that OS.**\nWhen one test body walks several platforms in sequence, split it.\nKeep the host-native arm on the Linux lane and move the other arm into its own marked test.\n\n**Use the marker, never a bare `skipif`.** `scripts/ci/list_os_marked_tests.py`\ndecides which files the macOS/Windows lanes import by grepping for the marker\n*name*, and the lane then filters with `-m <marker>`. A test gated with\n`@pytest.mark.skipif(sys.platform != \"win32\")` therefore skips on Linux AND is\nnever imported on the Windows lane — it runs on no host at all, silently. The\nsame trap catches a file-local alias (`windows_only = pytest.mark.skipif(...)`):\nthe grep matches the name, so the file *is* listed, but `-m windows_only`\ndeselects every test in it and the lane reports green over zero coverage.\nEqually, don't `pytest.skip()` the non-host rows of a `@parametrize` over\nplatforms — split it into one marked test per OS, or only the host's row ever\nexecutes.\n\n### Don't write change-detector tests\n\nA test is a **change-detector** if it fails whenever data that is **expected\nto change** gets updated — model catalogs, config version numbers,\nenumeration counts, hardcoded lists of provider models. These tests add no\nbehavioral coverage; they just guarantee that routine source updates break\nCI and cost engineering time to \"fix.\"\n\n**Do not write:**\n\n```python\n# catalog snapshot — breaks every model release\nassert \"gemini-2.5-pro\" in _PROVIDER_MODELS[\"gemini\"]\nassert \"MiniMax-M2.7\" in models\n\n# config version literal — breaks every schema bump\nassert DEFAULT_CONFIG[\"_config_version\"] == 21\n\n# enumeration count — breaks every time a skill/provider is added\nassert len(_PROVIDER_MODELS[\"huggingface\"]) == 8\n```\n\n**Do write:**\n\n```python\n# behavior: does the catalog plumbing work at all?\nassert \"gemini\" in _PROVIDER_MODELS\nassert len(_PROVIDER_MODELS[\"gemini\"]) >= 1\n\n# behavior: does migration bump the user's version to current latest?\nassert raw[\"_config_version\"] == DEFAULT_CONFIG[\"_config_version\"]\n\n# invariant: no plan-only model leaks into the legacy list\nassert not (set(moonshot_models) & coding_plan_only_models)\n\n# invariant: every model in the catalog has a context-length entry\nfor m in _PROVIDER_MODELS[\"huggingface\"]:\n    assert m.lower() in DEFAULT_CONTEXT_LENGTHS_LOWER\n```\n\nThe rule: if the test reads like a snapshot of current data, delete it. If\nit reads like a contract about how two pieces of data must relate, keep it.\nWhen a PR adds a new provider/model and you want a test, make the test\nassert the relationship (e.g. \"catalog entries all have context lengths\"),\nnot the specific names.\n\nReviewers should reject new change-detector tests; authors should convert\nthem into invariants before re-requesting review.\n\n### Never read source code in tests\n\nA test that reads a source file's text is testing *the shape of the\nsource code*, not its behavior. This is a hard antipattern, banned outright.\nAny test that reads a .py, .ts, .tsx, etc., file is suspect.\n\n**Why it's actively harmful, not just weak:**\n\n- It passes when the implementation is subtly broken (the regex matches a\n  call site that exists but is wired wrong) and fails when a correct\n  refactor changes formatting, variable names, or control flow with\n  identical runtime behavior. Both directions of failure are wrong.\n- It can't be run against a built/bundled/minified artifact, so it silently\n  stops testing anything the moment code moves, gets renamed, or a\n  dependency reformats it.\n- It actively blocks refactors: reviewers see \"keeps a pattern intact\" tests\n  fail during pure structural cleanup with no behavior change, and either\n  hand-wave the failure (dangerous) or waste time updating regexes that add\n  nothing (waste).\n- It gives false confidence. a green suite full of source-regex tests\n  looks like coverage but has never once executed the code path it claims\n  to guard.\n\n**Do not write:**\n\n```ts\nconst source = fs.readFileSync(path.join(__dirname, 'main.ts'), 'utf8')\n\ntest('backend spawn hides the Windows console', () => {\n  assert.match(source, /spawn\\(\\s*backend\\.command,\\s*backend\\.args[\\s\\S]{0,300}hiddenWindowsChildOptions/)\n})\n```\n\n**Do write — extract the logic into a small pure/DI-testable function and\ncall it for real:**\n\n```ts\n// backend-spawn.ts\nexport function hiddenWindowsChildOptions(options: SpawnOptionsLike = {}, isWindows = process.platform === 'win32') {\n  if (!isWindows || 'windowsHide' in options) return options\n  return { ...options, windowsHide: true }\n}\n\n// backend-spawn.test.ts\ntest('windowsHide defaults to true on Windows, is left alone elsewhere', () => {\n  assert.equal(hiddenWindowsChildOptions({}, true).windowsHide, true)\n  assert.equal(hiddenWindowsChildOptions({}, false).windowsHide, undefined)\n  assert.equal(hiddenWindowsChildOptions({ windowsHide: false }, true).windowsHide, false)\n})\n```\n\nIf the logic lives inline in a god-file (`main.ts`, `cli.py`,\n`gateway/run.py`) and extracting it feels disruptive: that's the actual\nsignal to do the extraction, not to regex around it.\n","category":"root","tokens":20169}]}