clarify

Ask the user a question when you need clarification, feedback, or a decision before proceeding. Supports two modes:

1. **Multiple choice** — provide up to 4 choices. The user picks one or types their own answer via a 5th 'Other' option.
2. **Open-ended** — omit choices entirely. The user types a free-form response.

Use this tool when:
- The task is ambiguous and you need the user to choose an approach
- You want post-task feedback ('How did that work out?')
- You want to offer to save a skill or update memory
- A decision has meaningful trade-offs the user should weigh in on

Do 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.

The question to present to the user.

Choices:
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.

cronjob

Manage scheduled cron jobs with a single compressed tool.

Use action='create' to schedule a new job from a prompt or one or more skills.
Use action='list' to inspect jobs.
Use action='update', 'pause', 'resume', 'remove', or 'run' to manage an existing job.

To 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.

Jobs run in a fresh session with no current-chat context, so prompts must be self-contained.
If skills are provided on create, the future cron run loads those skills in order, then follows the prompt as the task instruction.
On update, passing skills=[] clears attached skills.

NOTE: The agent's final response is auto-delivered to the target. Put the primary
user-facing content in the final response. Cron jobs run autonomously with no user
present — they cannot ask questions or request clarification.

Important safety rule: cron-run sessions should not recursively schedule more cron jobs.

One of: create, list, update, pause, resume, remove, run

Required for update/pause/resume/remove/run

For create: the full self-contained prompt. If skills are also provided, this becomes the task instruction paired with those skills.

For create/update: '30m', 'every 2h', '0 9 * * *', or ISO timestamp

Optional human-friendly name

Optional repeat count. Omit for defaults (once for one-shot, forever for recurring).

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.

Optional ordered list of skill names to load before executing the cron prompt. On update, pass an empty array to clear attached skills.

Optional per-job model override. If provider is omitted, the current main provider is pinned at creation time so the job stays stable.

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 name (e.g. 'anthropic/claude-sonnet-4', 'claude-sonnet-4')

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.

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.

REQUIREMENTS when True: ``script`` MUST be set (``prompt`` and ``skills`` are ignored).

DELIVERY 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.

WHEN 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.

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.

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.

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.

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.

TWO MODES (one of 'goal' or 'tasks' is required):
1. Single task: provide 'goal' (+ optional context, toolsets)
2. 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.

WHEN TO USE delegate_task:
- Reasoning-heavy subtasks (debugging, code review, research synthesis)
- Tasks that would flood your context with intermediate data
- Parallel independent workstreams (research A and B simultaneously)

WHEN NOT TO USE (use these instead):
- Mechanical multi-step work with no reasoning needed -> use execute_code
- Single tool call -> just call the tool directly
- Tasks needing user interaction -> subagents cannot use clarify
- 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.

IMPORTANT:
- Subagents have NO memory of your conversation. Pass all relevant info (file paths, error messages, constraints) via the 'context' field.
- 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.
- 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.
- Leaf subagents (role='leaf', the default) CANNOT call: delegate_task, clarify, memory, send_message, execute_code.
- 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.
- Each subagent gets its own terminal session (separate working directory and state).
- Results are always returned as an array, one entry per task.

What the subagent should accomplish. Be specific and self-contained -- the subagent knows nothing about your conversation history.

Background information the subagent needs: file paths, error messages, project structure, constraints. The more specific you are, the better the subagent performs.

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.

Task goal

Task-specific context

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.

Per-task ACP command override (e.g. 'claude'). Overrides the top-level acp_command for this task only.

Per-task ACP args override.

Per-task role override. See top-level 'role' for semantics.

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 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.

Override ACP command for child agents (e.g. 'claude', 'copilot'). When set, children use ACP subprocess transport instead of inheriting the parent's transport. Enables spawning Claude Code (claude --acp --stdio) or other ACP-capable agents from any parent, including Discord/Telegram/CLI.

Arguments for the ACP command (default: ['--acp', '--stdio']). Only used when acp_command is set. Example: ['--acp', '--stdio', '--model', 'claude-opus-4-6']

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).

Use 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.

Available via `from hermes_tools import ...`:

  read_file(path: str, offset: int = 1, limit: int = 500) -> dict
    Lines are 1-indexed. Returns {"content": "...", "total_lines": N}
  write_file(path: str, content: str) -> dict
    Always overwrites the entire file.
  search_files(pattern: str, target="content", path=".", file_glob=None, limit=50) -> dict
    target: "content" (search inside files) or "files" (find files by name). Returns {"matches": [...]}
  patch(path: str, old_string: str, new_string: str, replace_all: bool = False) -> dict
    Replaces old_string with new_string in the file.
  terminal(command: str, timeout=None, workdir=None) -> dict
    Foreground only (no background/pty). Returns {"output": "...", "exit_code": N}

Limits: 5-minute timeout, 50KB stdout cap, max 50 tool calls per script. terminal() is foreground-only (no background or pty).

Scripts 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().

Print your final result to stdout. Use Python stdlib (json, re, math, csv, datetime, collections, etc.) for processing between tool calls.

Also available (no import needed — built into hermes_tools):
  json_parse(text: str) — json.loads with strict=False; use for terminal() output with control chars
  shell_quote(s: str) — shlex.quote(); use when interpolating dynamic strings into shell commands
  retry(fn, max_attempts=3, delay=2) — retry with exponential backoff for transient failures

Python code to execute. Import tools with `from hermes_tools import terminal, ...` and print your final result to stdout.

memory

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.

WHEN TO SAVE (do this proactively, don't wait to be asked):
- User corrects you or says 'remember this' / 'don't do that again'
- User shares a preference, habit, or personal detail (name, role, timezone, coding style)
- You discover something about the environment (OS, installed tools, project structure)
- You learn a convention, API quirk, or workflow specific to this user's setup
- You identify a stable fact that will be useful again in future sessions

PRIORITY: User preferences and corrections > environment facts > procedural knowledge. The most valuable memory prevents the user from having to repeat themselves.

Do 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.

TWO TARGETS:
- 'user': who the user is -- name, role, preferences, communication style, pet peeves
- 'memory': your notes -- environment facts, project conventions, tool quirks, lessons learned

ACTIONS: add (new entry), replace (update existing -- old_text identifies it), remove (delete -- old_text identifies it).

SKIP: trivial/obvious info, things easily re-discovered, raw data dumps, and temporary task state.

The action to perform.

Which memory store: 'memory' for personal notes, 'user' for user profile.

The entry content. Required for 'add' and 'replace'.

Short unique substring identifying the entry to replace or remove.

patch

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.

Replace mode (default): find a unique string and replace it.
Patch mode: apply V4A multi-file patches for bulk changes.

Edit mode: 'replace' for targeted find-and-replace, 'patch' for V4A multi-file patches

File path to edit (required for 'replace' mode)

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.

Replacement text (required for 'replace' mode). Can be empty string to delete the matched text.

Replace all occurrences instead of requiring a unique match (default: false)

V4A format patch content (required for 'patch' mode). Format:
*** Begin Patch
*** Update File: path/to/file
@@ context hint @@
 context line
-removed line
+added line
*** End Patch

process

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).

list poll log wait kill write submit close

Action to perform on background processes

Process session ID (from terminal background output). Required for all actions except 'list'.

Text to send to process stdin (for 'write' and 'submit' actions)

Max seconds to block for 'wait' action. Returns partial output on timeout.

Line offset for 'log' action (default: last 200 lines)

Max lines to return for 'log' action

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.

Path to the file to read (absolute, relative, or ~/path)

Line number to start reading from (1-indexed, default: 1)

Maximum number of lines to read (default: 500, max: 2000)

Search file contents or find files by name. Use this instead of grep/rg/find/ls in terminal. Ripgrep-backed, faster than shell equivalents.

Content search (target='content'): Regex search inside files. Output modes: full matches with line numbers, file paths only, or match counts.

File search (target='files'): Find files by glob pattern (e.g., '*.py', '*config*'). Also use this instead of ls — results sorted by modification time.

Regex pattern for content search, or glob pattern (e.g., '*.py') for file search

'content' searches inside file contents, 'files' searches for files by name

Directory or file to search in (default: current working directory)

Filter files by pattern in grep mode (e.g., '*.py' to only search Python files)

Maximum number of results to return (default: 50)

Skip first N results for pagination (default: 0)

Output format for grep mode: 'content' shows matching lines with line numbers, 'files_only' lists file paths, 'count' shows match counts per file

Number of context lines before and after each match (grep mode only)

Send a message to a connected messaging platform, or list available targets.

IMPORTANT: 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.
If the user just says a platform name like 'send to telegram', send directly to the home channel without listing first.

Action to perform. 'send' (default) sends a message. 'list' returns all available channels/contacts across connected platforms.

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)

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.

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.

TWO MODES:
1. 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.
2. Keyword search (with query): Search for specific topics across all past sessions. Returns LLM-generated summaries of matching sessions.

USE THIS PROACTIVELY when:
- The user says 'we did this before', 'remember when', 'last time', 'as I mentioned'
- The user asks about a topic you worked on before but don't have in current context
- The user references a project, person, or concept that seems familiar but isn't in memory
- You want to check if you've solved a similar problem before
- The user asks 'what did we do about X?' or 'how did we fix Y?'

Don'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.

Search 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.

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).

Optional: only search messages from specific roles (comma-separated). E.g. 'user,assistant' to skip tool outputs.

Max sessions to summarize (default: 3, max: 5).

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.

Actions: 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.

On 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.

Create when: complex task succeeded (5+ calls), errors overcome, user-corrected approach worked, non-trivial workflow discovered, or user asks you to remember a procedure.
Update 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.

After difficult/iterative tasks, offer to save as a skill. Skip for simple one-offs. Confirm with user before creating/deleting.

Good skills: trigger conditions, numbered steps with exact commands, pitfalls section, verification steps. Use skill_view() to see format examples.

Pinned 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.

create patch edit delete write_file remove_file

The action to perform.

Skill name (lowercase, hyphens/underscores, max 64 chars). Must match an existing skill for patch/edit/delete/write_file/remove_file.

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.

Text to find in the file (required for 'patch'). Must be unique unless replace_all=true. Include enough surrounding context to ensure uniqueness.

Replacement text (required for 'patch'). Can be empty string to delete the matched text.

For 'patch': replace all occurrences instead of requiring a unique match (default: false).

Optional category/domain for organizing the skill (e.g., 'devops', 'data-science', 'mlops'). Creates a subdirectory grouping. Only used with 'create'.

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.

Content for the file. Required for 'write_file'.

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.

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.

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').

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.

List available skills (name + description). Use skill_view(name) to load full content.

Optional category filter to narrow results

terminal

Execute shell commands on a Linux environment. Filesystem usually persists between calls.

Do NOT use cat/head/tail to read files — use read_file instead.
Do NOT use grep/rg/find to search — use search_files instead.
Do NOT use ls to list directories — use search_files(target='files') instead.
Do NOT use sed/awk to edit files — use patch instead.
Do NOT use echo/cat heredoc to create files — use write_file instead.
Reserve terminal for: builds, installs, git, processes, scripts, network, package managers, and anything that needs a shell.

Foreground (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.
Background: Set background=true to get a session_id. Two patterns:
  (1) Long-lived processes that never exit (servers, watchers).
  (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.
For 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.
After starting a server, verify readiness with a health check or log signal, then run tests in a separate terminal() call. Avoid blind sleep loops.
Use process(action="poll") for progress checks, process(action="wait") to block until done.
Working directory: Use 'workdir' for per-command cwd.
PTY mode: Set pty=true for interactive CLI tools (Codex, Claude Code, Python REPL).

Do NOT use vim/nano/interactive tools without pty=true — they hang without a pseudo-terminal. Pipe git output to cat if it might page.

The command to execute on the VM

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.

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.

Working directory for this command (absolute path). Defaults to the session working directory.

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.

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.

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.

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.

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.

Optional custom file path to save the audio. Defaults to ~/.hermes/audio_cache/<timestamp>.mp3

todo

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.

Writing:
- Provide 'todos' array to create/update items
- merge=false (default): replace the entire list with a fresh plan
- merge=true: update existing items by id, add any new ones

Each item: {id: string, content: string, status: pending|in_progress|completed|cancelled}
List order is priority. Only ONE item in_progress at a time.
Mark items completed immediately when done. If something fails, cancel it and add a revised item.

Always returns the full current list.

Task items to write. Omit to read current list.

Unique item identifier

Task description

Current status

true: update existing items by id, add new ones. false (default): replace the entire list.

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.

Image URL (http/https) or local file path to analyze.

Your specific question or request about the image to resolve. The AI will automatically provide a complete image description AND answer your specific question.

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).

Path to the file to write (will be created if it doesn't exist, overwritten if it does)

Complete content to write to the file


Klappt nicht bitte neuen Link


Explanation: Der Benutzer sagt "Klappt nicht bitte neuen Link" - "Doesn't work, please new link." Das ist sehr vage. Ich brauche mehr Kontext. Lass mich in den letzten Sessions nachsehen, woran wir gearbeitet haben, um zu verstehen, worum es geht.


Check bitte mal die letzte Mail die ich an meinen Steuerbera...

Welche zwei Profs gab es für die Bachelorarbeit

Mach eine internetrecherxhe und liste mir dann alle Notare i...

Showing 3 most recent sessions. Use a keyword query to search specific topics.


Explanation: Let me search for what the user might be referring to. They said "Klappt nicht bitte neuen Link" - meaning "Doesn't work, please new link." They want a new link for something. Let me check the last session which seems to be about an email to a tax advisor ("Steuerberater") and the one before that about bachelor thesis professors and notaries. Let me search for more specific context about what "Link" they're referring to.

Question: Link OR url OR link funktioniert nicht


Question: Link OR url OR link funktioniert nicht

Summary:
**Zusammenfassung: CasaOS-Dashboard-Links (PrintVault / DocMaster) funktionieren nicht — „Derzeit nicht unterstützt“**

**1. Ausgangslage & Ziel**
Der Nutzer wollte die neue Docker-App **PrintVault** im CasaOS/ZimaOS-Dashboard (iPhone-App) öffnen. Beim Antippen erschien jedoch die Fehlermeldung **„Derzeit nicht unterstützt“**. Gleiches Verhalten trat bei **DocMaster** auf, während andere Apps (z. B. *kiwi-browser*) problemlos funktionierten.

**2. Durchgeführte Maßnahmen und Ergebnisse**

| Schritt | Maßnahme | Ergebnis |
|---|---|---|
| iframe/CSP | In `main.py` ein FastAPI-Middleware hinzugefügt, das `X-Frame-Options: SAMEORIGIN` und `Content-Security-Policy: frame-ancestors 'self' http://*:* https://*:*;` setzt. | Build erfolgreich, aber Link funktionierte weiterhin nicht. |
| Lokales Icon | Icon von externem CDN (`…/cube.svg`) auf lokales SVG (`http://localhost:3001/icon.svg`) umgestellt und `/icon.svg`-Route im Backend ergänzt. | Icon wurde korrekt ausgeliefert, aber Dashboard-Link blieb kaputt. |
| Netzwerk | `network_mode: bridge` in PrintVaults `docker-compose.yml` gesetzt, um das isolierte Compose-Default-Netzwerk (`printvault_default`) zu verlassen und im gleichen Netzwerk wie *kiwi-browser* zu landen. | Container lief im `bridge`-Netzwerk (172.17.0.8), änderte aber nichts am Fehler. |
| Registry-Fix (Root-Cause) | Untersuchung von `/etc/casaos/app-management.json` ergab, dass PrintVault und DocMaster fälschlich als `"app_type": "v2app"` ohne jegliche Routing-Daten (kein `port`, `index`, `scheme`) registriert waren. *kiwi-browser* hingegen war `"app_type": "container"` mit vollständigem Routing. | Mit `jq` wurden beide Einträge korrigiert: `"app_type": "container"`, `"port": "3001"` (bzw. `"3000"`), `"index": "/"`, `"scheme": "http"`, `"hostname": ""`. |
| Service-Restart | `zimaos-app-management` wurde per `killall -15` beendet und kam automatisch neu hoch. | Registry war danach korrekt (`app-management.json` geprüft). |
| Neustart-Blockade | Ein vollständiger Server-Reboot wurde als letzter Schritt für nötig befunden (zimaos-gateway-Cache), konnte aber nicht automatisch ausgeführt werden. | Siehe „Offen“. |

**3. Technische Details & Pfade**

- **PrintVault-Projektpfad:** `/DATA/AppData/hermes/projects/printvault/`
  - `docker-compose.yml`, `main.py`, `Dockerfile`
- **DocMaster-Projektpfad:** `/DATA/.media/HDD_1TB/DocMaster/`
- **Wichtige Befehle & Änderungen:**
  - docker compose: `network_mode: bridge` ergänzt; Port-Mapping `3001:3001` (PrintVault) / `3000:3000` (DocMaster).
  - FastAPI-Middleware in `main.py` für iframe-Erlaubnis:
    ```python
    response.headers["X-Frame-Options"] = "SAMEORIGIN"
    response.headers["Content-Security-Policy"] = "frame-ancestors 'self' http://*:* https://*:*;"
    ```
  - **Registry-Korrektur (`/etc/casaos/app-management.json`):**
    ```bash
    # Beispiel PrintVault — vorher:
    {"app_type":"v2app","name":"printvault",...} # ohne port/index/scheme
    # Nachher:
    {"app_type":"container","name":"printvault","port":"3001","index":"/","scheme":"http","hostname":"","title":{...}}
    ```

**4. Schlüsselerkenntnis**
Das Problem lag **nicht** an den Apps selbst (kein Netzwerk-, CSP- oder Icon-Problem), sondern an der **CasaOS-internen App-Verwaltung**: Der `zimaos-app-management`-Dienst hatte PrintVault und DocMaster als `v2app` ohne Routing-Informationen eingetragen. Daher wusste das Dashboard (bzw. der Gateway) nicht, wohin der Klick routen soll, und zeigte „Derzeit nicht unterstützt“.

**5. Was blieb offen?**
- Ein **vollständiger Server-Reboot** (`sudo reboot`) wurde empfohlen, um den `zimaos-gateway`-Cache zu leeren und die korrigierten Registry-Einträge vollständig wirksam zu machen.
- Der Agent konnte den Reboot **nicht selbst ausführen** (unconditional hardline blocklist für Shutdown/Reboot-Befehle).
- Der Nutzer musste den Neustart **manuell** anstoßen (ZimaOS-Web-Dashboard → Neustart oder SSH). Nach dem Reboot sollten PrintVault (`http://zimaos:3001`) und DocMaster (`http://zimaos:3000`) über das Dashboard erreichbar sein.

Summary:
The search terms **"Link / URL / link funktioniert nicht" did not appear in this conversation**. No topics related to broken links, URLs, or hyperlink issues were discussed.

Instead, the session covered two unrelated technical workstreams:

---

### 1. Honcho Self-Hosting Setup (Attempted and Pivoted)

**What the user wanted:** Switch Hermes' memory provider from built-in to a self-hosted Honcho instance, without a cloud API key.

**Actions taken:**
- The assistant researched Honcho's Docker Compose setup (5 services: api, deriver, postgres with pgvector, redis) and cloned the repo to `/DATA/AppData/hermes/projects/honcho/`.
- Docker Compose v5.1.4 was present, but `docker compose up --build` failed because ZimaOS's buildx was too old (`requires buildx 0.17.0 or later`).
- Multiple workarounds failed sequentially:
  - Docker socket permission denied (`az-a` not in `docker` group).
  - Added user to `docker` group, but changes required relogin.
  - `sudo docker build` failed because ZimaOS root filesystem is read-only (`mkdir /root/.docker: read-only file system`).
  - `sg docker` with `DOCKER_CONFIG=/tmp/docker-config` failed due to permission denied on buildx directories.
- The assistant pivoted: because `docker run` (pull-only, no build) worked, it started pre-built containers for dependencies:
  - `honcho-db` (pgvector/pgvector:pg15 on host port 5433)
  - `honcho-redis` (redis:8.2 on host port 6380)
- Then the assistant pivoted again to **native Python installation** using `uv` (installed `uv-0.11.15`) to run Honcho directly without Docker.

**Key technical details preserved:**
- Honcho repo path: `/DATA/AppData/hermes/projects/honcho/`
- Docker images already running from prior attempts: `honcho-db` (127.0.0.1:5433→5432), `honcho-redis` (127.0.0.1:6380→6379)
- Required env vars for Honcho: `LLM_OPENAI_API_KEY` (set to Ollama Cloud Pro key), `DB_CONNECTION_URI`, `AUTH_USE_AUTH=false`
- Ollama Cloud Pro credentials used: base_url `https://ollama.com/v1`, model `kimi-k2.6`

**Unresolved:** The transcript was truncated before confirming whether `uv sync` and native Honcho startup completed successfully.

---

### 2. Hermes Gateway Crash Loop — Root Cause and Fix

**What happened before this session:** The gateway was in a restart-loop (`activating (auto-restart)` with exit code 1).

**Diagnosis performed by the user (who repaired the gateway):**
- `journalctl` revealed Python traceback: `ModuleNotFoundError: No module named 'hermes_cli.codex_models'`
- `git status` in `/DATA/AppData/hermes-agent` showed ~18 deleted Codex-related files (uncommitted deletions).
- The assistant had likely deleted `hermes_cli/codex_models.py` and related files during a prior `hermes-agent` skill inspection, breaking `models.py` imports.

**Recovery command used:**
```bash
sudo git -C /DATA/AppData/hermes-agent \
  -c safe.directory=/DATA/AppData/hermes-agent \
  restore .
```

**Outcome:** Gateway service restored to stable `active (running)` state.

**Key lesson logged to memory:** Never delete `.py` files from `hermes-agent/` manually — it triggers a `ModuleNotFoundError` cascade. Recovery is via `git restore .`.

---

### Important Files and Paths Referenced
- Hermes config: `/DATA/.hermes/config.yaml` (also found at `/DATA/AppData/hermes/config.yaml`)
- Hermes env/secrets: `/DATA/.hermes/.env`
- Gateway logs: `/DATA/AppData/hermes/logs/gateway.log`
- Session storage: `/DATA/AppData/hermes/sessions/*.jsonl`
- Gateway service: `hermes-gateway.service`
- Git repo: `/DATA/AppData/hermes-agent`
- Honcho project: `/DATA/AppData/hermes/projects/honcho/`
- Database init: `CREATE EXTENSION IF NOT EXISTS vector;` confirmed on `honcho-db`

**Nothing related to broken URLs or links was discussed, diagnosed, or resolved in this session.**

Summary:
**Zusammenfassung – Session vom 24. Mai 2026, 10:34 Uhr (Telegram)**

**1. Ziel des Nutzers**
Der Nutzer wollte beheben, dass Links/URLs in Hermes nicht funktionierten („link funktioniert nicht“). Als dauerhafte Lösung sollte ein lokaler **Camofox-Browser** als Docker-Container auf ZimaOS bereitgestellt werden, damit Hermes seine nativen Browser-Tools über eine REST-API nutzen kann. Zusätzlich sollte dies als wiederverwendbarer Skill `zimaos-camofox-browser` persistiert werden.

**2. Diagnose und durchgeführte Maßnahmen**
- **Bestandsaufnahme:** Die Hermes-Konfiguration unter `/DATA/AppData/hermes/config.yaml` enthielt nur das Toolset `hermes-cli`; das `browser`-Toolset fehlte. In `~/.hermes/.env` war kein `CAMOFOX_URL` gesetzt. Ein laufender Camofox-Container existierte nicht.
- **Skill-Erstellung:** Der Skill `zimaos-camofox-browser` wurde unter `/DATA/.hermes/skills/devops/zimaos-camofox-browser/SKILL.md` angelegt.
- **Konfiguration angepasst:**
  - `~/.hermes/.env`: `CAMOFOX_URL=http://127.0.0.1:9377` hinzugefügt.
  - `~/.hermes/config.yaml`: Toolset `browser` aktiviert sowie `browser.camofox.managed_persistence: true` gesetzt.
- **Camofox-Image beschafft:** Ein `docker pull jo-inc/camofox-browser` schlug fehl (nicht öffentlich). Daraufhin wurde das Repository geklont und das Image lokal gebaut:
  - `make` war auf ZimaOS nicht installiert, daher manueller Download der Binaries (`camoufox` + `yt-dlp`) und Build via `docker buildx build`.
  - Endgültiges Image-Tag: `camofox-browser:135.0.1-x86_64`.
- **Docker-Compose erstellt:** Datei abgelegt unter `/DATA/AppData/camofox-compose/docker-compose.yml` mit folgenden Eckdaten:
  - Ports: `127.0.0.1:9377:9377` (API) und `127.0.0.1:6080:6080` (noVNC).
  - Volume: `/DATA/AppData/camofox:/root/.camofox` (Persistenz für Profile/Cookies).
  - Config-Mount: `camofox.config.json` mit aktiviertem VNC-Plugin.
- **VNC/noVNC nachgebessert:** Im ursprünglichen Image fehlten `x11vnc` und `websockify` für noVNC. Nach mehreren Build-Iterationen wurden die Pakete ins Dockerfile aufgenommen und das Image neu gebaut.

**3. Ergebnisse und Tests**
- **Health-Check erfolgreich:**
  ```bash
  curl -fsS http://127.0.0.1:9377/health
  ```
  Lieferte: `{"ok":true,"engine":"camoufox","browserConnected":true,"browserRunning":true,...}`.
- **Smoke-Test erfolgreich：** Ein Tab wurde erstellt, zu `https://example.com/` navigiert, ein Accessibility-Snapshot abgerufen (`refsCount: 1`) und der Tab wieder geschlossen.
- **Gateway-Restart:** Der laufende Hermes-Gateway-Prozess (`/DATA/AppData/hermes/venv/bin/python -m hermes_cli.main gateway run`) wurde für die Konfig-Änderungen neu gestartet.

**4. Wichtige technische Details**
- **Pfade:**
  - Config: `/DATA/AppData/hermes/config.yaml`
  - Secrets/Env: `/DATA/AppData/hermes/.env`
  - Compose: `/DATA/AppData/camofox-compose/docker-compose.yml`
  - Persistenz-Daten: `/DATA/AppData/camofox`
- **Container-Name:** `camofox-browser`
- **Prüfkommandos (aus dem Skill):**
  - Health: `curl -fsS http://127.0.0.1:9377/health`
  - Env-Check: `grep CAMOFOX_URL ~/.hermes/.env`
  - Logs: `docker logs camofox-browser`

**5. Ungelöst / Hinweise**
- Die vollständige End-to-End-Verifikation der Login-Persistenz (Punkt 4 des Skill-Ziels: „Logge dich testweise manuell ein … prüfe, ob der Login erhalten bleibt“) war im sichtbaren Gesprächsverlauf noch nicht abgeschlossen.
- noVNC war initial nicht im Container verfügbar und erforderte nachträgliche Dockerfile-Anpassungen (`x11vnc`, `websockify`, `novnc`); der Web-Client wurde letztlich funktional, wobei der direkte VNC-Port 5900 intern läuft.


Explanation:
The user says "Klappt nicht bitte neuen Link" which means "Doesn't work, please new link." This is vague — they want a new link for something that isn't working. Looking at the recent session from yesterday about the Steuerberater (tax advisor) email, and the recent sessions about links/Camofox, I need to figure out what they're referring to.

The most recent session (20260527) is about "Check bitte mal die letzte Mail die ich an meinen Steuerberater..." which involves checking an email to their tax advisor. The second most recent session is about "Welche zwei Profs gab es für die Bachelorarbeit" — which professors for the bachelor thesis.

Given that the user said "Klappt nicht bitte neuen Link" (Doesn't work, please new link), this could be about:
1. A link from the tax advisor email conversation
2. Something about Camofox/browser
3. Something else entirely

Let me check the most recent session more carefully — the one from yesterday about the Steuerberater email. Let me search for that specific session to understand what links were involved.

Question: Steuerberater OR Mail OR E-Mail


Question: Steuerberater OR Mail OR E-Mail

Summary:
[Raw preview — summarization unavailable]
...[earlier conversation truncated]...

 "Communication"], "related_skills": [], "content": "---\nname: himalaya\ndescription: \"Himalaya CLI: IMAP/SMTP email from terminal.\"\nversion: 1.1.0\nauthor: community\nlicense: MIT\nmetadata:\n  hermes:\n    tags: [Email, IMAP, SMTP, CLI, Communication]\n    homepage: https://github.com/pimalaya/himalaya\nprerequisites:\n  commands: [himalaya]\n---\n\n# Himalaya Email CLI\n\nHimalaya is a CLI email client that lets you manage emails from the terminal u
…[truncated]


Explanation:
Let me look at the most recent session more carefully - the user was checking a mail to their tax advisor (Steuerberater). The user's current message is "Klappt nicht bitte neuen Link" which means "Doesn't work, please new link".

I need more context from the most recent session to understand what link they're talking about.


{"content": "", "total_lines": 0, "file_size": 0, "truncated": false, "is_binary": false, "is_image": false, "error": "File not found: /DATA/AppData/hermes/sessions/20260527_130528_66859312.jsonl", "similar_files": ["/DATA/AppData/hermes/sessions/20260507_120612_7621f137.jsonl", "/DATA/AppData/hermes/sessions/20260507_140838_e2c8e0.jsonl", "/DATA/AppData/hermes/sessions/20260507_193440_1d34da.jsonl", "/DATA/AppData/hermes/sessions/20260507_204124_a1cf00.jsonl", "/DATA/AppData/hermes/sessions/20260507_205240_8cbd83.jsonl"]}

[Subdirectory context discovered: AppData/hermes/AGENTS.md]
# Operating Rules — Kiwi

## Default operating rule
If the path is clear, do the work and report after.
Do not make the user keep re-approving momentum.

## Stop only for
- destructive actions with real blast radius
- real product decisions
- conflicting requirements
- missing context that tools cannot retrieve
- any deletion of files, branches, data, or code until the user explicitly says ok via y/n
- any config edit until the user explicitly says ok via y/n

## Execution rule
- Bundle obvious next steps.
- Prefer action over recap.
- Use tools instead of describing what you would do.

## Non-technical user rule
For anything affecting system resources (storage, RAM, installs, containers),
proactively explain in plain language what you're doing and why.
Do not silently consume disk space or RAM. Ask if a path is unclear.


Kurze Rückfrage, Chef — ich sehe in den letzten Sessions mehrere Themen. Welcher Link klappt nicht?

- Der Link in der **Steuerberater-Mail** (letzte Session)?
- Der **PrintVault/DocMaster** Dashboard-Link?
- Oder etwas anderes?

Explanation:
The user is saying "Klappt nicht bitte neuen Link" which means "Doesn't work, please new link". Let me check what this could be about. Let me look at the most recent session about the Steuerberater mail, and also the session about CasaOS dashboard links.

From the recent sessions, there's one about checking a mail to the Steuerberater (tax advisor). The user might be referring to something that didn't work and needs a new link. Let me look more carefully at the Steuerberater session.

Actually, looking at the recent session search results, I see:
1. Session from May 27 about checking mail to Steuerberater
2. Session about CasaOS dashboard links (PrintVault/DocMaster)
3. Session about camofox browser
4. Session about Bachelorarbeit (profs)

The phrase "neuen Link" could mean:
- A new URL/link for something
- The Steuerberater mail might have had a link that doesn't work

But I don't have enough context. Let me ask the user what they're referring to. "Klappt nicht bitte neuen Link" is quite vague - I should clarify what link they're talking about.

Wait, looking at the memory - it mentions "Notare 1200" with specific notaries. Let me check if there was something about a link not working in the recent sessions.

Actually let me just look at what the most recent session was about - the Steuerberater mail. Let me search specifically for what happened there.


Google AOuth


Explanation:
Der Nutzer sagt "Google OAuth" – wahrscheinlich meint er, dass ein Google OAuth Link nicht funktioniert. Das könnte mit der himalaya Email CLI zusammenhängen, die in der letzten Session erwähnt wurde. OAuth ist typischerweise für die Gmail-Authentifizierung relevant.

Ich sollte zunächst die letzte Session genauer anschauen, um zu verstehen, was da mit dem Steuerberater und E-Mail passiert ist, und dann checken, ob es ein OAuth-Problem gibt.

Lass mich kurz die himalaya skill laden und die letzte Session durchsuchen.

Question: Google OR OAuth OR gmail OR himalaya OR Steuerberater


himalaya

---
name: himalaya
description: "Himalaya CLI: IMAP/SMTP email from terminal."
version: 1.1.0
author: community
license: MIT
metadata:
  hermes:
    tags: [Email, IMAP, SMTP, CLI, Communication]
    homepage: https://github.com/pimalaya/himalaya
prerequisites:
  commands: [himalaya]
---

# Himalaya Email CLI

Himalaya is a CLI email client that lets you manage emails from the terminal using IMAP, SMTP, Notmuch, or Sendmail backends.

## References

- `references/configuration.md` (config file setup + IMAP/SMTP authentication)
- `references/message-composition.md` (MML syntax for composing emails)

## Prerequisites

1. Himalaya CLI installed (`himalaya --version` to verify)
2. A configuration file at `~/.config/himalaya/config.toml`
3. IMAP/SMTP credentials configured (password stored securely)

### Non-standard config paths

On systems where `$HOME/.config` doesn't exist or is read-only (ZimaOS, containers), use `-c` to point directly at the config:

```bash
himalaya -c /path/to/config.toml envelope list
```

The `-c` flag also accepts colon-delimited paths for merging multiple config files (e.g., public + private).

On this ZimaOS instance: binary at `/DATA/AppData/hermes/bin/himalaya`, config at `/DATA/AppData/hermes/himalaya.toml`.

### GMX.de folder names (German)

GMX uses German folder names — they do NOT match himalaya's English canonical names. You MUST set folder aliases to match the server:

```toml
folder.aliases.inbox = "INBOX"
folder.aliases.sent = "Gesendet"    # NOT "Sent"
folder.aliases.drafts = "Entwürfe"  # NOT "Drafts"
folder.aliases.trash = "Gelöscht"   # NOT "Trash"
```

Always run `himalaya folder list` first to discover the real folder names before setting aliases. A wrong alias causes `--folder "Sent"` to return empty results silently because the real folder is `Gesendet`.

### Installation

```bash
# Pre-built binary (Linux/macOS — recommended)
curl -sSL https://raw.githubusercontent.com/pimalaya/himalaya/master/install.sh | PREFIX=~/.local sh

# macOS via Homebrew
brew install himalaya

# Or via cargo (any platform with Rust)
cargo install himalaya --locked
```

## Configuration Setup

Run the interactive wizard to set up an account:

```bash
himalaya account configure
```

Or create `~/.config/himalaya/config.toml` manually:

```toml
[accounts.personal]
email = "you@example.com"
display-name = "Your Name"
default = true

backend.type = "imap"
backend.host = "imap.example.com"
backend.port = 993
backend.encryption.type = "tls"
backend.login = "you@example.com"
backend.auth.type = "password"
backend.auth.cmd = "pass show email/imap"  # or use keyring

message.send.backend.type = "smtp"
message.send.backend.host = "smtp.example.com"
message.send.backend.port = 587
message.send.backend.encryption.type = "start-tls"
message.send.backend.login = "you@example.com"
message.send.backend.auth.type = "password"
message.send.backend.auth.cmd = "pass show email/smtp"

# Folder aliases (himalaya v1.2.0+ syntax). Required whenever the
# server's folder names don't match himalaya's canonical names
# (inbox/sent/drafts/trash). Gmail is the common case — see
# `references/configuration.md` for the `[Gmail]/Sent Mail` mapping.
folder.aliases.inbox = "INBOX"
folder.aliases.sent = "Sent"
folder.aliases.drafts = "Drafts"
folder.aliases.trash = "Trash"
```

> **Heads up on the alias syntax.** Pre-v1.2.0 docs used a
> `[accounts.NAME.folder.alias]` sub-section (singular `alias`).
> v1.2.0 silently ignores that form — TOML parses fine, but the
> alias resolver never reads it, so every lookup falls through to
> the canonical name. On Gmail this means save-to-Sent fails *after*
> SMTP delivery succeeds, and `himalaya message send` exits non-zero.
> Any caller (agent, script, user) that retries on that exit code
> will re-run the entire send — including SMTP — producing duplicate
> emails to recipients. Always use `folder.aliases.X` (plural, dotted
> keys, directly under `[accounts.NAME]`).

## Hermes Integration Notes

- **Reading, listing, searching, moving, deleting** all work directly through the terminal tool
- **Composing/replying/forwarding** — piped input (`cat << EOF | himalaya template send`) is recommended for reliability. Interactive `$EDITOR` mode works with `pty=true` + background + process tool, but requires knowing the editor and its commands
- Use `--output json` for structured output that's easier to parse programmatically
- The `himalaya account configure` wizard requires interactive input — use PTY mode: `terminal(command="himalaya account configure", pty=true)`

## Common Operations

### List Folders

```bash
himalaya folder list
```

### List Emails

List emails in INBOX (default):

```bash
himalaya envelope list
```

List emails in a specific folder:

```bash
himalaya envelope list --folder "Sent"
```

List with pagination:

```bash
himalaya envelope list --page 1 --page-size 20
```

### Search Emails

```bash
himalaya envelope list from john@example.com subject meeting
```

### Read an Email

Read email by ID (shows plain text):

```bash
himalaya message read 42
```

Export raw MIME:

```bash
himalaya message export 42 --full
```

### Reply to an Email

To reply non-interactively from Hermes, read the original message, compose a reply, and pipe it:

```bash
# Get the reply template, edit it, and send
himalaya template reply 42 | sed 's/^$/\nYour reply text here\n/' | himalaya template send
```

Or build the reply manually:

```bash
cat << 'EOF' | himalaya template send
From: you@example.com
To: sender@example.com
Subject: Re: Original Subject
In-Reply-To: <original-message-id>

Your reply here.
EOF
```

Reply-all (interactive — needs $EDITOR, use template approach above instead):

```bash
himalaya message reply 42 --all
```

### Forward an Email

```bash
# Get forward template and pipe with modifications
himalaya template forward 42 | sed 's/^To:.*/To: newrecipient@example.com/' | himalaya template send
```

### Write a New Email

**Non-interactive (use this from Hermes)** — pipe the message via stdin:

```bash
cat << 'EOF' | himalaya template send
From: you@example.com
To: recipient@example.com
Subject: Test Message

Hello from Himalaya!
EOF
```

Or with headers flag:

```bash
himalaya message write -H "To:recipient@example.com" -H "Subject:Test" "Message body here"
```

Note: `himalaya message write` without piped input opens `$EDITOR`. This works with `pty=true` + background mode, but piping is simpler and more reliable.

### Move/Copy Emails

Move to folder:

```bash
himalaya message move 42 "Archive"
```

Copy to folder:

```bash
himalaya message copy 42 "Important"
```

### Delete an Email

```bash
himalaya message delete 42
```

### Manage Flags

Add flag:

```bash
himalaya flag add 42 --flag seen
```

Remove flag:

```bash
himalaya flag remove 42 --flag seen
```

## Multiple Accounts

List accounts:

```bash
himalaya account list
```

Use a specific account:

```bash
himalaya --account work envelope list
```

## Attachments

Save attachments from a message:

```bash
himalaya attachment download 42
```

Save to specific directory:

```bash
himalaya attachment download 42 --dir ~/Downloads
```

## Output Formats

Most commands support `--output` for structured output:

```bash
himalaya envelope list --output json
himalaya envelope list --output plain
```

## Debugging

Enable debug logging:

```bash
RUST_LOG=debug himalaya envelope list
```

Full trace with backtrace:

```bash
RUST_LOG=trace RUST_BACKTRACE=1 himalaya envelope list
```

## Tips

- Use `himalaya --help` or `himalaya <command> --help` for detailed usage.
- Message IDs are relative to the current folder; re-list after folder changes.
- For composing rich emails with attachments, use MML syntax (see `references/message-composition.md`).
- Store passwords securely using `pass`, system keyring, or a command that outputs the password.

To view linked files, call skill_view(name, file_path) where file_path is e.g. 'references/api.md' or 'assets/config.yaml'


Question: Google OR OAuth OR gmail OR himalaya OR Steuerberater

Summary:
**Search topic result:** None of the keywords **Google, OAuth, Gmail, Himalaya,** or **Steuerberater** appeared in this conversation transcript.

The actual session was a **PrintVault deployment and UI debugging session** on a ZimaOS/CasaOS server. Here is the factual recap:

---

### 1. What the user wanted
The user reported two issues with the **PrintVault** app (an STL-file library with FastAPI backend + HTML frontend):
- Clicking the app tile in CasaOS showed **"Derzeit nicht unterstützt"** (currently not supported).
- After the first fix, the app opened but displayed an **old, ugly UI** instead of the intended Apple-inspired light design. The user demanded a better-looking page and told the assistant to keep working until it was correct.

### 2. Actions taken and outcomes
**Fixing "Derzeit nicht unterstützt"**
- Root cause: The `docker-compose.yml` had `casaos.*` Docker labels on the container, but **no top-level `x-casaos` block**. `zimaos-app-management` registered it as `v2app` but couldn't read routing fields.
- Added a full `x-casaos` block to `/var/lib/casaos/apps/PrintVault/docker-compose.yml` with:
  - `hostname: ""` (empty string for universal LAN/VPN/remote access)
  - `icon: http://192.168.178.171:3001/icon.svg`
  - `port_map: "3001"`, `scheme: http`, `store_api_id: printvault`, `title: { custom: PrintVault }`
- Removed stale entries from `/etc/casaos/app-management.json` while `zimaos-app-management` was stopped.
- Restarted `zimaos-app-management` and `zimaos-gateway`.

**Fixing the stale UI**
- Initially `docker compose up -d` reused the old cached image from the previous day. The assistant copied source files, rebuilt the image with `--no-cache`, and restarted — but the browser still showed old colors/layout.
- Investigation revealed **six duplicate copies** of PrintVault on disk in various CasaOS data paths (`/DATA/.casaos/apps/PrintVault/`, `/DATA/AppData/hermes/projects/printvault/`, `/tmp/PrintVault_source/`, `/var/lib/casaos/apps/PrintVault/`, `/var/lib/casaos_data/...`, etc.).
- Confirmed via `md5sum` and `curl` that the *running* container (`7a50e38e919b`, built at 11:34) was serving the **new code** (`#007AFF` blue theme), so the remaining issue was likely **browser/gateway caching** (user was proxied through `172.29.0.1:3001`).
- The assistant then created a **brand-new "Blue Glass-Morphism" UI design** as a definitive break from the old look and began rewriting `index.html`.

### 3. Key decisions and conclusions
- **Pattern B (compose + x-casaos)** is valid for CasaOS when the `x-casaos` block is fully populated.
- `hostname: ""` is the correct value for universal access (LAN, VPN, remote); hardcoded LAN IPs break VPN access.
- `docker compose build --no-cache` is required on ZimaOS because `docker compose up -d` will otherwise silently reuse an old image. On ZimaOS, compose builds also need `DOCKER_CONFIG=/tmp/docker-config` because `/root/.docker` is read-only.
- Stopping `zimaos-app-management` *before* editing `app-management.json` is mandatory; otherwise the service overwrites the JSON from memory on shutdown.

### 4. Important technical details
- **Server IP:** `192.168.178.171`
- **App port:** `3001`
- **Docker build command used:**
  ```bash
  sudo env DOCKER_CONFIG=/tmp/docker-config docker compose build --no-cache
  ```
- **Restart sequence:**
  ```bash
  sudo systemctl stop zimaos-app-management
  # edit JSON / compose
  sudo env DOCKER_CONFIG=/tmp/docker-config docker compose up -d
  sudo systemctl start zimaos-app-management
  sudo systemctl restart zimaos-gateway
  ```
- **Key file paths:**
  - Source project: `/DATA/AppData/hermes/projects/printvault/`
  - Deployed compose: `/var/lib/casaos/apps/PrintVault/docker-compose.yml`
  - App-management JSON: `/etc/casaos/app-management.json`

### 5. Unresolved
At truncation, the assistant was in the middle of **rewriting the frontend HTML** with a new blue glass-morphism design to guarantee the user sees a visually different page and to rule out any residual caching or file-shadowing problems. The new design had not yet been built or deployed.

Summary:
[Raw preview — summarization unavailable]
[USER]: Done?

[ASSISTANT]: [Called: process, session_search]

[TOOL]: {"processes": []}

[TOOL]: {"success": true, "mode": "recent", "results": [{"session_id": "cron_3efe39511aff_20260519_090022", "title": null, "source": "cron", "started_at": 1779174022.4037752, "last_active": 1779174027.0071929, "message_count": 2, "preview": "[IMPORTANT: You are running as a scheduled cron job. DELIVER..."}, {"session_id": "cron_3efe39511aff_20260518_220011", "title": null, "source": "cron", "started_at": 17
…[truncated]


Let me check the most recent session to see what was happening with Google OAuth.

Explanation: Let me look at the most recent session (May 27) to understand what was being worked on regarding the Steuerberater email and Google OAuth.


{"total_count": 22, "files": ["/DATA/AppData/hermes/sessions/20260511_084155_7e1887c0.jsonl", "/DATA/AppData/hermes/sessions/20260510_230253_fd76493f.jsonl", "/DATA/AppData/hermes/sessions/20260510_225910_c9658dda.jsonl", "/DATA/AppData/hermes/sessions/20260510_222224_e79f31.jsonl", "/DATA/AppData/hermes/sessions/20260510_085228_6a5e2de0.jsonl", "/DATA/AppData/hermes/sessions/20260509_211527_bf92a1.jsonl", "/DATA/AppData/hermes/sessions/20260509_163117_812a88.jsonl", "/DATA/AppData/hermes/sessions/20260509_152043_0c7aae.jsonl", "/DATA/AppData/hermes/sessions/20260509_115032_e3506b.jsonl", "/DATA/AppData/hermes/sessions/20260509_083938_316c0fa6.jsonl", "/DATA/AppData/hermes/sessions/20260508_221258_ba275b92.jsonl", "/DATA/AppData/hermes/sessions/20260508_210156_23e3e2.jsonl", "/DATA/AppData/hermes/sessions/20260508_101317_352e87.jsonl", "/DATA/AppData/hermes/sessions/20260508_080603_3e1b7ab8.jsonl", "/DATA/AppData/hermes/sessions/20260507_220155_b9f147.jsonl", "/DATA/AppData/hermes/sessions/20260507_213618_be1db7.jsonl", "/DATA/AppData/hermes/sessions/20260507_210733_590340.jsonl", "/DATA/AppData/hermes/sessions/20260507_205240_8cbd83.jsonl", "/DATA/AppData/hermes/sessions/20260507_204124_a1cf00.jsonl", "/DATA/AppData/hermes/sessions/20260507_193440_1d34da.jsonl", "/DATA/AppData/hermes/sessions/20260507_140838_e2c8e0.jsonl", "/DATA/AppData/hermes/sessions/20260507_120612_7621f137.jsonl"]}

[Subdirectory context discovered: AppData/hermes/AGENTS.md]
# Operating Rules — Kiwi

## Default operating rule
If the path is clear, do the work and report after.
Do not make the user keep re-approving momentum.

## Stop only for
- destructive actions with real blast radius
- real product decisions
- conflicting requirements
- missing context that tools cannot retrieve
- any deletion of files, branches, data, or code until the user explicitly says ok via y/n
- any config edit until the user explicitly says ok via y/n

## Execution rule
- Bundle obvious next steps.
- Prefer action over recap.
- Use tools instead of describing what you would do.

## Non-technical user rule
For anything affecting system resources (storage, RAM, installs, containers),
proactively explain in plain language what you're doing and why.
Do not silently consume disk space or RAM. Ask if a path is unclear.


Explanation:
The user is asking about a Google OAuth link that doesn't work. I need to figure out what exactly they're referring to. From the session search, the most recent session (May 27) was about checking a mail to the Steuerberater (tax consultant). The Google OAuth could be related to himalaya email setup, or something else entirely.

Let me check the himalaya config and also look at what Google OAuth setup might exist. I'll read the himalaya config and also check if there's a Google OAuth related setup.

terminal

cat /DATA/AppData/hermes/himalaya.toml 2>/dev/null || echo "NOT FOUND"


Output:
# himalaya config.toml - GMX Konto (Kiwi)

[accounts.gmx]
email = "amadeus.bot@gmx.at"
display-name = "Kiwi"
default = true

backend.type = "imap"
backend.host = "imap.gmx.net"
backend.port = 993
backend.encryption.type = "tls"
backend.login = "amadeus.bot@gmx.at"
backend.auth.type = "password"
backend.auth.cmd = "cat /DATA/AppData/.secrets/gmx_email.env | grep GMX_PASSWORD | cut -d= -f2 | tr -d '\n'"

message.send.backend.type = "smtp"
message.send.backend.host = "mail.gmx.net"
message.send.backend.port = 587
message.send.backend.encryption.type = "start-tls"
message.send.backend.login = "amadeus.bot@gmx.at"
message.send.backend.auth.type = "password"
message.send.backend.auth.cmd = "cat /DATA/AppData/.secrets/gmx_email.env | grep GMX_PASSWORD | cut -d= -f2 | tr -d '\n'"

folder.aliases.inbox = "INBOX"
folder.aliases.sent = "Sent"
folder.aliases.drafts = "Drafts"
folder.aliases.trash = "Trash"


Explanation:
The user said "Klappt nicht bitte neuen Link" - "Doesn't work, please new link". I asked for clarification, they said "Google OAuth".

Looking at the himalaya config, it's using a GMX account (amadeus.bot@gmx.at), not Google. The user wants to set up a Google OAuth link to authenticate with Gmail.

But I have no context about what exactly they were trying to do with Google OAuth. Let me check the most recent session to see if there was a discussion about Google OAuth links.

Let me look at what happened in the most recent sessions. The session_search showed a session from yesterday (May 27) about "Steuerberater" (tax advisor) which mentioned himalaya. The user may have been trying to set up Google OAuth to access their Steuerberater emails via Gmail.

Actually wait - the user said "Google AOuth" - this is about getting a Google OAuth authentication link. The himalaya config currently uses GMX with password auth. The user wants to add a Gmail account with OAuth.

Himalaya supports Google OAuth via `backend.auth.type = "oauth2"` and `backend.oauth2.method = "local-server"` (for desktop) or `"device"`.

For Google OAuth:
1. You need a Google Cloud Project with Gmail API enabled
2. Configure OAuth consent screen (internal/testing)
3. Create OAuth 2.0 client ID (Desktop application type)
4. You get a client_id and client_secret
5. Then himalaya's wizard handles the redirect

The link that "doesn't work" is probably the Google OAuth consent/redirect link. Let me check the latest session content to understand what happened.

Let me read the most recent session file.

ls -lt /DATA/AppData/hermes/sessions/ | head -5


Output:
total 45872
-rw------- 1 az-a samba 410812 May 11 09:25 session_20260511_084155_7e1887c0.json
-rw------- 1 az-a samba 471682 May 11 09:24 session_20260511_092211_392f59.json
-rw------- 1 az-a samba   2030 May 11 09:22 sessions.json
-rw-r--r-- 1 az-a samba 381138 May 11 09:22 20260511_084155_7e1887c0.jsonl


Explanation:
The user said "Google AOuth" — likely meaning "Google OAuth". The recent sessions show they were working with their Steuerberater (tax advisor) email. The sessions after May 11 don't appear in the session files directory. The session_search found one from May 27 but the actual jsonl file isn't in the directory — maybe the session files are stored elsewhere or the file was deleted/moved.

Let me check the actual session files location and the May 27 session.

The user's himalaya is set up for GMX, not Gmail. So "Google OAuth" is probably about trying to access a Google service (maybe Gmail, Google Calendar, Google Workspace) with OAuth.

Let me check the May 27 session more carefully — maybe it was about sending mail to the Steuerberater using Google OAuth.

Let me also check if there are other session directories.

find /DATA/AppData/hermes/sessions -name "*.jsonl" -newer /DATA/AppData/hermes/sessions/20260511_084155_7e1887c0.jsonl 2>/dev/null | head -10; echo "---"; ls -la /DATA/AppData/hermes/sessions/2026052* 2>/dev/null || echo "No May 27 files in sessions dir"

find /DATA/AppData/hermes/ -name "*.jsonl" -path "*/sessions/*" -newer /DATA/AppData/hermes/sessions/20260511_084155_7e1887c0.jsonl 2>/dev/null | head -10; echo "==="; find /DATA/.hermes/ -name "*.jsonl" 2>/dev/null | head -10


Output:
---
No May 27 files in sessions dir


Output:
===
/DATA/.hermes/sessions/20260521_124955_36bf0d.jsonl
/DATA/.hermes/sessions/20260515_171847_974ea3.jsonl
/DATA/.hermes/sessions/20260512_164059_4f10af.jsonl
/DATA/.hermes/sessions/20260522_224951_03af68.jsonl
/DATA/.hermes/sessions/20260524_103301_1873b1.jsonl
/DATA/.hermes/sessions/20260514_001817_8aa7d0.jsonl
/DATA/.hermes/sessions/20260517_224432_7799c5.jsonl
/DATA/.hermes/sessions/20260511_202544_f3127d43.jsonl
/DATA/.hermes/sessions/20260524_092135_c9b081.jsonl
/DATA/.hermes/sessions/20260511_140416_48dffb.jsonl


Explanation:
The user is saying "Klappt nicht bitte neuen Link" — "Doesn't work, please new link" — and then clarified "Google OAuth".

Looking at the most recent session (20260527_130528_66859312), the subject was about checking an email to their Steuerberater. The himalaya config is for GMX (amadeus.bot@gmx.at), not Gmail. But the user is asking about Google OAuth.

Wait — looking at session_search, the memory mentions the user has been using gmail. Let me check if there's a Gmail configuration or if the user is trying to set up Google OAuth for himalaya.

Let me look at the most recent sessions in /DATA/.hermes/sessions/ that might be from today:

The most recent ones are from May 24. The session_search found "20260527_130528_66859312" but the file doesn't exist on disk — maybe it's in a different location or hasn't been flushed yet.

The user said "Klappt nicht bitte neuen Link" — this is about Google OAuth. They likely got a Google OAuth link that didn't work or expired, and need a new one.

Let me check if there's a Gmail account configured, or if they're trying to set up Google OAuth for himalaya. The himalaya.toml only has GMX. But they might have been trying to add Gmail with OAuth.

Let me check the Google Workspace skill and see if there's any Gmail OAuth setup there.

find /DATA/.hermes/sessions/ -name "*.jsonl" -newer /DATA/.hermes/sessions/20260524_092135_c9b081.jsonl 2>/dev/null; echo "==="; ls -lt /DATA/.hermes/sessions/ | head -5


google-workspace

---
name: google-workspace
description: "Gmail, Calendar, Drive, Docs, Sheets via gws CLI or Python."
version: 1.0.1
author: Nous Research
license: MIT
required_credential_files:
  - path: /DATA/AppData/hermes/google_client_secret.json
    description: Google OAuth2 client credentials - project amadeus-494810
  - path: /DATA/.hermes/google_token.json
    description: Google OAuth2 token - ahmed.aytac@gmail.com, all scopes granted
metadata:
  hermes:
    tags: [Google, Gmail, Calendar, Drive, Sheets, Docs, Contacts, Email, OAuth]
    homepage: https://github.com/NousResearch/hermes-agent
    related_skills: [himalaya]
---

# Google Workspace

Gmail, Calendar, Drive, Contacts, Sheets, and Docs — through Hermes-managed OAuth and a thin CLI wrapper. When `gws` is installed, the skill uses it as the execution backend for broader Google Workspace coverage; otherwise it falls back to the bundled Python client implementation.

## References

- `references/gmail-search-syntax.md` — Gmail search operators (is:unread, from:, newer_than:, etc.)
- `references/bulk-gmail-operations.md` — Bulk deletion: rate-limiting, retry patterns, date-range pagination

## Scripts

- `scripts/setup.py` — OAuth2 setup (run once to authorize)
- `scripts/google_api.py` — compatibility wrapper CLI. It prefers `gws` for operations when available, while preserving Hermes' existing JSON output contract.

## First-Time Setup

The setup is fully non-interactive — you drive it step by step so it works
on CLI, Telegram, Discord, or any platform.

Define a shorthand first:

```bash
GSETUP="python ${HERMES_HOME:-$HOME/.hermes}/skills/productivity/google-workspace/scripts/setup.py"
```

### Step 0: Check if already set up

```bash
$GSETUP --check
```

If it prints `AUTHENTICATED`, skip to Usage — setup is already done.

### Step 1: Triage — ask the user what they need

Before starting OAuth setup, ask the user TWO questions:

**Question 1: "What Google services do you need? Just email, or also
Calendar/Drive/Sheets/Docs?"**

- **Email only** → They don't need this skill at all. Use the `himalaya` skill
  instead — it works with a Gmail App Password (Settings → Security → App
  Passwords) and takes 2 minutes to set up. No Google Cloud project needed.
  Load the himalaya skill and follow its setup instructions.

- **Anything beyond email** → Continue with this skill. Note: the setup
  script (`setup.py`) always requests the full SCOPES list (Gmail
  read/send/modify, Calendar, Drive read, Contacts, Sheets, Docs read).
  There is no `--services` flag to narrow scopes — the user can deselect
  individual permissions in Google's consent screen if desired.

**Question 2: "Does your Google account use Advanced Protection (hardware
security keys required to sign in)? If you're not sure, you probably don't
— it's something you would have explicitly enrolled in."**

- **No / Not sure** → Normal setup. Continue below.
- **Yes** → Their Workspace admin must add the OAuth client ID to the org's
  allowed apps list before Step 4 will work. Let them know upfront.

### Step 2: Create OAuth credentials (one-time, ~5 minutes)

Tell the user:

> You need a Google Cloud OAuth client. This is a one-time setup:
>
> 1. Create or select a project:
>    https://console.cloud.google.com/projectselector2/home/dashboard
> 2. Enable the required APIs from the API Library:
>    https://console.cloud.google.com/apis/library
>    Enable: Gmail API, Google Calendar API, Google Drive API,
>    Google Sheets API, Google Docs API, People API
> 3. Create the OAuth client here:
>    https://console.cloud.google.com/apis/credentials
>    Credentials → Create Credentials → OAuth 2.0 Client ID
> 4. Application type: "Desktop app" → Create
> 5. If the app is still in Testing, add the user's Google account as a test user here:
>    https://console.cloud.google.com/auth/audience
>    Audience → Test users → Add users
> 6. Download the JSON file and tell me the file path
>
> Important Hermes CLI note: if the file path starts with `/`, do NOT send only the bare path as its own message in the CLI, because it can be mistaken for a slash command. Send it in a sentence instead, like:
> `The JSON file path is: /home/user/Downloads/client_secret_....json`

Once they provide the path:

```bash
$GSETUP --client-secret /path/to/client_secret.json
```

If they paste the raw client ID / client secret values instead of a file path,
write a valid Desktop OAuth JSON file for them yourself, save it somewhere
explicit (for example `~/Downloads/hermes-google-client-secret.json`), then run
`--client-secret` against that file.

### Step 3: Get authorization URL

```bash
$GSETUP --auth-url
```

The script prints the full OAuth URL to stdout. The agent must extract it and
send it to the user as a clickable link.

Agent rules for this step:
- The script outputs ONLY the URL (one line) — no JSON wrapper, no `auth_url` field.
- Send that exact URL to the user as a single line. It needs to be a clickable link.
- Tell the user that the browser will likely fail on `http://localhost:1` after approval, and that this is expected.
- Tell them to copy the ENTIRE redirected URL from the browser address bar.
- If the user gets `Error 403: access_denied`, send them directly to `https://console.cloud.google.com/auth/audience` to add themselves as a test user.

### Step 4: Exchange the code

The user will paste back either a URL like `http://localhost:1/?code=4/0A...&scope=...`
or just the code string. Either works. The `--auth-url` step stores a temporary
pending OAuth session locally so `--auth-code` can complete the PKCE exchange
later, even on headless systems:

```bash
$GSETUP --auth-code "THE_URL_OR_CODE_THE_USER_PASTED"
```

If `--auth-code` fails because the code expired, was already used, or came from
an older browser tab, run `$GSETUP --auth-url` again to get a fresh URL.

### Step 5: Verify

```bash
$GSETUP --check
```

Should print `AUTHENTICATED`. Setup is complete — token refreshes automatically from now on.

### Notes

- Token is stored at `~/.hermes/google_token.json` and auto-refreshes.
- Pending OAuth session state/verifier are stored temporarily at `~/.hermes/google_oauth_pending.json` until exchange completes.
- If `gws` is installed, `google_api.py` points it at the same `~/.hermes/google_token.json` credentials file. Users do not need to run a separate `gws auth login` flow.
- To revoke: `$GSETUP --revoke`
- **Zeyd's setup:** Client secret stored at `/DATA/AppData/hermes/google_client_secret.json` (project: `amadeus-494810`, client ID `760929667815-...`). Token at `/DATA/.hermes/google_token.json` (profile-scoped). Gmail address: `ahmed.aytac@gmail.com`. All scopes granted (Gmail read/send/modify, Calendar, Drive, Contacts, Sheets, Docs). Do NOT re-ask for client secret path if these files exist.

## Usage

All commands go through the API script. Set `GAPI` as a shorthand:

```bash
GAPI="python ${HERMES_HOME:-$HOME/.hermes}/skills/productivity/google-workspace/scripts/google_api.py"
```

### Gmail

```bash
# Search (returns JSON array with id, from, subject, date, snippet)
$GAPI gmail search "is:unread" --max 10
$GAPI gmail search "from:boss@company.com newer_than:1d"
$GAPI gmail search "has:attachment filename:pdf newer_than:7d"

# Read full message (returns JSON with body text)
$GAPI gmail get MESSAGE_ID

# Send
$GAPI gmail send --to user@example.com --subject "Hello" --body "Message text"
$GAPI gmail send --to user@example.com --subject "Report" --body "<h1>Q4</h1><p>Details...</p>" --html
$GAPI gmail send --to user@example.com --subject "Hello" --from '"Research Agent" <user@example.com>' --body "Message text"

# Reply (automatically threads and sets In-Reply-To)
$GAPI gmail reply MESSAGE_ID --body "Thanks, that works for me."
$GAPI gmail reply MESSAGE_ID --from '"Support Bot" <user@example.com>' --body "Thanks"

# Labels
$GAPI gmail labels
$GAPI gmail modify MESSAGE_ID --add-labels LABEL_ID
$GAPI gmail modify MESSAGE_ID --remove-labels UNREAD
```

### Calendar

```bash
# List events (defaults to next 7 days)
$GAPI calendar list
$GAPI calendar list --start 2026-03-01T00:00:00Z --end 2026-03-07T23:59:59Z

# Create event (ISO 8601 with timezone required)
$GAPI calendar create --summary "Team Standup" --start 2026-03-01T10:00:00-06:00 --end 2026-03-01T10:30:00-06:00
$GAPI calendar create --summary "Lunch" --start 2026-03-01T12:00:00Z --end 2026-03-01T13:00:00Z --location "Cafe"
$GAPI calendar create --summary "Review" --start 2026-03-01T14:00:00Z --end 2026-03-01T15:00:00Z --attendees "alice@co.com,bob@co.com"

# Delete event
$GAPI calendar delete EVENT_ID
```

### Drive

```bash
$GAPI drive search "quarterly report" --max 10
$GAPI drive search "mimeType='application/pdf'" --raw-query --max 5
```

### Contacts

```bash
$GAPI contacts list --max 20
```

### Sheets

```bash
# Read
$GAPI sheets get SHEET_ID "Sheet1!A1:D10"

# Write
$GAPI sheets update SHEET_ID "Sheet1!A1:B2" --values '[["Name","Score"],["Alice","95"]]'

# Append rows
$GAPI sheets append SHEET_ID "Sheet1!A:C" --values '[["new","row","data"]]'
```

### Docs

```bash
$GAPI docs get DOC_ID
```

## Output Format

All commands return JSON. Parse with `jq` or read directly. Key fields:

- **Gmail search**: `[{id, threadId, from, to, subject, date, snippet, labels}]`
- **Gmail get**: `{id, threadId, from, to, subject, date, labels, body}`
- **Gmail send/reply**: `{status: "sent", id, threadId}`
- **Calendar list**: `[{id, summary, start, end, location, description, htmlLink}]`
- **Calendar create**: `{status: "created", id, summary, htmlLink}`
- **Drive search**: `[{id, name, mimeType, modifiedTime, webViewLink}]`
- **Contacts list**: `[{name, emails: [...], phones: [...]}]`
- **Sheets get**: `[[cell, cell, ...], ...]`

## Rules

1. **Never send email or create/delete events without confirming with the user first.** Show the draft content and ask for approval.
2. **Check auth before first use** — run `setup.py --check`. If it fails, guide the user through setup.
3. **Use the Gmail search syntax reference** for complex queries — load it with `skill_view("google-workspace", file_path="references/gmail-search-syntax.md")`.
4. **Calendar times must include timezone** — always use ISO 8601 with offset (e.g., `2026-03-01T10:00:00-06:00`) or UTC (`Z`).
5. **Respect rate limits** — avoid rapid-fire sequential API calls. Batch reads when possible.

## Pitfalls

- **Image-extracted addresses**: When the recipient email comes from an image (screenshot, WhatsApp share, photo), OCR/vision can misread characters — e.g. `sanktmarien.at` read as `sanktmariaen.at`. Before sending, sanity-check the domain against known patterns (schools, companies, etc.) and confirm with the user if anything looks off. A wrong domain means the email goes into a black hole with no bounce.

## Troubleshooting

| Problem | Fix |
|---------|-----|
| `NOT_AUTHENTICATED` | Run setup Steps 2-5 above |
| `REFRESH_FAILED` | Token revoked or expired — redo Steps 3-5 |
| `HttpError 403: Insufficient Permission` | Missing API scope — `$GSETUP --revoke` then redo Steps 3-5 |
| `HttpError 403: Access Not Configured` | API not enabled — user needs to enable it in Google Cloud Console |
| `ModuleNotFoundError` | Run `$GSETUP --install-deps` |
| Advanced Protection blocks auth | Workspace admin must allowlist the OAuth client ID |
| Terminal tool blocks `&` in subject/body as backgrounding | False positive from the terminal sandbox — just re-run; it usually succeeds on the retry. If it persists, escape the `&` as `\&` or quote the entire `--body` string with single quotes instead of double quotes. |

## Revoking Access

```bash
$GSETUP --revoke
```

Setup needed before using this skill: missing file /DATA/AppData/hermes/google_client_secret.json, file /DATA/.hermes/google_token.json.


terminal

Output:
/DATA/.hermes/sessions/20260524_103301_1873b1.jsonl
/DATA/.hermes/sessions/20260524_093321_5787b8.jsonl
/DATA/.hermes/sessions/20260524_155521_467093.jsonl
/DATA/.hermes/sessions/20260524_103412_f5caca5b.jsonl
/DATA/.hermes/sessions/20260524_101704_4eec0e.jsonl
/DATA/.hermes/sessions/20260524_163025_d0bf93.jsonl
/DATA/.hermes/sessions/20260527_130528_66859312.jsonl
/DATA/.hermes/sessions/20260528_085605_f803e054.jsonl
/DATA/.hermes/sessions/20260524_164253_849645.jsonl
/DATA/.hermes/sessions/20260526_112341_7ea4040f.jsonl
/DATA/.hermes/sessions/20260525_104651_f6582a02.jsonl
/DATA/.hermes/sessions/20260526_123514_d3230e.jsonl
/DATA/.hermes/sessions/20260524_101256_e87b8b.jsonl
/DATA/.hermes/sessions/20260526_113615_b9fd55.jsonl
===
total 90380
-rw------- 1 az-a samba 129901 May 28 09:24 session_20260528_085605_f803e054.json
-rw------- 1 az-a samba   1000 May 28 09:13 sessions.json
-rw-r--r-- 1 az-a samba  68174 May 28 09:13 20260528_085605_f803e054.jsonl
-rw-r--r-- 1 az-a samba 207890 May 27 16:08 20260527_130528_66859312.jsonl


Explanation: Let me look at the most recent session (May 27) and today's session (May 28) to understand what "Google OAuth" task was being worked on.