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


Hallo


Hallo Chef! 👋 Wie kann ich dir heute helfen?

Explanation: The user just said "Hallo" (German for "Hello"). This is a simple greeting. I don't need any skills for this. I should greet them back warmly in German, as they're speaking German. The user prefers to be called "Boss" or "Chef".


Schau dir nochmal Print Vault an, irgendwie sieht das komisch aus, kannst du das bitte fixen


Explanation:
The user wants me to look at PrintVault and fix something that looks "komisch" (weird/strange). Let me first check what PrintVault is - I have it in memory as a CasaOS app. Let me load the relevant skill first and then investigate.

Let me start by checking the PrintVault deployment and seeing what's going on.


zimaos-web-app

---
name: zimaos-web-app
version: 1.0.0
description: Build small single-file web apps for ZimaOS using FastAPI + vanilla HTML/CSS/JS. Apple-inspired minimal design, mobile-optimized, no auth unless specified.
author: Kiwi
metadata:
  hermes:
    tags: [zimaos, web-app, fastapi, html, mobile]
---

# ZimaOS Web App

## Purpose
Build small, self-contained web applications that run on ZimaOS under `/DATA/AppData/hermes/projects/`. The pattern: one Python file (FastAPI backend + static serving) + one HTML file (frontend). Accessible from any device on the local network. No Docker, no Node.js, no build step.

## When to Use
Use when the user asks for a "small web app", "tool", "web-ui", or any browser-based utility that runs on their ZimaOS server.

## Design Rules (user preferences)

**UI Style (primary — Zeyd's blue glass-morphism style):**
- Blue color scheme: primary `#2563EB`, dark accent `#1E3A5F`, subtle gradients
- Glass-morphism cards: `background: rgba(255,255,255,0.7)`, `backdrop-filter: blur(12px)`, subtle border
- Dark header with blue accent, large stats with gradient text
- Mobile-first with safe-area insets (`env(safe-area-inset-*)`), viewport-fit=cover
- Bottom-sheet modals (slide-up from bottom, max-height 85vh)
- Rounded corners: cards 16-20px, buttons 12px
- Touch-friendly: minimum 44px tap targets, card `:active` scale feedback
- Smooth transitions: `cubic-bezier(0.25, 0.1, 0.25, 1)`
- Reference apps: DocMaster, DailyDose (style orientation)

**UI Style (alternative — Apple-inspired minimal):**
- SF Pro fonts, rounded corners (16px), subtle shadows, frosted glass header
- Color palette: background `#F2F2F7`, cards `#FFFFFF`, text `#1D1D1F`, blue `#007AFF`, green `#34C759`, red `#FF3B30`
- Use only when user explicitly requests Apple/light-minimal style

**Auth:**
- No authentication unless the user explicitly requests it
- If auth needed, use HTTP Basic Auth middleware (like DocMaster)

## Deployment Patterns

### Option A: Direct Python (quick dev)
Run via: `python main.py` (uses uvicorn in `__main__`).
Port: pick an unused port near 3000 (check with `ss -tlnp | grep 300`).

### Option B: Docker Container (production, user preference)
Use when the user wants a persistent container with CasaOS dashboard integration.

**Build (ZimaOS quirks):**
```bash
# ZimaOS has read-only /root/.docker — must use HOME=/tmp
# User az-a is NOT in docker group — always sudo
sudo env HOME=/tmp docker build -t <appname> /DATA/AppData/hermes/projects/<app>
```

**Deploy — choose pattern A or B:**

See *Two valid deployment patterns* below for complete instructions with correct hostname/icon conventions.

**Dockerfile (if needed):**
```dockerfile
FROM python:3.11-slim
RUN pip install --no-cache-dir fastapi uvicorn <extra-deps>
WORKDIR /app
COPY main.py .
COPY frontend/ frontend/
ENV MPLCONFIGDIR=/tmp/matplotlib  # if using matplotlib
EXPOSE <port>
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "<port>"]
```

## CasaOS Dashboard Integration

### "Derzeit nicht unterstützt" — Root Cause & Complete Fix

When clicking an app tile in CasaOS shows "Derzeit nicht unterstützt" (currently not supported), there are **two layers** to the fix. Apply both:

**Layer 1: CSP iframe middleware** — allow CasaOS to embed your app:
```python
@app.middleware("http")
async def add_frame_options(request: Request, call_next):
    """Allow iframe embedding for CasaOS dashboard."""
    response = await call_next(request)
    response.headers["X-Frame-Options"] = "ALLOWALL"
    response.headers["Content-Security-Policy"] = "frame-ancestors 'self' http://*:* https://*:*;"
    return response
```

**Layer 2: App type registration** — this is the REAL root cause. `zimaos-app-management` discovers containers by scanning Docker labels and compose files. It assigns an `app_type`:

- `container` — discovered via direct `docker run` (no `com.docker.compose.*` labels). Works. The gateway reads `casaos.*` Docker labels directly for routing.
- `v2app` — discovered via compose files with `com.docker.compose.project` labels. Works when a proper `x-casaos` extension block is present in the compose file. Without `x-casaos`, the service logs `error: "extension x-casaos not found"` → dashboard shows "Derzeit nicht unterstützt".

**Both patterns work:** `docker run` with `casaos.*` labels (Pattern A, no compose needed) OR compose file with `x-casaos` block (Pattern B). Never use compose WITHOUT `x-casaos`.

**Complete fix — switch from compose to docker run, then clean up app-management.json:**
```bash
# 1. Stop and remove compose-managed container
sudo docker stop <AppName> 2>/dev/null
sudo docker rm <AppName> 2>/dev/null

# 2. Start directly with casaos.* labels only (NO compose labels)
sudo docker run -d \
  --name <AppName> \
  --network bridge \
  --restart unless-stopped \
  -p <port>:<port> \
  -v /media/HDD_1TB/<data-dir>:/data \
  -e PORT=<port> \
  -l casaos.title="<App Name>" \
  -l casaos.description="<description>" \
  -l casaos.icon="http://localhost:<port>/icon.svg" \
  -l casaos.scheme="http" \
  -l casaos.hostname="" \
  -l casaos.port="<port>" \
  -l casaos.index="/" \
  -l casaos.category="Utilities" \
  <image-name>

# 3. Stop app-management, remove old v2app entries, restart
sudo systemctl stop zimaos-app-management
sudo python3 -c "
import json
with open('/etc/casaos/app-management.json') as f:
    apps = json.load(f)
# Remove old v2app entries by name AND old container hash entries
apps = [a for a in apps if a.get('name','') not in ('<appname>','<old-hash>')]
with open('/etc/casaos/app-management.json','w') as f:
    json.dump(apps, f, indent=2)
"
sudo systemctl start zimaos-app-management
sleep 5
sudo systemctl restart zimaos-gateway

# 4. Verify: both apps should now be type 'container'
sudo docker ps --format '{{.Names}} {{.Status}}' | grep -E '<AppName>'
# Also check no x-casaos errors in logs:
sudo journalctl -u zimaos-app-management --since "1 min ago" --no-pager | grep -i x-casaos
```

**Critical details:**
- Stop app-management BEFORE editing the JSON — the service overwrites it from memory on shutdown. Edit while stopped, then start.
- Remove ALL old entries for the app (both the `v2app` by name and any stale `container` entry by Docker hash ID). Otherwise duplicates appear.
- `zimaos-gateway` must be restarted after app-management to pick up the new routes. Gateway caches are the #1 cause of "fixed JSON but still shows error".
- This approach survives reboots — `docker run` with `--restart unless-stopped` re-launches the container with the same labels. No compose file needed.

**Verification — check the appgrid API:**
```bash
PORT=$(sudo ss -tlnp | grep zimaos-app-man | awk '{print $4}' | cut -d: -f2 | head -1)
curl -s http://127.0.0.1:$PORT/v2/app_management/web/appgrid | python3 -c "
import json,sys
for item in json.load(sys.stdin)['data']:
    if item.get('app_type') == 'container':
        print(item.get('title',{}).get('en_US','?'), '-> type:', item.get('app_type'))
"
```

### network_mode: bridge

Apps deployed via docker compose get isolated networks by default (e.g., `printvault_default` on 172.19.x). CasaOS can only reach containers on the default `bridge` network. Add to docker-compose.yml:
```yaml
    network_mode: bridge
```

### Two valid deployment patterns

**Pattern A: `container` type via `docker run` + `casaos.*` labels** — recommended for simple apps. Container is discovered via Docker daemon scanning and registered as `container` type. Routing data is read directly from Docker labels at gateway time — no compose file needed.

```bash
sudo docker run -d \
  --name <AppName> --network bridge --restart unless-stopped \
  -p <port>:<port> -e PORT=<port> \
  -l casaos.title="<App Name>" \
  -l casaos.icon="http://<SERVER_IP>:<port>/icon.svg" \
  -l casaos.scheme="http" \
  -l casaos.hostname="<SERVER_IP>" \
  -l casaos.port="<port>" \
  -l casaos.index="/" \
  -l casaos.category="Utilities" \
  <image-name>
```

**Pattern B: `v2app` type via `x-casaos` compose file** — for apps that need complex compose config (volumes, env files, depends_on). Place a `docker-compose.yml` in `/var/lib/casaos/apps/<StoreAppID>/` with an `x-casaos` top-level block. The service discovers it and registers as `v2app` type with all fields populated from the `x-casaos` block. **This works — the "never compose" rule below was wrong. See Pitfalls for the distinction.**

Example `/var/lib/casaos/apps/PrintVault/docker-compose.yml`:
```yaml
name: printvault
services:
  PrintVault:
    image: printvault
    network_mode: bridge
    container_name: PrintVault
    ports: ["3001:3001"]
    environment: [PORT=3001]
    restart: unless-stopped
x-casaos:
  author: self
  category: self
  hostname: ""    # empty = works everywhere (LAN, VPN, remote) — all official apps use this
  icon: http://192.168.178.171:3001/icon.svg
  index: /
  is_uncontrolled: false
  port_map: "3001"
  scheme: http
  store_app_id: printvault
  title:
    custom: PrintVault
```

**Pattern B deployment steps (proven working):**
```bash
# 1. Write compose file with x-casaos block (see template above)
sudo mkdir -p /var/lib/casaos/apps/<StoreAppID>
sudo tee /var/lib/casaos/apps/<StoreAppID>/docker-compose.yml << 'EOF'
# Top-level name must match store_app_id for discovery
name: <store-app-id>
services:
  ...
x-casaos:
  store_app_id: <store-app-id>
  ...
EOF

# 2. Stop app-management, start container via compose, restart service
sudo systemctl stop zimaos-app-management
cd /var/lib/casaos/apps/<StoreAppID> && sudo docker compose up -d
sudo systemctl start zimaos-app-management
sleep 6

# 3. Restart gateway (MANDATORY — routes are cached)
sudo systemctl restart zimaos-gateway
sleep 8

# 4. Verify the app appears in installed list
PORT=$(sudo ss -tlnp | grep zimaos-app-man | awk '{print $4}' | cut -d: -f2 | head -1)
curl -s "http://127.0.0.1:$PORT/v2/app_management/apps" | python3 -c "
import json,sys
data=json.load(sys.stdin)
print('Installed:', data['data']['installed'])
"
```

**Why compose without x-casaos fails:** Docker compose generates `com.docker.compose.*` labels even without an `x-casaos` block. These labels trigger `v2app` registration, but without the `x-casaos` extension the app-management service logs `error: "extension x-casaos not found"` → dashboard shows "Derzeit nicht unterstützt". The fix is either: (A) switch to `docker run` with only `casaos.*` labels, OR (B) add the proper `x-casaos` block to the compose file.

Manual edits to `/etc/casaos/app-management.json` are **reverted by the service on restart** because it regenerates the JSON from in-memory state. To clean up old entries: stop the service first (`sudo systemctl stop zimaos-app-management`), edit the JSON, then start.

Note: `title` in app-management.json is an i18n dict (e.g. `{"en_US": "PrintVault"}` or `{"custom": "PrintVault"}`), NOT a flat string — parse with `.get('en_US', '') or .get('custom', '')`, never cast directly. To verify app is registered, query the simpler `installed` list endpoint: `/v2/app_management/apps` → `data.installed` is a flat array of store_app_id strings.

### Icon & hostname — critical correctness

**`hostname` field determines iframe URL construction.** The CasaOS frontend uses it to build the URL that loads your app in an iframe:
- `hostname=""` (empty string) → frontend uses `window.location.hostname` (the same host the dashboard was accessed from) → works for both LAN and VPN/remote access ✅ (**RECOMMENDED** — all official apps like Plex, Immich, Komga use this)
- `hostname="localhost"` → frontend constructs `localhost:<port>` → resolves to **the client browser's machine**, NOT the ZimaOS server → blank page ❌
- `hostname="192.168.178.171"` (hardcoded LAN IP) → works on LAN but **breaks over VPN/remote access** (client browser can't reach the LAN IP through the VPN tunnel)
- `hostname="172.17.0.x"` (Docker bridge IP) → only reachable from within Docker network → fails from client browser

**Icon URL follows a different rule:** the icon must be reachable from the client browser. For LAN-only access, use the server's LAN IP (e.g. `http://192.168.178.171:<port>/icon.svg`). Over VPN, the LAN IP icon URL won't load — but the app still works (icon is cosmetic). If you need universal icon reachability, serve it through the gateway proxy or use a data URI. For simple apps, the LAN IP icon is fine.

For both patterns, determine server IP: `ip route get 1 2>/dev/null | awk '{print $7}' | head -1`

Serve a local SVG icon at `/icon.svg` (don't use external CDN links — they may fail on some ZimaOS builds):

```python
@app.get("/icon.svg")
def serve_icon():
    return FileResponse(FRONTEND_DIR / "icon.svg", media_type="image/svg+xml")
```

Then reference it with the server's LAN IP in your deployment labels/block: `casaos.icon: "http://<SERVER_IP>:<port>/icon.svg"` (see Icon & hostname section above for why localhost doesn't work).

## Project Structure

```
/DATA/AppData/hermes/projects/<app-name>/
├── main.py              # FastAPI app — all backend logic
└── frontend/
    └── index.html       # Single HTML file — inline CSS + JS
```

## FastAPI Backend Template

```python
"""
<App Name> — Description
FastAPI Backend + Static Frontend
"""
from pathlib import Path
from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.middleware.cors import CORSMiddleware

FRONTEND_DIR = Path(__file__).parent / "frontend"

app = FastAPI(title="<App Name>")
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])

@app.get("/")
def serve_frontend():
    return FileResponse(FRONTEND_DIR / "index.html")

@app.get("/api/stats")
def stats():
    return {"status": "ok"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=3001)
```

## Common API Patterns

Add to any media/file-library app's backend:

**File download endpoint:**
```python
@app.get("/api/download/{file_id}")
def download_file(file_id: str):
    file_path = STORAGE_DIR / f"{file_id}.<ext>"
    if not file_path.exists():
        raise HTTPException(404, "Datei nicht gefunden")
    meta = load_meta()
    display_name = meta.get(file_id, {}).get("name", file_id).replace(" ", "_") + ".<ext>"
    return FileResponse(file_path, media_type="application/octet-stream", filename=display_name)
```

## Frontend Skeleton

```html
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>App Name</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
  --blue: #007AFF; --red: #FF3B30; --green: #34C759;
  --bg: #F2F2F7; --card: #FFFFFF; --text: #1D1D1F; --secondary: #8E8E93;
  --radius: 16px; --radius-sm: 10px; --shadow-sm: 0 1px 3px rgba(0,0,0,0.06);
  --transition: 0.2s cubic-bezier(0.25, 0.1, 0.25, 1);
}
body {
  font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, sans-serif;
  background: var(--bg); color: var(--text); min-height: 100vh;
  -webkit-font-smoothing: antialiased;
}
header {
  position: sticky; top: 0;
  background: rgba(242,242,247,0.85);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(0,0,0,0.06);
  padding: 12px 20px;
}
.header-inner { max-width: 800px; margin: 0 auto; display: flex; justify-content: space-between; align-items: center; }
.header-inner h1 { font-size: 22px; font-weight: 700; letter-spacing: -0.3px; }
.content { max-width: 800px; margin: 0 auto; padding: 20px; }

/* Mobile grid */
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));
  gap: 14px;
}
@media (max-width: 400px) {
  .grid { grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px; }
}

/* Modal (slide-up, mobile style) */
.modal-overlay {
  position: fixed; inset: 0; background: rgba(0,0,0,0.3); z-index: 500;
  display: flex; align-items: flex-end; justify-content: center;
  backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px);
  animation: fadeIn 0.2s ease;
}
@keyframes fadeIn { from { opacity: 0; } }
@keyframes slideUp { from { transform: translateY(100%); } }
.modal {
  background: var(--card); border-radius: var(--radius) var(--radius) 0 0;
  width: 100%; max-width: 500px; max-height: 85vh; overflow-y: auto;
  animation: slideUp 0.3s cubic-bezier(0.32, 0.72, 0, 1);
  padding: 24px 20px 40px;
  -webkit-overflow-scrolling: touch;
}

/* Toast */
.toast {
  position: fixed; top: 20px; left: 50%; transform: translateX(-50%);
  background: var(--text); color: white; padding: 12px 24px;
  border-radius: 30px; font-size: 14px; font-weight: 500; z-index: 1000;
  animation: toastIn 0.3s ease, toastOut 0.3s ease 2s forwards;
}
@keyframes toastIn { from { opacity: 0; transform: translateX(-50%) translateY(-10px); } }
@keyframes toastOut { to { opacity: 0; transform: translateX(-50%) translateY(-10px); } }
/* ── Dark Mode ──────────────────────────── */
@media (prefers-color-scheme: dark) {
  :root {
    --bg: #1C1C1E; --card: #2C2C2E; --text: #FFFFFF; --secondary: #98989D;
    --border: rgba(255,255,255,0.08);
  }
  header { background: rgba(28,28,30,0.85); }
  .upload-box { border-color: rgba(255,255,255,0.12); }
  .upload-box:hover, .upload-box.drag-over { background: rgba(0,122,255,0.1); }
  .stat-card, .tag, .modal .close { background: #3A3A3C; }
  .search-box, .sort-btn, .field input, .field textarea { background: #3A3A3C; color: var(--text); }
  .btn-delete { background: rgba(255,59,48,0.15); color: #FF453A; }
  .card .thumb { background: #2C2C2E; }
  .modal .preview-large { background: #2C2C2E; }
  .toast { background: #3A3A3C; }
}
</style>
</head>
<body>
<header><div class="header-inner"><h1>📦 App Name</h1></div></header>
<div class="content">
  <!-- app content -->
</div>
</body>
</html>
```

### Full-width design (when user asks "nutze die gesamte Breite")

When the user requests full-width layout, the correct approach is:
- **Remove** `max-width: 800px` from `.header-inner`, `.controls`, `.upload-zone`, `.grid`
- **Keep** the natural 20px content padding (like `margin: 0 20px` or inherited from `header { padding: 12px 20px }`)
- **Do NOT** replace with `max-width: 100%` + larger fixed margins (like `32px`) — that creates awkward spacing on mobile and conflicts with the header's own padding, resulting in 52px total offset from the edge. User will say "Sieht irgendwie nicht richtig aus."
- The grid's `auto-fill` and card sizes already handle responsive width naturally — removing the max-width constraint is sufficient.

## Checklist

Before declaring done, verify:
- [ ] Port is free (`ss -tlnp`)
- [ ] `curl localhost:<port>/` returns HTML
- [ ] `curl localhost:<port>/api/stats` returns JSON
- [ ] Background process is running and not blocked on permissions
- [ ] HDD paths exist with correct ownership (`sudo mkdir` + `sudo chown az-a:users` if needed)
- [ ] Mobile viewport meta tag present
- [ ] No external CSS/JS dependencies (no CDN links)
- [ ] Toast notifications work
- [ ] Card :active feedback works on mobile

## Pitfalls

| Symptom | Cause | Fix |
|---------|-------|-----|
| `PermissionError` on `/media/HDD_1TB/` | Root-owned mount, user `az-a` can't write | `sudo mkdir -p <path>` + `sudo chown az-a:users <path>` |
| Port already in use | Another service | Pick next available (3002, 3003…) |
| Frontend not found (404) | Wrong FRONTEND_DIR path | Use `Path(__file__).parent / "frontend"` |
| `ImportError: Library "GL" not found` | pyglet needs OpenGL on headless ZimaOS | Use matplotlib with `Agg` backend for 3D thumbnails instead of `trimesh.scene.save_image()` |
| Matplotlib permission warning | Can't write `~/.config/matplotlib` | Set `MPLCONFIGDIR=/tmp` — harmless |
| Background process dies immediately | Module import error (missing dep) | Check `process log` for traceback |
| Docker build fails with `read-only file system` | ZimaOS has `/root/.docker` on read-only FS | For plain `docker build`: `sudo env HOME=/tmp docker build ...`. For `docker compose build`: `sudo env DOCKER_CONFIG=/tmp/docker-config docker compose build --no-cache`. The `HOME` variable alone is NOT sufficient for compose — `DOCKER_CONFIG` overrides where compose writes its config. Also: `sudo env` is required because `sudo` doesn't pass env vars and ZimaOS disallows `sudo -E` for env var propagation. |
| Docker build blocked (tool policy: "foreground command appears to start a long-lived server") | Build takes 90-180s which exceeds foreground threshold | Always use `background=true` + `notify_on_complete=true` for docker build. Check result with `process poll` after notification. |
| `docker compose up -d --wait` hangs or fails | Container has no healthcheck defined | Use plain `docker compose up -d` (without `--wait`). App-management will discover the running container on restart. |
| `curl -I` (HEAD) returns 405 on icon.svg or other static routes | FastAPI route handler (`@app.get`) only handles GET, not HEAD | Use `curl -s` (GET) for verification. The CasaOS frontend uses GET, not HEAD, so this is a testing-only issue. |
| `curl` returns nothing (exit code 7) | Container not ready yet | Wait 3-5s after `up -d`, then retry |
| "Derzeit nicht unterstützt" when clicking app tile | Container registered as `v2app` type without proper `x-casaos` extension. Docker compose generates `com.docker.compose.*` labels that trigger v2app registration, but without an `x-casaos` top-level block the service can't read routing fields. | Option A (simpler): redeploy via `docker run` with only `casaos.*` labels. Option B (full): add proper `x-casaos` block to the compose file with all required fields (hostname, icon, index, port_map, scheme, store_app_id, title). Stop app-management, deploy, restart. See full workflow above. |
| "Derzeit nicht unterstützt" or blank page when clicking app tile over VPN/remote access | **(1)** `hostname` is hardcoded to a LAN IP (e.g. `192.168.178.171`) that is unreachable through a VPN tunnel — the client browser can't resolve the LAN IP. **(2)** `hostname="localhost"` causes the frontend to resolve to the client machine instead of ZimaOS server. **(3)** `hostname="172.17.0.x"` (Docker bridge IP) is only reachable from inside Docker. | Set `hostname=""` (empty string) for universal compatibility — works on LAN, VPN, and remote. Every official CasaOS app (Plex, Immich, Komga, Audiobookshelf) ships with empty hostname. **This is the #1 VPN access bug** — user says "drücke drauf und komme nicht rein, bin über VPN". The JSON `app_type` field is NOT the issue (all apps are `v2app`). Check `hostname` first. Only hardcode the LAN IP in `casaos.icon` if you need the icon to display on the dashboard. |
| Codex CLI / Node.js install fails on ZimaOS | No apt/dnf/apk/yum/pacman on ZimaOS. Read-only `/usr/local`. Only way is manual tarball extract, then npm global installs hit permission errors. **Don't waste time** — if user says "lass das über Codex laufen" on ZimaOS, tell them Codex can't be installed here and offer to do the work directly instead. |\n| Next.js app blocked in iframe (blank page, console CSP error) | `next.config.ts` headers block framing: `X-Frame-Options: DENY` + `frame-ancestors 'none'` | Patch `next.config.ts` security headers: set `X-Frame-Options: ALLOWALL` and `frame-ancestors *`. Rebuild image, redeploy. |
| `ModuleNotFoundError: No module named 'scipy'` in trimesh | ZimaOS has no scipy. `trimesh.fix_normals()`, `split()`, `boolean difference`, and many advanced mesh operations import scipy internally. | Avoid `fix_normals()`, `split()`, and `Mesh.connected_components`. Use basic creation functions (`trimesh.creation.*`). For boolean ops, try `manifold3d` if available. The venv at `/DATA/AppData/hermes/venv` has trimesh+manifold3d but no scipy. |
| `docker inspect` shows empty `Config.Labels` | Container was started without labels | Redeploy via `docker run` with `-l` flags |
| JSON edit reverted after service restart | `zimaos-app-management` overwrites JSON from memory on shutdown | Stop service first (`sudo systemctl stop zimaos-app-management`), edit JSON, then start |
| `title` field shows as dict object, not string | `title` is i18n dict `{"en_US": "AppName"}` | Parse with `.get('en_US', '')`, never cast directly |
| App reappears as `v2app` after cleanup | Service re-discovers compose-managed container with `com.docker.compose.*` labels | Redeploy via `docker run` (step 2 of fix pipeline) — compose labels are sticky |

## Reference Apps

- **PrintVault** — `/DATA/AppData/hermes/projects/printvault/` — STL library with upload, trimesh analysis, matplotlib thumbnails, tag management
- **DocMaster** — inspiration for port pattern (3000 + Next.js), file-on-HDD storage, optional Basic Auth

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


Explanation: The user wants me to look at PrintVault and fix it because it looks "komisch" (weird). Let me check the current state of PrintVault - the app files, the Docker container status, and how it appears in CasaOS.

from hermes_tools import terminal

# Check current PrintVault container status
print("=== Container Status ===")
print(terminal("sudo docker ps -a --filter name=PrintVault --format '{{.ID}} {{.Names}} {{.Status}} {{.Ports}} {{.Labels}}'"))

print("\n=== CasaOS app-management.json ===")
print(terminal("sudo python3 -c \"import json; apps=json.load(open('/etc/casaos/app-management.json')); [print(json.dumps(a, indent=2)) for a in apps if 'printvault' in str(a).lower() or 'PrintVault' in str(a).lower()]\""))


Output:
=== Container Status ===
{'output': '923d4bb1a036 PrintVault Up 36 minutes 0.0.0.0:3001->3001/tcp, :::3001->3001/tcp com.docker.compose.service=printvault,com.docker.compose.version=2.32.4,casaos.title=PrintVault,com.docker.compose.config-hash=c045445e7ecf8f9db59fce78a66f849c06ca37a00366d09beef89ae99555a12e,com.docker.compose.project.working_dir=/var/lib/casaos/apps/PrintVault,casaos.port=3001,casaos.description=STL-Bibliothek mit automatischer Analyse,casaos.index=/,casaos.scheme=http,com.docker.compose.image=sha256:1698f1826adf2d452223a625c9776a6490c0302b19616762a3100ac0452a6514,com.docker.compose.oneoff=False,com.docker.compose.project.config_files=/var/lib/casaos/apps/PrintVault/docker-compose.yml,casaos.category=Utilities,casaos.icon=http://localhost:3001/icon.svg,com.docker.compose.container-number=1,com.docker.compose.depends_on=,com.docker.compose.project=printvault,casaos.hostname=', 'exit_code': 0, 'error': None}

=== CasaOS app-management.json ===
{'output': '{\n  "app_type": "v2app",\n  "author_type": "unknown",\n  "is_uncontrolled": false,\n  "name": "printvault",\n  "title": {\n    "en_US": "printvault"\n  }\n}', 'exit_code': 0, 'error': None}


Explanation:
Let me analyze what's going on with PrintVault:

1. Container is running as "PrintVault" - status is "Up 36 minutes" on port 3001
2. It has `com.docker.compose.*` labels, meaning it was started via docker compose
3. In app-management.json, it's registered as `"app_type": "v2app"` with `"name": "printvault"` and `"title": {"en_US": "printvault"}`

The problem is clear:
- The container has compose labels (`com.docker.compose.*`) which triggers v2app registration
- But the app-management.json entry has NO `x-casaos` extension data — that's why the title is just "printvault" (lowercase from compose project name) instead of "PrintVault"
- The icon is `http://localhost:3001/icon.svg` — localhost won't work from the client browser (the user is on a different device)
- The hostname is empty — that's good for the hostname field

Wait, let me check the actual compose file to see if it has the `x-casaos` block.

terminal

curl -s http://localhost:3001/ 2>&1 | head -20

curl -s http://localhost:3001/icon.svg 2>&1 | head -5


     1|name: printvault
     2|services:
     3|  printvault:
     4|    build: .
     5|    container_name: PrintVault
     6|    ports:
     7|      - "3001:3001"
     8|    volumes:
     9|      - /media/HDD_1TB/STL_Bibliothek:/data
    10|    environment:
    11|      - DATA_DIR=/data
    12|    restart: unless-stopped
    13|    network_mode: bridge
    14|    labels:
    15|      casaos.title: "PrintVault"
    16|      casaos.description: "STL-Bibliothek mit automatischer Analyse"
    17|      casaos.icon: "http://localhost:3001/icon.svg"
    18|      casaos.scheme: "http"
    19|      casaos.hostname: ""
    20|      casaos.port: "3001"
    21|      casaos.index: "/"
    22|      casaos.category: "Utilities"
    23|


Output:
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>PrintVault</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

:root {
  --blue: #007AFF;
  --red: #FF3B30;
  --green: #34C759;
  --orange: #FF9500;
  --bg: #F2F2F7;
  --card: #FFFFFF;
  --text: #1D1D1F;
  --secondary: #8E8E93;
  --border: rgba(0,0,0,0.06);
  --shadow-sm: 0 1px 3px rgba(0,0,0,0.06);


Output:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
  <defs>
    <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
      <stop offset="0%" stop-color="#2563EB"/>
      <stop offset="100%" stop-color="#1D4ED8"/>


Genau — das Problem ist klar. Die `docker-compose.yml` hat die `casaos.*` Labels, aber **keinen `x-casaos` Block**. Dadurch registriert `zimaos-app-management` den Container als `v2app`, findet aber keine Routing-Infos → "Derzeit nicht unterstützt".

Ich fixe das jetzt:

Explanation:
Let me analyze the situation:

1. **Container**: PrintVault is running fine on port 3001, app is accessible
2. **Compose file**: Has `casaos.*` labels BUT no `x-casaos` block — this is the problem!
3. **app-management.json**: Registered as `v2app` type with `"title": {"en_US": "printvault"}` — lowercase, wrong

The problem is clear: The compose file uses `casaos.*` Docker labels but NO `x-casaos` top-level block. According to the skill:
- Docker compose generates `com.docker.compose.*` labels → triggers `v2app` registration
- Without `x-casaos` block → app-management logs `"extension x-casaos not found"` → shows "Derzeit nicht unterstützt"

The fix: Add the proper `x-casaos` block to the compose file. This is Pattern B from the skill.

According to the skill, Pattern B works — the "never compose" rule was wrong. Let me add the proper `x-casaos` block.

Let me also check:
- `casaos.hostname=""` ✓ (empty is correct)
- `casaos.icon="http://localhost:3001/icon.svg"` — this should use the server's LAN IP, not localhost

Let me get the server IP and fix both issues.

Steps:
1. Get server LAN IP
2. Add `x-casaos` block to compose file
3. Stop app-management, rebuild/restart container
4. Start app-management, restart gateway
5. Verify

ip route get 1 2>/dev/null | awk '{print $7}' | head -1


Explanation:
The problem is clear: the docker-compose.yml has casaos.* labels but no x-casaos block. The container gets registered as v2app type but without routing information. I need to:

1. Stop app-management
2. Update the docker-compose.yml to add x-casaos block
3. Rebuild and redeploy the container
4. Restart app-management and gateway

Let me also fix the icon URL — currently it's `http://localhost:3001/icon.svg` which won't work from the client browser. Should be the server IP.

Let me write the updated compose file with x-casaos block.

sudo systemctl stop zimaos-app-management


Explanation:
The issue is that the docker-compose.yml has casaos labels but no x-casaos block. The app-management service discovers the container via compose labels, registers it as v2app, but can't find routing info because there's no x-casaos extension. I need to add the x-casaos block to the compose file.

Let me write the updated compose file with the x-casaos block.

name: printvault
services:
  printvault:
    build: .
    container_name: PrintVault
    ports:
      - "3001:3001"
    volumes:
      - /media/HDD_1TB/STL_Bibliothek:/data
    environment:
      - DATA_DIR=/data
    restart: unless-stopped
    network_mode: bridge

x-casaos:
  author: self
  category: self
  hostname: ""
  icon: http://192.168.178.171:3001/icon.svg
  index: /
  is_uncontrolled: false
  port_map: "3001"
  scheme: http
  store_app_id: printvault
  title:
    custom: PrintVault


Failed to write file: /usr/bin/bash: line 3: /var/lib/casaos/apps/PrintVault/docker-compose.yml: Permission denied


Explanation: The write failed because of permission denied. I need to use sudo to write the file. Let me use a different approach - pipe the content with sudo tee.

sudo tee /var/lib/casaos/apps/PrintVault/docker-compose.yml << 'EOF'
name: printvault
services:
  printvault:
    build: .
    container_name: PrintVault
    ports:
      - "3001:3001"
    volumes:
      - /media/HDD_1TB/STL_Bibliothek:/data
    environment:
      - DATA_DIR=/data
    restart: unless-stopped
    network_mode: bridge

x-casaos:
  author: self
  category: self
  hostname: ""
  icon: http://192.168.178.171:3001/icon.svg
  index: /
  is_uncontrolled: false
  port_map: "3001"
  scheme: http
  store_app_id: printvault
  title:
    custom: PrintVault
EOF


Output:
name: printvault
services:
  printvault:
    build: .
    container_name: PrintVault
    ports:
      - "3001:3001"
    volumes:
      - /media/HDD_1TB/STL_Bibliothek:/data
    environment:
      - DATA_DIR=/data
    restart: unless-stopped
    network_mode: bridge

x-casaos:
  author: self
  category: self
  hostname: ""
  icon: http://192.168.178.171:3001/icon.svg
  index: /
  is_uncontrolled: false
  port_map: "3001"
  scheme: http
  store_app_id: printvault
  title:
    custom: PrintVault


Jetzt noch die alten Einträge aus `app-management.json` entfernen, Container neu bauen und Services starten:

Explanation: Now I need to clean up the old entries from app-management.json, rebuild the container, and restart the services.

sudo python3 -c "
import json
with open('/etc/casaos/app-management.json') as f:
    apps = json.load(f)
before = len(apps)
apps = [a for a in apps if 'printvault' not in str(a.get('name','')).lower() and 'PrintVault' not in str(a.get('title','')).lower()]
after = len(apps)
print(f'Removed {before - after} entries')
with open('/etc/casaos/app-management.json','w') as f:
    json.dump(apps, f, indent=2)
"


Output: Removed 1 entries


Explanation: Now I need to rebuild the container and redeploy. Let me also rebuild the image since we changed the compose file.

cd /var/lib/casaos/apps/PrintVault && sudo env DOCKER_CONFIG=/tmp/docker-config docker compose down 2>&1


Output:
Container PrintVault  Stopping
 Container PrintVault  Stopped
 Container PrintVault  Removing
 Container PrintVault  Removed


Explanation:
The container was stopped and removed. Now I need to rebuild the image and bring it back up. According to the skill, for compose builds on ZimaOS I need `sudo env DOCKER_CONFIG=/tmp/docker-config docker compose build --no-cache`. And since builds take 90-180s, I should use background=true + notify_on_complete=true. But wait - actually the image already exists. Let me check - the old compose had `build: .` and the new one also has `build: .` - I could just do `up -d` since we haven't changed the source code. But to be safe and ensure a clean state, let me rebuild. Let me bring it up first and see.

Actually, let me just do `docker compose up -d` - we only changed the compose file, not the app code. The image should still be there from the previous build.

cd /var/lib/casaos/apps/PrintVault && sudo env DOCKER_CONFIG=/tmp/docker-config docker compose up -d 2>&1


This foreground command appears to start a long-lived server/watch process. Run it with background=true, verify readiness (health endpoint/log signal), then execute tests in a separate command.


Explanation: The `docker compose up -d` should return immediately since it's detached mode, but the system is detecting it as a long-lived server. Let me try running it with background=true and notify_on_complete=true as suggested.


Output: Background process started


Explanation: The docker compose up -d completed. Now I need to start zimaos-app-management and restart the gateway.


process

Output:
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified

 ____  __  _  _   __      __   ____
(__  )(  )( \/ ) / _\    /  \ / ___)
 / _/  )( / \/ \/    \  (  O )\___ \
(____)(__)\_)(_/\_/\_/   \__/ (____/

─── Welcome to Zima OS, az-a ───
Date: Monday, May 18, 2026 | Uptime: up 13 hours, 25 minutes

 Container PrintVault  Creating
 Container PrintVault  Created
 Container PrintVault  Starting
 Container PrintVault  Started


Explanation: Container is up. Now let me restart app-management and gateway to pick up the new registration.

terminal

sudo systemctl start zimaos-app-management && sleep 6 && echo "app-management gestartet"


Output: app-management gestartet


Explanation: The PrintVault container is now running. Let me verify everything is working properly — check the API, verify the CasaOS registration, restart gateway, etc.

PORT=$(sudo ss -tlnp | grep zimaos-app-man | awk '{print $4}' | cut -d: -f2 | head -1); echo "App-Management-Port: $PORT"; curl -s "http://127.0.0.1:$PORT/v2/app_management/apps" | python3 -c "import json,sys; d=json.load(sys.stdin); print('Installed:', d['data']['installed'])"


Output:
App-Management-Port: 43239
Installed: ['docmaster', 'immich', 'audiobookshelf', 'breathtaking_maryann', 'printvault', 'fervent_james', 'komga', 'noble_andres', 'openclaw', 'plex']


Explanation: PrintVault ist jetzt in der installed-Liste. Jetzt noch Gateway neustarten und dann die Appgrid-API prüfen.

sudo systemctl restart zimaos-gateway && sleep 8 && echo "Gateway neugestartet"


Output: Gateway neugestartet


Explanation: Let me verify everything is working correctly now.

from hermes_tools import terminal

# Verify container is running
print("=== Container Status ===")
print(terminal("sudo docker ps --filter name=PrintVault --format '{{.Names}} {{.Status}}'"))

# Check app-management JSON for PrintVault
print("\n=== App-Management Eintrag ===")
result = terminal("sudo python3 -c \"import json; apps=json.load(open('/etc/casaos/app-management.json')); [print(json.dumps(a, indent=2)) for a in apps if 'printvault' in str(a.get('name','')).lower() or 'PrintVault' in str(a.get('title','')).lower()]\"")

# Also check appgrid
PORT = terminal("sudo ss -tlnp | grep zimaos-app-man | awk '{print $4}' | cut -d: -f2 | head -1").output.strip()
print(f"\n=== AppGrid (port={PORT}) ===")
print(terminal(f"curl -s http://127.0.0.1:{PORT}/v2/app_management/web/appgrid | python3 -c \"import json,sys; [print(item.get('title',{}).get('custom',item.get('title',{}).get('en_US','?')), '-> type:', item.get('app_type')) for item in json.load(sys.stdin)['data'] if 'print' in str(item).lower()]\""))


Output:
--- stderr ---
  File "/tmp/hermes_sandbox_gssruinz/script.py", line 15
    print(terminal(f"curl -s http://127.0.0.1:{PORT}/v2/app_management/web/appgrid | python3 -c \"import json,sys; [print(item.get('title',{}).get('custom',item.get('title',{}).get('en_US','?')), '-> type:', item.get('app_type')) for item in json.load(sys.stdin)['data'] if 'print' in str(item).lower()]\""))
                                                                                ^
SyntaxError: f-string: empty expression not allowed

  File "/tmp/hermes_sandbox_gssruinz/script.py", line 15
    print(terminal(f"curl -s http://127.0.0.1:{PORT}/v2/app_management/web/appgrid | python3 -c \"import json,sys; [print(item.get('title',{}).get('custom',item.get('title',{}).get('en_US','?')), '-> type:', item.get('app_type')) for item in json.load(sys.stdin)['data'] if 'print' in str(item).lower()]\""))
                                                                                ^
SyntaxError: f-string: empty expression not allowed


Explanation: Bash escaping got messy in execute_code. Let me just use direct terminal calls instead.

sudo docker ps --filter name=PrintVault --format '{{.Names}} {{.Status}} {{.Labels}}'

sudo python3 -c "
import json
with open('/etc/casaos/app-management.json') as f:
    apps = json.load(f)
for a in apps:
    if 'printvault' in str(a.get('name','')).lower() or 'PrintVault' in str(a.get('title','')).lower():
        print(json.dumps(a, indent=2))
"

sys_port=$(sudo ss -tlnp | grep zimaos-app-man | awk '{print $4}' | cut -d: -f2 | head -1) && curl -s "http://127.0.0.1:$sys_port/v2/app_management/web/appgrid" | python3 -c "
import json,sys
for item in json.load(sys.stdin)['data']:
    t = item.get('title',{})
    title = t.get('custom', t.get('en_US','?'))
    if 'print' in str(item).lower() or 'PrintVault' in str(item).lower():
        print(title, '-> type:', item.get('app_type'))
"


Output:
{
  "app_type": "v2app",
  "author_type": "community",
  "hostname": "",
  "icon": "http://192.168.178.171:3001/icon.svg",
  "image": "",
  "index": "/",
  "is_uncontrolled": false,
  "name": "printvault",
  "port": "3001",
  "scheme": "http",
  "status": "running",
  "store_app_id": "printvault",
  "title": {
    "custom": "PrintVault"
  }
}


Output: PrintVault -> type: v2app


✅ **PrintVault ist gefixt!** Das Problem war die `docker-compose.yml` — sie hatte nur die `casaos.*` Labels im Container, aber keinen `x-casaos` Block auf Top-Level. `zimaos-app-management` hat den Container deshalb als `v2app` registriert, konnte aber keine Routing-Infos auslesen → "Derzeit nicht unterstützt" beim Klick.

**Was ich gemacht hab:**
1. `x-casaos` Block mit allen Feldern (`hostname`, `icon`, `port_map`, `scheme`, `store_app_id`, `title`) hinzugefügt
2. Alten Eintrag aus `app-management.json` entfernt
3. Container neu gestartet via Compose
4. `app-management` + `gateway` neugestartet

Jetzt zeigt der App-Management-Eintrag:
- `hostname: ""` — funktioniert über LAN, VPN und Remote ✓
- `title: "PrintVault"` ✓
- `status: "running"` ✓

Probier's mal aus — sollte jetzt normal aufgehen! 🚀

Explanation:
Alles ist jetzt korrekt. Der app-management.json Eintrag zeigt:

- `hostname: ""` ✓ (funktioniert überall)
- `icon: "http://192.168.178.171:3001/icon.svg"` ✓
- `title: {custom: "PrintVault"}` ✓
- `app_type: "v2app"` ✓ (mit korrektem x-casaos Block)
- `status: "running"` ✓

Die App erscheint in "installed" und im AppGrid mit allen korrekten Feldern. Das Problem war: die docker-compose.yml hatte die casaos.* Labels, aber keinen x-casaos Block. app-management hat daraus einen v2app Eintrag ohne Routing-Infos gemacht → "Derzeit nicht unterstützt".

Jetzt mit dem x-casaos Block hat app-management alle Felder korrekt geparst. Gateway ist neugestartet.

Ich melde Chef dass es fertig ist.


Die App funktioniert aber sie sieht nicht gut aus, da ist irgendwas komisch


Explanation: The user says the app works but doesn't look good - something looks weird. Let me look at the app from the browser perspective. I need to check what's going on with the frontend. Let me look at the PrintVault frontend HTML and the app itself.

from hermes_tools import terminal

# Check the full frontend HTML
print("=== index.html first 100 lines ===")
print(terminal("wc -l /DATA/AppData/hermes/projects/printvault/frontend/index.html"))

print("\n=== main.py ===")
print(terminal("head -40 /DATA/AppData/hermes/projects/printvault/main.py"))


Output:
=== index.html first 100 lines ===
{'output': '707 /DATA/AppData/hermes/projects/printvault/frontend/index.html', 'exit_code': 0, 'error': None}

=== main.py ===
{'output': '"""\nPrintVault — STL-Bibliothek für ZimaOS\nFastAPI Backend + Static Frontend\n"""\n\nimport json\nimport os\nimport uuid\nimport shutil\nimport time\nfrom pathlib import Path\nfrom datetime import datetime\nfrom typing import Optional\n\nfrom fastapi import FastAPI, File, UploadFile, HTTPException, Query, Request\nfrom fastapi.responses import FileResponse, JSONResponse, HTMLResponse\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.middleware.cors import CORSMiddleware\nimport trimesh\nimport numpy as np\n\n# ── Konfiguration ──────────────────────────────────────────\n\nBASE_DIR = Path(os.environ.get("DATA_DIR", "/media/HDD_1TB/STL_Bibliothek"))\nSTL_DIR = BASE_DIR / "stls"\nTHUMB_DIR = BASE_DIR / "thumbs"\nMETA_FILE = BASE_DIR / "metadata.json"\n\nBASE_DIR.mkdir(parents=True, exist_ok=True)\nSTL_DIR.mkdir(parents=True, exist_ok=True)\nTHUMB_DIR.mkdir(parents=True, exist_ok=True)\n\napp = FastAPI(title="PrintVault", version="1.0.0")\n\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=["*"],\n    allow_methods=["*"],\n    allow_headers=["*"],\n)', 'exit_code': 0, 'error': None}


Explanation:
The user says the app works but doesn't look good — something looks off. I need to look at the frontend more carefully to understand what might be visually broken. Let me check the CSS and look for issues. I should also check if the app renders properly by looking at the actual HTML structure and CSS.

Let me think about what "komisch" could mean:
1. Maybe the CSS is broken after the compose rebuild?
2. Maybe the dark mode doesn't work right?
3. Maybe the layout is off?

Let me read the full frontend HTML to check for issues.


{"content": "     1|<!DOCTYPE html>\n     2|\n     3|\n     4|<meta charset=\"UTF-8\">\n     5|<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">\n     6|<title>PrintVault</title>\n     7|\n   420|\n   421|\n   422|\n   423|\n   424|\n   425|
\n   426|
📦 PrintVault
\n   427|
\n   428|       0 druckbar\n   429|      0 Modelle\n   430|
\n   431|
\n   432|\n   433|\n   434|\n   435|
\n   436|  <input type=\"text\" class=\"search-box\" placeholder=\"Suchen…\" id=\"search\" oninput=\"loadFiles()\">\n   437|  <select class=\"sort-btn\" id=\"sort\" onchange=\"loadFiles()\">\n   438|    <option value=\"date\">Neueste</option>\n   439|    <option value=\"name\">Name</option>\n   440|    <option value=\"size\">Größe</option>\n   441|    <option value=\"volume\">Volumen</option>\n   442|  </select>\n   443|
\n   444|\n   445|\n   446|
\n   447|  \n   448|
⬆
\n   449|
STL hochladen
\n   450|
Drag & Drop oder tippen
\n   451|    <input type=\"file\" accept=\".stl\" id=\"fileInput\" onchange=\"uploadFile(this)\">\n   452|  \n   453|
\n   454|\n   455|\n   456|
\n   457|

\n   458|
\n   459|\n   460|\n   461|

\n   462|\n   463|\n   464|


Explanation: Let me look at a screenshot or what the app looks like to understand the visual issue. Let me open it in a browser or take a screenshot.


501|    toast('Nur .stl-Dateien erlaubt');
   502|    return;
   503|  }
   504|  const form = new FormData();
   505|  form.append('file', file);
   506|  try {
   507|    const res = await fetch(API + '/upload', { method: 'POST', body: form });
   508|    if (!res.ok) throw new Error();
   509|    toast('✅ Hochgeladen & analysiert!');
   510|    loadFiles();
   511|  } catch { toast('Fehler beim Upload'); }
   512|}
   513|
   514|// ── Load Files ────────────────────────────────────
   515|async function loadFiles() {
   516|  const search = document.getElementById('search').value;
   517|  const sort = document.getElementById('sort').value;
   518|  const url = API + '/files?sort=' + sort + '&search=' + encodeURIComponent(search);
   519|
   520|  const res = await fetch(url);
   521|  currentFiles = await res.json();
   522|  renderGrid();
   523|
   524|  // Stats
   525|  fetch(API + '/stats')
   526|    .then(r => r.json())
   527|    .then(s => {
   528|      document.getElementById('stat-ok').textContent = s.watertight;
   529|      document.getElementById('stat-total').textContent = s.total_files;
   530|    });
   531|}
   532|
   533|function renderGrid() {
   534|  const grid = document.getElementById('grid');
   535|  if (currentFiles.length === 0) {
   536|    grid.innerHTML = `

   537|
📦

   538|
Noch keine Modelle

   539|
`;
   540|    return;
   541|  }
   542|  grid.innerHTML = currentFiles.map(f => `
   543|

   544|

   545|        ${f.has_thumb
   546|          ? `<img src="${API}/thumbs/${f.id}.png" style="width:100%;height:100%;object-fit:cover;border-radius:0" loading="lazy">`
   547|          : '🔷'}
   548|

   549|

   550|
${esc(f.name)}

   551|

   552|          ${f.analysis.volume_cm3 ? f.analysis.volume_cm3 + ' cm³' : '—'}
   553|
   554|            ${f.analysis.watertight ? '✓ druckbar' : '⚠ offen'}
   555|
   556|

   557|

   558|

   559|  `).join('');
   560|}
   561|
   562|function esc(s) {
   563|  const d = document.createElement('div');
   564|  d.textContent = s;
   565|  return d.innerHTML;
   566|}
   567|
   568|// ── Detail Modal ─────────────────────────────────
   569|async function openDetail(id) {
   570|  const res = await fetch(API + '/files/' + id);
   571|  const f = await res.json();
   572|  const a = f.analysis;
   573|
   574|  const overlay = document.createElement('div');
   575|  overlay.className = 'modal-overlay';
   576|  overlay.onclick = e => { if (e.target === overlay) overlay.remove(); };
   577|
   578|  const dims = a.width_mm ? `${a.width_mm} × ${a.depth_mm} × ${a.height_mm} mm` : '—';
   579|
   580|  overlay.innerHTML = `
   581|

   582|    <button class="close" onclick="this.closest('.modal-overlay').remove()">✕</button>
   583|
${esc(f.name)}

   584|    ${f.has_thumb
   585|      ? `<img src="${API}/thumbs/${f.id}.png" class="preview-large">`
   586|      : '
🔷
'}
   587|

   588|

   589|
Maße

   590|
${dims}

   591|

   592|

   593|
Volumen

   594|
${a.volume_cm3 ? a.volume_cm3 + ' cm³' : '—'}

   595|

   596|

   597|
Filament (PLA)

   598|
${a.filament_grams ? a.filament_grams + ' g' : '—'}

   599|

   600|

   601|
Polygone

   602|
${a.faces?.toLocaleString() || '—'}

   603|

   604|

   605|
Wasserfest

   606|
${a.watertight ? '✅ Ja' : '❌ Nein'}

   607|

   608|

   609|
Manifold

   610|
${a.manifold ? '✅ Ja' : '⚠ Nein'}

   611|

   612|

   613|
   614|

   615|      Name
   616|      <input type="text" id="edit-name" value="${esc(f.name)}">
   617|

   618|

   619|      Tags
   620|

   621|        ${(f.tags || []).map(t => `<span class="tag">${esc(t)} <span class="remove" onclick="removeTag('${f.id}', '${esc(t)}')">×</span></span>`).join('')}
   622|

   623|

   624|        <input type="text" id="tag-input" placeholder="Tag hinzufügen…">
   625|        <button onclick="addTag('${f.id}')">+</button>
   626|

   627|

   628|

   629|      Notiz
   630|      <textarea id="edit-note">${esc(f.note || '')}</textarea>
   631|

   632|

   633|      <button class="btn-delete" onclick="deleteFile('${f.id}')">🗑 Löschen</button>
   634|      <button class="btn-save" onclick="saveFile('${f.id}')">Speichern</button>
   635|

   636|
`;
   637|  document.body.appendChild(overlay);
   638|
   639|  // Save tag input on Enter
   640|  document.getElementById('tag-input').addEventListener('keydown', e => {
   641|    if (e.key === 'Enter') addTag(f.id);
   642|  });
   643|}
   644|
   645|async function saveFile(id) {
   646|  const body = {
   647|    name: document.getElementById('edit-name').value,
   648|    note: document.getElementById('edit-note').value,
   649|  };
   650|  await fetch(API + '/files/' + id, {
   651|    method: 'PATCH',
   652|    headers: { 'Content-Type': 'application/json' },
   653|    body: JSON.stringify(body),
   654|  });
   655|  toast('Gespeichert ✅');
   656|  document.querySelector('.modal-overlay')?.remove();
   657|  loadFiles();
   658|}
   659|
   660|async function deleteFile(id) {
   661|  if (!confirm('Wirklich löschen?')) return;
   662|  await fetch(API + '/files/' + id, { method: 'DELETE' });
   663|  toast('Gelöscht 🗑');
   664|  document.querySelector('.modal-overlay')?.remove();
   665|  loadFiles();
   666|}
   667|
   668|async function addTag(id) {
   669|  const input = document.getElementById('tag-input');
   670|  const tag = input.value.trim();
   671|  if (!tag) return;
   672|  const res = await fetch(API + '/files/' + id);
   673|  const f = await res.json();
   674|  const tags = [...(f.tags || []), tag];
   675|  await fetch(API + '/files/' + id, {
   676|    method: 'PATCH',
   677|    headers: { 'Content-Type': 'application/json' },
   678|    body: JSON.stringify({ tags }),
   679|  });
   680|  input.value = '';
   681|  document.querySelector('.modal-overlay')?.remove();
   682|  openDetail(id);
   683|}
   684|
   685|async function removeTag(id, tag) {
   686|  const res = await fetch(API + '/files/' + id);
   687|  const f = await res.json();
   688|  const tags = (f.tags || []).filter(t => t !== tag);
   689|  await fetch(API + '/files/' + id, {
   690|    method: 'PATCH',
   691|    headers: { 'Content-Type': 'application/json' },
   692|    body: JSON.stringify({ tags }),
   693|  });
   694|  document.querySelector('.modal-overlay')?.remove();
   695|  openDetail(id);
   696|}
   697|
   698|// ── Init ────────────────────────────────────────
   699|loadFiles();
   700|
   701|// Reload on visibility change (tab switch)
   702|document.addEventListener('visibilitychange', () => {
   703|  if (!document.hidden) loadFiles();
   704|});
   705|</script>
   706|
   707|
   708|


Explanation:
The user says the app doesn't look good — "irgendwas komisch". Let me check what the current deployed version looks like. The issue might be that the container wasn't rebuilt after changes were made to the project files. Let me check the Dockerfile and the main.py to see if the CSP middleware and icon endpoint are present.

Let me also check if the container needs a rebuild. The memory says PrintVault uses Pattern B (x-casaos block), image is `printvault-printvault`. The rebuild workflow is: cp files to /var/lib/casaos/apps/PrintVault/, then sudo env DOCKER_CONFIG=/tmp/docker-config docker compose build --no-cache && docker compose up -d.

But first, let me look at the actual problem. The user says it "looks weird". Let me check:

1. Is the CSP middleware in main.py?
2. Is the icon endpoint there?
3. Does the frontend look correct?

Let me also check if perhaps the issue is that the container image is old and needs rebuilding. The compose file uses `build: .` so it's building from the directory. But when we just did `docker compose up -d` without rebuild, it used the old image.

Wait, let me re-read the compose file. It has `build: .` — but the compose file at `/var/lib/casaos/apps/PrintVault/docker-compose.yml` builds from that directory. Where are the actual project files? They're at `/DATA/AppData/hermes/projects/printvault/`. Are they also at `/var/lib/casaos/apps/PrintVault/`?

Let me check if the files are synced. The memory says: "cp files to /var/lib/casaos/apps/PrintVault/, then sudo env DOCKER_CONFIG=/tmp/docker-config docker compose build --no-cache && docker compose up -d."

So I need to check if the files at `/var/lib/casaos/apps/PrintVault/` are up to date with `/DATA/AppData/hermes/projects/printvault/`.

But actually, the user is saying the app looks bad — maybe it's a design issue. Let me look at the frontend more carefully. The issue could be:
1. The header has `max-width: none` and `margin: 0` which is different from the template
2. Maybe the dark mode isn't set up properly
3. Maybe there are visual glitches

Actually, let me first check what exact state the deployed container has vs the project files. Let me also check if there are changes needed. Let me look at the main.py to see if CSP middleware is there, and check the full source.

Let me take a step back. The user says "sieht nicht gut aus, da ist irgendwas komisch." I should:
1. Check what's currently deployed
2. Check what's in the project dir
3. Compare and identify issues

Let me look at main.py and Dockerfile, then check if the container was rebuilt properly, and look at the actual visual issues.