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


Claude Code Ist eigentlich ein Harness. Erkläre mir das bitte


Gute Frage, Boss. Der Begriff "Harness" ist hier sehr treffend. Lass es mich aufdröseln:

## Was ein Harness ist

Ein **Harness** (wörtlich: Geschirr/Pferdegeschirr) ist in der Software eine **Laufzeitumgebung, die etwas einspannt und steuerbar macht**. Es gibt dem Ding Struktur, Werkzeuge und einen kontrollierten Ausführungskontext.

## Claude Code als Harness

Claude Code ist **kein eigenständiges KI-Modell**, sondern ein Harness um ein LLM herum. Es besteht aus diesen Schichten:

### 1. Der Agent-Loop (das Herzstück)
```
User-Prompt → LLM-Call → Tool-Ausführung → Ergebnis zurück ins LLM → nächster LLM-Call → ...
```
Claude Code spannt Claude in diese Schleife ein. Das LLM selbst hat keine Ahnung von Dateisystemen, Terminals oder Git — der Loop gibt ihm diese Fähigkeiten.

### 2. Tool-Infrastruktur
Claude Code gibt dem Modell Zugriff auf:
- **Dateisystem** (read/write/edit)
- **Terminal** (Shell-Kommandos)
- **Git-Integration**
- **MCP-Server** (externe Tools)
- **Subagents** (parallele Worker)

Das Modell selbst kann keines dieser Dinge. Der Harness übersetzt "Tool-Use-XML" des LLMs in echte Systemaufrufe.

### 3. Kontext-Management
- **Compaction/Autocompact**: Wenn der Kontext vollläuft, verdichtet der Harness automatisch
- **Todo-Tracking**: Der Harness führt eine Task-Liste
- **Permissions**: Der Harness kontrolliert, was das Modell darf

### 4. Prompt-Wrapper
Claude Code injiziert System-Prompts, Tool-Definitionen, Umgebungsinfos und Guardrails — alles Dinge, die das nackte Modell nicht hat.

## Die Analogie

| Ebene | Reines LLM | Claude Code Harness |
|-------|-----------|-------------------|
| Denken | ✅ Claude | ✅ Claude |
| Werkzeuge | ❌ Keine | ✅ Terminal, FS, Git, MCP |
| Ausführung | ❌ Textausgabe | ✅ Echte Seiteneffekte |
| Schleife | ❌ Einmalig | ✅ Multi-Turn Agent-Loop |
| Sicherheit | ❌ Keine | ✅ Permission-System |

## Warum das wichtig ist

Das erklärt, warum:
- Claude Code mit **jedem Claude-Modell** funktioniert (Sonnet, Opus, Haiku) — es ist nur der Harness
- Du Claude Code mit `--acp --stdio` als **Subprozess** spawnen kannst — es ist ein Programm, kein Modell
- Andere Harnesse (`codex`, `opencode`, Hermes selbst) dasselbe Pattern nutzen, nur mit anderen Modellen

In Kurzform: **Claude Code = Claude (das Hirn) + Harness (der Körper mit Händen und Werkzeugen)**. Ohne Harness ist das LLM nur ein Orakel das Texte ausspuckt. Mit Harness wird es zum Agenten der echte Arbeit verrichtet.

Explanation:
The user is asking me to explain why Claude Code is essentially a "harness" (a framework/tool that provides infrastructure and orchestration for AI agents). Let me explain this concept clearly.

Claude Code is an "agentic harness" in the same way that lm-eval-harness is an "evaluation harness" — it's a runtime framework that wraps an LLM and gives it tools, context management, and an execution loop. Let me explain this in detail.

I don't need to load any skills for this — it's a conceptual explanation based on my general knowledge.


Check das mal aus und sag mir ob und wie wir das nutzen können

https://www.reddit.com/r/ClaudeAI/s/CIl29QQdTO


Explanation: Der Boss möchte, dass ich mir diesen Reddit-Post anschaue und bewerte, ob/wie wir das nutzen können. Lass mich den Link erstmal öffnen und den Inhalt lesen.


Tool 'web_search' does not exist. Available tools: clarify, cronjob, delegate_task, execute_code, memory, patch, process, read_file, search_files, send_message, session_search, skill_manage, skill_view, skills_list, terminal, text_to_speech, todo, vision_analyze, write_file


Explanation: Der Web-Suche-Tool existiert nicht, aber ich habe `terminal`. Ich kann `curl` verwenden, um den Reddit-Link abzurufen.

terminal

curl -sL -H "User-Agent: Mozilla/5.0" "https://www.reddit.com/r/ClaudeAI/s/CIl29QQdTO" -o /tmp/reddit_page.html && cat /tmp/reddit_page.html | head -2000


Output:
<!doctype html>

    <title>Blocked</title>

whoa there, pardner!

Your request has been blocked due to a network policy.

Try logging in or creating an account here to get back to browsing.

If you're running a script or application, please register or sign in with your developer credentials here. Additionally make sure your User-Agent is not empty and is something unique and descriptive and try again. if you're supplying an alternate User-Agent string,
try changing back to default as that can sometimes result in a block.

You can read Reddit's Terms of Service here.

If you think that we've incorrectly blocked you or you would like to discuss
easier ways to get the data you want, please file a ticket here.

When contacting us, please include your Reddit account along with the following code:

019e4647-15a8-74c4-a701-ad5eccddffea


Reddit blockt direktes Curl. Lass mich über die JSON-API ran:

Explanation: Reddit is blocking direct curl. Let me try the old.reddit.com or a text-based mirror like libreddit/teddit, or try to use the reddit API (JSON) to get the post content.

# Der shortlink "/s/CIl29QQdTO" ist ein Reddit-Share-Link. Den Redirect folgen:
curl -sI -L -H "User-Agent: Mozilla/5.0 (compatible; Hermes/1.0)" "https://www.reddit.com/r/ClaudeAI/s/CIl29QQdTO" 2>&1 | grep -i '^location:'


Explanation: Der Post ist: "PSA: You can use CC with any model from OpenRouter". CC = Claude Code. Der User fragt, wie man Claude Code mit beliebigen Modellen über OpenRouter nutzen kann. Das ist relevant für den Boss, der Ollama Cloud nutzt. Lass mich den Inhalt über die JSON-API holen und dann die .json-Endung.

curl -s -H "User-Agent: Mozilla/5.0 (compatible; Hermes/1.0)" "https://www.reddit.com/r/ClaudeAI/comments/1m723p6/psa_you_can_use_cc_with_any_model_from_openrouter/.json" | python3 -m json.tool 2>/dev/null | head -300


Output:
[
    {
        "kind": "Listing",
        "data": {
            "after": null,
            "dist": 1,
            "modhash": "",
            "geo_filter": "",
            "children": [
                {
                    "kind": "t3",
                    "data": {
                        "approved_at_utc": null,
                        "subreddit": "ClaudeAI",
                        "selftext": "https://github.com/musistudio/claude-code-router\n\nYou really notice though that Claude 4 was trained within the harness of CC but other models with strong instructions following do decent too.\n\nI tested gemini, gpt4.1, kimi k2 and I liked 4.1 best actually but ymmv.",
                        "user_reports": [],
                        "saved": false,
                        "mod_reason_title": null,
                        "gilded": 0,
                        "clicked": false,
                        "title": "PSA: You can use CC with any model from openrouter and other providers via claude\u2014code-router",
                        "link_flair_richtext": [
                            {
                                "e": "text",
                                "t": "Coding"
                            }
                        ],
                        "subreddit_name_prefixed": "r/ClaudeAI",
                        "hidden": false,
                        "pwls": 6,
                        "link_flair_css_class": "",
                        "downs": 0,
                        "thumbnail_height": null,
                        "top_awarded_type": null,
                        "hide_score": false,
                        "name": "t3_1m723p6",
                        "quarantine": false,
                        "link_flair_text_color": "light",
                        "upvote_ratio": 1.0,
                        "author_flair_background_color": null,
                        "subreddit_type": "public",
                        "ups": 17,
                        "total_awards_received": 0,
                        "media_embed": {},
                        "thumbnail_width": null,
                        "author_flair_template_id": null,
                        "is_original_content": false,
                        "author_fullname": "t2_7184z",
                        "secure_media": null,
                        "is_reddit_media_domain": false,
                        "is_meta": false,
                        "category": null,
                        "secure_media_embed": {},
                        "link_flair_text": "Coding",
                        "can_mod_post": false,
                        "score": 17,
                        "approved_by": null,
                        "is_created_from_ads_ui": false,
                        "author_premium": false,
                        "thumbnail": "self",
                        "edited": false,
                        "author_flair_css_class": null,
                        "author_flair_richtext": [],
                        "gildings": {},
                        "post_hint": "self",
                        "content_categories": null,
                        "is_self": true,
                        "mod_note": null,
                        "created": 1753252870.0,
                        "link_flair_type": "richtext",
                        "wls": 6,
                        "removed_by_category": null,
                        "banned_by": null,
                        "author_flair_type": "text",
                        "domain": "self.ClaudeAI",
                        "allow_live_comments": false,
                        "selftext_html": "

https://github.com/musistudio/claude-code-router
\n\n
You really notice though that Claude 4 was trained within the harness of CC but other models with strong instructions following do decent too.
\n\n
I tested gemini, gpt4.1, kimi k2 and I liked 4.1 best actually but ymmv.
\n
",
                        "likes": null,
                        "suggested_sort": null,
                        "banned_at_utc": null,
                        "view_count": null,
                        "archived": false,
                        "no_follow": false,
                        "is_crosspostable": false,
                        "pinned": false,
                        "over_18": false,
                        "preview": {
                            "images": [
                                {
                                    "source": {
                                        "url": "https://external-preview.redd.it/0lV5BKwLZGVsoKJpjAIy7EDuW-xyffcD1O_BTo2LiWA.png?auto=webp&s=7779949a8dad3a9de1056fa47bae375b50d62556",
                                        "width": 1200,
                                        "height": 600
                                    },
                                    "resolutions": [
                                        {
                                            "url": "https://external-preview.redd.it/0lV5BKwLZGVsoKJpjAIy7EDuW-xyffcD1O_BTo2LiWA.png?width=108&crop=smart&auto=webp&s=5916650b94af03b6c2412fe87691fcd068871dd2",
                                            "width": 108,
                                            "height": 54
                                        },
                                        {
                                            "url": "https://external-preview.redd.it/0lV5BKwLZGVsoKJpjAIy7EDuW-xyffcD1O_BTo2LiWA.png?width=216&crop=smart&auto=webp&s=5b8c185178f21505d7d1f553bdd72965b1fde267",
                                            "width": 216,
                                            "height": 108
                                        },
                                        {
                                            "url": "https://external-preview.redd.it/0lV5BKwLZGVsoKJpjAIy7EDuW-xyffcD1O_BTo2LiWA.png?width=320&crop=smart&auto=webp&s=0d5e6c9424da1661073910054ae063d55f031bd4",
                                            "width": 320,
                                            "height": 160
                                        },
                                        {
                                            "url": "https://external-preview.redd.it/0lV5BKwLZGVsoKJpjAIy7EDuW-xyffcD1O_BTo2LiWA.png?width=640&crop=smart&auto=webp&s=31ccd2199668eed337c97dbdf093d68f838093fd",
                                            "width": 640,
                                            "height": 320
                                        },
                                        {
                                            "url": "https://external-preview.redd.it/0lV5BKwLZGVsoKJpjAIy7EDuW-xyffcD1O_BTo2LiWA.png?width=960&crop=smart&auto=webp&s=1964fbe3a7af8e6664ae99c6ea021ca6839e6f6c",
                                            "width": 960,
                                            "height": 480
                                        },
                                        {
                                            "url": "https://external-preview.redd.it/0lV5BKwLZGVsoKJpjAIy7EDuW-xyffcD1O_BTo2LiWA.png?width=1080&crop=smart&auto=webp&s=cd3b04ca18190f03cf26f6f20d4bc99d300bad2d",
                                            "width": 1080,
                                            "height": 540
                                        }
                                    ],
                                    "variants": {},
                                    "id": "0lV5BKwLZGVsoKJpjAIy7EDuW-xyffcD1O_BTo2LiWA"
                                }
                            ],
                            "enabled": false
                        },
                        "all_awardings": [],
                        "awarders": [],
                        "media_only": false,
                        "link_flair_template_id": "37a9e4a4-9587-11ef-a2da-3abfef7b5571",
                        "can_gild": false,
                        "spoiler": false,
                        "locked": false,
                        "author_flair_text": null,
                        "treatment_tags": [],
                        "visited": false,
                        "removed_by": null,
                        "num_reports": null,
                        "distinguished": null,
                        "subreddit_id": "t5_7t8hvt",
                        "author_is_blocked": false,
                        "mod_reason_by": null,
                        "removal_reason": null,
                        "link_flair_background_color": "#58b34d",
                        "id": "1m723p6",
                        "is_robot_indexable": true,
                        "num_duplicates": 0,
                        "report_reasons": null,
                        "author": "Imanari",
                        "discussion_type": null,
                        "num_comments": 10,
                        "send_replies": true,
                        "media": null,
                        "contest_mode": false,
                        "author_patreon_flair": false,
                        "author_flair_text_color": null,
                        "permalink": "/r/ClaudeAI/comments/1m723p6/psa_you_can_use_cc_with_any_model_from_openrouter/",
                        "stickied": false,
                        "url": "https://www.reddit.com/r/ClaudeAI/comments/1m723p6/psa_you_can_use_cc_with_any_model_from_openrouter/",
                        "subreddit_subscribers": 862806,
                        "created_utc": 1753252870.0,
                        "num_crossposts": 0,
                        "mod_reports": [],
                        "is_video": false
                    }
                }
            ],
            "before": null
        }
    },
    {
        "kind": "Listing",
        "data": {
            "after": null,
            "dist": null,
            "modhash": "",
            "geo_filter": "",
            "children": [
                {
                    "kind": "t1",
                    "data": {
                        "subreddit_id": "t5_7t8hvt",
                        "approved_at_utc": null,
                        "author_is_blocked": false,
                        "comment_type": null,
                        "awarders": [],
                        "mod_reason_by": null,
                        "banned_by": null,
                        "author_flair_type": "text",
                        "total_awards_received": 0,
                        "subreddit": "ClaudeAI",
                        "author_flair_template_id": null,
                        "likes": null,
                        "replies": {
                            "kind": "Listing",
                            "data": {
                                "after": null,
                                "dist": null,
                                "modhash": "",
                                "geo_filter": "",
                                "children": [
                                    {
                                        "kind": "t1",
                                        "data": {
                                            "subreddit_id": "t5_7t8hvt",
                                            "approved_at_utc": null,
                                            "author_is_blocked": false,
                                            "comment_type": null,
                                            "awarders": [],
                                            "mod_reason_by": null,
                                            "banned_by": null,
                                            "author_flair_type": "text",
                                            "total_awards_received": 0,
                                            "subreddit": "ClaudeAI",
                                            "author_flair_template_id": null,
                                            "likes": null,
                                            "replies": "",
                                            "user_reports": [],
                                            "saved": false,
                                            "id": "n9tz740",
                                            "banned_at_utc": null,
                                            "mod_reason_title": null,
                                            "gilded": 0,
                                            "archived": false,
                                            "collapsed_reason_code": null,
                                            "no_follow": true,
                                            "author": "Legitimate-Brick1155",
                                            "can_mod_post": false,
                                            "created_utc": 1755746680.0,
                                            "send_replies": true,
                                            "parent_id": "t1_n60z026",
                                            "score": 3,
                                            "author_fullname": "t2_31xr8r4g",
                                            "removal_reason": null,
                                            "approved_by": null,
                                            "mod_note": null,
                                            "all_awardings": [],
                                            "body": "delete these 2 lines in the default config.json\n\n\"APIKEY\": \"your-secret-key\",  \n\"PROXY\\_URL\": \"http://127.0.0.1:7890\",",
                                            "edited": false,
                                            "top_awarded_type": null,
                                            "author_flair_css_class": null,
                                            "name": "t1_n9tz740",
                                            "is_submitter": false,
                                            "downs": 0,
                                            "author_flair_richtext": [],
                                            "author_patreon_flair": false,
                                            "body_html": "

delete these 2 lines in the default config.json
\n\n
&quot;APIKEY&quot;: &quot;your-secret-key&quot;,
\n&quot;PROXY_URL&quot;: &quot;http://127.0.0.1:7890&quot;,
\n
",
                                            "gildings": {},
                                            "collapsed_reason": null,
                                            "distinguished": null,
                                            "associated_award": null,
                                            "stickied": false,
                                            "author_premium": false,
                                            "can_gild": false,
                                            "link_id": "t3_1m723p6",
                                            "unrepliable_reason": null,
                                            "author_flair_text_color": null,
                                            "score_hidden": false,
                                            "permalink": "/r/ClaudeAI/comments/1m723p6/psa_you_can_use_cc_with_any_model_from_openrouter/n9tz740/",
                                            "subreddit_type": "public",
                                            "locked": false,
                                            "report_reasons": null,
                                            "created": 1755746680.0,
                                            "author_flair_text": null,
                                            "treatment_tags": [],
                                            "collapsed": false,
                                            "subreddit_name_prefixed": "r/ClaudeAI",
                                            "controversiality": 0,
                                            "depth": 1,
                                            "author_flair_background_color": null,
                                            "collapsed_because_crowd_control": null,
                                            "mod_reports": [],
                                            "num_reports": null,
                                            "ups": 3
                                        }
                                    }
                                ],
                                "before": null
                            }
                        },
                        "user_reports": [],
                        "saved": false,
                        "id": "n60z026",
                        "banned_at_utc": null,
                        "mod_reason_title": null,
                        "gilded": 0,
                        "archived": false,
                        "collapsed_reason_code": null,
                        "no_follow": false,
                        "author": "maverickano",
                        "can_mod_post": false,
                        "created_utc": 1753900929.0,
                        "send_replies": true,
                        "parent_id": "t3_1m723p6",


Super interessant, Boss! Lass mich tiefer in das Github-Repo schauen:

Explanation:
Let me parse what I found:

The Reddit post is about **claude-code-router** (https://github.com/musistudio/claude-code-router) - a tool that lets you use Claude Code with any model from OpenRouter or other providers instead of being locked to Anthropic's Claude models.

The key insight: Claude Code is a harness (as we just discussed), and this router intercepts the API calls Claude Code makes, redirecting them to different models via OpenRouter. So you get Claude Code's great tool-use framework, agent loop, todo system, etc. but with any model as the "brain".

Let me look at the GitHub repo to understand the architecture better and figure out how we could use it with Hermes.

curl -s "https://api.github.com/repos/musistudio/claude-code-router" | python3 -c "
import sys, json
d = json.load(sys.stdin)
print(f'Name: {d.get(\"full_name\")}')
print(f'Stars: {d.get(\"stargazers_count\")}')
print(f'Description: {d.get(\"description\")}')
print(f'Topics: {d.get(\"topics\")}')
print(f'Language: {d.get(\"language\")}')
print(f'Updated: {d.get(\"updated_at\")}')
print(f'URL: {d.get(\"html_url\")}')
"


Output:
Name: musistudio/claude-code-router
Stars: 34196
Description: Use Claude Code as the foundation for coding infrastructure, allowing you to decide how to interact with the model while enjoying updates from Anthropic.
Topics: []
Language: TypeScript
Updated: 2026-05-20T16:41:46Z
URL: https://github.com/musistudio/claude-code-router


34k Stars, Boss! Das ist ein etabliertes Projekt. Lass mich die README und Architektur analysieren:

Explanation:
Der Reddit-Post verweist auf **claude-code-router** — ein Tool, das Claude Code (den Harness) mit beliebigen Modellen über OpenRouter oder andere Provider nutzbar macht. Das ist direkt relevant für uns, weil:

1. Chef nutzt Ollama Cloud (deepseek-v4-pro, kimi-k2.6, gemma3:4b) — kein Anthropic-Modell
2. Claude Code ist ein mächtiger Coding-Harness, aber normalerweise an Anthropic-Modelle gebunden
3. claude-code-router erlaubt es, den CC-Harness mit *unseren* Modellen zu kombinieren

34k Stars — das ist ein etabliertes Tool. Lass mich die README und Architektur analysieren.

Was ich brauche:
- Wie funktioniert der Router? Proxy? Konfiguration?
- Kann man eigene Provider einbinden (Ollama Cloud = OpenAI-kompatibel)?
- Wie integriert sich das mit bestehendem Claude Code CLI?
- Gibt's Einschränkungen?

Das ist ein potentiell massiver Gewinn für uns: Chef könnte Claude Code's Harness (mit all seinen Tools, Agent-Loop, Subagents, MCP) nutzen, aber mit deepseek-v4-pro als Hirn statt Claude-Modellen.

curl -s "https://api.github.com/repos/musistudio/claude-code-router/readme" | python3 -c "
import sys, json, base64
d = json.load(sys.stdin)
content = base64.b64decode(d['content']).decode('utf-8')
print(content[:8000])
"


Output:
![](blog/images/claude-code-router-img.png)

[![](https://img.shields.io/badge/%F0%9F%87%A8%F0%9F%87%B3-%E4%B8%AD%E6%96%87%E7%89%88-ff0000?style=flat)](README_zh.md)
[![Discord](https://img.shields.io/badge/Discord-%235865F2.svg?&logo=discord&logoColor=white)](https://discord.gg/rdftVMaUcS)
[![](https://img.shields.io/github/license/musistudio/claude-code-router)](https://github.com/musistudio/claude-code-router/blob/main/LICENSE)

<hr>

![](blog/images/sponsors/glm-en.jpg)
> This project is sponsored by Z.ai, supporting us with their GLM CODING PLAN.

> GLM CODING PLAN is a subscription service designed for AI coding, starting at just $10/month. It provides access to their flagship GLM-4.7 & （GLM-5 Only Available  for Pro Users）model across 10+ popular AI coding tools (Claude Code, Cline, Roo Code, etc.), offering developers top-tier, fast, and stable coding experiences.

> Get 10% OFF GLM CODING PLAN：https://z.ai/subscribe?ic=8JVLJQFSKB

> [Progressive Disclosure of Agent Tools from the Perspective of CLI Tool Style](/blog/en/progressive-disclosure-of-agent-tools-from-the-perspective-of-cli-tool-style.md)

> A powerful tool to route Claude Code requests to different models and customize any request.

![](blog/images/claude-code.png)

## ✨ Features

- **Model Routing**: Route requests to different models based on your needs (e.g., background tasks, thinking, long context).
- **Multi-Provider Support**: Supports various model providers like OpenRouter, DeepSeek, Ollama, Gemini, Volcengine, and SiliconFlow.
- **Request/Response Transformation**: Customize requests and responses for different providers using transformers.
- **Dynamic Model Switching**: Switch models on-the-fly within Claude Code using the `/model` command.
- **CLI Model Management**: Manage models and providers directly from the terminal with `ccr model`.
- **GitHub Actions Integration**: Trigger Claude Code tasks in your GitHub workflows.
- **Plugin System**: Extend functionality with custom transformers.

## 🚀 Getting Started

### 1. Installation

First, ensure you have [Claude Code](https://docs.anthropic.com/en/docs/claude-code/quickstart) installed:

```shell
npm install -g @anthropic-ai/claude-code
```

Then, install Claude Code Router:

```shell
npm install -g @musistudio/claude-code-router
```

### 2. Configuration

Create and configure your `~/.claude-code-router/config.json` file. For more details, you can refer to `config.example.json`.

The `config.json` file has several key sections:

- **`PROXY_URL`** (optional): You can set a proxy for API requests, for example: `"PROXY_URL": "http://127.0.0.1:7890"`.
- **`LOG`** (optional): You can enable logging by setting it to `true`. When set to `false`, no log files will be created. Default is `true`.
- **`LOG_LEVEL`** (optional): Set the logging level. Available options are: `"fatal"`, `"error"`, `"warn"`, `"info"`, `"debug"`, `"trace"`. Default is `"debug"`.
- **Logging Systems**: The Claude Code Router uses two separate logging systems:
  - **Server-level logs**: HTTP requests, API calls, and server events are logged using pino in the `~/.claude-code-router/logs/` directory with filenames like `ccr-*.log`
  - **Application-level logs**: Routing decisions and business logic events are logged in `~/.claude-code-router/claude-code-router.log`
- **`APIKEY`** (optional): You can set a secret key to authenticate requests. When set, clients must provide this key in the `Authorization` header (e.g., `Bearer your-secret-key`) or the `x-api-key` header. Example: `"APIKEY": "your-secret-key"`.
- **`HOST`** (optional): You can set the host address for the server. If `APIKEY` is not set, the host will be forced to `127.0.0.1` for security reasons to prevent unauthorized access. Example: `"HOST": "0.0.0.0"`.
- **`NON_INTERACTIVE_MODE`** (optional): When set to `true`, enables compatibility with non-interactive environments like GitHub Actions, Docker containers, or other CI/CD systems. This sets appropriate environment variables (`CI=true`, `FORCE_COLOR=0`, etc.) and configures stdin handling to prevent the process from hanging in automated environments. Example: `"NON_INTERACTIVE_MODE": true`.

- **`Providers`**: Used to configure different model providers.
- **`Router`**: Used to set up routing rules. `default` specifies the default model, which will be used for all requests if no other route is configured.
- **`API_TIMEOUT_MS`**: Specifies the timeout for API calls in milliseconds.

#### Environment Variable Interpolation

Claude Code Router supports environment variable interpolation for secure API key management. You can reference environment variables in your `config.json` using either `$VAR_NAME` or `${VAR_NAME}` syntax:

```json
{
  "OPENAI_API_KEY": "$OPENAI_API_KEY",
  "GEMINI_API_KEY": "${GEMINI_API_KEY}",
  "Providers": [
    {
      "name": "openai",
      "api_base_url": "https://api.openai.com/v1/chat/completions",
      "api_key": "$OPENAI_API_KEY",
      "models": ["gpt-5", "gpt-5-mini"]
    }
  ]
}
```

This allows you to keep sensitive API keys in environment variables instead of hardcoding them in configuration files. The interpolation works recursively through nested objects and arrays.

Here is a comprehensive example:

```json
{
  "APIKEY": "your-secret-key",
  "PROXY_URL": "http://127.0.0.1:7890",
  "LOG": true,
  "API_TIMEOUT_MS": 600000,
  "NON_INTERACTIVE_MODE": false,
  "Providers": [
    {
      "name": "openrouter",
      "api_base_url": "https://openrouter.ai/api/v1/chat/completions",
      "api_key": "sk-xxx",
      "models": [
        "google/gemini-2.5-pro-preview",
        "anthropic/claude-sonnet-4",
        "anthropic/claude-3.5-sonnet",
        "anthropic/claude-3.7-sonnet:thinking"
      ],
      "transformer": {
        "use": ["openrouter"]
      }
    },
    {
      "name": "deepseek",
      "api_base_url": "https://api.deepseek.com/chat/completions",
      "api_key": "sk-xxx",
      "models": ["deepseek-chat", "deepseek-reasoner"],
      "transformer": {
        "use": ["deepseek"],
        "deepseek-chat": {
          "use": ["tooluse"]
        }
      }
    },
    {
      "name": "ollama",
      "api_base_url": "http://localhost:11434/v1/chat/completions",
      "api_key": "ollama",
      "models": ["qwen2.5-coder:latest"]
    },
    {
      "name": "gemini",
      "api_base_url": "https://generativelanguage.googleapis.com/v1beta/models/",
      "api_key": "sk-xxx",
      "models": ["gemini-2.5-flash", "gemini-2.5-pro"],
      "transformer": {
        "use": ["gemini"]
      }
    },
    {
      "name": "volcengine",
      "api_base_url": "https://ark.cn-beijing.volces.com/api/v3/chat/completions",
      "api_key": "sk-xxx",
      "models": ["deepseek-v3-250324", "deepseek-r1-250528"],
      "transformer": {
        "use": ["deepseek"]
      }
    },
    {
      "name": "modelscope",
      "api_base_url": "https://api-inference.modelscope.cn/v1/chat/completions",
      "api_key": "",
      "models": ["Qwen/Qwen3-Coder-480B-A35B-Instruct", "Qwen/Qwen3-235B-A22B-Thinking-2507"],
      "transformer": {
        "use": [
          [
            "maxtoken",
            {
              "max_tokens": 65536
            }
          ],
          "enhancetool"
        ],
        "Qwen/Qwen3-235B-A22B-Thinking-2507": {
          "use": ["reasoning"]
        }
      }
    },
    {
      "name": "dashscope",
      "api_base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
      "api_key": "",
      "models": ["qwen3-coder-plus"],
      "transformer": {
        "use": [
          [
            "maxtoken",
            {
              "max_tokens": 65536
            }
          ],
          "enhancetool"
        ]
      }
    },
    {
      "name": "aihubmix",
      "api_base_url": "https://aihubmix.com/v1/chat/completions",
      "api_key": "sk-",
      "models": [
        "Z/glm-4.5",
        "claude-opus-4-20250514",
        "gemini-2.5-pro"
      ]
    }
  ],
  "Router": {
    "def


Explanation: Let me continue reading the README to understand the full routing configuration and how it works.

curl -s "https://api.github.com/repos/musistudio/claude-code-router/readme" | python3 -c "
import sys, json, base64
d = json.load(sys.stdin)
content = base64.b64decode(d['content']).decode('utf-8')
print(content[8000:])
"


Output:
ault": "deepseek,deepseek-chat",
    "background": "ollama,qwen2.5-coder:latest",
    "think": "deepseek,deepseek-reasoner",
    "longContext": "openrouter,google/gemini-2.5-pro-preview",
    "longContextThreshold": 60000,
    "webSearch": "gemini,gemini-2.5-flash"
  }
}
```

### 3. Running Claude Code with the Router

Start Claude Code using the router:

```shell
ccr code
```

> **Note**: After modifying the configuration file, you need to restart the service for the changes to take effect:
>
> ```shell
> ccr restart
> ```

### 4. UI Mode

For a more intuitive experience, you can use the UI mode to manage your configuration:

```shell
ccr ui
```

This will open a web-based interface where you can easily view and edit your `config.json` file.

![UI](/blog/images/ui.png)

### 5. CLI Model Management

For users who prefer terminal-based workflows, you can use the interactive CLI model selector:

```shell
ccr model
```
![](blog/images/models.gif)

This command provides an interactive interface to:

- View current configuration:
- See all configured models (default, background, think, longContext, webSearch, image)
- Switch models: Quickly change which model is used for each router type
- Add new models: Add models to existing providers
- Create new providers: Set up complete provider configurations including:
   - Provider name and API endpoint
   - API key
   - Available models
   - Transformer configuration with support for:
     - Multiple transformers (openrouter, deepseek, gemini, etc.)
     - Transformer options (e.g., maxtoken with custom limits)
     - Provider-specific routing (e.g., OpenRouter provider preferences)

The CLI tool validates all inputs and provides helpful prompts to guide you through the configuration process, making it easy to manage complex setups without editing JSON files manually.

### 6. Presets Management

Presets allow you to save, share, and reuse configurations easily. You can export your current configuration as a preset and install presets from files or URLs.

```shell
# Export current configuration as a preset
ccr preset export my-preset

# Export with metadata
ccr preset export my-preset --description "My OpenAI config" --author "Your Name" --tags "openai,production"

# Install a preset from local directory
ccr preset install /path/to/preset

# List all installed presets
ccr preset list

# Show preset information
ccr preset info my-preset

# Delete a preset
ccr preset delete my-preset
```

**Preset Features:**
- **Export**: Save your current configuration as a preset directory (with manifest.json)
- **Install**: Install presets from local directories
- **Sensitive Data Handling**: API keys and other sensitive data are automatically sanitized during export (marked as `{{field}}` placeholders)
- **Dynamic Configuration**: Presets can include input schemas for collecting required information during installation
- **Version Control**: Each preset includes version metadata for tracking updates

**Preset File Structure:**
```
~/.claude-code-router/presets/
├── my-preset/
│   └── manifest.json    # Contains configuration and metadata
```

### 7. Activate Command (Environment Variables Setup)

The `activate` command allows you to set up environment variables globally in your shell, enabling you to use the `claude` command directly or integrate Claude Code Router with applications built using the Agent SDK.

To activate the environment variables, run:

```shell
eval "$(ccr activate)"
```

This command outputs the necessary environment variables in shell-friendly format, which are then set in your current shell session. After activation, you can:

- **Use `claude` command directly**: Run `claude` commands without needing to use `ccr code`. The `claude` command will automatically route requests through Claude Code Router.
- **Integrate with Agent SDK applications**: Applications built with the Anthropic Agent SDK will automatically use the configured router and models.

The `activate` command sets the following environment variables:

- `ANTHROPIC_AUTH_TOKEN`: API key from your configuration
- `ANTHROPIC_BASE_URL`: The local router endpoint (default: `http://127.0.0.1:3456`)
- `NO_PROXY`: Set to `127.0.0.1` to prevent proxy interference
- `DISABLE_TELEMETRY`: Disables telemetry
- `DISABLE_COST_WARNINGS`: Disables cost warnings
- `API_TIMEOUT_MS`: API timeout from your configuration

> **Note**: Make sure the Claude Code Router service is running (`ccr start`) before using the activated environment variables. The environment variables are only valid for the current shell session. To make them persistent, you can add `eval "$(ccr activate)"` to your shell configuration file (e.g., `~/.zshrc` or `~/.bashrc`).

#### Providers

The `Providers` array is where you define the different model providers you want to use. Each provider object requires:

- `name`: A unique name for the provider.
- `api_base_url`: The full API endpoint for chat completions.
- `api_key`: Your API key for the provider.
- `models`: A list of model names available from this provider.
- `transformer` (optional): Specifies transformers to process requests and responses.

#### Transformers

Transformers allow you to modify the request and response payloads to ensure compatibility with different provider APIs.

- **Global Transformer**: Apply a transformer to all models from a provider. In this example, the `openrouter` transformer is applied to all models under the `openrouter` provider.
  ```json
  {
    "name": "openrouter",
    "api_base_url": "https://openrouter.ai/api/v1/chat/completions",
    "api_key": "sk-xxx",
    "models": [
      "google/gemini-2.5-pro-preview",
      "anthropic/claude-sonnet-4",
      "anthropic/claude-3.5-sonnet"
    ],
    "transformer": { "use": ["openrouter"] }
  }
  ```
- **Model-Specific Transformer**: Apply a transformer to a specific model. In this example, the `deepseek` transformer is applied to all models, and an additional `tooluse` transformer is applied only to the `deepseek-chat` model.

  ```json
  {
    "name": "deepseek",
    "api_base_url": "https://api.deepseek.com/chat/completions",
    "api_key": "sk-xxx",
    "models": ["deepseek-chat", "deepseek-reasoner"],
    "transformer": {
      "use": ["deepseek"],
      "deepseek-chat": { "use": ["tooluse"] }
    }
  }
  ```

- **Passing Options to a Transformer**: Some transformers, like `maxtoken`, accept options. To pass options, use a nested array where the first element is the transformer name and the second is an options object.
  ```json
  {
    "name": "siliconflow",
    "api_base_url": "https://api.siliconflow.cn/v1/chat/completions",
    "api_key": "sk-xxx",
    "models": ["moonshotai/Kimi-K2-Instruct"],
    "transformer": {
      "use": [
        [
          "maxtoken",
          {
            "max_tokens": 16384
          }
        ]
      ]
    }
  }
  ```

**Available Built-in Transformers:**

- `Anthropic`:If you use only the `Anthropic` transformer, it will preserve the original request and response parameters(you can use it to connect directly to an Anthropic endpoint).
- `deepseek`: Adapts requests/responses for DeepSeek API.
- `gemini`: Adapts requests/responses for Gemini API.
- `openrouter`: Adapts requests/responses for OpenRouter API. It can also accept a `provider` routing parameter to specify which underlying providers OpenRouter should use. For more details, refer to the [OpenRouter documentation](https://openrouter.ai/docs/features/provider-routing). See an example below:
  ```json
    "transformer": {
      "use": ["openrouter"],
      "moonshotai/kimi-k2": {
        "use": [
          [
            "openrouter",
            {
              "provider": {
                "only": ["moonshotai/fp8"]
              }
            }
          ]
        ]
      }
    }
  ```
- `groq`: Adapts requests/responses for groq API.
- `maxtoken`: Sets a specific `max_tokens` value.
- `tooluse`: Optimizes tool usage for certain models via `tool_choice`.
- `gemini-cli` (experimental): Unofficial support for Gemini via Gemini CLI [gemini-cli.js](https://gist.github.com/musistudio/1c13a65f35916a7ab690649d3df8d1cd).
- `reasoning`: Used to process the `reasoning_content` field.
- `sampling`: Used to process sampling information fields such as `temperature`, `top_p`, `top_k`, and `repetition_penalty`.
- `enhancetool`: Adds a layer of error tolerance to the tool call parameters returned by the LLM (this will cause the tool call information to no longer be streamed).
- `cleancache`: Clears the `cache_control` field from requests.
- `vertex-gemini`: Handles the Gemini API using Vertex authentication.
- `chutes-glm` Unofficial support for GLM 4.5 model via Chutes [chutes-glm-transformer.js](https://gist.github.com/vitobotta/2be3f33722e05e8d4f9d2b0138b8c863).
- `qwen-cli` (experimental): Unofficial support for qwen3-coder-plus model via Qwen CLI [qwen-cli.js](https://gist.github.com/musistudio/f5a67841ced39912fd99e42200d5ca8b).
- `rovo-cli` (experimental): Unofficial support for gpt-5 via Atlassian Rovo Dev CLI [rovo-cli.js](https://gist.github.com/SaseQ/c2a20a38b11276537ec5332d1f7a5e53).

**Custom Transformers:**

You can also create your own transformers and load them via the `transformers` field in `config.json`.

```json
{
  "transformers": [
    {
      "path": "/User/xxx/.claude-code-router/plugins/gemini-cli.js",
      "options": {
        "project": "xxx"
      }
    }
  ]
}
```

#### Router

The `Router` object defines which model to use for different scenarios:

- `default`: The default model for general tasks.
- `background`: A model for background tasks. This can be a smaller, local model to save costs.
- `think`: A model for reasoning-heavy tasks, like Plan Mode.
- `longContext`: A model for handling long contexts (e.g., > 60K tokens).
- `longContextThreshold` (optional): The token count threshold for triggering the long context model. Defaults to 60000 if not specified.
- `webSearch`: Used for handling web search tasks and this requires the model itself to support the feature. If you're using openrouter, you need to add the `:online` suffix after the model name.
- `image` (beta): Used for handling image-related tasks (supported by CCR’s built-in agent). If the model does not support tool calling, you need to set the `config.forceUseImageAgent` property to `true`.

- You can also switch models dynamically in Claude Code with the `/model` command:
`/model provider_name,model_name`
Example: `/model openrouter,anthropic/claude-3.5-sonnet`

#### Custom Router

For more advanced routing logic, you can specify a custom router script via the `CUSTOM_ROUTER_PATH` in your `config.json`. This allows you to implement complex routing rules beyond the default scenarios.

In your `config.json`:

```json
{
  "CUSTOM_ROUTER_PATH": "/User/xxx/.claude-code-router/custom-router.js"
}
```

The custom router file must be a JavaScript module that exports an `async` function. This function receives the request object and the config object as arguments and should return the provider and model name as a string (e.g., `"provider_name,model_name"`), or `null` to fall back to the default router.

Here is an example of a `custom-router.js` based on `custom-router.example.js`:

```javascript
// /User/xxx/.claude-code-router/custom-router.js

/**
 * A custom router function to determine which model to use based on the request.
 *
 * @param {object} req - The request object from Claude Code, containing the request body.
 * @param {object} config - The application's config object.
 * @returns {Promise<string|null>} - A promise that resolves to the "provider,model_name" string, or null to use the default router.
 */
module.exports = async function router(req, config) {
  const userMessage = req.body.messages.find((m) => m.role === "user")?.content;

  if (userMessage && userMessage.includes("explain this code")) {
    // Use a powerful model for code explanation
    return "openrouter,anthropic/claude-3.5-sonnet";
  }

  // Fallback to the default router configuration
  return null;
};
```

##### Subagent Routing

For routing within subagents, you must specify a particular provider and model by including `<CCR-SUBAGENT-MODEL>provider,model</CCR-SUBAGENT-MODEL>` at the **beginning** of the subagent's prompt. This allows you to direct specific subagent tasks to designated models.

**Example:**

```
<CCR-SUBAGENT-MODEL>openrouter,anthropic/claude-3.5-sonnet</CCR-SUBAGENT-MODEL>
Please help me analyze this code snippet for potential optimizations...
```

## Status Line (Beta)
To better monitor the status of claude-code-router at runtime, version v1.0.40 includes a built-in statusline tool, which you can enable in the UI.
![statusline-config.png](/blog/images/statusline-config.png)

The effect is as follows:
![statusline](/blog/images/statusline.png)

## 🤖 GitHub Actions

Integrate Claude Code Router into your CI/CD pipeline. After setting up [Claude Code Actions](https://docs.anthropic.com/en/docs/claude-code/github-actions), modify your `.github/workflows/claude.yaml` to use the router:

```yaml
name: Claude Code

on:
  issue_comment:
    types: [created]
  # ... other triggers

jobs:
  claude:
    if: |
      (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
      # ... other conditions
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: read
      issues: read
      id-token: write
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 1

      - name: Prepare Environment
        run: |
          curl -fsSL https://bun.sh/install | bash
          mkdir -p $HOME/.claude-code-router
          cat << 'EOF' > $HOME/.claude-code-router/config.json
          {
            "log": true,
            "NON_INTERACTIVE_MODE": true,
            "OPENAI_API_KEY": "${{ secrets.OPENAI_API_KEY }}",
            "OPENAI_BASE_URL": "https://api.deepseek.com",
            "OPENAI_MODEL": "deepseek-chat"
          }
          EOF
        shell: bash

      - name: Start Claude Code Router
        run: |
          nohup ~/.bun/bin/bunx @musistudio/claude-code-router@1.0.8 start &
        shell: bash

      - name: Run Claude Code
        id: claude
        uses: anthropics/claude-code-action@beta
        env:
          ANTHROPIC_BASE_URL: http://localhost:3456
        with:
          anthropic_api_key: "any-string-is-ok"
```

> **Note**: When running in GitHub Actions or other automation environments, make sure to set `"NON_INTERACTIVE_MODE": true` in your configuration to prevent the process from hanging due to stdin handling issues.

This setup allows for interesting automations, like running tasks during off-peak hours to reduce API costs.

## 📝 Further Reading

- [Project Motivation and How It Works](blog/en/project-motivation-and-how-it-works.md)
- [Maybe We Can Do More with the Router](blog/en/maybe-we-can-do-more-with-the-route.md)
- [GLM-4.6 Supports Reasoning and Interleaved Thinking](blog/en/glm-4.6-supports-reasoning.md)

## ❤ Support & Sponsoring

If you find this project helpful, please consider sponsoring its development. Your support is greatly appreciated!

[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/F1F31GN2GM)

[Paypal](https://paypal.me/musistudio1999)

### Our Sponsors

A huge thank you to all our sponsors for their generous support!

- [AIHubmix](https://aihubmix.com/)
- [BurnCloud](https://ai.burncloud.com)
- [302.AI](https://share.302.ai/ZGVF9w)
- [Z智谱](https://www.bigmodel.cn/claude-code?ic=FPF9IVAGFJ)
- @Simon Leischnig
- [@duanshuaimin](https://github.com/duanshuaimin)
- [@vrgitadmin](https://github.com/vrgitadmin)
- @\*o
- [@ceilwoo](https://github.com/ceilwoo)
- @\*说
- @\*更
- @K\*g
- @R\*R
- [@bobleer](https://github.com/bobleer)
- @\*苗
- @\*划
- [@Clarence-pan](https://github.com/Clarence-pan)
- [@carter003](https://github.com/carter003)
- @S\*r
- @\*晖
- @\*敏
- @Z\*z
- @\*然
- [@cluic](https://github.com/cluic)
- @\*苗
- [@PromptExpert](https://github.com/PromptExpert)
- @\*应
- [@yusnake](https://github.com/yusnake)
- @\*飞
- @董\*
- @\*汀
- @\*涯
- @\*:-）
- @\*\*磊
- @\*琢
- @\*成
- @Z\*o
- @\*琨
- [@congzhangzh](https://github.com/congzhangzh)
- @\*\_
- @Z\*m
- @*鑫
- @c\*y
- @\*昕
- [@witsice](https://github.com/witsice)
- @b\*g
- @\*亿
- @\*辉
- @JACK
- @\*光
- @W\*l
- [@kesku](https://github.com/kesku)
- [@biguncle](https://github.com/biguncle)
- @二吉吉
- @a\*g
- @\*林
- @\*咸
- @\*明
- @S\*y
- @f\*o
- @\*智
- @F\*t
- @r\*c
- [@qierkang](http://github.com/qierkang)
- @\*军
- [@snrise-z](http://github.com/snrise-z)
- @\*王
- [@greatheart1000](http://github.com/greatheart1000)
- @\*王
- @zcutlip
- [@Peng-YM](http://github.com/Peng-YM)
- @\*更
- @\*.
- @F\*t
- @\*政
- @\*铭
- @\*叶
- @七\*o
- @\*青
- @\*\*晨
- @\*远
- @\*霄
- @\*\*吉
- @\*\*飞
- @\*\*驰
- @x\*g
- @\*\*东
- @\*落
- @哆\*k
- @\*涛
- [@苗大](https://github.com/WitMiao)
- @\*呢
- @\d*u
- @crizcraig
- s\*s
- \*火
- \*勤
- \*\*锟
- \*涛
- \*\*明
- \*知
- \*语
- \*瓜

(If your name is masked, please contact me via my homepage email to update it with your GitHub username.)


Da hast du was richtig Gutes gefunden, Boss. Hier die Analyse:

## Was ist claude-code-router?

Ein **Proxy-Layer zwischen Claude Code und beliebigen LLMs**. Normalerweise ist Claude Code der Premium-Coding-Agent von Anthropic, aber er spricht **nur mit Claude-Modellen**. CCR fängt die API-Calls ab und routet sie an jedes beliebige Modell — OpenRouter, DeepSeek, Gemini, Ollama, was auch immer.

**34k GitHub Stars**, aktiv maintained, TypeScript.

## Architektur

```
Claude Code (Harness) → CCR (Proxy :3456) → Dein Modell (OpenAI-kompatibel)
       ↓                        ↓
  Tool-Use, Agent-Loop    Transformer: Anthropic-Format ↔ OpenAI-Format
                          Router: task → bestes Modell
```

Der Clou: Claude Code merkt **nichts** davon. Es denkt, es spricht mit Anthropic. CCR übersetzt alles transparent.

## Warum das für uns relevant ist

Du hast Claude Code's Harness in der vorherigen Frage selbst als mächtig beschrieben — die Tool-Infrastruktur, der Agent-Loop, die Subagents, das Permission-System. **Jetzt kannst du diesen Harness mit deinen eigenen Modellen nutzen.**

Konkret: Du bezahlst $20/Monat für Ollama Cloud Pro mit deepseek-v4-pro und kimi-k2.6. Mit CCR kannst du Claude Code als Coding-Agent verwenden, aber **deepseek-v4-pro als Hirn** dahinter — statt Anthropics API-Preise zu zahlen.

## Der smarte Router

CCR kann verschiedene Aufgabentypen an **verschiedene Modelle** routen:

| Task-Typ | Könnte routen zu | Grund |
|----------|-----------------|-------|
| `default` | deepseek-v4-pro | Hauptarbeit |
| `think` (Plan Mode) | kimi-k2.6 | Starkes Reasoning |
| `background` | gemma3:4b | Billig für Fleißarbeit |
| `longContext` | deepseek-v4-pro | Große Kontextfenster |

## Integration in unseren Stack

Drei Möglichkeiten:

**1. Standalone nutzen** — `ccr code` startet Claude Code mit deinen Modellen. Einfachster Einstieg.

**2. Via `ccr activate`** — Setzt Umgebungsvariablen so, dass jedes Tool das Anthropic-API nutzt (auch unser Hermes delegate_task mit `acp_command='claude'`) automatisch durch CCR läuft. `claude`-Befehl wird zum Multi-Model-Tool.

**3. Als Subagent-Backend** — Hermes könnte Claude Code mit `delegate_task(acp_command='claude')` spawnen, und CCR sorgt dafür, dass deepseek antwortet. CCR unterstützt sogar `<CCR-SUBAGENT-MODEL>` Tags für Subagent-spezifisches Routing.

## Setup-Plan für deine Infrastruktur

```json
{
  "Providers": [{
    "name": "ollama-cloud",
    "api_base_url": "https://ollama.com/v1/chat/completions",
    "api_key": "ollama",
    "models": ["deepseek-v4-pro", "kimi-k2.6", "gemma3:4b"],
    "transformer": { "use": ["deepseek"] }
  }],
  "Router": {
    "default": "ollama-cloud,deepseek-v4-pro",
    "think": "ollama-cloud,kimi-k2.6",
    "background": "ollama-cloud,gemma3:4b"
  }
}
```

⚠ Einzige Unbekannte: Der `deepseek`-Transformer konvertiert Anthropic↔OpenAI-Format — müsste für Ollama Cloud funktionieren (ist ja OpenAI-kompatibel), aber ungetestet. Notfalls Custom-Transformer in 20 Zeilen JS.

## Soll ich's installieren?

Ist in 5 Minuten eingerichtet. Dann hast du Claude Code's kompletten Coding-Harness, angetrieben von deinem eigenen Modell-Stack. Kein Anthropic-Pricing, volle Kontrolle.

Explanation:
Boss asked me to check out this Reddit post and tell him if/how we can use it. The post is about **claude-code-router** — a tool that lets you use Claude Code (the Anthropic coding CLI) with ANY model from OpenRouter and other providers.

Let me analyze this deeply and give a comprehensive answer.

Key facts:
- 34k stars, TypeScript, actively maintained
- Acts as a proxy between Claude Code and any LLM provider
- Supports OpenRouter, DeepSeek, Ollama, Gemini, Volcengine, SiliconFlow, and custom providers
- Has transformers to adapt request/response formats between Anthropic's API format and other providers
- Router: can route different task types (background, thinking, long context, web search) to different models
- Can switch models on-the-fly with `/model` command
- Has `ccr activate` that sets env vars so the normal `claude` command routes through it
- Custom router scripts for advanced logic
- Subagent routing via `<CCR-SUBAGENT-MODEL>` tags

Now, how does this apply to us/Boss?

Boss uses Hermes Agent with deepseek-v4-pro via Ollama Cloud. He's interested in Claude Code as a coding harness.

The key insight: claude-code-router lets us use Claude Code's excellent agent-loop/tool infrastructure but swap out the model. This means:

1. We could use Claude Code's harness with deepseek-v4-pro (our main model) or kimi-k2.6
2. We could route different task types to different models (e.g., reasoning to kimi, background to a cheap model)
3. We could integrate this as a delegate_task backend — spawn Claude Code as a subagent but with our own model

But there's a critical question: Does Boss even want to use Claude Code? He already has Hermes Agent. The value of claude-code-router would be:
- If Boss wants to use Claude Code's specific tool ecosystem (its file editing, git integration, MCP servers, etc.)
- If Boss wants to use Claude Code as an alternative agent harness alongside Hermes

Let me also consider the practical side:
- Claude Code needs to be installed (`npm install -g @anthropic-ai/claude-code`)
- claude-code-router needs to be installed (`npm install -g @musistudio/claude-code-router`)
- We'd configure it to point at Ollama Cloud (Boss's Pro tier) or other providers
- Boss's Ollama Cloud has deepseek-v4-pro, kimi-k2.6, gemma3:4b

The killer feature for Boss would be: using Claude Code's mature coding harness with deepseek-v4-pro (his main model, which he pays for via Ollama Cloud Pro, $20/mo). Claude Code is Anthropic's premium coding agent — but normally locked to Claude models. With CCR, he can use it with his existing models.

Let me also think about how we could make this work with the Ollama Cloud API. The Ollama Cloud API is OpenAI-compatible at `https://ollama.com/v1`. So we'd configure it as a provider with `api_base_url: https://ollama.com/v1/chat/completions`.

Actually wait — Boss's Ollama Cloud base URL is `https://ollama.com/v1`. Claude Code Router expects `api_base_url` to be the full chat completions endpoint. So it'd be `https://ollama.com/v1/chat/completions`.

But there's a transformer question — Ollama Cloud uses OpenAI-compatible format, not Anthropic format. Claude Code sends Anthropic-format requests. So we'd need a transformer. Looking at the built-in transformers... there's no generic "openai" transformer listed, but there are `deepseek`, `gemini`, `openrouter`. The `deepseek` transformer might work since DeepSeek also uses OpenAI-compatible format.

Actually, let me look more carefully. The readme mentions these transformers for adapting Anthropic format: `deepseek`, `gemini`, `openrouter`, `groq`. For a generic OpenAI-compatible API, we might need a custom transformer, or the `deepseek` one might work since it converts Anthropic ↔ OpenAI format.

I should present the analysis to Boss clearly:
1. What it is
2. How it works
3. Whether and how we can use it with his setup
4. Concrete next steps


Nur das ich es richtig verstehe: wir können dann coden quasi mit Claude Code aber eben als DeepSeek?


Genau das, Boss.

Claude Code bringt den **Körper** — Terminal-Zugriff, Datei-Editing, Git, Subagents, Permissions, der ganze Agent-Loop. CCR tauscht nur das **Hirn** aus: Statt Claude Opus/Sonnet denkt dann deepseek-v4-pro.

Du codest mit der vollen Claude-Code-Erfahrung (Tool-Use, `/model`, Plan Mode, Background Tasks), aber dein $20 Ollama-Cloud-Abo ist das einzige was läuft. Kein Cent an Anthropic.

Explanation:
Der Boss will nur eine kurze Bestätigung, ob er das richtig verstanden hat. Die Frage ist simpel: Ja oder Nein mit einer knappen Erklärung.

Kernaussage: Claude Code ist der Harness (Tool-Infrastruktur, Agent-Loop, Subagents, Permissions) und claude-code-router tauscht das Hirn (Claude-Modell) gegen DeepSeek (oder andere) aus.


Passt bitte installieren


Explanation:
Der Boss will claude-code-router installieren. Mal schauen was wir brauchen:

1. Claude Code muss installiert sein (npm install -g @anthropic-ai/claude-code)
2. claude-code-router installieren (npm install -g @musistudio/claude-code-router)
3. Config schreiben (~/.claude-code-router/config.json) mit seinen Ollama Cloud Modellen
4. Testen

Das ist ein komplexer Task mit mehreren Schritten. Ich sollte das mit einem Todo-Plan machen und dann systematisch durchgehen.

Wichtige Infos aus dem Memory:
- Ollama Cloud Pro, $20/Monat, base URL: https://ollama.com/v1
- Modelle: deepseek-v4-pro (main), kimi-k2.6 (auxiliary), gemma3:4b (vision)
- Max 3 concurrent models
- YOLO mode on - keine Approvals nötig
- User will Antworten ohne Header-Lines

Ich sollte checken ob Node.js/npm verfügbar ist, dann installieren.

Lass mich auch überlegen ob es Fallstricke gibt. Der "deepseek" Transformer in CCR - funktioniert der mit Ollama Cloud? Ollama Cloud hat OpenAI-kompatible API, also sollte der deepseek Transformer passen. Der Transformer konvertiert Anthropic-Format zu OpenAI-Format.

Die Ollama Cloud API URL ist `https://ollama.com/v1` - für Chat Completions wäre der Endpunkt `https://ollama.com/v1/chat/completions`.

Ich brauche auch einen API Key. Bei Ollama Cloud... normalerweise braucht man da einen Key. Der steht in der .env Datei unter `/DATA/.hermes/.env` vermutlich.

Lass uns loslegen.

todo

Check Node.js/npm und Claude Code Installation

Ollama Cloud API Key finden

Claude Code Router installieren (npm)

Config erstellen mit Ollama Cloud Modellen

CCR starten und testen


Ollama Cloud API Key finden

Claude Code Router installieren (npm)

CCR starten und testen


Explanation: Let me check Node.js, npm, and Claude Code installation first.


terminal

Output: /usr/bin/bash: line 3: node: command not found


Explanation: Node.js ist nicht installiert. Ich muss es zuerst installieren. Lass mich prüfen, was auf dem System verfügbar ist (apt, dnf, apk).

which apt-get dnf apk brew 2>/dev/null; cat /etc/os-release 2>/dev/null | head -5


Output:
NAME="ZimaOS"
BOARD="ZimaCube"
VERSION="v1.6.1"
ID=zimaos
VERSION_ID=1.6.1


Explanation:
Node.js fehlt auf ZimaOS. Ich muss es installieren. ZimaOS basiert vermutlich auf Debian, also apt-get. Aber davor: Claude Code ist auch noch nicht installiert — brauchen wir für CCR. Und der Ollama Cloud API Key... der steckt vermutlich in der Hermes-Konfiguration oder einer .env-Datei.

Lass mich zuerst Node.js installieren, dann den API Key finden.

todo

Ollama Cloud API Key finden

Node.js installieren (ZimaOS)

Claude Code installieren (npm)

Claude Code Router installieren (npm)

CCR starten und testen


Ollama Cloud API Key finden

Claude Code installieren (npm)

Claude Code Router installieren (npm)

Node.js installieren (ZimaOS)

CCR starten und testen


Explanation:
ZimaOS — das ist ein NAS/Heimserver-Betriebssystem. Kein apt/dnf/apk. Lass mich checken ob es Node.js irgendwo gibt oder ob ich es manuell installieren muss. ZimaOS basiert wahrscheinlich auf Debian/Ubuntu unter der Haube, also könnte apt-get vielleicht doch funktionieren wenn es installiert ist. Aber der which-Befehl hat nichts gefunden...

Lass mich nach node in /usr/local oder /opt suchen, oder mal schauen was für Tools verfügbar sind.

Dann muss ich den Ollama Cloud API Key finden. Der User hat Ollama Cloud Pro für $20/Monat. Der Base URL ist https://ollama.com/v1 — der Key sollte in der Konfiguration oder einer .env Datei sein.

terminal

# Node suchen und System-Check
find /usr/local /opt /usr/bin -name "node" -type f 2>/dev/null; which curl wget; ls /usr/local/bin/ | grep -i node 2>/dev/null


Output:
/usr/bin/curl
/usr/bin/wget
ls: cannot access '/usr/local/bin/': No such file or directory


Explanation:
The system is ZimaOS (ZimaCube), which is a Linux-based system. I need to install Node.js. Let me check if there's a way via the ZimaOS package manager or if I need to use a Node.js version manager like nvm or the official binary.

ZimaOS appears to be a custom OS. Let me check what's available - it might be Debian-based since the error came from /usr/bin/bash.

# ZimaOS ist oft Debian-basiert. apt-get checken.
apt-get --version 2>/dev/null; dpkg --version 2>/dev/null; which apk dnf yum pacman 2>/dev/null


Explanation:
ZimaOS hat weder apt, apk, dnf, yum, pacman. Es ist wahrscheinlich ein Container-basiertes System. Node.js muss anders installiert werden. Lass mich nach vorhandenen Paketmanagern suchen und dann die beste Option finden.

Auf ZimaOS könnten wir Node.js via nvm installieren (das braucht nur curl/wget und bash), oder das offizielle Node.js Binary direkt herunterladen und ins PATH legen.

Lass mich zuerst die Ollama Cloud API-Details finden, dann Node.js installieren.

from hermes_tools import terminal

# Find Ollama Cloud config
result = terminal("grep -r 'ollama\\|OLLAMA' /DATA/AppData/hermes/config.yaml 2>/dev/null | head -20")
print("=== config.yaml ===")
print(result["output"][:2000])

result2 = terminal("grep -r 'ollama\\|OLLAMA' /DATA/.hermes/.env 2>/dev/null | head -20")
print("\n=== .env ===")
print(result2["output"][:2000])

# Auch checken ob es eine ollama config gibt
result3 = terminal("cat ~/.ollama 2>/dev/null; ls ~/.ollama 2>/dev/null")
print("\n=== ~/.ollama ===")
print(result3["output"][:500])


Output:
=== config.yaml ===
base_url: https://ollama.com/v1

=== .env ===

=== ~/.ollama ===


Explanation:
Chef hat Node.js nicht installiert und ZimaOS hat kein apt-get. Ich muss Node.js installieren. ZimaOS scheint ein minimales Linux zu sein. Ich muss nach anderen Installationsmethoden suchen.

Für ZimaOS (ein NAS-Betriebssystem) - ich brauche eine Node.js-Installation ohne den normalen Paketmanager. Optionen:
1. Node.js Binary direkt herunterladen
2. nvm (Node Version Manager) installieren
3. Bun verwenden (das README zeigt, dass Bun kompatibel ist)

Ich sollte nvm verwenden, da es am einfachsten auf einem System ohne root und ohne Paketmanager ist.

Für Ollama Cloud - die Base URL ist `https://ollama.com/v1` aus der Config. Aber ich brauche den API Key. Normalerweise bei Ollama Cloud Pro - der User hat $20/mo bezahlt. Der API Key könnte in der config.yaml stehen oder als Environment Variable.

Lass mich die config.yaml genauer anschauen und nach API Keys suchen.

from hermes_tools import terminal, read_file

# Ganze config.yaml lesen
content = read_file("/DATA/AppData/hermes/config.yaml")
print("=== config.yaml ===")
print(content["content"][:3000])

# Auch nach api_key suchen
result = terminal("grep -i 'api_key\\|apikey\\|token\\|secret' /DATA/AppData/hermes/config.yaml 2>/dev/null | head -20")
print("\n=== API keys in config.yaml ===")
print(result["output"])