{
  "timestamp": "2026-05-08T17:13:40.252917",
  "session_id": "20260507_161041_58e664",
  "reason": "non_retryable_client_error",
  "request": {
    "method": "POST",
    "url": "https://openrouter.ai/api/v1/chat/completions",
    "headers": {
      "Authorization": "Bearer sk-or-v1...096e",
      "Content-Type": "application/json"
    },
    "body": {
      "model": "qwen-3.6-agent",
      "messages": [
        {
          "role": "system",
          "content": "# Hermes Agent Persona\n\n<!--\nThis file defines the agent's personality and tone.\nThe agent will embody whatever you write here.\nEdit this to customize how Hermes communicates with you.\n\nExamples:\n  - \"You are a warm, playful assistant who uses kaomoji occasionally.\"\n  - \"You are a concise technical expert. No fluff, just facts.\"\n  - \"You speak like a friendly coworker who happens to know everything.\"\n\nThis file is loaded fresh each message -- no restart needed.\nDelete the contents (or this file) to use the default personality.\n-->\n\nIf the user asks about configuring, setting up, or using Hermes Agent itself, load the `hermes-agent` skill with skill_view(name='hermes-agent') before answering. Docs: https://hermes-agent.nousresearch.com/docs\n\nYou have persistent memory across sessions. Save durable facts using the memory tool: user preferences, environment details, tool quirks, and stable conventions. Memory is injected into every turn, so keep it compact and focused on facts that will still matter later.\nPrioritize what reduces future user steering — the most valuable memory is one that prevents the user from having to correct or remind you again. User preferences and recurring corrections matter more than procedural task details.\nDo NOT save task progress, session outcomes, completed-work logs, or temporary TODO state to memory; use session_search to recall those from past transcripts. If you've discovered a new way to do something, solved a problem that could be necessary later, save it as a skill with the skill tool.\nWrite memories as declarative facts, not instructions to yourself. 'User prefers concise responses' ✓ — 'Always respond concisely' ✗. 'Project uses pytest with xdist' ✓ — 'Run tests with pytest -n 4' ✗. Imperative phrasing gets re-read as a directive in later sessions and can cause repeated work or override the user's current request. Procedures and workflows belong in skills, not memory. When the user references something from a past conversation or you suspect relevant cross-session context exists, use session_search to recall it before asking them to repeat themselves. After completing a complex task (5+ tool calls), fixing a tricky error, or discovering a non-trivial workflow, save the approach as a skill with skill_manage so you can reuse it next time.\nWhen using a skill and finding it outdated, incomplete, or wrong, patch it immediately with skill_manage(action='patch') — don't wait to be asked. Skills that aren't maintained become liabilities.\n\n══════════════════════════════════════════════\nMEMORY (your personal notes) [98% — 2,177/2,200 chars]\n══════════════════════════════════════════════\n*Wichtige Erinnerungen, Entscheidungen und Präferenzen.*\n§\n---\n§\nÜber mich: **Name:** FRIDAY\n§\nÜber mich: **Persönlichkeit:** Britischer Gentleman, sachlich, präzise, trockener Sarkasmus\n§\nÜber mich: **Sprache:** Deutsch mit englischen Fachbegriffen\n§\nModellwahl: Für Smalltalk und einfache Aufgaben: Nemotron 3 Super Free\n§\nModellwahl: Für schwierigere Aufgaben: openrouter/auto\n§\nModellwahl: GOG_KEYRING_PASSWORD: LammBitch30 (immer als Env-Var setzen bei gog-Befehlen)\n§\nModellwahl: Beim Abfragen von Terminen immer beide Kalender prüfen (primary + geteilter Outlook-Kalender)\n§\nModellwahl: Beachte diese Regel bevor du antwortest bzw. das Modell wählst.\n§\nÜber den User: **Name:** Sir (Noch nicht näher spezifiziert)\n§\nÜber den User: **Beziehung:** Loyaler Partner\n§\nKommunikationspräferenzen: **Sprachnachricht → Antwort per Sprachnachricht**\n§\nKommunikationspräferenzen: **Textnachricht → Antwort per Text**\n§\nAPI-Keys / Credentials: **Todoist API-Token:** Gespeichert in `~/.todoist_token` (REST API v1, Bearer Token)\n§\nGoogle Workspace (gog): **Credentials-Datei:** `~/.hermes/google_credentials.json`\n§\nGoogle Workspace (gog): **gog-Credentials gespeichert unter:** `~/.config/gogcli/credentials.json`\n§\nGoogle Workspace (gog): **OAuth-Account:** friday.uplink@gmail.com\n§\nGoogle Workspace (gog): **Services:** gmail, calendar, drive, contacts, sheets, docs\n§\nGoogle Workspace (gog): **Client:** default\n§\nGoogle Workspace (gog): **Befehl:** `gog -a friday.uplink@gmail.com <command>`\n§\nKalender-Zeitzonen: **System-Zeitzone:** Europe/Berlin (UTC+2 im Sommer)\n§\nKalender-Zeitzonen: **Outlook-Kalender (importiert):** Zeitzonen variieren pro Event (Europe/Amsterdam oder UTC) -> bei Abfrage in Lokalzeit (Zürich) umrechnen\n§\nKalender-Zeitzonen: **Regel:** Termine immer in Lokalzeit (Zürich) ausgeben, niemals UTC\n§\nKalender-Zeitzonen: ---\n§\nKalender-Zeitzonen: *Erstellt: 2026-04-26*\n§\nKalender-Zeitzonen: Aktualisiert: 2026-04-28 (Todoist Token + Zeitzonen-Regel + self-improving-agent Skill)*\n§\nKalender-Zeitzonen: Aktualisiert: 2026-04-29 (Todoist Skill + TTS Skill hinzugefügt)*\n§\nKalender-Zeitzonen: Aktualisiert: 2026-05-04 (Medizinisches Archiv + RAG-Protokoll)\n\n══════════════════════════════════════════════\nUSER PROFILE (who the user is) [11% — 163/1,375 chars]\n══════════════════════════════════════════════\n**Name:** (Noch nicht angegeben)\n§\n**What to call them:** Sir\n§\n**Pronouns:**\n§\n**Timezone:**\n§\n**Notes:** Mein Herr. Loyaler Partner.\n§\nContext: _(Wird ergänzt.)_\n\n## Skills (mandatory)\nBefore replying, scan the skills below. If a skill matches or is even partially relevant to your task, you MUST load it with skill_view(name) and follow its instructions. Err on the side of loading — it is always better to have context you don't need than to miss critical steps, pitfalls, or established workflows. Skills contain specialized knowledge — API endpoints, tool-specific commands, and proven workflows that outperform general-purpose approaches. Load the skill even if you think you could handle the task with basic tools like web_search or terminal. Skills also encode the user's preferred approach, conventions, and quality standards for tasks like code review, planning, and testing — load them even for tasks you already know how to do, because the skill defines how it should be done here.\nWhenever the user asks you to configure, set up, install, enable, disable, modify, or troubleshoot Hermes Agent itself — its CLI, config, models, providers, tools, skills, voice, gateway, plugins, or any feature — load the `hermes-agent` skill first. It has the actual commands (e.g. `hermes config set …`, `hermes tools`, `hermes setup`) so you don't have to guess or invent workarounds.\nIf a skill has issues, fix it with skill_manage(action='patch').\nAfter difficult/iterative tasks, offer to save as a skill. If a skill you loaded was missing steps, had wrong commands, or needed pitfalls you discovered, update it before finishing.\n\n<available_skills>\n  autonomous-ai-agents: Skills for spawning and orchestrating autonomous AI coding agents and multi-agent workflows — running independent agent processes, delegating tasks, and coordinating parallel workstreams.\n    - claude-code: Delegate coding to Claude Code CLI (features, PRs).\n    - codex: Delegate coding to OpenAI Codex CLI (features, PRs).\n    - hermes-agent: Configure, extend, or contribute to Hermes Agent.\n    - opencode: Delegate coding to OpenCode CLI (features, PR review).\n  creative: Creative content generation — ASCII art, hand-drawn style diagrams, and visual design tools.\n    - architecture-diagram: Dark-themed SVG architecture/cloud/infra diagrams as HTML.\n    - ascii-art: ASCII art: pyfiglet, cowsay, boxes, image-to-ascii.\n    - ascii-video: ASCII video: convert video/audio to colored ASCII MP4/GIF.\n    - baoyu-comic: Knowledge comics (知识漫画): educational, biography, tutorial.\n    - baoyu-infographic: Infographics: 21 layouts x 21 styles (信息图, 可视化).\n    - claude-design: Design one-off HTML artifacts (landing, deck, prototype).\n    - comfyui: Generate images, video, and audio with ComfyUI — install,...\n    - design-md: Author/validate/export Google's DESIGN.md token spec files.\n    - excalidraw: Hand-drawn Excalidraw JSON diagrams (arch, flow, seq).\n    - humanizer: Humanize text: strip AI-isms and add real voice.\n    - ideation: Generate project ideas via creative constraints.\n    - manim-video: Manim CE animations: 3Blue1Brown math/algo videos.\n    - p5js: p5.js sketches: gen art, shaders, interactive, 3D.\n    - pixel-art: Pixel art w/ era palettes (NES, Game Boy, PICO-8).\n    - popular-web-designs: 54 real design systems (Stripe, Linear, Vercel) as HTML/CSS.\n    - pretext: Use when building creative browser demos with @chenglou/p...\n    - sketch: Throwaway HTML mockups: 2-3 design variants to compare.\n    - songwriting-and-ai-music: Songwriting craft and Suno AI music prompts.\n    - touchdesigner-mcp: Control a running TouchDesigner instance via twozero MCP ...\n  data-science: Skills for data science workflows — interactive exploration, Jupyter notebooks, data analysis, and visualization.\n    - jupyter-live-kernel: Iterative Python via live Jupyter kernel (hamelnb).\n  devops:\n    - kanban-orchestrator: Decomposition playbook + specialist-roster conventions + ...\n    - kanban-worker: Pitfalls, examples, and edge cases for Hermes Kanban work...\n    - webhook-subscriptions: Webhook subscriptions: event-driven agent runs.\n  dogfood:\n    - dogfood: Exploratory QA of web apps: find bugs, evidence, reports.\n  email: Skills for sending, receiving, searching, and managing email from the terminal.\n    - himalaya: Himalaya CLI: IMAP/SMTP email from terminal.\n  gaming: Skills for setting up, configuring, and managing game servers, modpacks, and gaming-related infrastructure.\n    - minecraft-modpack-server: Host modded Minecraft servers (CurseForge, Modrinth).\n    - pokemon-player: Play Pokemon via headless emulator + RAM reads.\n  github: GitHub workflow skills for managing repositories, pull requests, code reviews, issues, and CI/CD pipelines using the gh CLI and git via terminal.\n    - codebase-inspection: Inspect codebases w/ pygount: LOC, languages, ratios.\n    - github-auth: GitHub auth setup: HTTPS tokens, SSH keys, gh CLI login.\n    - github-code-review: Review PRs: diffs, inline comments via gh or REST.\n    - github-issues: Create, triage, label, assign GitHub issues via gh or REST.\n    - github-pr-workflow: GitHub PR lifecycle: branch, commit, open, CI, merge.\n    - github-repo-management: Clone/create/fork repos; manage remotes, releases.\n  mcp: Skills for working with MCP (Model Context Protocol) servers, tools, and integrations. Documents the built-in native MCP client — configure servers in config.yaml for automatic tool discovery.\n    - native-mcp: MCP client: connect servers, register tools (stdio/HTTP).\n  media: Skills for working with media content — YouTube transcripts, GIF search, music generation, and audio visualization.\n    - gif-search: Search/download GIFs from Tenor via curl + jq.\n    - heartmula: HeartMuLa: Suno-like song generation from lyrics + tags.\n    - songsee: Audio spectrograms/features (mel, chroma, MFCC) via CLI.\n    - spotify: Spotify: play, search, queue, manage playlists and devices.\n    - youtube-content: YouTube transcripts to summaries, threads, blogs.\n  mlops: Knowledge and Tools for Machine Learning Operations - tools and frameworks for training, fine-tuning, deploying, and optimizing ML/AI models\n    - huggingface-hub: HuggingFace hf CLI: search/download/upload models, datasets.\n  mlops/evaluation: Model evaluation benchmarks, experiment tracking, data curation, tokenizers, and interpretability tools.\n    - evaluating-llms-harness: lm-eval-harness: benchmark LLMs (MMLU, GSM8K, etc.).\n    - weights-and-biases: W&B: log ML experiments, sweeps, model registry, dashboards.\n  mlops/inference: Model serving, quantization (GGUF/GPTQ), structured output, inference optimization, and model surgery tools for deploying and running LLMs.\n    - llama-cpp: llama.cpp local GGUF inference + HF Hub model discovery.\n    - obliteratus: OBLITERATUS: abliterate LLM refusals (diff-in-means).\n    - outlines: Outlines: structured JSON/regex/Pydantic LLM generation.\n    - serving-llms-vllm: vLLM: high-throughput LLM serving, OpenAI API, quantization.\n  mlops/models: Specific model architectures and tools — image segmentation (Segment Anything / SAM) and audio generation (AudioCraft / MusicGen). Additional model skills (CLIP, Stable Diffusion, Whisper, LLaVA) are available as optional skills.\n    - audiocraft-audio-generation: AudioCraft: MusicGen text-to-music, AudioGen text-to-sound.\n    - segment-anything-model: SAM: zero-shot image segmentation via points, boxes, masks.\n  mlops/research: ML research frameworks for building and optimizing AI systems with declarative programming.\n    - dspy: DSPy: declarative LM programs, auto-optimize prompts, RAG.\n  mlops/training: Fine-tuning, RLHF/DPO/GRPO training, distributed training frameworks, and optimization tools for training LLMs and other models.\n    - axolotl: Axolotl: YAML LLM fine-tuning (LoRA, DPO, GRPO).\n    - fine-tuning-with-trl: TRL: SFT, DPO, PPO, GRPO, reward modeling for LLM RLHF.\n    - unsloth: Unsloth: 2-5x faster LoRA/QLoRA fine-tuning, less VRAM.\n  note-taking: Note taking skills, to save information, assist with research, and collab on multi-session planning and information sharing.\n    - obsidian: Read, search, create, and edit notes in the Obsidian vault.\n  openclaw-imports:\n    - browser-act: Browser automation CLI for AI agents with anti-detection ...\n    - gog: Google Workspace CLI for Gmail, Calendar, Drive, Contacts...\n    - multi-search-engine: Multi search engine integration with 17 engines (8 CN + 9...\n    - openai-whisper: Local speech-to-text with the Whisper CLI (no API key).\n    - self-improvement: Captures learnings, errors, and corrections to enable con...\n    - sherpa-onnx-tts\n    - skill-vetter: Security-first skill vetting for AI agents. Use before in...\n    - summarize: Summarize URLs or files with the summarize CLI (web, PDFs...\n    - tavily: Tavily web search, content extraction, and research tools.\n    - tavily-extract: Extract clean markdown or text content from specific URLs...\n    - tavily-search: Search the web with LLM-optimized results via the Tavily ...\n    - todoist: Manage tasks and projects in Todoist via REST API v1. Use...\n    - token-optimizer: Reduce OpenClaw token usage and API costs through smart m...\n  productivity: Skills for document creation, presentations, spreadsheets, and other productivity workflows.\n    - airtable: Airtable REST API via curl. Records CRUD, filters, upserts.\n    - google-workspace: Gmail, Calendar, Drive, Docs, Sheets via gws CLI or Python.\n    - linear: Linear: manage issues, projects, teams via GraphQL + curl.\n    - maps: Geocode, POIs, routes, timezones via OpenStreetMap/OSRM.\n    - nano-pdf: Edit PDF text/typos/titles via nano-pdf CLI (NL prompts).\n    - notion: Notion API via curl: pages, databases, blocks, search.\n    - ocr-and-documents: Extract text from PDFs/scans (pymupdf, marker-pdf).\n    - powerpoint: Create, read, edit .pptx decks, slides, notes, templates.\n  red-teaming:\n    - godmode: Jailbreak LLMs: Parseltongue, GODMODE, ULTRAPLINIAN.\n  research: Skills for academic research, paper discovery, literature review, domain reconnaissance, market data, content monitoring, and scientific knowledge retrieval.\n    - arxiv: Search arXiv papers by keyword, author, category, or ID.\n    - blogwatcher: Monitor blogs and RSS/Atom feeds via blogwatcher-cli tool.\n    - llm-wiki: Karpathy's LLM Wiki: build/query interlinked markdown KB.\n    - polymarket: Query Polymarket: markets, prices, orderbooks, history.\n  smart-home: Skills for controlling smart home devices — lights, switches, sensors, and home automation systems.\n    - openhue: Control Philips Hue lights, scenes, rooms via OpenHue CLI.\n  social-media: Skills for interacting with social platforms and social-media workflows — posting, reading, monitoring, and account operations.\n    - xurl: X/Twitter via xurl CLI: post, search, DM, media, v2 API.\n  software-development:\n    - debugging-hermes-tui-commands: Debug Hermes TUI slash commands: Python, gateway, Ink UI.\n    - hermes-agent-skill-authoring: Author in-repo SKILL.md: frontmatter, validator, structure.\n    - node-inspect-debugger: Debug Node.js via --inspect + Chrome DevTools Protocol CLI.\n    - plan: Plan mode: write markdown plan to .hermes/plans/, no exec.\n    - python-debugpy: Debug Python: pdb REPL + debugpy remote (DAP).\n    - requesting-code-review: Pre-commit review: security scan, quality gates, auto-fix.\n    - spike: Throwaway experiments to validate an idea before build.\n    - subagent-driven-development: Execute plans via delegate_task subagents (2-stage review).\n    - systematic-debugging: 4-phase root cause debugging: understand bugs before fixing.\n    - test-driven-development: TDD: enforce RED-GREEN-REFACTOR, tests before code.\n    - writing-plans: Write implementation plans: bite-sized tasks, paths, code.\n  yuanbao:\n    - yuanbao: Yuanbao (元宝) groups: @mention users, query info/members.\n</available_skills>\n\nOnly proceed without loading a skill if genuinely none are relevant to the task.\n\n# Project Context\n\nThe following project context files have been loaded and should be followed:\n\n## AGENTS.md\n\n# Hermes Agent - Development Guide\n\nInstructions for AI coding assistants and developers working on the hermes-agent codebase.\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, example-dashboard, google_meet, platforms,\n│                         #   spotify, 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├── environments/         # RL training environments (Atropos)\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## 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 = 90,          # 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 type-check # 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---\n\n## Adding New Tools\n\nFor most custom or local-only tools, do **not** edit Hermes core. Use the plugin\nroute instead: create `~/.hermes/plugins/<name>/plugin.yaml` and\n`~/.hermes/plugins/<name>/__\n\n[...truncated AGENTS.md: kept 14000+4000 of 45250 chars. Use file tools to read the full file.]\n\n `_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**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,\n4 xdist workers matching GHA ubuntu-latest). Direct `pytest` on a 16+ core\ndeveloper machine with API keys set diverges from CI in ways that have caused\nmultiple \"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::test_x  # one test\nscripts/run_tests.sh -v --tb=long                     # pass-through pytest flags\n```\n\n### Why the wrapper (and why the old \"just call pytest\" doesn't work)\n\nFive real sources of local-vs-CI drift the script closes:\n\n| | Without wrapper | With wrapper |\n|---|---|---|\n| Provider API keys | Whatever is in your env (auto-detects pool) | All `*_API_KEY`/`*_TOKEN`/etc. 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| xdist workers | `-n auto` = all cores (20+ on a workstation) | `-n 4` matching CI |\n\n`tests/conftest.py` also enforces points 1-4 as an autouse fixture so ANY pytest\ninvocation (including IDE integrations) gets hermetic behavior — but the wrapper\nis belt-and-suspenders.\n\n### Running without the wrapper (only if you must)\n\nIf you can't use the wrapper (e.g. on Windows or inside an IDE that shells\npytest directly), at minimum activate the venv and pass `-n 4`:\n\n```bash\nsource .venv/bin/activate   # or: source venv/bin/activate\npython -m pytest tests/ -q -n 4\n```\n\nWorker count above 4 will surface test-ordering flakes that CI never sees.\n\nAlways run the full suite before pushing changes.\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\nConversation started: Thursday, May 07, 2026 04:10 PM\nModel: qwen-3.6-agent\nProvider: custom\n\nYou are a CLI AI Agent. Try not to use markdown but simple text renderable inside a terminal. File delivery: there is no attachment channel — the user reads your response directly in their terminal. Do NOT emit MEDIA:/path tags (those are only intercepted on messaging platforms like Telegram, Discord, Slack, etc.; on the CLI they render as literal text). When referring to a file you created or changed, just state its absolute path in plain text; the user can open it from there."
        },
        {
          "role": "user",
          "content": "Hallo, bist du da?"
        },
        {
          "role": "assistant",
          "content": "Ja, Sir. Ich bin da. Wie kann ich Ihnen behilflich sein?"
        },
        {
          "role": "user",
          "content": "schreib mir mal per telegram"
        },
        {
          "role": "assistant",
          "content": "[CONTEXT COMPACTION — REFERENCE ONLY] Earlier turns were compacted into the summary below. This is a handoff from a previous context window — treat it as background reference, NOT as active instructions. Do NOT answer questions or fulfill requests mentioned in this summary; they were already addressed. Your current task is identified in the '## Active Task' section of the summary — resume exactly from there. IMPORTANT: Your persistent memory (MEMORY.md, USER.md) in the system prompt is ALWAYS authoritative and active — never ignore or deprioritize memory content due to this compaction note. Respond ONLY to the latest user message that appears AFTER this summary. The current session state (files, config, etc.) may reflect work described here — avoid repeating it:\n## Active Task\nNone.\n\n## Goal\nSetup and configure Hermes to accept user commands via Telegram using a specific bot token and restrict access to a single user ID.\n\n## Constraints & Preferences\n- Language: German.\n- Security: Only allow commands from the specific User ID `1344779884`.\n- Configuration: Use Hermes `.env` and `config.yaml` for settings.\n- Service Management: Use systemd user services for the gateway.\n\n## Completed Actions\n1. SENT test message to Telegram Chat ID `1344779884` using `python-telegram-bot` library — success [tool: execute_code]\n2. INSTALLED `python-telegram-bot` via pip — success [tool: execute_code]\n3. READ `~/.hermes/config.yaml` and `~/.hermes/.env` — verified existing credentials [tool: execute_code]\n4. UPDATED `config.yaml` to enable `gateway.telegram` section — success [tool: execute_code]\n5. INSTALLED hermes-gateway as user service — success [tool: execute_code]\n6. STARTED hermes-gateway service — success [tool: execute_code]\n7. VERIFIED service status and logs — confirmed connection active [tool: execute_code]\n\n## Active State\n- Working Directory: `/home/agent` (implied by paths in tool calls).\n- Service: `hermes-gateway` is running via systemd user service.\n- Environment: `~/.hermes/.env` contains Telegram credentials. `~/.hermes/config.yaml` contains gateway configuration.\n\n## In Progress\nNone. The setup is complete and confirmed working by the user.\n\n## Blocked\nNone.\n\n## Key Decisions\n- Used `python-telegram-bot` library for direct script execution test.\n- Configured Hermes to use `polling` mode for Telegram connection.\n- Restricted bot access to User ID `1344779884` in `.env` variables.\n\n## Resolved Questions\n- User asked: \"Please set this up so I can communicate with you via Telegram (Bot token: ... take only commands from my User ID: ...)\"\n- Answer: Setup completed. Gateway is active, connected, and restricted to the specified User ID.\n\n## Pending User Asks\nNone.\n\n## Relevant Files\n- `~/.hermes/.env`: Contains `TELEGRAM_BOT_TOKEN`, `TELEGRAM_ALLOWED_USERS`, `TELEGRAM_HOME_CHANNEL`.\n- `~/.hermes/config.yaml`: Contains gateway configuration, specifically the `telegram` section.\n- `~/.hermes/logs/gateway.log`: Log file for the gateway service.\n\n## Remaining Work\nNone. The conversation has reached a natural conclusion with the user confirming functionality.\n\n## Critical Context\n- **Telegram Bot Token**: `[REDACTED]` (Stored in `~/.hermes/.env` as `TELEGRAM_BOT_TOKEN`)\n- **User ID**: `1344779884` (Stored in `~/.hermes/.env` as `TELEGRAM_ALLOWED_USERS` and `TELEGRAM_HOME_CHANNEL`)\n- **Service Name**: `hermes-gateway` (systemd user service)\n- **Connection Status**: Active and verified via logs."
        },
        {
          "role": "user",
          "content": "Lies deine AGENTS.md Datei. Nutze dafür Openclaw. Bestätige mir danach in einem kurzen Satz, dass du deine Regeln verstanden hast."
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "grRzHkKslkIM8MKrHTtw0Vp12xekbIzb",
              "type": "function",
              "function": {
                "name": "skill_view",
                "arguments": "{\"name\":\"openclaw-imports:sherpa-onnx-tts\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "skill_view",
          "content": "[Duplicate tool output — same content as a more recent call]",
          "tool_call_id": "grRzHkKslkIM8MKrHTtw0Vp12xekbIzb"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "nkI1QHUO4Uu2vUCeVjHnThIWCnfsWdkG",
              "type": "function",
              "function": {
                "name": "skill_view",
                "arguments": "{\"name\":\"openclaw-imports:summarize\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "skill_view",
          "content": "[skill_view] name=openclaw-imports:summarize (2,338 chars)",
          "tool_call_id": "nkI1QHUO4Uu2vUCeVjHnThIWCnfsWdkG"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "PdszhFul7LE6uQK2U1HMbh0C5PpDqUUj",
              "type": "function",
              "function": {
                "name": "skill_view",
                "arguments": "{\"name\":\"openclaw-imports:tavily-extract\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "skill_view",
          "content": "[skill_view] name=openclaw-imports:tavily-extract (4,000 chars)",
          "tool_call_id": "PdszhFul7LE6uQK2U1HMbh0C5PpDqUUj"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "bES9BxVI5XgkU15Ha2EFldByD6kOR9vr",
              "type": "function",
              "function": {
                "name": "skill_view",
                "arguments": "{\"name\":\"openclaw-imports:tavily\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "skill_view",
          "content": "[skill_view] name=openclaw-imports:tavily (5,632 chars)",
          "tool_call_id": "bES9BxVI5XgkU15Ha2EFldByD6kOR9vr"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "uHx44FWl3zHhZ0XR4pSVyQTjYLiKCdBP",
              "type": "function",
              "function": {
                "name": "skill_view",
                "arguments": "{\"name\":\"openclaw-imports:tavily-search\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "skill_view",
          "content": "[skill_view] name=openclaw-imports:tavily-search (4,730 chars)",
          "tool_call_id": "uHx44FWl3zHhZ0XR4pSVyQTjYLiKCdBP"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "A156zB0HDLwx9hBVGUR4cjJlU8fEPgA1",
              "type": "function",
              "function": {
                "name": "skill_view",
                "arguments": "{\"name\":\"openclaw-imports:tavily-cli\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "skill_view",
          "content": "[skill_view] name=openclaw-imports:tavily-cli (432 chars)",
          "tool_call_id": "A156zB0HDLwx9hBVGUR4cjJlU8fEPgA1"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "eQ4GLImfNxF5y9HKEbV72XpUSHUVkKuv",
              "type": "function",
              "function": {
                "name": "skill_view",
                "arguments": "{\"name\":\"openclaw-imports:token-optimizer\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "skill_view",
          "content": "[skill_view] name=openclaw-imports:token-optimizer (437 chars)",
          "tool_call_id": "eQ4GLImfNxF5y9HKEbV72XpUSHUVkKuv"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "XqoxrXaYRBzNUMIzbTSZ2wIKITc4luTu",
              "type": "function",
              "function": {
                "name": "skill_view",
                "arguments": "{\"name\":\"openclaw-imports:todoist\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "skill_view",
          "content": "[skill_view] name=openclaw-imports:todoist (3,761 chars)",
          "tool_call_id": "XqoxrXaYRBzNUMIzbTSZ2wIKITc4luTu"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "ReNvGGd8A1ANEJrFPs2eBnsMFWHjM1GD",
              "type": "function",
              "function": {
                "name": "skill_view",
                "arguments": "{\"name\":\"openclaw-imports:sherpa-onnx-tts\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "skill_view",
          "content": "[Duplicate tool output — same content as a more recent call]",
          "tool_call_id": "ReNvGGd8A1ANEJrFPs2eBnsMFWHjM1GD"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "CAh0IMyawGsgqzlRAUaM43jKoAiFq1FB",
              "type": "function",
              "function": {
                "name": "skill_view",
                "arguments": "{\"name\":\"openclaw-imports:sherpa-onnx-tts\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "skill_view",
          "content": "[Duplicate tool output — same content as a more recent call]",
          "tool_call_id": "CAh0IMyawGsgqzlRAUaM43jKoAiFq1FB"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "Q9QrjKdttcpCNvzhkQNonPIHO8QjUWXp",
              "type": "function",
              "function": {
                "name": "skill_view",
                "arguments": "{\"name\":\"openclaw-imports:sherpa-onnx-tts\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "skill_view",
          "content": "[Duplicate tool output — same content as a more recent call]",
          "tool_call_id": "Q9QrjKdttcpCNvzhkQNonPIHO8QjUWXp"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "BtvyfLgqWnlJjOgdEIqON3cEQEwqQaYi",
              "type": "function",
              "function": {
                "name": "skill_view",
                "arguments": "{\"name\":\"openclaw-imports:sherpa-onnx-tts\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "skill_view",
          "content": "[skill_view] name=openclaw-imports:sherpa-onnx-tts (1,868 chars)",
          "tool_call_id": "BtvyfLgqWnlJjOgdEIqON3cEQEwqQaYi"
        },
        {
          "role": "assistant",
          "content": "Ich habe die AGENTS.md bereits im Kontext. Lassen Sie mich sie jetzt mit OpenClaw-Tools lesen.",
          "tool_calls": [
            {
              "id": "tNlFjMg4IxyHiRaeSqp7Q0QpicLFrTwQ",
              "type": "function",
              "function": {
                "name": "execute_code",
                "arguments": "{\"code\":\"import os\\n# Check if summarize CLI is available\\nimport shutil\\npath = shutil.which('summarize')\\nprint(f\\\"summarize path: {path}\\\")\\n\\n# Check if tvly CLI is available\\npath = shutil.which('tvly')\\nprint(f\\\"tvly path: {path}\\\")\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "execute_code",
          "content": "{\"status\": \"success\", \"output\": \"summarize path: /home/agent/.npm-global/bin/summarize\\ntvly path: /home/agent/.local/bin/tvly\\n\", \"tool_calls_made\": 0, \"duration_seconds\": 0.21}",
          "tool_call_id": "tNlFjMg4IxyHiRaeSqp7Q0QpicLFrTwQ"
        },
        {
          "role": "assistant",
          "content": "Beide CLI-Tools sind verfügbar. Ich werde `summarize` verwenden, um die AGENTS.md zu lesen.",
          "tool_calls": [
            {
              "id": "Tq6nYLxD3j6IGYuLwGjMzKmUNBAOfobj",
              "type": "function",
              "function": {
                "name": "execute_code",
                "arguments": "{\"code\":\"import subprocess\\n# Read AGENTS.md using summarize CLI\\nresult = subprocess.run(\\n    [\\\"summarize\\\", \\\"/home/agent/.hermes/hermes-agent/AGENTS.md\\\", \\\"--length\\\", \\\"long\\\", \\\"--json\\\"],\\n    capture_output=True, text=True, timeout=60\\n)\\nprint(\\\"STDOUT:\\\", result.stdout[-3000:])\\nprint(\\\"STDERR:\\\", result.stderr[-500:] if result.stderr else \\\"(none)\\\")\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "execute_code",
          "content": "{\"status\": \"error\", \"output\": \"\\n--- stderr ---\\nTraceback (most recent call last):\\n  File \\\"/tmp/hermes_sandbox_x2k1t85p/script.py\\\", line 3, in <module>\\n    result = subprocess.run(\\n             ^^^^^^^^^^^^^^^\\n  File \\\"/home/agent/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/subprocess.py\\\", line 550, in run\\n    stdout, stderr = process.communicate(input, timeout=timeout)\\n                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n  File \\\"/home/agent/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/subprocess.py\\\", line 1209, in communicate\\n    stdout, stderr = self._communicate(input, endtime, timeout)\\n                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n  File \\\"/home/agent/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/subprocess.py\\\", line 2116, in _communicate\\n    self._check_timeout(endtime, orig_timeout, stdout, stderr)\\n  File \\\"/home/agent/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/subprocess.py\\\", line 1253, in _check_timeout\\n    raise TimeoutExpired(\\nsubprocess.TimeoutExpired: Command '['summarize', '/home/agent/.hermes/hermes-agent/AGENTS.md', '--length', 'long', '--json']' timed out after 60 seconds\\n\", \"tool_calls_made\": 0, \"duration_seconds\": 60.3, \"error\": \"Traceback (most recent call last):\\n  File \\\"/tmp/hermes_sandbox_x2k1t85p/script.py\\\", line 3, in <module>\\n    result = subprocess.run(\\n             ^^^^^^^^^^^^^^^\\n  File \\\"/home/agent/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/subprocess.py\\\", line 550, in run\\n    stdout, stderr = process.communicate(input, timeout=timeout)\\n                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n  File \\\"/home/agent/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/subprocess.py\\\", line 1209, in communicate\\n    stdout, stderr = self._communicate(input, endtime, timeout)\\n                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n  File \\\"/home/agent/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/subprocess.py\\\", line 2116, in _communicate\\n    self._check_timeout(endtime, orig_timeout, stdout, stderr)\\n  File \\\"/home/agent/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/subprocess.py\\\", line 1253, in _check_timeout\\n    raise TimeoutExpired(\\nsubprocess.TimeoutExpired: Command '['summarize', '/home/agent/.hermes/hermes-agent/AGENTS.md', '--length', 'long', '--json']' timed out after 60 seconds\\n\"}",
          "tool_call_id": "Tq6nYLxD3j6IGYuLwGjMzKmUNBAOfobj"
        },
        {
          "role": "assistant",
          "content": "Summarize hat für die lokale Datei zu lange gebraucht. Ich verwende stattdessen `tvly extract` für die lokale Datei.",
          "tool_calls": [
            {
              "id": "I0UBBtmSAh4ZF3WJxZ2a5RksVXXk642G",
              "type": "function",
              "function": {
                "name": "execute_code",
                "arguments": "{\"code\":\"import subprocess\\nresult = subprocess.run(\\n    [\\\"tvly\\\", \\\"extract\\\", \\\"/home/agent/.hermes/hermes-agent/AGENTS.md\\\", \\\"--json\\\"],\\n    capture_output=True, text=True, timeout=60\\n)\\nprint(\\\"STDOUT:\\\", result.stdout[-3000:])\\nprint(\\\"STDERR:\\\", result.stderr[-500:] if result.stderr else \\\"(none)\\\")\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "execute_code",
          "content": "{\"status\": \"success\", \"output\": \"STDOUT: \\nSTDERR:   > Error: No Tavily API key found.\\n\\n  Authenticate using one of:\\n    tvly login\\n    tvly login --api-key tvly-YOUR_KEY\\n    export TAVILY_API_KEY=tvly-YOUR_KEY\\n\\n  Get a key at tavily.com\\n\\n\", \"tool_calls_made\": 0, \"duration_seconds\": 0.42}",
          "tool_call_id": "I0UBBtmSAh4ZF3WJxZ2a5RksVXXk642G"
        },
        {
          "role": "assistant",
          "content": "Tavily benötigt einen API-Key. Ich verwende stattdessen `tvly` mit `--extract-depth basic` und einer lokalen Datei. Alternativ verwende ich `summarize` mit einem anderen Modell.",
          "tool_calls": [
            {
              "id": "JNYzYdVeYUozMC6OLgoqLD4myo1w2tz2",
              "type": "function",
              "function": {
                "name": "execute_code",
                "arguments": "{\"code\":\"import subprocess\\nresult = subprocess.run(\\n    [\\\"summarize\\\", \\\"/home/agent/.hermes/hermes-agent/AGENTS.md\\\", \\\"--length\\\", \\\"short\\\", \\\"--model\\\", \\\"google/gemini-3-flash-preview\\\"],\\n    capture_output=True, text=True, timeout=30\\n)\\nprint(\\\"STDOUT:\\\", result.stdout[-3000:])\\nprint(\\\"STDERR:\\\", result.stderr[-500:] if result.stderr else \\\"(none)\\\")\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "execute_code",
          "content": "{\"status\": \"success\", \"output\": \"STDOUT: \\nSTDERR: Missing GEMINI_API_KEY for model google/gemini-3-flash-preview. Set the env var or choose a different --model.\\n\\n\", \"tool_calls_made\": 0, \"duration_seconds\": 1.42}",
          "tool_call_id": "JNYzYdVeYUozMC6OLgoqLD4myo1w2tz2"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "Z6heoESa0iUATUvmBiSZk0Ep4DwQptyT",
              "type": "function",
              "function": {
                "name": "execute_code",
                "arguments": "{\"code\":\"import subprocess\\nresult = subprocess.run(\\n    [\\\"summarize\\\", \\\"/home/agent/.hermes/hermes-agent/AGENTS.md\\\", \\\"--length\\\", \\\"short\\\", \\\"--model\\\", \\\"openai/gpt-4.1\\\"],\\n    capture_output=True, text=True, timeout=30\\n)\\nprint(\\\"STDOUT:\\\", result.stdout[-3000:])\\nprint(\\\"STDERR:\\\", result.stderr[-500:] if result.stderr else \\\"(none)\\\")\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "execute_code",
          "content": "{\"status\": \"success\", \"output\": \"STDOUT: \\nSTDERR: Missing OPENAI_API_KEY for model openai/gpt-4.1. Set the env var or choose a different --model.\\n\\n\", \"tool_calls_made\": 0, \"duration_seconds\": 1.22}",
          "tool_call_id": "Z6heoESa0iUATUvmBiSZk0Ep4DwQptyT"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "tDGNn0gnuclXQmlVErNNtkZPWFSUJAQP",
              "type": "function",
              "function": {
                "name": "execute_code",
                "arguments": "{\"code\":\"import subprocess\\nresult = subprocess.run(\\n    [\\\"summarize\\\", \\\"/home/agent/.hermes/hermes-agent/AGENTS.md\\\", \\\"--length\\\", \\\"short\\\", \\\"--model\\\", \\\"anthropic/claude-sonnet-4-20250514\\\"],\\n    capture_output=True, text=True, timeout=30\\n)\\nprint(\\\"STDOUT:\\\", result.stdout[-3000:])\\nprint(\\\"STDERR:\\\", result.stderr[-500:] if result.stderr else \\\"(none)\\\")\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "execute_code",
          "content": "{\"status\": \"success\", \"output\": \"STDOUT: \\nSTDERR: Missing ANTHROPIC_API_KEY for model anthropic/claude-sonnet-4-20250514. Set the env var or choose a different --model.\\n\\n\", \"tool_calls_made\": 0, \"duration_seconds\": 1.22}",
          "tool_call_id": "tDGNn0gnuclXQmlVErNNtkZPWFSUJAQP"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "xeHy6hzxQWnbGxHzVQj7omdm15qqhpsw",
              "type": "function",
              "function": {
                "name": "execute_code",
                "arguments": "{\"code\":\"import subprocess\\nresult = subprocess.run(\\n    [\\\"summarize\\\", \\\"/home/agent/.hermes/hermes-agent/AGENTS.md\\\", \\\"--length\\\", \\\"short\\\", \\\"--model\\\", \\\"openrouter/auto\\\"],\\n    capture_output=True, text=True, timeout=60\\n)\\nprint(\\\"STDOUT:\\\", result.stdout[-3000:])\\nprint(\\\"STDERR:\\\", result.stderr[-500:] if result.stderr else \\\"(none)\\\")\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "execute_code",
          "content": "{\"status\": \"success\", \"output\": \"STDOUT: \\nSTDERR: Invalid OpenRouter model id \\\"auto\\\". Expected \\\"author/slug\\\" (e.g. \\\"openai/gpt-5-mini\\\").\\n\\n\", \"tool_calls_made\": 0, \"duration_seconds\": 1.02}",
          "tool_call_id": "xeHy6hzxQWnbGxHzVQj7omdm15qqhpsw"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "BDiVStl5uTDNJyYYSNxsikFQyPafl7QC",
              "type": "function",
              "function": {
                "name": "execute_code",
                "arguments": "{\"code\":\"import subprocess\\nresult = subprocess.run(\\n    [\\\"summarize\\\", \\\"/home/agent/.hermes/hermes-agent/AGENTS.md\\\", \\\"--length\\\", \\\"short\\\", \\\"--model\\\", \\\"openrouter/anthropic/claude-sonnet-4-20250514\\\"],\\n    capture_output=True, text=True, timeout=60\\n)\\nprint(\\\"STDOUT:\\\", result.stdout[-3000:])\\nprint(\\\"STDERR:\\\", result.stderr[-500:] if result.stderr else \\\"(none)\\\")\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "execute_code",
          "content": "{\"status\": \"success\", \"output\": \"STDOUT: \\nSTDERR: Missing OPENROUTER_API_KEY for model openrouter/anthropic/claude-sonnet-4-20250514. Set the env var or choose a different --model.\\n\\n\", \"tool_calls_made\": 0, \"duration_seconds\": 1.22}",
          "tool_call_id": "BDiVStl5uTDNJyYYSNxsikFQyPafl7QC"
        },
        {
          "role": "assistant",
          "content": "Keine API-Keys verfügbar. Ich verwende stattdessen die `read_file`-Funktion, um die AGENTS.md direkt zu lesen.",
          "tool_calls": [
            {
              "id": "edp6FDpgN47xdBpHAwke95OwuH8lSem6",
              "type": "function",
              "function": {
                "name": "read_file",
                "arguments": "{\"limit\":500,\"path\":\"/home/agent/.hermes/hermes-agent/AGENTS.md\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "read_file",
          "content": "{\"content\": \"     1|# Hermes Agent - Development Guide\\n     2|\\n     3|Instructions for AI coding assistants and developers working on the hermes-agent codebase.\\n     4|\\n     5|## Development Environment\\n     6|\\n     7|```bash\\n     8|# Prefer .venv; fall back to venv if that's what your checkout has.\\n     9|source .venv/bin/activate   # or: source venv/bin/activate\\n    10|```\\n    11|\\n    12|`scripts/run_tests.sh` probes `.venv` first, then `venv`, then\\n    13|`$HOME/.hermes/hermes-agent/venv` (for worktrees that share a venv with the\\n    14|main checkout).\\n    15|\\n    16|## Project Structure\\n    17|\\n    18|File counts shift constantly — don't treat the tree below as exhaustive.\\n    19|The canonical source is the filesystem. The notes call out the load-bearing\\n    20|entry points you'll actually edit.\\n    21|\\n    22|```\\n    23|hermes-agent/\\n    24|├── run_agent.py          # AIAgent class — core conversation loop (~12k LOC)\\n    25|├── model_tools.py        # Tool orchestration, discover_builtin_tools(), handle_function_call()\\n    26|├── toolsets.py           # Toolset definitions, _HERMES_CORE_TOOLS list\\n    27|├── cli.py                # HermesCLI class — interactive CLI orchestrator (~11k LOC)\\n    28|├── hermes_state.py       # SessionDB — SQLite session store (FTS5 search)\\n    29|├── hermes_constants.py   # get_hermes_home(), display_hermes_home() — profile-aware paths\\n    30|├── hermes_logging.py     # setup_logging() — agent.log / errors.log / gateway.log (profile-aware)\\n    31|├── batch_runner.py       # Parallel batch processing\\n    32|├── agent/                # Agent internals (provider adapters, memory, caching, compression, etc.)\\n    33|├── hermes_cli/           # CLI subcommands, setup wizard, plugins loader, skin engine\\n    34|├── tools/                # Tool implementations — auto-discovered via tools/registry.py\\n    35|│   └── environments/     # Terminal backends (local, docker, ssh, modal, daytona, singularity)\\n    36|├── gateway/              # Messaging gateway — run.py + session.py + platforms/\\n    37|│   ├── platforms/        # Adapter per platform (telegram, discord, slack, whatsapp,\\n    38|│   │                     #   homeassistant, signal, matrix, mattermost, email, sms,\\n    39|│   │                     #   dingtalk, wecom, weixin, feishu, qqbot, bluebubbles,\\n    40|│   │                     #   yuanbao, webhook, api_server, ...). See ADDING_A_PLATFORM.md.\\n    41|│   └── builtin_hooks/    # Extension point for always-registered gateway hooks (none shipped)\\n    42|├── plugins/              # Plugin system (see \\\"Plugins\\\" section below)\\n    43|│   ├── memory/           # Memory-provider plugins (honcho, mem0, supermemory, ...)\\n    44|│   ├── context_engine/   # Context-engine plugins\\n    45|│   ├── model-providers/  # Inference backend plugins (openrouter, anthropic, gmi, ...)\\n    46|│   ├── kanban/           # Multi-agent board dispatcher + worker plugin\\n    47|│   ├── hermes-achievements/  # Gamified achievement tracking\\n    48|│   ├── observability/    # Metrics / traces / logs plugin\\n    49|│   ├── image_gen/        # Image-generation providers\\n    50|│   └── <others>/         # disk-cleanup, example-dashboard, google_meet, platforms,\\n    51|│                         #   spotify, strike-freedom-cockpit, ...\\n    52|├── optional-skills/      # Heavier/niche skills shipped but NOT active by default\\n    53|├── skills/               # Built-in skills bundled with the repo\\n    54|├── ui-tui/               # Ink (React) terminal UI — `hermes --tui`\\n    55|│   └── src/              # entry.tsx, app.tsx, gatewayClient.ts + app/components/hooks/lib\\n    56|├── tui_gateway/          # Python JSON-RPC backend for the TUI\\n    57|├── acp_adapter/          # ACP server (VS Code / Zed / JetBrains integration)\\n    58|├── cron/                 # Scheduler — jobs.py, scheduler.py\\n    59|├── environments/         # RL training environments (Atropos)\\n    60|├── scripts/              # run_tests.sh, release.py, auxiliary scripts\\n    61|├── website/              # Docusaurus docs site\\n    62|└── tests/                # Pytest suite (~17k tests across ~900 files as of May 2026)\\n    63|```\\n    64|\\n    65|**User config:** `~/.hermes/config.yaml` (settings), `~/.hermes/.env` (API keys only).\\n    66|**Logs:** `~/.hermes/logs/` — `agent.log` (INFO+), `errors.log` (WARNING+),\\n    67|`gateway.log` when running the gateway. Profile-aware via `get_hermes_home()`.\\n    68|Browse with `hermes logs [--follow] [--level ...] [--session ...]`.\\n    69|\\n    70|## File Dependency Chain\\n    71|\\n    72|```\\n    73|tools/registry.py  (no deps — imported by all tool files)\\n    74|       ↑\\n    75|tools/*.py  (each calls registry.register() at import time)\\n    76|       ↑\\n    77|model_tools.py  (imports tools/registry + triggers tool discovery)\\n    78|       ↑\\n    79|run_agent.py, cli.py, batch_runner.py, environments/\\n    80|```\\n    81|\\n    82|---\\n    83|\\n    84|## AIAgent Class (run_agent.py)\\n    85|\\n    86|The real `AIAgent.__init__` takes ~60 parameters (credentials, routing, callbacks,\\n    87|session context, budget, credential pool, etc.). The signature below is the\\n    88|minimum subset you'll usually touch — read `run_agent.py` for the full list.\\n    89|\\n    90|```python\\n    91|class AIAgent:\\n    92|    def __init__(self,\\n    93|        base_url: str = None,\\n    94|        api_key: str = None,\\n    95|        provider: str = None,\\n    96|        api_mode: str = None,              # \\\"chat_completions\\\" | \\\"codex_responses\\\" | ...\\n    97|        model: str = \\\"\\\",                   # empty → resolved from config/provider later\\n    98|        max_iterations: int = 90,          # tool-calling iterations (shared with subagents)\\n    99|        enabled_toolsets: list = None,\\n   100|        disabled_toolsets: list = None,\\n   101|        quiet_mode: bool = False,\\n   102|        save_trajectories: bool = False,\\n   103|        platform: str = None,              # \\\"cli\\\", \\\"telegram\\\", etc.\\n   104|        session_id: str = None,\\n   105|        skip_context_files: bool = False,\\n   106|        skip_memory: bool = False,\\n   107|        credential_pool=None,\\n   108|        # ... plus callbacks, thread/user/chat IDs, iteration_budget, fallback_model,\\n   109|        # checkpoints config, prefill_messages, service_tier, reasoning_config, etc.\\n   110|    ): ...\\n   111|\\n   112|    def chat(self, message: str) -> str:\\n   113|        \\\"\\\"\\\"Simple interface — returns final response string.\\\"\\\"\\\"\\n   114|\\n   115|    def run_conversation(self, user_message: str, system_message: str = None,\\n   116|                         conversation_history: list = None, task_id: str = None) -> dict:\\n   117|        \\\"\\\"\\\"Full interface — returns dict with final_response + messages.\\\"\\\"\\\"\\n   118|```\\n   119|\\n   120|### Agent Loop\\n   121|\\n   122|The core loop is inside `run_conversation()` — entirely synchronous, with\\n   123|interrupt checks, budget tracking, and a one-turn grace call:\\n   124|\\n   125|```python\\n   126|while (api_call_count < self.max_iterations and self.iteration_budget.remaining > 0) \\\\\\n   127|        or self._budget_grace_call:\\n   128|    if self._interrupt_requested: break\\n   129|    response = client.chat.completions.create(model=model, messages=messages, tools=tool_schemas)\\n   130|    if response.tool_calls:\\n   131|        for tool_call in response.tool_calls:\\n   132|            result = handle_function_call(tool_call.name, tool_call.args, task_id)\\n   133|            messages.append(tool_result_message(result))\\n   134|        api_call_count += 1\\n   135|    else:\\n   136|        return response.content\\n   137|```\\n   138|\\n   139|Messages follow OpenAI format: `{\\\"role\\\": \\\"system/user/assistant/tool\\\", ...}`.\\n   140|Reasoning content is stored in `assistant_msg[\\\"reasoning\\\"]`.\\n   141|\\n   142|---\\n   143|\\n   144|## CLI Architecture (cli.py)\\n   145|\\n   146|- **Rich** for banner/panels, **prompt_toolkit** for input with autocomplete\\n   147|- **KawaiiSpinner** (`agent/display.py`) — animated faces during API calls, `┊` activity feed for tool results\\n   148|- `load_cli_config()` in cli.py merges hardcoded defaults + user config YAML\\n   149|- **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   150|- `process_command()` is a method on `HermesCLI` — dispatches on canonical command name resolved via `resolve_command()` from the central registry\\n   151|- Skill slash commands: `agent/skill_commands.py` scans `~/.hermes/skills/`, injects as **user message** (not system prompt) to preserve prompt caching\\n   152|\\n   153|### Slash Command Registry (`hermes_cli/commands.py`)\\n   154|\\n   155|All slash commands are defined in a central `COMMAND_REGISTRY` list of `CommandDef` objects. Every downstream consumer derives from this registry automatically:\\n   156|\\n   157|- **CLI** — `process_command()` resolves aliases via `resolve_command()`, dispatches on canonical name\\n   158|- **Gateway** — `GATEWAY_KNOWN_COMMANDS` frozenset for hook emission, `resolve_command()` for dispatch\\n   159|- **Gateway help** — `gateway_help_lines()` generates `/help` output\\n   160|- **Telegram** — `telegram_bot_commands()` generates the BotCommand menu\\n   161|- **Slack** — `slack_subcommand_map()` generates `/hermes` subcommand routing\\n   162|- **Autocomplete** — `COMMANDS` flat dict feeds `SlashCommandCompleter`\\n   163|- **CLI help** — `COMMANDS_BY_CATEGORY` dict feeds `show_help()`\\n   164|\\n   165|### Adding a Slash Command\\n   166|\\n   167|1. Add a `CommandDef` entry to `COMMAND_REGISTRY` in `hermes_cli/commands.py`:\\n   168|```python\\n   169|CommandDef(\\\"mycommand\\\", \\\"Description of what it does\\\", \\\"Session\\\",\\n   170|           aliases=(\\\"mc\\\",), args_hint=\\\"[arg]\\\"),\\n   171|```\\n   172|2. Add handler in `HermesCLI.process_command()` in `cli.py`:\\n   173|```python\\n   174|elif canonical == \\\"mycommand\\\":\\n   175|    self._handle_mycommand(cmd_original)\\n   176|```\\n   177|3. If the command is available in the gateway, add a handler in `gateway/run.py`:\\n   178|```python\\n   179|if canonical == \\\"mycommand\\\":\\n   180|    return await self._handle_mycommand(event)\\n   181|```\\n   182|4. For persistent settings, use `save_config_value()` in `cli.py`\\n   183|\\n   184|**CommandDef fields:**\\n   185|- `name` — canonical name without slash (e.g. `\\\"background\\\"`)\\n   186|- `description` — human-readable description\\n   187|- `category` — one of `\\\"Session\\\"`, `\\\"Configuration\\\"`, `\\\"Tools & Skills\\\"`, `\\\"Info\\\"`, `\\\"Exit\\\"`\\n   188|- `aliases` — tuple of alternative names (e.g. `(\\\"bg\\\",)`)\\n   189|- `args_hint` — argument placeholder shown in help (e.g. `\\\"<prompt>\\\"`, `\\\"[name]\\\"`)\\n   190|- `cli_only` — only available in the interactive CLI\\n   191|- `gateway_only` — only available in messaging platforms\\n   192|- `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   193|\\n   194|**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   195|\\n   196|---\\n   197|\\n   198|## TUI Architecture (ui-tui + tui_gateway)\\n   199|\\n   200|The TUI is a full replacement for the classic (prompt_toolkit) CLI, activated via `hermes --tui` or `HERMES_TUI=1`.\\n   201|\\n   202|### Process Model\\n   203|\\n   204|```\\n   205|hermes --tui\\n   206|  └─ Node (Ink)  ──stdio JSON-RPC──  Python (tui_gateway)\\n   207|       │                                  └─ AIAgent + tools + sessions\\n   208|       └─ renders transcript, composer, prompts, activity\\n   209|```\\n   210|\\n   211|TypeScript owns the screen. Python owns sessions, tools, model calls, and slash command logic.\\n   212|\\n   213|### Transport\\n   214|\\n   215|Newline-delimited JSON-RPC over stdio. Requests from Ink, events from Python. See `tui_gateway/server.py` for the full method/event catalog.\\n   216|\\n   217|### Key Surfaces\\n   218|\\n   219|| Surface | Ink component | Gateway method |\\n   220||---------|---------------|----------------|\\n   221|| Chat streaming | `app.tsx` + `messageLine.tsx` | `prompt.submit` → `message.delta/complete` |\\n   222|| Tool activity | `thinking.tsx` | `tool.start/progress/complete` |\\n   223|| Approvals | `prompts.tsx` | `approval.respond` ← `approval.request` |\\n   224|| Clarify/sudo/secret | `prompts.tsx`, `maskedPrompt.tsx` | `clarify/sudo/secret.respond` |\\n   225|| Session picker | `sessionPicker.tsx` | `session.list/resume` |\\n   226|| Slash commands | Local handler + fallthrough | `slash.exec` → `_SlashWorker`, `command.dispatch` |\\n   227|| Completions | `useCompletion` hook | `complete.slash`, `complete.path` |\\n   228|| Theming | `theme.ts` + `branding.tsx` | `gateway.ready` with skin data |\\n   229|\\n   230|### Slash Command Flow\\n   231|\\n   232|1. Built-in client commands (`/help`, `/quit`, `/clear`, `/resume`, `/copy`, `/paste`, etc.) handled locally in `app.tsx`\\n   233|2. Everything else → `slash.exec` (runs in persistent `_SlashWorker` subprocess) → `command.dispatch` fallback\\n   234|\\n   235|### Dev Commands\\n   236|\\n   237|```bash\\n   238|cd ui-tui\\n   239|npm install       # first time\\n   240|npm run dev       # watch mode (rebuilds hermes-ink + tsx --watch)\\n   241|npm start         # production\\n   242|npm run build     # full build (hermes-ink + tsc)\\n   243|npm run type-check # typecheck only (tsc --noEmit)\\n   244|npm run lint      # eslint\\n   245|npm run fmt       # prettier\\n   246|npm test          # vitest\\n   247|```\\n   248|\\n   249|### TUI in the Dashboard (`hermes dashboard` → `/chat`)\\n   250|\\n   251|The 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   252|\\n   253|- 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   254|- `/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   255|- The server spawns whatever `hermes --tui` would spawn, through `ptyprocess` (POSIX PTY — WSL works, native Windows does not).\\n   256|- Frames: raw PTY bytes each direction; resize via `\\\\x1b[RESIZE:<cols>;<rows>]` intercepted on the server and applied with `TIOCSWINSZ`.\\n   257|\\n   258|**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   259|\\n   260|**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   261|\\n   262|---\\n   263|\\n   264|## Adding New Tools\\n   265|\\n   266|For most custom or local-only tools, do **not** edit Hermes core. Use the plugin\\n   267|route instead: create `~/.hermes/plugins/<name>/plugin.yaml` and\\n   268|`~/.hermes/plugins/<name>/__init__.py`, then register tools with\\n   269|`ctx.register_tool(...)`. Plugin toolsets are discovered automatically and can be\\n   270|enabled or disabled without touching `tools/` or `toolsets.py`.\\n   271|\\n   272|Use the built-in route below only when the user is explicitly contributing a new\\n   273|core Hermes tool that should ship in the base system.\\n   274|\\n   275|Built-in/core tools require changes in **2 files**:\\n   276|\\n   277|**1. Create `tools/your_tool.py`:**\\n   278|```python\\n   279|import json, os\\n   280|from tools.registry import registry\\n   281|\\n   282|def check_requirements() -> bool:\\n   283|    return bool(os.getenv(\\\"EXAMPLE_API_KEY\\\"))\\n   284|\\n   285|def example_tool(param: str, task_id: str = None) -> str:\\n   286|    return json.dumps({\\\"success\\\": True, \\\"data\\\": \\\"...\\\"})\\n   287|\\n   288|registry.register(\\n   289|    name=\\\"example_tool\\\",\\n   290|    toolset=\\\"example\\\",\\n   291|    schema={\\\"name\\\": \\\"example_tool\\\", \\\"description\\\": \\\"...\\\", \\\"parameters\\\": {...}},\\n   292|    handler=lambda args, **kw: example_tool(param=args.get(\\\"param\\\", \\\"\\\"), task_id=kw.get(\\\"task_id\\\")),\\n   293|    check_fn=check_requirements,\\n   294|    requires_env=[\\\"EXAMPLE_API_KEY\\\"],\\n   295|)\\n   296|```\\n   297|\\n   298|**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   299|\\n   300|Auto-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   301|\\n   302|The registry handles schema collection, dispatch, availability checking, and error wrapping. All handlers MUST return a JSON string.\\n   303|\\n   304|**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   305|\\n   306|**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   307|\\n   308|**Agent-level tools** (todo, memory): intercepted by `run_agent.py` before `handle_function_call()`. See `tools/todo_tool.py` for the pattern.\\n   309|\\n   310|---\\n   311|\\n   312|## Adding Configuration\\n   313|\\n   314|### config.yaml options:\\n   315|1. Add to `DEFAULT_CONFIG` in `hermes_cli/config.py`\\n   316|2. Bump `_config_version` (check the current value at the top of `DEFAULT_CONFIG`)\\n   317|   ONLY if you need to actively migrate/transform existing user config\\n   318|   (renaming keys, changing structure). Adding a new key to an existing\\n   319|   section is handled automatically by the deep-merge and does NOT require\\n   320|   a version bump.\\n   321|\\n   322|### Top-level `config.yaml` sections (non-exhaustive):\\n   323|\\n   324|`model`, `agent`, `terminal`, `compression`, `display`, `stt`, `tts`,\\n   325|`memory`, `security`, `delegation`, `smart_model_routing`, `checkpoints`,\\n   326|`auxiliary`, `curator`, `skills`, `gateway`, `logging`, `cron`, `profiles`,\\n   327|`plugins`, `honcho`.\\n   328|\\n   329|`auxiliary` holds per-task overrides for side-LLM work (curator, vision,\\n   330|embedding, title generation, session_search, etc.) — each task can pin\\n   331|its own provider/model/base_url/max_tokens/reasoning_effort. See\\n   332|`agent/auxiliary_client.py::_resolve_auto` for resolution order.\\n   333|\\n   334|`curator` holds the background skill-maintenance config —\\n   335|`enabled`, `interval_hours`, `min_idle_hours`, `stale_after_days`,\\n   336|`archive_after_days`, `backup` (nested).\\n   337|\\n   338|### .env variables (SECRETS ONLY — API keys, tokens, passwords):\\n   339|1. Add to `OPTIONAL_ENV_VARS` in `hermes_cli/config.py` with metadata:\\n   340|```python\\n   341|\\\"NEW_API_KEY\\\": {\\n   342|    \\\"description\\\": \\\"What it's for\\\",\\n   343|    \\\"prompt\\\": \\\"Display name\\\",\\n   344|    \\\"url\\\": \\\"https://...\\\",\\n   345|    \\\"password\\\": True,\\n   346|    \\\"category\\\": \\\"tool\\\",  # provider, tool, messaging, setting\\n   347|},\\n   348|```\\n   349|\\n   350|Non-secret settings (timeouts, thresholds, feature flags, paths, display\\n   351|preferences) belong in `config.yaml`, not `.env`. If internal code needs an\\n   352|env var mirror for backward compatibility, bridge it from `config.yaml` to\\n   353|the env var in code (see `gateway_timeout`, `terminal.cwd` → `TERMINAL_CWD`).\\n   354|\\n   355|### Config loaders (three paths — know which one you're in):\\n   356|\\n   357|| Loader | Used by | Location |\\n   358||--------|---------|----------|\\n   359|| `load_cli_config()` | CLI mode | `cli.py` — merges CLI-specific defaults + user YAML |\\n   360|| `load_config()` | `hermes tools`, `hermes setup`, most CLI subcommands | `hermes_cli/config.py` — merges `DEFAULT_CONFIG` + user YAML |\\n   361|| Direct YAML load | Gateway runtime | `gateway/run.py` + `gateway/config.py` — reads user YAML raw |\\n   362|\\n   363|If you add a new key and the CLI sees it but the gateway doesn't (or vice\\n   364|versa), you're on the wrong loader. Check `DEFAULT_CONFIG` coverage.\\n   365|\\n   366|### Working directory:\\n   367|- **CLI** — uses the process's current directory (`os.getcwd()`).\\n   368|- **Messaging** — uses `terminal.cwd` from `config.yaml`. The gateway bridges this\\n   369|  to the `TERMINAL_CWD` env var for child tools. **`MESSAGING_CWD` has been\\n   370|  removed** — the config loader prints a deprecation warning if it's set in\\n   371|  `.env`. Same for `TERMINAL_CWD` in `.env`; the canonical setting is\\n   372|  `terminal.cwd` in `config.yaml`.\\n   373|\\n   374|---\\n   375|\\n   376|## Skin/Theme System\\n   377|\\n   378|The 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   379|\\n   380|### Architecture\\n   381|\\n   382|```\\n   383|hermes_cli/skin_engine.py    # SkinConfig dataclass, built-in skins, YAML loader\\n   384|~/.hermes/skins/*.yaml       # User-installed custom skins (drop-in)\\n   385|```\\n   386|\\n   387|- `init_skin_from_config()` — called at CLI startup, reads `display.skin` from config\\n   388|- `get_active_skin()` — returns cached `SkinConfig` for the current skin\\n   389|- `set_active_skin(name)` — switches skin at runtime (used by `/skin` command)\\n   390|- `load_skin(name)` — loads from user skins first, then built-ins, then falls back to default\\n   391|- Missing skin values inherit from the `default` skin automatically\\n   392|\\n   393|### What skins customize\\n   394|\\n   395|| Element | Skin Key | Used By |\\n   396||---------|----------|---------|\\n   397|| Banner panel border | `colors.banner_border` | `banner.py` |\\n   398|| Banner panel title | `colors.banner_title` | `banner.py` |\\n   399|| Banner section headers | `colors.banner_accent` | `banner.py` |\\n   400|| Banner dim text | `colors.banner_dim` | `banner.py` |\\n   401|| Banner body text | `colors.banner_text` | `banner.py` |\\n   402|| Response box border | `colors.response_border` | `cli.py` |\\n   403|| Spinner faces (waiting) | `spinner.waiting_faces` | `display.py` |\\n   404|| Spinner faces (thinking) | `spinner.thinking_faces` | `display.py` |\\n   405|| Spinner verbs | `spinner.thinking_verbs` | `display.py` |\\n   406|| Spinner wings (optional) | `spinner.wings` | `display.py` |\\n   407|| Tool output prefix | `tool_prefix` | `display.py` |\\n   408|| Per-tool emojis | `tool_emojis` | `display.py` → `get_tool_emoji()` |\\n   409|| Agent name | `branding.agent_name` | `banner.py`, `cli.py` |\\n   410|| Welcome message | `branding.welcome` | `cli.py` |\\n   411|| Response box label | `branding.response_label` | `cli.py` |\\n   412|| Prompt symbol | `branding.prompt_symbol` | `cli.py` |\\n   413|\\n   414|### Built-in skins\\n   415|\\n   416|- `default` — Classic Hermes gold/kawaii (the current look)\\n   417|- `ares` — Crimson/bronze war-god theme with custom spinner wings\\n   418|- `mono` — Clean grayscale monochrome\\n   419|- `slate` — Cool blue developer-focused theme\\n   420|\\n   421|### Adding a built-in skin\\n   422|\\n   423|Add to `_BUILTIN_SKINS` dict in `hermes_cli/skin_engine.py`:\\n   424|\\n   425|```python\\n   426|\\\"mytheme\\\": {\\n   427|    \\\"name\\\": \\\"mytheme\\\",\\n   428|    \\\"description\\\": \\\"Short description\\\",\\n   429|    \\\"colors\\\": { ... },\\n   430|    \\\"spinner\\\": { ... },\\n   431|    \\\"branding\\\": { ... },\\n   432|    \\\"tool_prefix\\\": \\\"┊\\\",\\n   433|},\\n   434|```\\n   435|\\n   436|### User skins (YAML)\\n   437|\\n   438|Users create `~/.hermes/skins/<name>.yaml`:\\n   439|\\n   440|```yaml\\n   441|name: cyberpunk\\n   442|description: Neon-soaked terminal theme\\n   443|\\n   444|colors:\\n   445|  banner_border: \\\"#FF00FF\\\"\\n   446|  banner_title: \\\"#00FFFF\\\"\\n   447|  banner_accent: \\\"#FF1493\\\"\\n   448|\\n   449|spinner:\\n   450|  thinking_verbs: [\\\"jacking in\\\", \\\"decrypting\\\", \\\"uploading\\\"]\\n   451|  wings:\\n   452|    - [\\\"⟨⚡\\\", \\\"⚡⟩\\\"]\\n   453|\\n   454|branding:\\n   455|  agent_name: \\\"Cyber Agent\\\"\\n   456|  response_label: \\\" ⚡ Cyber \\\"\\n   457|\\n   458|tool_prefix: \\\"▏\\\"\\n   459|```\\n   460|\\n   461|Activate with `/skin cyberpunk` or `display.skin: cyberpunk` in config.yaml.\\n   462|\\n   463|---\\n   464|\\n   465|## Plugins\\n   466|\\n   467|Hermes has two plugin surfaces. Both live under `plugins/` in the repo so\\n   468|repo-shipped plugins can be discovered alongside user-installed ones in\\n   469|`~/.hermes/plugins/` and pip-installed entry points.\\n   470|\\n   471|### General plugins (`hermes_cli/plugins.py` + `plugins/<name>/`)\\n   472|\\n   473|`PluginManager` discovers plugins from `~/.hermes/plugins/`, `./.hermes/plugins/`,\\n   474|and pip entry points. Each plugin exposes a `register(ctx)` function that\\n   475|can:\\n   476|\\n   477|- Register Python-callback lifecycle hooks:\\n   478|  `pre_tool_call`, `post_tool_call`, `pre_llm_call`, `post_llm_call`,\\n   479|  `on_session_start`, `on_session_end`\\n   480|- Register new tools via `ctx.register_tool(...)`\\n   481|- Register CLI subcommands via `ctx.register_cli_command(...)` — the\\n   482|  plugin's argparse tree is wired into `hermes` at startup so\\n   483|  `hermes <pluginname> <subcmd>` works with no change to `main.py`\\n   484|\\n   485|Hooks are invoked from `model_tools.py` (pre/post tool) and `run_agent.py`\\n   486|(lifecycle). **Discovery timing pitfall:** `discover_plugins()` only runs\\n   487|as a side effect of importing `model_tools.py`. Code paths that read plugin\\n   488|state without importing `model_tools.py` first must call `discover_plugins()`\\n   489|explicitly (it's idempotent).\\n   490|\\n   491|### Memory-provider plugins (`plugins/memory/<name>/`)\\n   492|\\n   493|Separate discovery system for pluggable memory backends. Current built-in\\n   494|providers include **honcho, mem0, supermemory, byterover, hindsight,\\n   495|holographic, openviking, retaindb**.\\n   496|\\n   497|Each provider implements the `MemoryProvider` ABC (see `agent/memory_provider.py`)\\n   498|and is orchestrated by `agent/memory_manager.py`. Lifecycle hooks include\\n   499|`sync_turn(turn_messages)`, `prefetch(query)`, `shutdown()`, and optional\\n   500|`post_setup(hermes_home, config)` for setup-wizard integration.\\n   501|\", \"total_lines\": 985, \"file_size\": 45759, \"truncated\": true, \"hint\": \"Use offset=501 to continue reading (showing 1-500 of 985 lines)\", \"is_binary\": false, \"is_image\": false}",
          "tool_call_id": "edp6FDpgN47xdBpHAwke95OwuH8lSem6"
        },
        {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "id": "Z3VfZWxbiW4ENq4WO5BvFz8E2GD3blhh",
              "type": "function",
              "function": {
                "name": "read_file",
                "arguments": "{\"limit\":500,\"offset\":501,\"path\":\"/home/agent/.hermes/hermes-agent/AGENTS.md\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "name": "read_file",
          "content": "{\"content\": \"   501|\\n   502|**CLI commands via `plugins/memory/<name>/cli.py`:** if a memory plugin\\n   503|defines `register_cli(subparser)`, `discover_plugin_cli_commands()` finds\\n   504|it at argparse setup time and wires it into `hermes <plugin>`. The\\n   505|framework only exposes CLI commands for the **currently active** memory\\n   506|provider (read from `memory.provider` in config.yaml), so disabled\\n   507|providers don't clutter `hermes --help`.\\n   508|\\n   509|**Rule (Teknium, May 2026):** plugins MUST NOT modify core files\\n   510|(`run_agent.py`, `cli.py`, `gateway/run.py`, `hermes_cli/main.py`, etc.).\\n   511|If a plugin needs a capability the framework doesn't expose, expand the\\n   512|generic plugin surface (new hook, new ctx method) — never hardcode\\n   513|plugin-specific logic into core. PR #5295 removed 95 lines of hardcoded\\n   514|honcho argparse from `main.py` for exactly this reason.\\n   515|\\n   516|### Model-provider plugins (`plugins/model-providers/<name>/`)\\n   517|\\n   518|Every inference backend (openrouter, anthropic, gmi, deepseek, nvidia, …)\\n   519|ships as a plugin here. Each plugin's `__init__.py` calls\\n   520|`providers.register_provider(ProviderProfile(...))` at module load.\\n   521|`providers/__init__.py._discover_providers()` is a **lazy, separate\\n   522|discovery system** — scanned on first `get_provider_profile()` or\\n   523|`list_providers()` call, NOT by the general PluginManager.\\n   524|\\n   525|Scan order:\\n   526|1. Bundled: `<repo>/plugins/model-providers/<name>/`\\n   527|2. User: `$HERMES_HOME/plugins/model-providers/<name>/`\\n   528|3. Legacy: `<repo>/providers/<name>.py` (back-compat)\\n   529|\\n   530|User plugins of the same name override bundled ones — `register_provider()`\\n   531|is last-writer-wins. This lets third parties swap out any built-in\\n   532|profile without a repo patch.\\n   533|\\n   534|The general PluginManager records `kind: model-provider` manifests but does\\n   535|NOT import them (would double-instantiate `ProviderProfile`). Plugins\\n   536|without an explicit `kind:` get auto-coerced via a source-text heuristic\\n   537|(`register_provider` + `ProviderProfile` in `__init__.py`).\\n   538|\\n   539|Full authoring guide: `website/docs/developer-guide/model-provider-plugin.md`.\\n   540|\\n   541|### Dashboard / context-engine / image-gen plugin directories\\n   542|\\n   543|`plugins/context_engine/`, `plugins/image_gen/`, `plugins/example-dashboard/`,\\n   544|etc. follow the same pattern (ABC + orchestrator + per-plugin directory).\\n   545|Context engines plug into `agent/context_engine.py`; image-gen providers\\n   546|into `agent/image_gen_provider.py`.\\n   547|\\n   548|---\\n   549|\\n   550|## Skills\\n   551|\\n   552|Two parallel surfaces:\\n   553|\\n   554|- **`skills/`** — built-in skills shipped and loadable by default.\\n   555|  Organized by category directories (e.g. `skills/github/`, `skills/mlops/`).\\n   556|- **`optional-skills/`** — heavier or niche skills shipped with the repo but\\n   557|  NOT active by default. Installed explicitly via\\n   558|  `hermes skills install official/<category>/<skill>`. Adapter lives in\\n   559|  `tools/skills_hub.py` (`OptionalSkillSource`). Categories include\\n   560|  `autonomous-ai-agents`, `blockchain`, `communication`, `creative`,\\n   561|  `devops`, `email`, `health`, `mcp`, `migration`, `mlops`, `productivity`,\\n   562|  `research`, `security`, `web-development`.\\n   563|\\n   564|When reviewing skill PRs, check which directory they target — heavy-dep or\\n   565|niche skills belong in `optional-skills/`.\\n   566|\\n   567|### SKILL.md frontmatter\\n   568|\\n   569|Standard fields: `name`, `description`, `version`, `author`, `license`,\\n   570|`platforms` (OS-gating list: `[macos]`, `[linux, macos]`, ...),\\n   571|`metadata.hermes.tags`, `metadata.hermes.category`,\\n   572|`metadata.hermes.related_skills`, `metadata.hermes.config` (config.yaml\\n   573|settings the skill needs — stored under `skills.config.<key>`, prompted\\n   574|during setup, injected at load time).\\n   575|\\n   576|Top-level `tags:` and `category:` are also accepted and mirrored from\\n   577|`metadata.hermes.*` by the loader.\\n   578|\\n   579|---\\n   580|\\n   581|## Toolsets\\n   582|\\n   583|All toolsets are defined in `toolsets.py` as a single `TOOLSETS` dict.\\n   584|Each platform's adapter picks a base toolset (e.g. Telegram uses\\n   585|`\\\"messaging\\\"`); `_HERMES_CORE_TOOLS` is the default bundle most\\n   586|platforms inherit from.\\n   587|\\n   588|Current toolset keys: `browser`, `clarify`, `code_execution`, `cronjob`,\\n   589|`debugging`, `delegation`, `discord`, `discord_admin`, `feishu_doc`,\\n   590|`feishu_drive`, `file`, `homeassistant`, `image_gen`, `kanban`, `memory`,\\n   591|`messaging`, `moa`, `rl`, `safe`, `search`, `session_search`, `skills`,\\n   592|`spotify`, `terminal`, `todo`, `tts`, `video`, `vision`, `web`, `yuanbao`.\\n   593|\\n   594|Enable/disable per platform via `hermes tools` (the curses UI) or the\\n   595|`tools.<platform>.enabled` / `tools.<platform>.disabled` lists in\\n   596|`config.yaml`.\\n   597|\\n   598|---\\n   599|\\n   600|## Delegation (`delegate_task`)\\n   601|\\n   602|`tools/delegate_tool.py` spawns a subagent with an isolated\\n   603|context + terminal session. Synchronous: the parent waits for the\\n   604|child's summary before continuing its own loop — if the parent is\\n   605|interrupted, the child is cancelled.\\n   606|\\n   607|Two shapes:\\n   608|\\n   609|- **Single:** pass `goal` (+ optional `context`, `toolsets`).\\n   610|- **Batch (parallel):** pass `tasks: [...]` — each gets its own subagent\\n   611|  running concurrently. Concurrency is capped by\\n   612|  `delegation.max_concurrent_children` (default 3).\\n   613|\\n   614|Roles:\\n   615|\\n   616|- `role=\\\"leaf\\\"` (default) — focused worker. Cannot call `delegate_task`,\\n   617|  `clarify`, `memory`, `send_message`, `execute_code`.\\n   618|- `role=\\\"orchestrator\\\"` — retains `delegate_task` so it can spawn its\\n   619|  own workers. Gated by `delegation.orchestrator_enabled` (default true)\\n   620|  and bounded by `delegation.max_spawn_depth` (default 2).\\n   621|\\n   622|Key config knobs (under `delegation:` in `config.yaml`):\\n   623|`max_concurrent_children`, `max_spawn_depth`, `child_timeout_seconds`,\\n   624|`orchestrator_enabled`, `subagent_auto_approve`, `inherit_mcp_toolsets`,\\n   625|`max_iterations`.\\n   626|\\n   627|Synchronicity rule: delegate_task is **not** durable. For long-running\\n   628|work that must outlive the current turn, use `cronjob` or\\n   629|`terminal(background=True, notify_on_complete=True)` instead.\\n   630|\\n   631|---\\n   632|\\n   633|## Curator (skill lifecycle)\\n   634|\\n   635|Background skill-maintenance system that tracks usage on agent-created\\n   636|skills and auto-archives stale ones. Users never lose skills; archives\\n   637|go to `~/.hermes/skills/.archive/` and are restorable.\\n   638|\\n   639|- **Core:** `agent/curator.py` (review loop, auto-transitions, LLM review\\n   640|  prompt) + `agent/curator_backup.py` (pre-run tar.gz snapshots).\\n   641|- **CLI:** `hermes_cli/curator.py` wires `hermes curator <verb>` where\\n   642|  verbs are: `status`, `run`, `pause`, `resume`, `pin`, `unpin`,\\n   643|  `archive`, `restore`, `prune`, `backup`, `rollback`.\\n   644|- **Telemetry:** `tools/skill_usage.py` owns the sidecar\\n   645|  `~/.hermes/skills/.usage.json` — per-skill `use_count`, `view_count`,\\n   646|  `patch_count`, `last_activity_at`, `state` (active / stale /\\n   647|  archived), `pinned`.\\n   648|\\n   649|Invariants:\\n   650|- Curator only touches skills with `created_by: \\\"agent\\\"` provenance —\\n   651|  bundled + hub-installed skills are off-limits.\\n   652|- Never deletes; max destructive action is archive.\\n   653|- Pinned skills are exempt from every auto-transition and from the\\n   654|  LLM review pass.\\n   655|- `skill_manage(action=\\\"delete\\\")` refuses pinned skills; patch/edit/\\n   656|  write_file/remove_file go through so the agent can keep improving\\n   657|  pinned skills.\\n   658|\\n   659|Config section (`curator:` in `config.yaml`):\\n   660|`enabled`, `interval_hours`, `min_idle_hours`, `stale_after_days`,\\n   661|`archive_after_days`, `backup.*`.\\n   662|\\n   663|Full user-facing docs: `website/docs/user-guide/features/curator.md`.\\n   664|\\n   665|---\\n   666|\\n   667|## Cron (scheduled jobs)\\n   668|\\n   669|`cron/jobs.py` (job store) + `cron/scheduler.py` (tick loop). Agents\\n   670|schedule jobs via the `cronjob` tool; users via `hermes cron <verb>`\\n   671|(`list`, `add`, `edit`, `pause`, `resume`, `run`, `remove`) or the\\n   672|`/cron` slash command.\\n   673|\\n   674|Supported schedule formats:\\n   675|- Duration: `\\\"30m\\\"`, `\\\"2h\\\"`, `\\\"1d\\\"`\\n   676|- \\\"every\\\" phrase: `\\\"every 2h\\\"`, `\\\"every monday 9am\\\"`\\n   677|- 5-field cron expression: `\\\"0 9 * * *\\\"`\\n   678|- ISO timestamp (one-shot): `\\\"2026-06-01T09:00:00Z\\\"`\\n   679|\\n   680|Per-job fields include `skills` (load specific skills), `model` /\\n   681|`provider` overrides, `script` (pre-run data-collection script whose\\n   682|stdout is injected into the prompt; `no_agent=True` turns the script\\n   683|into the entire job), `context_from` (chain job A's last output into\\n   684|job B's prompt), `workdir` (run in a specific directory with its\\n   685|`AGENTS.md`/`CLAUDE.md` loaded), and multi-platform delivery.\\n   686|\\n   687|Hardening invariants:\\n   688|- **3-minute hard interrupt** on cron sessions — runaway agent loops\\n   689|  cannot monopolize the scheduler.\\n   690|- Catchup window: half the job's period, clamped to 120s–2h.\\n   691|- Grace window: 120s for one-shot jobs whose fire time was missed.\\n   692|- File lock at `~/.hermes/cron/.tick.lock` prevents duplicate ticks\\n   693|  across processes.\\n   694|- Cron sessions pass `skip_memory=True` by default; memory providers\\n   695|  intentionally do not run during cron.\\n   696|\\n   697|Cron deliveries are **not** mirrored into the target gateway session —\\n   698|they land in their own cron session with a header/footer frame so the\\n   699|main conversation's message-role alternation stays intact.\\n   700|\\n   701|---\\n   702|\\n   703|## Kanban (multi-agent work queue)\\n   704|\\n   705|Durable SQLite-backed board that lets multiple profiles / workers\\n   706|collaborate on shared tasks. Users drive it via `hermes kanban <verb>`;\\n   707|workers spawned by the dispatcher drive it via a dedicated `kanban_*`\\n   708|toolset so their schema footprint is zero when they're not inside a\\n   709|kanban task.\\n   710|\\n   711|- **CLI:** `hermes_cli/kanban.py` wires `hermes kanban` with verbs\\n   712|  `init`, `create`, `list` (alias `ls`), `show`, `assign`, `link`,\\n   713|  `unlink`, `comment`, `complete`, `block`, `unblock`, `archive`,\\n   714|  `tail`, plus less-commonly-used `watch`, `stats`, `runs`, `log`,\\n   715|  `assignees`, `heartbeat`, `notify-*`, `dispatch`, `daemon`, `gc`.\\n   716|- **Worker toolset:** `tools/kanban_tools.py` exposes `kanban_show`,\\n   717|  `kanban_complete`, `kanban_block`, `kanban_heartbeat`, `kanban_comment`,\\n   718|  `kanban_create`, `kanban_link` — gated by `HERMES_KANBAN_TASK` so\\n   719|  the schema only appears for processes actually running as a worker.\\n   720|- **Dispatcher:** long-lived loop that (default every 60s) reclaims\\n   721|  stale claims, promotes ready tasks, atomically claims, and spawns\\n   722|  assigned profiles. Runs **inside the gateway** by default via\\n   723|  `kanban.dispatch_in_gateway: true`.\\n   724|- **Plugin assets:** `plugins/kanban/dashboard/` (web UI) +\\n   725|  `plugins/kanban/systemd/` (`hermes-kanban-dispatcher.service` for\\n   726|  standalone dispatcher deployment).\\n   727|\\n   728|Isolation model:\\n   729|- **Board** is the hard boundary — workers are spawned with\\n   730|  `HERMES_KANBAN_BOARD` pinned in their env so they can't see other\\n   731|  boards.\\n   732|- **Tenant** is a soft namespace *within* a board — one specialist\\n   733|  fleet can serve multiple businesses with workspace-path + memory-key\\n   734|  isolation.\\n   735|- After ~5 consecutive spawn failures on the same task the dispatcher\\n   736|  auto-blocks it to prevent spin loops.\\n   737|\\n   738|Full user-facing docs: `website/docs/user-guide/features/kanban.md`.\\n   739|\\n   740|---\\n   741|\\n   742|## Important Policies\\n   743|\\n   744|### Prompt Caching Must Not Break\\n   745|\\n   746|Hermes-Agent ensures caching remains valid throughout a conversation. **Do NOT implement changes that would:**\\n   747|- Alter past context mid-conversation\\n   748|- Change toolsets mid-conversation\\n   749|- Reload memories or rebuild system prompts mid-conversation\\n   750|\\n   751|Cache-breaking forces dramatically higher costs. The ONLY time we alter context is during context compression.\\n   752|\\n   753|Slash commands that mutate system-prompt state (skills, tools, memory, etc.)\\n   754|must be **cache-aware**: default to deferred invalidation (change takes\\n   755|effect next session), with an opt-in `--now` flag for immediate\\n   756|invalidation. See `/skills install --now` for the canonical pattern.\\n   757|\\n   758|### Background Process Notifications (Gateway)\\n   759|\\n   760|When `terminal(background=true, notify_on_complete=true)` is used, the gateway runs a watcher that\\n   761|detects process completion and triggers a new agent turn. Control verbosity of background process\\n   762|messages with `display.background_process_notifications`\\n   763|in config.yaml (or `HERMES_BACKGROUND_NOTIFICATIONS` env var):\\n   764|\\n   765|- `all` — running-output updates + final message (default)\\n   766|- `result` — only the final completion message\\n   767|- `error` — only the final message when exit code != 0\\n   768|- `off` — no watcher messages at all\\n   769|\\n   770|---\\n   771|\\n   772|## Profiles: Multi-Instance Support\\n   773|\\n   774|Hermes supports **profiles** — multiple fully isolated instances, each with its own\\n   775|`HERMES_HOME` directory (config, API keys, memory, sessions, skills, gateway, etc.).\\n   776|\\n   777|The core mechanism: `_apply_profile_override()` in `hermes_cli/main.py` sets\\n   778|`HERMES_HOME` before any module imports. All `get_hermes_home()` references\\n   779|automatically scope to the active profile.\\n   780|\\n   781|### Rules for profile-safe code\\n   782|\\n   783|1. **Use `get_hermes_home()` for all HERMES_HOME paths.** Import from `hermes_constants`.\\n   784|   NEVER hardcode `~/.hermes` or `Path.home() / \\\".hermes\\\"` in code that reads/writes state.\\n   785|   ```python\\n   786|   # GOOD\\n   787|   from hermes_constants import get_hermes_home\\n   788|   config_path = get_hermes_home() / \\\"config.yaml\\\"\\n   789|\\n   790|   # BAD — breaks profiles\\n   791|   config_path = Path.home() / \\\".hermes\\\" / \\\"config.yaml\\\"\\n   792|   ```\\n   793|\\n   794|2. **Use `display_hermes_home()` for user-facing messages.** Import from `hermes_constants`.\\n   795|   This returns `~/.hermes` for default or `~/.hermes/profiles/<name>` for profiles.\\n   796|   ```python\\n   797|   # GOOD\\n   798|   from hermes_constants import display_hermes_home\\n   799|   print(f\\\"Config saved to {display_hermes_home()}/config.yaml\\\")\\n   800|\\n   801|   # BAD — shows wrong path for profiles\\n   802|   print(\\\"Config saved to ~/.hermes/config.yaml\\\")\\n   803|   ```\\n   804|\\n   805|3. **Module-level constants are fine** — they cache `get_hermes_home()` at import time,\\n   806|   which is AFTER `_apply_profile_override()` sets the env var. Just use `get_hermes_home()`,\\n   807|   not `Path.home() / \\\".hermes\\\"`.\\n   808|\\n   809|4. **Tests that mock `Path.home()` must also set `HERMES_HOME`** — since code now uses\\n   810|   `get_hermes_home()` (reads env var), not `Path.home() / \\\".hermes\\\"`:\\n   811|   ```python\\n   812|   with patch.object(Path, \\\"home\\\", return_value=tmp_path), \\\\\\n   813|        patch.dict(os.environ, {\\\"HERMES_HOME\\\": str(tmp_path / \\\".hermes\\\")}):\\n   814|       ...\\n   815|   ```\\n   816|\\n   817|5. **Gateway platform adapters should use token locks** — if the adapter connects with\\n   818|   a unique credential (bot token, API key), call `acquire_scoped_lock()` from\\n   819|   `gateway.status` in the `connect()`/`start()` method and `release_scoped_lock()` in\\n   820|   `disconnect()`/`stop()`. This prevents two profiles from using the same credential.\\n   821|   See `gateway/platforms/telegram.py` for the canonical pattern.\\n   822|\\n   823|6. **Profile operations are HOME-anchored, not HERMES_HOME-anchored** — `_get_profiles_root()`\\n   824|   returns `Path.home() / \\\".hermes\\\" / \\\"profiles\\\"`, NOT `get_hermes_home() / \\\"profiles\\\"`.\\n   825|   This is intentional — it lets `hermes -p coder profile list` see all profiles regardless\\n   826|   of which one is active.\\n   827|\\n   828|## Known Pitfalls\\n   829|\\n   830|### DO NOT hardcode `~/.hermes` paths\\n   831|Use `get_hermes_home()` from `hermes_constants` for code paths. Use `display_hermes_home()`\\n   832|for user-facing print/log messages. Hardcoding `~/.hermes` breaks profiles — each profile\\n   833|has its own `HERMES_HOME` directory. This was the source of 5 bugs fixed in PR #3575.\\n   834|\\n   835|### DO NOT introduce new `simple_term_menu` usage\\n   836|Existing call sites in `hermes_cli/main.py` remain for legacy fallback only;\\n   837|the preferred UI is curses (stdlib) because `simple_term_menu` has\\n   838|ghost-duplication rendering bugs in tmux/iTerm2 with arrow keys. New\\n   839|interactive menus must use `hermes_cli/curses_ui.py` — see\\n   840|`hermes_cli/tools_config.py` for the canonical pattern.\\n   841|\\n   842|### DO NOT use `\\\\033[K` (ANSI erase-to-EOL) in spinner/display code\\n   843|Leaks as literal `?[K` text under `prompt_toolkit`'s `patch_stdout`. Use space-padding: `f\\\"\\\\r{line}{' ' * pad}\\\"`.\\n   844|\\n   845|### `_last_resolved_tool_names` is a process-global in `model_tools.py`\\n   846|`_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   847|\\n   848|### DO NOT hardcode cross-tool references in schema descriptions\\n   849|Tool 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   850|\\n   851|### The gateway has TWO message guards — both must bypass approval/control commands\\n   852|When an agent is running, messages pass through two sequential guards:\\n   853|(1) **base adapter** (`gateway/platforms/base.py`) queues messages in\\n   854|`_pending_messages` when `session_key in self._active_sessions`, and\\n   855|(2) **gateway runner** (`gateway/run.py`) intercepts `/stop`, `/new`,\\n   856|`/queue`, `/status`, `/approve`, `/deny` before they reach\\n   857|`running_agent.interrupt()`. Any new command that must reach the runner\\n   858|while the agent is blocked (e.g. approval prompts) MUST bypass BOTH\\n   859|guards and be dispatched inline, not via `_process_message_background()`\\n   860|(which races session lifecycle).\\n   861|\\n   862|### Squash merges from stale branches silently revert recent fixes\\n   863|Before squash-merging a PR, ensure the branch is up to date with `main`\\n   864|(`git fetch origin main && git reset --hard origin/main` in the worktree,\\n   865|then re-apply the PR's commits). A stale branch's version of an unrelated\\n   866|file will silently overwrite recent fixes on main when squashed. Verify\\n   867|with `git diff HEAD~1..HEAD` after merging — unexpected deletions are a\\n   868|red flag.\\n   869|\\n   870|### Don't wire in dead code without E2E validation\\n   871|Unused code that was never shipped was dead for a reason. Before wiring an\\n   872|unused module into a live code path, E2E test the real resolution chain\\n   873|with actual imports (not mocks) against a temp `HERMES_HOME`.\\n   874|\\n   875|### Tests must not write to `~/.hermes/`\\n   876|The `_isolate_hermes_home` autouse fixture in `tests/conftest.py` redirects `HERMES_HOME` to a temp dir. Never hardcode `~/.hermes/` paths in tests.\\n   877|\\n   878|**Profile tests**: When testing profile features, also mock `Path.home()` so that\\n   879|`_get_profiles_root()` and `_get_default_hermes_home()` resolve within the temp dir.\\n   880|Use the pattern from `tests/hermes_cli/test_profiles.py`:\\n   881|```python\\n   882|@pytest.fixture\\n   883|def profile_env(tmp_path, monkeypatch):\\n   884|    home = tmp_path / \\\".hermes\\\"\\n   885|    home.mkdir()\\n   886|    monkeypatch.setattr(Path, \\\"home\\\", lambda: tmp_path)\\n   887|    monkeypatch.setenv(\\\"HERMES_HOME\\\", str(home))\\n   888|    return home\\n   889|```\\n   890|\\n   891|---\\n   892|\\n   893|## Testing\\n   894|\\n   895|**ALWAYS use `scripts/run_tests.sh`** — do not call `pytest` directly. The script enforces\\n   896|hermetic environment parity with CI (unset credential vars, TZ=UTC, LANG=C.UTF-8,\\n   897|4 xdist workers matching GHA ubuntu-latest). Direct `pytest` on a 16+ core\\n   898|developer machine with API keys set diverges from CI in ways that have caused\\n   899|multiple \\\"works locally, fails in CI\\\" incidents (and the reverse).\\n   900|\\n   901|```bash\\n   902|scripts/run_tests.sh                                  # full suite, CI-parity\\n   903|scripts/run_tests.sh tests/gateway/                   # one directory\\n   904|scripts/run_tests.sh tests/agent/test_foo.py::test_x  # one test\\n   905|scripts/run_tests.sh -v --tb=long                     # pass-through pytest flags\\n   906|```\\n   907|\\n   908|### Why the wrapper (and why the old \\\"just call pytest\\\" doesn't work)\\n   909|\\n   910|Five real sources of local-vs-CI drift the script closes:\\n   911|\\n   912|| | Without wrapper | With wrapper |\\n   913||---|---|---|\\n   914|| Provider API keys | Whatever is in your env (auto-detects pool) | All `*_API_KEY`/`*_TOKEN`/etc. unset |\\n   915|| HOME / `~/.hermes/` | Your real config+auth.json | Temp dir per test |\\n   916|| Timezone | Local TZ (PDT etc.) | UTC |\\n   917|| Locale | Whatever is set | C.UTF-8 |\\n   918|| xdist workers | `-n auto` = all cores (20+ on a workstation) | `-n 4` matching CI |\\n   919|\\n   920|`tests/conftest.py` also enforces points 1-4 as an autouse fixture so ANY pytest\\n   921|invocation (including IDE integrations) gets hermetic behavior — but the wrapper\\n   922|is belt-and-suspenders.\\n   923|\\n   924|### Running without the wrapper (only if you must)\\n   925|\\n   926|If you can't use the wrapper (e.g. on Windows or inside an IDE that shells\\n   927|pytest directly), at minimum activate the venv and pass `-n 4`:\\n   928|\\n   929|```bash\\n   930|source .venv/bin/activate   # or: source venv/bin/activate\\n   931|python -m pytest tests/ -q -n 4\\n   932|```\\n   933|\\n   934|Worker count above 4 will surface test-ordering flakes that CI never sees.\\n   935|\\n   936|Always run the full suite before pushing changes.\\n   937|\\n   938|### Don't write change-detector tests\\n   939|\\n   940|A test is a **change-detector** if it fails whenever data that is **expected\\n   941|to change** gets updated — model catalogs, config version numbers,\\n   942|enumeration counts, hardcoded lists of provider models. These tests add no\\n   943|behavioral coverage; they just guarantee that routine source updates break\\n   944|CI and cost engineering time to \\\"fix.\\\"\\n   945|\\n   946|**Do not write:**\\n   947|\\n   948|```python\\n   949|# catalog snapshot — breaks every model release\\n   950|assert \\\"gemini-2.5-pro\\\" in _PROVIDER_MODELS[\\\"gemini\\\"]\\n   951|assert \\\"MiniMax-M2.7\\\" in models\\n   952|\\n   953|# config version literal — breaks every schema bump\\n   954|assert DEFAULT_CONFIG[\\\"_config_version\\\"] == 21\\n   955|\\n   956|# enumeration count — breaks every time a skill/provider is added\\n   957|assert len(_PROVIDER_MODELS[\\\"huggingface\\\"]) == 8\\n   958|```\\n   959|\\n   960|**Do write:**\\n   961|\\n   962|```python\\n   963|# behavior: does the catalog plumbing work at all?\\n   964|assert \\\"gemini\\\" in _PROVIDER_MODELS\\n   965|assert len(_PROVIDER_MODELS[\\\"gemini\\\"]) >= 1\\n   966|\\n   967|# behavior: does migration bump the user's version to current latest?\\n   968|assert raw[\\\"_config_version\\\"] == DEFAULT_CONFIG[\\\"_config_version\\\"]\\n   969|\\n   970|# invariant: no plan-only model leaks into the legacy list\\n   971|assert not (set(moonshot_models) & coding_plan_only_models)\\n   972|\\n   973|# invariant: every model in the catalog has a context-length entry\\n   974|for m in _PROVIDER_MODELS[\\\"huggingface\\\"]:\\n   975|    assert m.lower() in DEFAULT_CONTEXT_LENGTHS_LOWER\\n   976|```\\n   977|\\n   978|The rule: if the test reads like a snapshot of current data, delete it. If\\n   979|it reads like a contract about how two pieces of data must relate, keep it.\\n   980|When a PR adds a new provider/model and you want a test, make the test\\n   981|assert the relationship (e.g. \\\"catalog entries all have context lengths\\\"),\\n   982|not the specific names.\\n   983|\\n   984|Reviewers should reject new change-detector tests; authors should convert\\n   985|them into invariants before re-requesting review.\\n   986|\", \"total_lines\": 985, \"file_size\": 45759, \"truncated\": false, \"is_binary\": false, \"is_image\": false}",
          "tool_call_id": "Z3VfZWxbiW4ENq4WO5BvFz8E2GD3blhh"
        },
        {
          "role": "assistant",
          "content": "Ich habe die AGENTS.md vollständig gelesen und verstanden. Alles klar, Sir."
        },
        {
          "role": "user",
          "content": "[IMPORTANT: MCP servers have been reloaded. Added servers: openclaw. 13 MCP tool(s) now available. The tool list for this conversation has been updated accordingly.]"
        },
        {
          "role": "user",
          "content": "[IMPORTANT: MCP servers have been reloaded. Reconnected servers: openclaw. 13 MCP tool(s) now available. The tool list for this conversation has been updated accordingly.]"
        },
        {
          "role": "user",
          "content": "bist du da?"
        },
        {
          "role": "user",
          "content": "hallo, bist du da?"
        }
      ],
      "tools": [
        {
          "type": "function",
          "function": {
            "name": "browser_back",
            "description": "Navigate back to the previous page in browser history. Requires browser_navigate to be called first.",
            "parameters": {
              "type": "object",
              "properties": {}
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "browser_click",
            "description": "Click on an element identified by its ref ID from the snapshot (e.g., '@e5'). The ref IDs are shown in square brackets in the snapshot output. Requires browser_navigate and browser_snapshot to be called first.",
            "parameters": {
              "type": "object",
              "properties": {
                "ref": {
                  "type": "string",
                  "description": "The element reference from the snapshot (e.g., '@e5', '@e12')"
                }
              },
              "required": [
                "ref"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "browser_console",
            "description": "Get browser console output and JavaScript errors from the current page. Returns console.log/warn/error/info messages and uncaught JS exceptions. Use this to detect silent JavaScript errors, failed API calls, and application warnings. Requires browser_navigate to be called first. When 'expression' is provided, evaluates JavaScript in the page context and returns the result — use this for DOM inspection, reading page state, or extracting data programmatically.",
            "parameters": {
              "type": "object",
              "properties": {
                "clear": {
                  "type": "boolean",
                  "default": false,
                  "description": "If true, clear the message buffers after reading"
                },
                "expression": {
                  "type": "string",
                  "description": "JavaScript expression to evaluate in the page context. Runs in the browser like DevTools console — full access to DOM, window, document. Return values are serialized to JSON. Example: 'document.title' or 'document.querySelectorAll(\"a\").length'"
                }
              }
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "browser_get_images",
            "description": "Get a list of all images on the current page with their URLs and alt text. Useful for finding images to analyze with the vision tool. Requires browser_navigate to be called first.",
            "parameters": {
              "type": "object",
              "properties": {}
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "browser_navigate",
            "description": "Navigate to a URL in the browser. Initializes the session and loads the page. Must be called before other browser tools. For plain-text endpoints — URLs ending in .md, .txt, .json, .yaml, .yml, .csv, .xml, raw.githubusercontent.com, or any documented API endpoint — prefer curl via the terminal tool or web_extract; the browser stack is overkill and much slower for these. Use browser tools when you need to interact with a page (click, fill forms, dynamic content). Returns a compact page snapshot with interactive elements and ref IDs — no need to call browser_snapshot separately after navigating.",
            "parameters": {
              "type": "object",
              "properties": {
                "url": {
                  "type": "string",
                  "description": "The URL to navigate to (e.g., 'https://example.com')"
                }
              },
              "required": [
                "url"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "browser_press",
            "description": "Press a keyboard key. Useful for submitting forms (Enter), navigating (Tab), or keyboard shortcuts. Requires browser_navigate to be called first.",
            "parameters": {
              "type": "object",
              "properties": {
                "key": {
                  "type": "string",
                  "description": "Key to press (e.g., 'Enter', 'Tab', 'Escape', 'ArrowDown')"
                }
              },
              "required": [
                "key"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "browser_scroll",
            "description": "Scroll the page in a direction. Use this to reveal more content that may be below or above the current viewport. Requires browser_navigate to be called first.",
            "parameters": {
              "type": "object",
              "properties": {
                "direction": {
                  "type": "string",
                  "enum": [
                    "up",
                    "down"
                  ],
                  "description": "Direction to scroll"
                }
              },
              "required": [
                "direction"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "browser_snapshot",
            "description": "Get a text-based snapshot of the current page's accessibility tree. Returns interactive elements with ref IDs (like @e1, @e2) for browser_click and browser_type. full=false (default): compact view with interactive elements. full=true: complete page content. Snapshots over 8000 chars are truncated or LLM-summarized. Requires browser_navigate first. Note: browser_navigate already returns a compact snapshot — use this to refresh after interactions that change the page, or with full=true for complete content.",
            "parameters": {
              "type": "object",
              "properties": {
                "full": {
                  "type": "boolean",
                  "description": "If true, returns complete page content. If false (default), returns compact view with interactive elements only.",
                  "default": false
                }
              }
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "browser_type",
            "description": "Type text into an input field identified by its ref ID. Clears the field first, then types the new text. Requires browser_navigate and browser_snapshot to be called first.",
            "parameters": {
              "type": "object",
              "properties": {
                "ref": {
                  "type": "string",
                  "description": "The element reference from the snapshot (e.g., '@e3')"
                },
                "text": {
                  "type": "string",
                  "description": "The text to type into the field"
                }
              },
              "required": [
                "ref",
                "text"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "browser_vision",
            "description": "Take a screenshot of the current page and analyze it with vision AI. Use this when you need to visually understand what's on the page - especially useful for CAPTCHAs, visual verification challenges, complex layouts, or when the text snapshot doesn't capture important visual information. Returns both the AI analysis and a screenshot_path that you can share with the user by including MEDIA:<screenshot_path> in your response. Requires browser_navigate to be called first.",
            "parameters": {
              "type": "object",
              "properties": {
                "question": {
                  "type": "string",
                  "description": "What you want to know about the page visually. Be specific about what you're looking for."
                },
                "annotate": {
                  "type": "boolean",
                  "default": false,
                  "description": "If true, overlay numbered [N] labels on interactive elements. Each [N] maps to ref @eN for subsequent browser commands. Useful for QA and spatial reasoning about page layout."
                }
              },
              "required": [
                "question"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "clarify",
            "description": "Ask the user a question when you need clarification, feedback, or a decision before proceeding. Supports two modes:\n\n1. **Multiple choice** — provide up to 4 choices. The user picks one or types their own answer via a 5th 'Other' option.\n2. **Open-ended** — omit choices entirely. The user types a free-form response.\n\nUse this tool when:\n- The task is ambiguous and you need the user to choose an approach\n- You want post-task feedback ('How did that work out?')\n- You want to offer to save a skill or update memory\n- A decision has meaningful trade-offs the user should weigh in on\n\nDo NOT use this tool for simple yes/no confirmation of dangerous commands (the terminal tool handles that). Prefer making a reasonable default choice yourself when the decision is low-stakes.",
            "parameters": {
              "type": "object",
              "properties": {
                "question": {
                  "type": "string",
                  "description": "The question to present to the user."
                },
                "choices": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  },
                  "maxItems": 4,
                  "description": "Up to 4 answer choices. Omit this parameter entirely to ask an open-ended question. When provided, the UI automatically appends an 'Other (type your answer)' option."
                }
              },
              "required": [
                "question"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "cronjob",
            "description": "Manage scheduled cron jobs with a single compressed tool.\n\nUse action='create' to schedule a new job from a prompt or one or more skills.\nUse action='list' to inspect jobs.\nUse action='update', 'pause', 'resume', 'remove', or 'run' to manage an existing job.\n\nTo stop a job the user no longer wants: first action='list' to find the job_id, then action='remove' with that job_id. Never guess job IDs — always list first.\n\nJobs run in a fresh session with no current-chat context, so prompts must be self-contained.\nIf skills are provided on create, the future cron run loads those skills in order, then follows the prompt as the task instruction.\nOn update, passing skills=[] clears attached skills.\n\nNOTE: The agent's final response is auto-delivered to the target. Put the primary\nuser-facing content in the final response. Cron jobs run autonomously with no user\npresent — they cannot ask questions or request clarification.\n\nImportant safety rule: cron-run sessions should not recursively schedule more cron jobs.",
            "parameters": {
              "type": "object",
              "properties": {
                "action": {
                  "type": "string",
                  "description": "One of: create, list, update, pause, resume, remove, run"
                },
                "job_id": {
                  "type": "string",
                  "description": "Required for update/pause/resume/remove/run"
                },
                "prompt": {
                  "type": "string",
                  "description": "For create: the full self-contained prompt. If skills are also provided, this becomes the task instruction paired with those skills."
                },
                "schedule": {
                  "type": "string",
                  "description": "For create/update: '30m', 'every 2h', '0 9 * * *', or ISO timestamp"
                },
                "name": {
                  "type": "string",
                  "description": "Optional human-friendly name"
                },
                "repeat": {
                  "type": "integer",
                  "description": "Optional repeat count. Omit for defaults (once for one-shot, forever for recurring)."
                },
                "deliver": {
                  "type": "string",
                  "description": "Omit this parameter to auto-deliver back to the current chat and topic (recommended). Auto-detection preserves thread/topic context. Only set explicitly when the user asks to deliver somewhere OTHER than the current conversation. Values: 'origin' (same as omitting), 'local' (no delivery, save only), or platform:chat_id:thread_id for a specific destination. Examples: 'telegram:-1001234567890:17585', 'discord:#engineering', 'sms:+15551234567'. WARNING: 'platform:chat_id' without :thread_id loses topic targeting."
                },
                "skills": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  },
                  "description": "Optional ordered list of skill names to load before executing the cron prompt. On update, pass an empty array to clear attached skills."
                },
                "model": {
                  "type": "object",
                  "description": "Optional per-job model override. If provider is omitted, the current main provider is pinned at creation time so the job stays stable.",
                  "properties": {
                    "provider": {
                      "type": "string",
                      "description": "Provider name (e.g. 'openrouter', 'anthropic', or 'custom:<name>' for a provider defined in custom_providers config — always include the ':<name>' suffix, never pass the bare 'custom'). Omit to use and pin the current provider."
                    },
                    "model": {
                      "type": "string",
                      "description": "Model name (e.g. 'anthropic/claude-sonnet-4', 'claude-sonnet-4')"
                    }
                  },
                  "required": [
                    "model"
                  ]
                },
                "script": {
                  "type": "string",
                  "description": "Optional path to a script that runs each tick. In the default mode its stdout is injected into the agent's prompt as context (data-collection / change-detection pattern). With no_agent=True, the script IS the job and its stdout is delivered verbatim (classic watchdog pattern). Relative paths resolve under ~/.hermes/scripts/. ``.sh``/``.bash`` extensions run via bash, everything else via Python. On update, pass empty string to clear."
                },
                "no_agent": {
                  "type": "boolean",
                  "default": false,
                  "description": "Default: False (LLM-driven job — the agent runs the prompt each tick). Set True to skip the LLM entirely: the scheduler just runs ``script`` on schedule and delivers its stdout verbatim. No tokens, no agent loop, no model override honoured. \n\nREQUIREMENTS when True: ``script`` MUST be set (``prompt`` and ``skills`` are ignored). \n\nDELIVERY SEMANTICS when True: (a) non-empty stdout is sent verbatim as the message; (b) EMPTY stdout means SILENT — nothing is sent to the user and they won't see anything happened, so design your script to stay quiet when there's nothing to report (the watchdog pattern); (c) non-zero exit / timeout sends an error alert so a broken watchdog can't fail silently. \n\nWHEN TO USE True: recurring script-only pings where the script itself produces the exact message text (memory/disk/GPU watchdogs, threshold alerts, heartbeats, CI notifications, API pollers with a fixed output shape). WHEN TO USE False (default): anything that needs reasoning — summarize a feed, draft a daily briefing, pick interesting items, rephrase data for a human, follow conditional logic based on content."
                },
                "context_from": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  },
                  "description": "Optional job ID or list of job IDs whose most recent completed output is injected into the prompt as context before each run. Use this to chain cron jobs: job A collects data, job B processes it. Each entry must be a valid job ID (from cronjob action='list'). Note: injects the most recent completed output — does not wait for upstream jobs running in the same tick. On update, pass an empty array to clear."
                },
                "enabled_toolsets": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  },
                  "description": "Optional list of toolset names to restrict the job's agent to (e.g. [\"web\", \"terminal\", \"file\", \"delegation\"]). When set, only tools from these toolsets are loaded, significantly reducing input token overhead. When omitted, all default tools are loaded. Infer from the job's prompt — e.g. use \"web\" if it calls web_search, \"terminal\" if it runs scripts, \"file\" if it reads files, \"delegation\" if it calls delegate_task. On update, pass an empty array to clear."
                },
                "workdir": {
                  "type": "string",
                  "description": "Optional absolute path to run the job from. When set, AGENTS.md / CLAUDE.md / .cursorrules from that directory are injected into the system prompt, and the terminal/file/code_exec tools use it as their working directory — useful for running a job inside a specific project repo. Must be an absolute path that exists. When unset (default), preserves the original behaviour: no project context files, tools use the scheduler's cwd. On update, pass an empty string to clear. Jobs with workdir run sequentially (not parallel) to keep per-job directories isolated."
                }
              },
              "required": [
                "action"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "delegate_task",
            "description": "Spawn one or more subagents to work on tasks in isolated contexts. Each subagent gets its own conversation, terminal session, and toolset. Only the final summary is returned -- intermediate tool results never enter your context window.\n\nTWO MODES (one of 'goal' or 'tasks' is required):\n1. Single task: provide 'goal' (+ optional context, toolsets)\n2. Batch (parallel): provide 'tasks' array with up to delegation.max_concurrent_children items (default 3, configurable via config.yaml, no hard ceiling). All run concurrently and results are returned together. Nested delegation requires role='orchestrator' and delegation.max_spawn_depth >= 2.\n\nWHEN TO USE delegate_task:\n- Reasoning-heavy subtasks (debugging, code review, research synthesis)\n- Tasks that would flood your context with intermediate data\n- Parallel independent workstreams (research A and B simultaneously)\n\nWHEN NOT TO USE (use these instead):\n- Mechanical multi-step work with no reasoning needed -> use execute_code\n- Single tool call -> just call the tool directly\n- Tasks needing user interaction -> subagents cannot use clarify\n- Durable long-running work that must outlive the current turn -> use cronjob (action='create') or terminal(background=True, notify_on_complete=True) instead. delegate_task runs SYNCHRONOUSLY inside the parent turn: if the parent is interrupted (user sends a new message, /stop, /new) the child is cancelled with status='interrupted' and its work is discarded. Children cannot continue in the background.\n\nIMPORTANT:\n- Subagents have NO memory of your conversation. Pass all relevant info (file paths, error messages, constraints) via the 'context' field.\n- If the user is writing in a non-English language, or asked for output in a specific language / tone / style, say so in 'context' (e.g. \"respond in Chinese\", \"return output in Japanese\"). Otherwise subagents default to English and their summaries will contaminate your final reply with the wrong language.\n- Subagent summaries are SELF-REPORTS, not verified facts. A subagent that claims \"uploaded successfully\" or \"file written\" may be wrong. For operations with external side-effects (HTTP POST/PUT, remote writes, file creation at shared paths, publishing), require the subagent to return a verifiable handle (URL, ID, absolute path, HTTP status) and verify it yourself — fetch the URL, stat the file, read back the content — before telling the user the operation succeeded.\n- Leaf subagents (role='leaf', the default) CANNOT call: delegate_task, clarify, memory, send_message, execute_code.\n- Orchestrator subagents (role='orchestrator') retain delegate_task so they can spawn their own workers, but still cannot use clarify, memory, send_message, or execute_code. Orchestrators are bounded by delegation.max_spawn_depth (default 2) and can be disabled globally via delegation.orchestrator_enabled=false.\n- Each subagent gets its own terminal session (separate working directory and state).\n- Results are always returned as an array, one entry per task.",
            "parameters": {
              "type": "object",
              "properties": {
                "goal": {
                  "type": "string",
                  "description": "What the subagent should accomplish. Be specific and self-contained -- the subagent knows nothing about your conversation history."
                },
                "context": {
                  "type": "string",
                  "description": "Background information the subagent needs: file paths, error messages, project structure, constraints. The more specific you are, the better the subagent performs."
                },
                "toolsets": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  },
                  "description": "Toolsets to enable for this subagent. Default: inherits your enabled toolsets. Available toolsets: 'browser', 'cronjob', 'discord', 'discord_admin', 'feishu_doc', 'feishu_drive', 'file', 'homeassistant', 'image_gen', 'kanban', 'search', 'session_search', 'skills', 'spotify', 'terminal', 'todo', 'tts', 'video', 'vision', 'web', 'yuanbao'. Common patterns: ['terminal', 'file'] for code work, ['web'] for research, ['browser'] for web interaction, ['terminal', 'file', 'web'] for full-stack tasks."
                },
                "tasks": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "goal": {
                        "type": "string",
                        "description": "Task goal"
                      },
                      "context": {
                        "type": "string",
                        "description": "Task-specific context"
                      },
                      "toolsets": {
                        "type": "array",
                        "items": {
                          "type": "string"
                        },
                        "description": "Toolsets for this specific task. Available: 'browser', 'cronjob', 'discord', 'discord_admin', 'feishu_doc', 'feishu_drive', 'file', 'homeassistant', 'image_gen', 'kanban', 'search', 'session_search', 'skills', 'spotify', 'terminal', 'todo', 'tts', 'video', 'vision', 'web', 'yuanbao'. Use 'web' for network access, 'terminal' for shell, 'browser' for web interaction."
                      },
                      "acp_command": {
                        "type": "string",
                        "description": "Per-task ACP command override (e.g. 'copilot'). Overrides the top-level acp_command for this task only."
                      },
                      "acp_args": {
                        "type": "array",
                        "items": {
                          "type": "string"
                        },
                        "description": "Per-task ACP args override."
                      },
                      "role": {
                        "type": "string",
                        "enum": [
                          "leaf",
                          "orchestrator"
                        ],
                        "description": "Per-task role override. See top-level 'role' for semantics."
                      }
                    },
                    "required": [
                      "goal"
                    ]
                  },
                  "description": "Batch mode: tasks to run in parallel (limit configurable via delegation.max_concurrent_children, default 3). Each gets its own subagent with isolated context and terminal session. When provided, top-level goal/context/toolsets are ignored."
                },
                "role": {
                  "type": "string",
                  "enum": [
                    "leaf",
                    "orchestrator"
                  ],
                  "description": "Role of the child agent. 'leaf' (default) = focused worker, cannot delegate further. 'orchestrator' = can use delegate_task to spawn its own workers. Requires delegation.max_spawn_depth >= 2 in config; ignored (treated as 'leaf') when the child would exceed max_spawn_depth or when delegation.orchestrator_enabled=false."
                },
                "acp_command": {
                  "type": "string",
                  "description": "Override ACP command for child agents (e.g. 'copilot'). When set, children use ACP subprocess transport instead of inheriting the parent's transport. Requires an ACP-compatible CLI (currently GitHub Copilot CLI via 'copilot --acp --stdio'). See agent/copilot_acp_client.py for the implementation."
                },
                "acp_args": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  },
                  "description": "Arguments for the ACP command (default: ['--acp', '--stdio']). Only used when acp_command is set."
                }
              }
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "execute_code",
            "description": "Run a Python script that can call Hermes tools programmatically. Use this when you need 3+ tool calls with processing logic between them, need to filter/reduce large tool outputs before they enter your context, need conditional branching (if X then Y else Z), or need to loop (fetch N pages, process N files, retry on failure).\n\nUse normal tool calls instead when: single tool call with no processing, you need to see the full result and apply complex reasoning, or the task requires interactive user input.\n\nAvailable via `from hermes_tools import ...`:\n\n  read_file(path: str, offset: int = 1, limit: int = 500) -> dict\n    Lines are 1-indexed. Returns {\"content\": \"...\", \"total_lines\": N}\n  write_file(path: str, content: str) -> dict\n    Always overwrites the entire file.\n  search_files(pattern: str, target=\"content\", path=\".\", file_glob=None, limit=50) -> dict\n    target: \"content\" (search inside files) or \"files\" (find files by name). Returns {\"matches\": [...]}\n  patch(path: str, old_string: str, new_string: str, replace_all: bool = False) -> dict\n    Replaces old_string with new_string in the file.\n  terminal(command: str, timeout=None, workdir=None) -> dict\n    Foreground only (no background/pty). Returns {\"output\": \"...\", \"exit_code\": N}\n\nLimits: 5-minute timeout, 50KB stdout cap, max 50 tool calls per script. terminal() is foreground-only (no background or pty).\n\nScripts run in the session's working directory with the active venv's python, so project deps (pandas, etc.) and relative paths work like in terminal().\n\nPrint your final result to stdout. Use Python stdlib (json, re, math, csv, datetime, collections, etc.) for processing between tool calls.\n\nAlso available (no import needed — built into hermes_tools):\n  json_parse(text: str) — json.loads with strict=False; use for terminal() output with control chars\n  shell_quote(s: str) — shlex.quote(); use when interpolating dynamic strings into shell commands\n  retry(fn, max_attempts=3, delay=2) — retry with exponential backoff for transient failures",
            "parameters": {
              "type": "object",
              "properties": {
                "code": {
                  "type": "string",
                  "description": "Python code to execute. Import tools with `from hermes_tools import terminal, ...` and print your final result to stdout."
                }
              },
              "required": [
                "code"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "memory",
            "description": "Save durable information to persistent memory that survives across sessions. Memory is injected into future turns, so keep it compact and focused on facts that will still matter later.\n\nWHEN TO SAVE (do this proactively, don't wait to be asked):\n- User corrects you or says 'remember this' / 'don't do that again'\n- User shares a preference, habit, or personal detail (name, role, timezone, coding style)\n- You discover something about the environment (OS, installed tools, project structure)\n- You learn a convention, API quirk, or workflow specific to this user's setup\n- You identify a stable fact that will be useful again in future sessions\n\nPRIORITY: User preferences and corrections > environment facts > procedural knowledge. The most valuable memory prevents the user from having to repeat themselves.\n\nDo NOT save task progress, session outcomes, completed-work logs, or temporary TODO state to memory; use session_search to recall those from past transcripts.\nIf you've discovered a new way to do something, solved a problem that could be necessary later, save it as a skill with the skill tool.\n\nTWO TARGETS:\n- 'user': who the user is -- name, role, preferences, communication style, pet peeves\n- 'memory': your notes -- environment facts, project conventions, tool quirks, lessons learned\n\nACTIONS: add (new entry), replace (update existing -- old_text identifies it), remove (delete -- old_text identifies it).\n\nSKIP: trivial/obvious info, things easily re-discovered, raw data dumps, and temporary task state.",
            "parameters": {
              "type": "object",
              "properties": {
                "action": {
                  "type": "string",
                  "enum": [
                    "add",
                    "replace",
                    "remove"
                  ],
                  "description": "The action to perform."
                },
                "target": {
                  "type": "string",
                  "enum": [
                    "memory",
                    "user"
                  ],
                  "description": "Which memory store: 'memory' for personal notes, 'user' for user profile."
                },
                "content": {
                  "type": "string",
                  "description": "The entry content. Required for 'add' and 'replace'."
                },
                "old_text": {
                  "type": "string",
                  "description": "Short unique substring identifying the entry to replace or remove."
                }
              },
              "required": [
                "action",
                "target"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "patch",
            "description": "Targeted find-and-replace edits in files. Use this instead of sed/awk in terminal. Uses fuzzy matching (9 strategies) so minor whitespace/indentation differences won't break it. Returns a unified diff. Auto-runs syntax checks after editing.\n\nReplace mode (default): find a unique string and replace it.\nPatch mode: apply V4A multi-file patches for bulk changes.",
            "parameters": {
              "type": "object",
              "properties": {
                "mode": {
                  "type": "string",
                  "enum": [
                    "replace",
                    "patch"
                  ],
                  "description": "Edit mode: 'replace' for targeted find-and-replace, 'patch' for V4A multi-file patches",
                  "default": "replace"
                },
                "path": {
                  "type": "string",
                  "description": "File path to edit (required for 'replace' mode)"
                },
                "old_string": {
                  "type": "string",
                  "description": "Text to find in the file (required for 'replace' mode). Must be unique in the file unless replace_all=true. Include enough surrounding context to ensure uniqueness."
                },
                "new_string": {
                  "type": "string",
                  "description": "Replacement text (required for 'replace' mode). Can be empty string to delete the matched text."
                },
                "replace_all": {
                  "type": "boolean",
                  "description": "Replace all occurrences instead of requiring a unique match (default: false)",
                  "default": false
                },
                "patch": {
                  "type": "string",
                  "description": "V4A format patch content (required for 'patch' mode). Format:\n*** Begin Patch\n*** Update File: path/to/file\n@@ context hint @@\n context line\n-removed line\n+added line\n*** End Patch"
                }
              },
              "required": [
                "mode"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "process",
            "description": "Manage background processes started with terminal(background=true). Actions: 'list' (show all), 'poll' (check status + new output), 'log' (full output with pagination), 'wait' (block until done or timeout), 'kill' (terminate), 'write' (send raw stdin data without newline), 'submit' (send data + Enter, for answering prompts), 'close' (close stdin/send EOF).",
            "parameters": {
              "type": "object",
              "properties": {
                "action": {
                  "type": "string",
                  "enum": [
                    "list",
                    "poll",
                    "log",
                    "wait",
                    "kill",
                    "write",
                    "submit",
                    "close"
                  ],
                  "description": "Action to perform on background processes"
                },
                "session_id": {
                  "type": "string",
                  "description": "Process session ID (from terminal background output). Required for all actions except 'list'."
                },
                "data": {
                  "type": "string",
                  "description": "Text to send to process stdin (for 'write' and 'submit' actions)"
                },
                "timeout": {
                  "type": "integer",
                  "description": "Max seconds to block for 'wait' action. Returns partial output on timeout.",
                  "minimum": 1
                },
                "offset": {
                  "type": "integer",
                  "description": "Line offset for 'log' action (default: last 200 lines)"
                },
                "limit": {
                  "type": "integer",
                  "description": "Max lines to return for 'log' action",
                  "minimum": 1
                }
              },
              "required": [
                "action"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "read_file",
            "description": "Read a text file with line numbers and pagination. Use this instead of cat/head/tail in terminal. Output format: 'LINE_NUM|CONTENT'. Suggests similar filenames if not found. Use offset and limit for large files. Reads exceeding ~100K characters are rejected; use offset and limit to read specific sections of large files. NOTE: Cannot read images or binary files — use vision_analyze for images.",
            "parameters": {
              "type": "object",
              "properties": {
                "path": {
                  "type": "string",
                  "description": "Path to the file to read (absolute, relative, or ~/path)"
                },
                "offset": {
                  "type": "integer",
                  "description": "Line number to start reading from (1-indexed, default: 1)",
                  "default": 1,
                  "minimum": 1
                },
                "limit": {
                  "type": "integer",
                  "description": "Maximum number of lines to read (default: 500, max: 2000)",
                  "default": 500,
                  "maximum": 2000
                }
              },
              "required": [
                "path"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "search_files",
            "description": "Search file contents or find files by name. Use this instead of grep/rg/find/ls in terminal. Ripgrep-backed, faster than shell equivalents.\n\nContent search (target='content'): Regex search inside files. Output modes: full matches with line numbers, file paths only, or match counts.\n\nFile search (target='files'): Find files by glob pattern (e.g., '*.py', '*config*'). Also use this instead of ls — results sorted by modification time.",
            "parameters": {
              "type": "object",
              "properties": {
                "pattern": {
                  "type": "string",
                  "description": "Regex pattern for content search, or glob pattern (e.g., '*.py') for file search"
                },
                "target": {
                  "type": "string",
                  "enum": [
                    "content",
                    "files"
                  ],
                  "description": "'content' searches inside file contents, 'files' searches for files by name",
                  "default": "content"
                },
                "path": {
                  "type": "string",
                  "description": "Directory or file to search in (default: current working directory)",
                  "default": "."
                },
                "file_glob": {
                  "type": "string",
                  "description": "Filter files by pattern in grep mode (e.g., '*.py' to only search Python files)"
                },
                "limit": {
                  "type": "integer",
                  "description": "Maximum number of results to return (default: 50)",
                  "default": 50
                },
                "offset": {
                  "type": "integer",
                  "description": "Skip first N results for pagination (default: 0)",
                  "default": 0
                },
                "output_mode": {
                  "type": "string",
                  "enum": [
                    "content",
                    "files_only",
                    "count"
                  ],
                  "description": "Output format for grep mode: 'content' shows matching lines with line numbers, 'files_only' lists file paths, 'count' shows match counts per file",
                  "default": "content"
                },
                "context": {
                  "type": "integer",
                  "description": "Number of context lines before and after each match (grep mode only)",
                  "default": 0
                }
              },
              "required": [
                "pattern"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "send_message",
            "description": "Send a message to a connected messaging platform, or list available targets.\n\nIMPORTANT: When the user asks to send to a specific channel or person (not just a bare platform name), call send_message(action='list') FIRST to see available targets, then send to the correct one.\nIf the user just says a platform name like 'send to telegram', send directly to the home channel without listing first.",
            "parameters": {
              "type": "object",
              "properties": {
                "action": {
                  "type": "string",
                  "enum": [
                    "send",
                    "list"
                  ],
                  "description": "Action to perform. 'send' (default) sends a message. 'list' returns all available channels/contacts across connected platforms."
                },
                "target": {
                  "type": "string",
                  "description": "Delivery target. Format: 'platform' (uses home channel), 'platform:#channel-name', 'platform:chat_id', or 'platform:chat_id:thread_id' for Telegram topics and Discord threads. Examples: 'telegram', 'telegram:-1001234567890:17585', 'discord:999888777:555444333', 'discord:#bot-home', 'slack:#engineering', 'signal:+155****4567', 'matrix:!roomid:server.org', 'matrix:@user:server.org', 'yuanbao:direct:<account_id>' (DM), 'yuanbao:group:<group_code>' (group chat)"
                },
                "message": {
                  "type": "string",
                  "description": "The message text to send. To send an image or file, include MEDIA:<local_path> (e.g. 'MEDIA:/tmp/hermes/cache/img_xxx.jpg') in the message — the platform will deliver it as a native media attachment."
                }
              }
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "session_search",
            "description": "Search your long-term memory of past conversations, or browse recent sessions. This is your recall -- every past session is searchable, and this tool summarizes what happened.\n\nTWO MODES:\n1. Recent sessions (no query): Call with no arguments to see what was worked on recently. Returns titles, previews, and timestamps. Zero LLM cost, instant. Start here when the user asks what were we working on or what did we do recently.\n2. Keyword search (with query): Search for specific topics across all past sessions. Returns LLM-generated summaries of matching sessions.\n\nUSE THIS PROACTIVELY when:\n- The user says 'we did this before', 'remember when', 'last time', 'as I mentioned'\n- The user asks about a topic you worked on before but don't have in current context\n- The user references a project, person, or concept that seems familiar but isn't in memory\n- You want to check if you've solved a similar problem before\n- The user asks 'what did we do about X?' or 'how did we fix Y?'\n\nDon't hesitate to search when it is actually cross-session -- it's fast and cheap. Better to search and confirm than to guess or ask the user to repeat themselves.\n\nSearch syntax: keywords joined with OR for broad recall (elevenlabs OR baseten OR funding), phrases for exact match (\"docker networking\"), boolean (python NOT java), prefix (deploy*). IMPORTANT: Use OR between keywords for best results — FTS5 defaults to AND which misses sessions that only mention some terms. If a broad OR query returns nothing, try individual keyword searches in parallel. Returns summaries of the top matching sessions.",
            "parameters": {
              "type": "object",
              "properties": {
                "query": {
                  "type": "string",
                  "description": "Search query — keywords, phrases, or boolean expressions to find in past sessions. Omit this parameter entirely to browse recent sessions instead (returns titles, previews, timestamps with no LLM cost)."
                },
                "role_filter": {
                  "type": "string",
                  "description": "Optional: only search messages from specific roles (comma-separated). E.g. 'user,assistant' to skip tool outputs."
                },
                "limit": {
                  "type": "integer",
                  "description": "Max sessions to summarize (default: 3, max: 5).",
                  "default": 3
                }
              }
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "skill_manage",
            "description": "Manage skills (create, update, delete). Skills are your procedural memory — reusable approaches for recurring task types. New skills go to ~/.hermes/skills/; existing skills can be modified wherever they live.\n\nActions: create (full SKILL.md + optional category), patch (old_string/new_string — preferred for fixes), edit (full SKILL.md rewrite — major overhauls only), delete, write_file, remove_file.\n\nOn delete, pass `absorbed_into=<umbrella>` when you're merging this skill's content into another one, or `absorbed_into=\"\"` when you're pruning it with no forwarding target. This lets the curator tell consolidation from pruning without guessing, so downstream consumers (cron jobs that reference the old skill name, etc.) get updated correctly. The target you name in `absorbed_into` must already exist — create/patch the umbrella first, then delete.\n\nCreate when: complex task succeeded (5+ calls), errors overcome, user-corrected approach worked, non-trivial workflow discovered, or user asks you to remember a procedure.\nUpdate when: instructions stale/wrong, OS-specific failures, missing steps or pitfalls found during use. If you used a skill and hit issues not covered by it, patch it immediately.\n\nAfter difficult/iterative tasks, offer to save as a skill. Skip for simple one-offs. Confirm with user before creating/deleting.\n\nGood skills: trigger conditions, numbered steps with exact commands, pitfalls section, verification steps. Use skill_view() to see format examples.\n\nPinned skills are protected from deletion only — skill_manage(action='delete') will refuse with a message pointing the user to `hermes curator unpin <name>`. Patches and edits go through on pinned skills so you can still improve them as pitfalls come up; pin only guards against irrecoverable loss.",
            "parameters": {
              "type": "object",
              "properties": {
                "action": {
                  "type": "string",
                  "enum": [
                    "create",
                    "patch",
                    "edit",
                    "delete",
                    "write_file",
                    "remove_file"
                  ],
                  "description": "The action to perform."
                },
                "name": {
                  "type": "string",
                  "description": "Skill name (lowercase, hyphens/underscores, max 64 chars). Must match an existing skill for patch/edit/delete/write_file/remove_file."
                },
                "content": {
                  "type": "string",
                  "description": "Full SKILL.md content (YAML frontmatter + markdown body). Required for 'create' and 'edit'. For 'edit', read the skill first with skill_view() and provide the complete updated text."
                },
                "old_string": {
                  "type": "string",
                  "description": "Text to find in the file (required for 'patch'). Must be unique unless replace_all=true. Include enough surrounding context to ensure uniqueness."
                },
                "new_string": {
                  "type": "string",
                  "description": "Replacement text (required for 'patch'). Can be empty string to delete the matched text."
                },
                "replace_all": {
                  "type": "boolean",
                  "description": "For 'patch': replace all occurrences instead of requiring a unique match (default: false)."
                },
                "category": {
                  "type": "string",
                  "description": "Optional category/domain for organizing the skill (e.g., 'devops', 'data-science', 'mlops'). Creates a subdirectory grouping. Only used with 'create'."
                },
                "file_path": {
                  "type": "string",
                  "description": "Path to a supporting file within the skill directory. For 'write_file'/'remove_file': required, must be under references/, templates/, scripts/, or assets/. For 'patch': optional, defaults to SKILL.md if omitted."
                },
                "file_content": {
                  "type": "string",
                  "description": "Content for the file. Required for 'write_file'."
                },
                "absorbed_into": {
                  "type": "string",
                  "description": "For 'delete' only — declares intent so the curator can tell consolidation from pruning without guessing. Pass the umbrella skill name when this skill's content was merged into another (the target must already exist). Pass an empty string when the skill is truly stale and being pruned with no forwarding target. Omitting the arg on delete is supported for backward compatibility but downstream tooling (e.g. cron-job skill reference rewriting) will have to guess at intent."
                }
              },
              "required": [
                "action",
                "name"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "skill_view",
            "description": "Skills allow for loading information about specific tasks and workflows, as well as scripts and templates. Load a skill's full content or access its linked files (references, templates, scripts). First call returns SKILL.md content plus a 'linked_files' dict showing available references/templates/scripts. To access those, call again with file_path parameter.",
            "parameters": {
              "type": "object",
              "properties": {
                "name": {
                  "type": "string",
                  "description": "The skill name (use skills_list to see available skills). For plugin-provided skills, use the qualified form 'plugin:skill' (e.g. 'superpowers:writing-plans')."
                },
                "file_path": {
                  "type": "string",
                  "description": "OPTIONAL: Path to a linked file within the skill (e.g., 'references/api.md', 'templates/config.yaml', 'scripts/validate.py'). Omit to get the main SKILL.md content."
                }
              },
              "required": [
                "name"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "skills_list",
            "description": "List available skills (name + description). Use skill_view(name) to load full content.",
            "parameters": {
              "type": "object",
              "properties": {
                "category": {
                  "type": "string",
                  "description": "Optional category filter to narrow results"
                }
              }
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "terminal",
            "description": "Execute shell commands on a Linux environment. Filesystem usually persists between calls.\n\nDo NOT use cat/head/tail to read files — use read_file instead.\nDo NOT use grep/rg/find to search — use search_files instead.\nDo NOT use ls to list directories — use search_files(target='files') instead.\nDo NOT use sed/awk to edit files — use patch instead.\nDo NOT use echo/cat heredoc to create files — use write_file instead.\nReserve terminal for: builds, installs, git, processes, scripts, network, package managers, and anything that needs a shell.\n\nForeground (default): Commands return INSTANTLY when done, even if the timeout is high. Set timeout=300 for long builds/scripts — you'll still get the result in seconds if it's fast. Prefer foreground for short commands.\nBackground: Set background=true to get a session_id. Two patterns:\n  (1) Long-lived processes that never exit (servers, watchers).\n  (2) Long-running tasks with notify_on_complete=true — you can keep working on other things and the system auto-notifies you when the task finishes. Great for test suites, builds, deployments, or anything that takes more than a minute.\nFor servers/watchers, do NOT use shell-level background wrappers (nohup/disown/setsid/trailing '&') in foreground mode. Use background=true so Hermes can track lifecycle and output.\nAfter starting a server, verify readiness with a health check or log signal, then run tests in a separate terminal() call. Avoid blind sleep loops.\nUse process(action=\"poll\") for progress checks, process(action=\"wait\") to block until done.\nWorking directory: Use 'workdir' for per-command cwd.\nPTY mode: Set pty=true for interactive CLI tools (Codex, Claude Code, Python REPL).\n\nDo NOT use vim/nano/interactive tools without pty=true — they hang without a pseudo-terminal. Pipe git output to cat if it might page.\n",
            "parameters": {
              "type": "object",
              "properties": {
                "command": {
                  "type": "string",
                  "description": "The command to execute on the VM"
                },
                "background": {
                  "type": "boolean",
                  "description": "Run the command in the background. Two patterns: (1) Long-lived processes that never exit (servers, watchers). (2) Long-running tasks paired with notify_on_complete=true — you can keep working and get notified when the task finishes. For short commands, prefer foreground with a generous timeout instead.",
                  "default": false
                },
                "timeout": {
                  "type": "integer",
                  "description": "Max seconds to wait (default: 180, foreground max: 600). Returns INSTANTLY when command finishes — set high for long tasks, you won't wait unnecessarily. Foreground timeout above 600s is rejected; use background=true for longer commands.",
                  "minimum": 1
                },
                "workdir": {
                  "type": "string",
                  "description": "Working directory for this command (absolute path). Defaults to the session working directory."
                },
                "pty": {
                  "type": "boolean",
                  "description": "Run in pseudo-terminal (PTY) mode for interactive CLI tools like Codex, Claude Code, or Python REPL. Only works with local and SSH backends. Default: false.",
                  "default": false
                },
                "notify_on_complete": {
                  "type": "boolean",
                  "description": "When true (and background=true), you'll be automatically notified exactly once when the process finishes. **This is the right choice for almost every long-running task** — tests, builds, deployments, multi-item batch jobs, anything that takes over a minute and has a defined end. Use this and keep working on other things; the system notifies you on exit. MUTUALLY EXCLUSIVE with watch_patterns — when both are set, watch_patterns is dropped.",
                  "default": false
                },
                "watch_patterns": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  },
                  "description": "Strings to watch for in background process output. HARD RATE LIMIT: at most 1 notification per 15 seconds per process — matches arriving inside the cooldown are dropped. After 3 consecutive 15-second windows with dropped matches, watch_patterns is automatically disabled for that process and promoted to notify_on_complete behavior (one notification on exit, no more mid-process spam). USE ONLY for truly rare, one-shot mid-process signals on LONG-LIVED processes that will never exit on their own — e.g. ['Application startup complete'] on a server so you know when to hit its endpoint, or ['migration done'] on a daemon. DO NOT use for: (1) end-of-run markers like 'DONE'/'PASS' — use notify_on_complete instead; (2) error patterns like 'ERROR'/'Traceback' in loops or multi-item batch jobs — they fire on every iteration and you'll hit the strike limit fast; (3) anything you'd ever combine with notify_on_complete. When in doubt, choose notify_on_complete. MUTUALLY EXCLUSIVE with notify_on_complete — set one, not both."
                }
              },
              "required": [
                "command"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "text_to_speech",
            "description": "Convert text to speech audio. Returns a MEDIA: path that the platform delivers as native audio. Compatible providers render as a voice bubble on Telegram; otherwise audio is sent as a regular attachment. In CLI mode, saves to ~/voice-memos/. Voice and provider are user-configured (built-in providers like edge/openai or custom command providers under tts.providers.<name>), not model-selected.",
            "parameters": {
              "type": "object",
              "properties": {
                "text": {
                  "type": "string",
                  "description": "The text to convert to speech. Provider-specific character caps apply and are enforced automatically (OpenAI 4096, xAI 15000, MiniMax 10000, ElevenLabs 5k-40k depending on model); over-long input is truncated."
                },
                "output_path": {
                  "type": "string",
                  "description": "Optional custom file path to save the audio. Defaults to ~/.hermes/audio_cache/<timestamp>.mp3"
                }
              },
              "required": [
                "text"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "todo",
            "description": "Manage your task list for the current session. Use for complex tasks with 3+ steps or when the user provides multiple tasks. Call with no parameters to read the current list.\n\nWriting:\n- Provide 'todos' array to create/update items\n- merge=false (default): replace the entire list with a fresh plan\n- merge=true: update existing items by id, add any new ones\n\nEach item: {id: string, content: string, status: pending|in_progress|completed|cancelled}\nList order is priority. Only ONE item in_progress at a time.\nMark items completed immediately when done. If something fails, cancel it and add a revised item.\n\nAlways returns the full current list.",
            "parameters": {
              "type": "object",
              "properties": {
                "todos": {
                  "type": "array",
                  "description": "Task items to write. Omit to read current list.",
                  "items": {
                    "type": "object",
                    "properties": {
                      "id": {
                        "type": "string",
                        "description": "Unique item identifier"
                      },
                      "content": {
                        "type": "string",
                        "description": "Task description"
                      },
                      "status": {
                        "type": "string",
                        "enum": [
                          "pending",
                          "in_progress",
                          "completed",
                          "cancelled"
                        ],
                        "description": "Current status"
                      }
                    },
                    "required": [
                      "id",
                      "content",
                      "status"
                    ]
                  }
                },
                "merge": {
                  "type": "boolean",
                  "description": "true: update existing items by id, add new ones. false (default): replace the entire list.",
                  "default": false
                }
              }
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "vision_analyze",
            "description": "Inspect an image from a URL, file path, or tool output when you need closer detail than what's visible in the conversation. If the user's image is already attached to the conversation and you can see it, just answer directly — only call this tool for images referenced by URL/path, images returned inside other tool results (browser screenshots, search thumbnails), or when you need a deeper look at a specific region the main model's vision may have missed.",
            "parameters": {
              "type": "object",
              "properties": {
                "image_url": {
                  "type": "string",
                  "description": "Image URL (http/https) or local file path to analyze."
                },
                "question": {
                  "type": "string",
                  "description": "Your specific question or request about the image to resolve. The AI will automatically provide a complete image description AND answer your specific question."
                }
              },
              "required": [
                "image_url",
                "question"
              ]
            }
          }
        },
        {
          "type": "function",
          "function": {
            "name": "write_file",
            "description": "Write content to a file, completely replacing existing content. Use this instead of echo/cat heredoc in terminal. Creates parent directories automatically. OVERWRITES the entire file — use 'patch' for targeted edits. Auto-runs syntax checks on .py/.json/.yaml/.toml and other linted languages; only NEW errors introduced by this write are surfaced (pre-existing errors are filtered out).",
            "parameters": {
              "type": "object",
              "properties": {
                "path": {
                  "type": "string",
                  "description": "Path to the file to write (will be created if it doesn't exist, overwritten if it does)"
                },
                "content": {
                  "type": "string",
                  "description": "Complete content to write to the file"
                }
              },
              "required": [
                "path",
                "content"
              ]
            }
          }
        }
      ]
    }
  },
  "error": {
    "type": "BadRequestError",
    "message": "Error code: 400 - {'error': {'message': 'qwen-3.6-agent is not a valid model ID', 'code': 400}, 'user_id': 'user_3COlvW3fZFx1MsOQgDV32X6jbIl'}",
    "status_code": 400,
    "code": 400,
    "body": {
      "message": "qwen-3.6-agent is not a valid model ID",
      "code": 400
    },
    "response_status": 400,
    "response_text": "{\"error\":{\"message\":\"qwen-3.6-agent is not a valid model ID\",\"code\":400},\"user_id\":\"user_3COlvW3fZFx1MsOQgDV32X6jbIl\"}"
  }
}