Hermes context optimization

From AtlasOmnia/hermes-custom-pack · View interactive version

Hermes context optimization is an AI agent skill from the GitHub repository AtlasOmnia/hermes-custom-pack. hermes-context-optimization — Optimize Hermes startup/context payloads, compression, tool-schema loading, memory/skill injection, and visual-context experiments.

How to use this skill

Skill file

Hermes Context Optimization

Use this when the user asks about Hermes prompt/context size, “hello” startup cost, compression behavior, memory/profile bloat, tool-schema overhead, skill loading, session-store/search-index storage, or multimodal/visual-context approaches such as Snapcompact.

For large state.db search-index maintenance, resumable optimize-storage --no-vacuum runs, foreground timeout handling, and post-run verification, follow references/session-store-optimization.md.

When bounded workers repeatedly fail with session_persistence_failed because a live profile DB is lock-contended, preserve the worktree handoff and use the non-disruptive isolated-HERMES_HOME workflow in references/isolated-worker-state-store.md. Diagnose the profile-specific DB and lock owners first; never terminate a user's live TUI or optimize its store merely to unblock a coding worker.

Operating style for the user

Long standing-goal payloads

When a long /goal prompt is displayed as a compact token such as [[ … [77 lines] … ]], treat that representation as potentially lossy rendered text, not as the authoritative goal body. Hermes' goal state stores the string it receives and does not dereference wiki-style links or recover omitted lines. Before allowing a goal worker to edit anything, require it to read the complete authoritative specification from a file and verify that the first turn contains the expected task scope. Use a short file-backed goal such as: Read and execute the complete goal specification at /absolute/path/goal.md; treat that file as authoritative; do not act on truncated display text. If the worker loads Obsidian or searches for a note matching the compact label, pause/clear the goal: it received the display placeholder, not the task. Do not accept a “goal achieved” result caused only by missing input; require artifact or test evidence.

Reference: references/goal-long-prompt-preservation.md.

Native first-turn inspection

When the question is what Hermes loads or sends on the first message of a fresh session, start with the native surfaces rather than reconstructing the prompt manually:

Full command matrix, Docker examples, and interpretation pitfalls: references/native-context-inspection.md.

Explain schema growth correctly

Tool definitions do not grow merely because a conversation gets older. They are a fixed schema surface for that session/request. The baseline grows when Hermes updates, enabled toolsets, plugins, MCP servers, Office integrations, or dynamic provider tools register additional callable schemas. Prompt caching may reduce repeat billing and latency, but it does not return the occupied context window. State these distinctions before recommending pruning, profile specialization, consolidation, or dynamic routing.

Initial payload triage

When analyzing Hermes startup cost, split the payload into these buckets:

| Bucket | Can be compressed/lazy-loaded? | Notes |

|---|---:|---|

| Core system/developer rules | Partly, but keep authoritative text | Identity, safety, tool policy, authority hierarchy, injection handling, platform rules need reliable system-channel text. |

| Tool schemas | No, unless tools are pruned | Provider needs machine-readable JSON schemas to expose function calls. A screenshot of schemas is not a callable tool registry. |

| Memory/user profile | Yes | Good candidate for tiering, retrieval, or visual appendix. |

| Skill directory/index | Yes | Prefer tiny router/index at startup; load skills on demand. |

| Environment/project notes | Yes | Reference context; retrieve or attach only when relevant. |

| Prior sessions/compressed history | Yes | Good candidate for summary + artifact fallback. |

Preferred optimization order

  1. Measure the payload composition if tools/logs are available: system text, memory/profile, skill directory, tool schemas, platform metadata.
  2. Prune/gate tool schemas first. Tool schemas often dominate startup cost and cannot be replaced by images.
  3. Shrink the authoritative bootloader to core identity/rules only.
  4. Tier memory/profile into always-loaded core facts vs domain/project facts retrieved on demand.
  5. Gate skill directory behind a tiny class-level index and explicit skill_view loading.
  6. Use visual context/Snapcompact only for reference material, not for authority or tool registration.

Live latency attribution

For gateway or voice latency, measure one clean tool-free turn first and inspect logs from a separate controller afterward. Never have the measured agent call log/file tools inside its own latency probe; those calls add model round trips and invalidate the sample. Break the result into model time, actual tool execution, framework overhead, client-to-gateway transport, STT endpointing, and TTS synthesis/playback. Label boundaries that the current build does not timestamp as unmeasured rather than estimating them.

Tool-heavy turns commonly spend most of their time in the repeated model calls around tools, not in tool execution. Compare single-call turns at several input-token sizes to prove context-pressure effects. Tool Router can reduce schemas and unnecessary tool selection, but it does not shrink accumulated conversation history; pair it with an explicit compression/context policy when history is the bottleneck.

Full calculation method and voice-specific acceptance shape: references/gateway-voice-latency-attribution.md.

Snapcompact / visual-context guidance

Snapcompact-style image context can reduce reference-text tokens by roughly the article’s observed ratio:

10,000 text tokens -> 3,279 image tokens ≈ 67.2% reduction

Quick estimate:

image_tokens ≈ text_tokens * 0.3279
saved_tokens ≈ text_tokens * 0.6721

For Hermes startup, report realistic savings only for the imageable portion:

Do not claim the entire initial payload can become an image unless tool schemas and authoritative rules are separately handled.

Safe architecture

Recommended shape:

minimal authoritative text bootloader
+ typed user prompt
+ minimal/gated tool schemas
+ optional visual reference appendix
+ retrieval/lazy loading for memory, skills, and project/domain context

For local-first setups, consider:

snapcompact image -> local vision model extracts relevant section -> main model receives extracted text

This avoids forcing the primary model to OCR every appendix on every turn, but adds latency and OCR risk.

Memory compaction pattern (for reducing initial prompt)

When shrinking always-loaded memory/user_profile:

Operational pitfalls

Memory compaction (proven batch workflow)

When shrinking memory or user_profile:

1) Inspect current entries via terminal if possible:

2) Use a single operations batch instead of many small calls:

3) Avoid tool-loop traps:

4) Expected savings:

Pitfalls

Displayed output vs model-visible context

When the user asks whether a long tool result shown on screen is also fully reread by the model, distinguish the presentation layer from the active prompt. The UI/gateway may display the complete tool output, while Hermes later compacts the model-visible transcript. During context cleanup, the compressor receives the full transcript including tool messages, then performs a cheap pre-pass before any LLM summary: older tool results are replaced with informative one-line records (tool name, operation, exit status or size), identical results are deduplicated while the newest full copy is retained, and old tool-call arguments are truncated. Recent tool results remain verbatim. This is context pruning, not merely a JSON transport separator; JSON is used for message/tool structure and structured summaries, while the token savings come from replacing old content. The original full session remains available in the session store.

Use this concise explanation when asked: “The screen and model context are separate. Hermes can show the full result, but older tool output is later replaced internally with a compact record; recent output stays full.” Do not incorrectly imply that every long result is immediately omitted or that JSON encoding itself causes the reduction.

Compression model requirements (from official behavior)

usable_prompt = parent_context - parent_max_tokens
trigger = usable_prompt × compression.threshold
middle ≈ trigger × (1 - compression.target_ratio)

Then add headroom for the structured-summary instructions, prior summaries, tool metadata, and token-estimation variance. Never describe the raw middle estimate as the whole request size.

Ref: https://hermes-agent.nousresearch.com/docs/developer-guide/context-compression-and-caching

Compression runtime behavior

How Hermes actually routes compression requests:

So the effective path is:

Compression → call_llm(task="compression")

→ auxiliary_client reads auxiliary.compression.*

→ uses that provider/model for the summary call

Implication: to debug "compression still using main model", check BOTH:

A frequent scenario:

Compression troubleshooting (silent failures)

If compression appears stuck, still hitting a previous provider, or silently falling back:

1) Confirm auxiliary.compression is what you expect:

2) Confirm config:

3) Check if compression.summary_model is wired into agent_init.py:

4) Verify the provider block is NOT empty:

5) Fix empty provider:

providers:

lmstudio-windows:

base_url: http://127.0.0.1:1234/v1

api_key: lm-studio

6) Restart gateway:

7) Confirm live:

See references/prompt-composition-baseline.md for measured breakdowns; use those to decide whether enabling the router justifies added latency vs token savings for a given profile.

Silent fallback to main model during compression (IMPORTANT)

Hermes will silently fall back to the main (often expensive/cloud) model for context compression when the configured summary model fails, times out, or returns invalid JSON. This is implemented as _fallback_to_main_for_compression in agent/context_compressor.py.

Behavior:

Common triggers:

How to detect:

How to mitigate (without patching Hermes core):

If you need to prevent fallback entirely, that requires patching _fallback_to_main_for_compression in context_compressor.py. Prefer adjusting model choice or timeout behavior first.

Skill pruning workflow

When reducing initial prompt size by disabling unused skills:

  1. Extract actually-used skill names from session history via state.db. The raw query returns category-prefixed names (apple:imessage, productivity:some-domain-skill) — strip prefixes with sed to match directory names:

```bash

sqlite3 ~/.hermes/state.db "

SELECT DISTINCT json_extract(args, '\$.name')

FROM (

SELECT json_extract(tool_calls, '\$[0].function.arguments') as args

FROM messages

WHERE tool_calls LIKE '%skill_view%' OR tool_calls LIKE '%skill_manage%'

)

WHERE args IS NOT NULL

AND json_extract(args, '\$.name') IS NOT NULL

AND json_extract(args, '\$.name') != ''

" | sed 's|^[a-z]:||; s|./||' | sort -u > /tmp/used_skills.txt

```

  1. Get all installed skill names:

```bash

find ~/.hermes/skills -name "SKILL.md" -exec dirname {} \; | xargs -I{} basename {} | sort > /tmp/all_skills.txt

```

  1. Diff to find unused skills:

```bash

comm -23 /tmp/all_skills.txt /tmp/used_skills.txt > /tmp/unused_skills.txt

```

  1. Check cron jobs for skill references before disabling — a skill may be loaded by cron even if never called interactively. Search actual YAML config files, not log output:

```bash

find ~/.hermes/cron -name "*.yaml" -exec grep -l "skills:" {} \; 2>/dev/null

for f in $(find ~/.hermes/cron -name "*.yaml" 2>/dev/null); do

if grep -q "skills:" "$f"; then

echo "=== $f ===" && grep -A5 "skills:" "$f"

fi

done

```

  1. Add skills.disabled list to ~/.hermes/config.yaml under the top-level skills: key (same level as external_dirs). The patch tool refuses config.yaml — use Python instead:

```python

import yaml

with open('~/.hermes/config.yaml') as f:

content = f.read()

# Insert before ' config:' or append to existing disabled list

content = content.replace(

' - last-skill\n config:',

' - last-skill\n - new-skill\n config:'

)

with open('~/.hermes/config.yaml', 'w') as f:

f.write(content)

```

Alternatively use sed for single-line inserts: sed -i '' '/ - last-skill/a\ - new-skill' ~/.hermes/config.yaml. Avoid multiline \n in macOS sed — it breaks.

  1. Verify with Python YAML parsing — watch for duplicate disabled: keys (YAML silently uses the last one):

```bash

grep -n "disabled:" ~/.hermes/config.yaml # must be exactly one

python3 -c "import yaml; c=yaml.safe_load(open('~/.hermes/config.yaml')); print(len(c['skills']['disabled']))"

```

  1. Restart gateway for changes to take effect:

```bash

launchctl stop ai.hermes.gateway && sleep 2 && launchctl start ai.hermes.gateway

```

See references/skill-pruning-workflow.md for the full session transcript and rationale.

Jinja chat-template auditing

When reviewing a custom Jinja chat-template (e.g., for llama.cpp, vLLM, or Hermes gateway), check for these recurring issues:

  1. Hardcoded overrides block caller params — {%- set enable_thinking = false %} at top level always wins over any external enable_thinking passed in. Fix: wrap in {%- if enable_thinking is not defined %} guard.
  2. Image/video items emit no data — detecting the item type but only outputting \n\n without passing through item.image_url, item.url, or item.image. The model receives a placeholder with no reference to act on. Fix: add .get() fallbacks for common key names.
  3. Double-counting from multi-pass rendering — if render_content is called both in a reverse-scan pass and the main forward loop, ensure the scan pass uses do_vision_count=false so namespace counters stay correct.
  4. Tool arguments as JSON string — OpenAI-format tool calls often send arguments as a JSON string, not a dict. Calling |items on a string iterates characters. Fix: branch on {%- if args is string %} and json.loads(args) first.
  5. Reverse-scan heuristics are fragile — checking content.startswith('...') for tool-result boundaries breaks if user messages coincidentally match. Prefer explicit role-based checks where possible.
  6. Unknown roles crash silently — always include the actual role in the error: 'Unexpected message role: ' + message.role.
  7. Test with representative payloads — use Jinja2's DictLoader + env.globals['raise_exception'] to validate before deploying. Cover: basic conversation, multi-modal content, tool calls with string args, consecutive tool results, reasoning_content, and edge cases (None content, unknown roles).

See references/jinja-chat-template-audit.md for the full audit checklist and test harness pattern.

Recovery from an unrecoverable session context

When a CLI or messaging session reports that context length was exceeded and Hermes cannot compress further, treat the failure as session-scoped, not as evidence that the gateway, topic, project files, or external application are corrupted.

  1. Confirm the failure boundary from the live logs or status surface. A message such as Max compression attempts reached or cannot compress further means another /compress retry is unlikely to recover the in-memory conversation.
  2. Preserve the old session. Do not delete it, and do not restore it with /resume or /topic <session-id> merely to continue the task; those paths can reload the same oversized history.
  3. Start a fresh session in the same messaging topic with /new (or the equivalent new-session command for the client). In Telegram topics, /new resets only the current topic's session and leaves other topics untouched.
  4. Continue with a short, authoritative handoff: current checkout/writer ownership, last verified artifact or acceptance boundary, remaining gate, exclusions, and the evidence required before claiming success. Prefer a file-backed handoff for long work; never ferry the entire transcript into the new session.
  5. Keep the first fresh-session turn narrow and verification-first. Reconcile the checkout and incumbent writer before any write-capable resume, then work only the remaining gate.
  6. Use /context or /usage after several turns. If the new session is again approaching its compression threshold, close it at a clean handoff boundary and hand off again instead of repeatedly forcing compression.

Thin control planes for multi-profile work

A dedicated specialist Telegram bot is not the default fix for context overflow. Keep the assistant as the single user-facing control plane and route long Dev work into tracked profile processes or Kanban instead:

the user → assistant intake/status → domain controller → owning specialist worker

The coordinator topic should carry scope, approvals, compact status, and final evidence—not the worker's full implementation transcript. The domain controller owns architecture/integration and may route bounded child work to specialist profiles; workers return short, file-backed handoffs rather than screenshots, accessibility trees, raw logs, or copied conversation history. Create the durable root card before launch when work outlives the turn, spans profiles, has dependencies/review, or needs restart recovery. Use a separate specialist bot only for deliberate direct access or independent notifications; it adds another gateway/session surface and does not repair delegation by itself.

When a session overflows, do not bypass the control plane by restoring the old transcript in a specialist surface. Start a fresh session, preserve the old history, and resume from a concise handoff after reconciling the exact profile, checkout, and writer owner.

For the Telegram-specific recovery recipe, official command behavior, and the verified incident boundary, see references/context-overflow-recovery.md.

References

Public support files

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.