Hermes plugin development

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

Hermes plugin development is an AI agent skill from the GitHub repository AtlasOmnia/hermes-custom-pack. hermes-plugin-development — Design, register, and debug Hermes plugins — hooks, YAML wiring, profile detection, token routing patterns.

How to use this skill

Skill file

Hermes Plugin Development

Use when: creating, debugging, or integrating Hermes Agent plugins, including Python backend plugins (tools, hooks, routers, middleware) and JavaScript Hermes Desktop runtime plugins.

Core patterns

Reloading Desktop runtime plugins

Desktop plugins normally hot-reload whenever their plugin.js changes. Use the least disruptive path:

  1. Preferred: save the file and verify the contribution updates.
  2. Manual rescan: in Hermes Desktop, open the command palette (⌘K) and run Reload desktop plugins.
  3. If GUI control is unavailable or denied while the user's reload request still stands, retrigger each existing plugin's file watcher without reloading the renderer:

```bash

for f in "${HERMES_HOME:-$HOME/.hermes}"/desktop-plugins/*/plugin.js; do

[ -e "$f" ] && touch "$f"

done

```

Verify the target files' modification times changed, the Hermes process remains running, and—when UI access is available—the plugin contribution is present with no load-error toast.

Do not substitute Electron's View → Reload unless a full renderer reload is acceptable; it is broader than a desktop-plugin reload and can unnecessarily disturb current UI state. Touching a watched file reloads an already-discovered plugin. A newly added plugin directory may still need the command-palette rescan or the app's periodic directory scan.

YAML wiring (critical)

```yaml

name: my-plugin

version: 1.0.0

description: "My plugin"

kind: standalone

requires_env: []

provides_hooks:

```

Hook function naming

```python

def register(ctx):

ctx.register_hook("pre_agent_init", pre_agent_init)

ctx.register_hook("pre_llm_call", pre_llm_call)

ctx.register_hook("post_tool_call", post_tool_call)

```

Profile detection inside plugins

Hermes does NOT reliably set HERMES_PROFILE when using --profile <name>. Don't trust it blindly.

Safe pattern (from the hardened hermes-token-router):

For the user's router experiments, use a dedicated isolated test profile, snapshot the installed plugin/config first, and keep global/default routing disabled.

Token router / tool routing patterns

For plugins that predict or reduce tools:

See references/tool-router-production-hardening.md for the full implementation, intent-collision pitfalls, and live validation workflow.

Composing with external model-routing gateways

When Hermes is placed behind an OpenAI-compatible model gateway, compose the systems instead of merging repositories: Hermes owns the agent/tool loop, a tool router owns schema reduction, and the gateway owns upstream model choice. Use a separate profile-gated llm_request middleware plugin to inject a stable session-affinity header; do not fold provider routing, credentials, or privacy policy into the tool router.

Keep document/add-in bridge authorization separate from model affinity, use explicit allowlisted model pools, and fail closed for sensitive routes rather than bypassing the gateway through an unrelated cloud fallback. Generic custom providers are the first integration target; specialized Hermes-managed OAuth transports require an independent compatibility design.

Full architecture, privacy rules, and verification gates: references/external-model-gateway-affinity.md.

Runtime hook-composition contract

Never read or replace a plugin context's private hook storage (for example, ctx.hooks). A runtime may expose only ctx.register_hook(...), and even when multiple registrations are accepted their replacement/chaining semantics are runtime-specific.

For a wrapper that adds policy around a base hook:

  1. Build one merged kwargs mapping in the wrapper, resolving every wrapper-owned dependency (profile_name, surface, registry/audit paths, etc.). If the runtime supplies a key with None or an empty value, dict.setdefault() will not apply the fallback; assign the resolved value explicitly (merged['registry_path'] = resolved_registry_path) so required dependencies cannot be erased by a null runtime field.
  2. Pass that same merged mapping to both the wrapper's additional policy and the base hook. Computing defaults and then calling the base hook with the original kwargs silently discards the dependencies.
  3. Prefer an explicit composed callback registered through the public API; do not assume a second register_hook call preserves a previous callback.
  4. Add a regression fake that has register_hook and register_tool but deliberately lacks hooks, then invoke the registered hook without private injected parameters. Assert the normal policy path works rather than returning a configuration-path error.
  5. Prove the actual live runtime with a fresh process; local fake-context success alone does not establish hook ordering or discovery behavior.

See references/runtime-hook-composition-regression.md for the concrete policy-plugin failure sequence and canary matrix.

Controlled-launch preflight disagreement

For policy-plugin repairs that must use a controlled inspect_project / launch_specialist seam, treat a non-zero Git preflight inside the registered candidate root as a hard checkout-accessibility HOLD, even if a registry snapshot says the root is clean and writer-free. Never work around that by launching an ungoverned writer or deploying a previously staged payload. A staged manifest proves only the bytes present when it was created; compare the staged hashes for every required repair file—especially wrapper/bootstrap files—before considering it a candidate. If the active repair requires a later wrapper/config-propagation change absent from staging, preserve the stage and restore/reconcile source Git accessibility before retrying the one controlled launch. Record the exact Git subcommand and exit status as evidence.

Self-gated repair deadlock (policy plugin blocks its own deployment)

When the policy plugin that gates general execution is itself the broken component and its installed payload is stale:

  1. Expect every fresh profile session (default and specialist profiles) to resolve as the default profile and deny terminal/execute_code with default profile must use controlled supervisory tools. Proven live: a specialist-profile one-shot received the default-profile verdict.
  2. Agent-routed deployment is therefore impossible — including cron agent ticks, whose delegates inherit the same denied surface AND do not expose the controlled tools (tool_search finds none in subagent runtimes).
  3. Use the scheduler script channel instead: a no_agent: true cron job executes its script directly in the scheduler process, entirely outside the agent tool surface — the same mechanism apply-patches.sh and watchdog scripts already use. This is sanctioned infrastructure operation, not a guard bypass; keep the canary and rollback gates intact.
  4. Split the deployment into two phases with a review boundary: Phase A read-only (verify HEAD/dirty set, run the real test suite, snapshot per-profile installed hashes for rollback, stage an immutable merged payload with a hash manifest); Phase B (atomic per-profile replacement, fresh-process discovery canaries, gateway restart only after all pass, automatic rollback on any failure, exact result artifact DEPLOYED_AND_VERIFIED/ROLLED_BACK/HOLD).
  5. Never deploy a staged payload whose provenance predates the final candidate dirty set; re-stage from current candidate bytes.

Launch mechanics learned alongside this case:

See references/self-gated-policy-plugin-deployment.md for the worked case and script skeleton.

Debugging checklist

When a plugin loads but does nothing:

Provider API format mismatches

When a plugin calls an external model/API directly (without going through Hermes' provider routing):

Router prediction — provider selection

For plugins that call a small classifier before the main turn, latency and failure isolation matter more than model sophistication.

the user-specific default: deterministic-first, external classifier disabled unless needed. If enabled, prefer direct DeepSeek or a local OpenAI-compatible endpoint. Use OpenRouter only when the user explicitly requests it.

Requirements:

Avoid Codex for small router calls unless you intentionally implement its Responses API transport.

Trusted hook state across copied contexts

Hermes may run a tool handler and post_tool_call hook in a copied execution context rather than the exact context that ran pre_tool_call. Never create a ContextVar.Token in the parent hook, transport it through another context variable, and call Token.reset() in the copied worker: Python raises a cross-context ValueError, while isolated hook-error handling can make the tool appear successful and leave sensitive payload/trust state retained in the parent.

Use a bounded, synchronized one-shot holder keyed only by trusted runtime identity. Consumption and cleanup must be atomic and valid from either context, fail closed on stale/missing/mismatched state, and leave no usable payload or trusted metadata in parent or worker. Test the real topology with contextvars.copy_context() or Hermes' context-propagation helper; same-context hook tests are insufficient. Require one dispatch, no cleanup exception, no retained state in either context, concurrent isolation, and duplicate-turn rejection before mutation.

See references/hook-contextvar-lifecycle.md for the failure reproduction, durable design rules, and regression matrix.

Threaded timeout for plugin API calls

When a plugin makes an external API call, enforce a real caller deadline and fail open.

Pitfall: with ThreadPoolExecutor(...) plus future.result(timeout=...) is not a hard deadline. After the timeout, leaving the context manager calls executor shutdown and may wait for the hung worker.

Use a daemon worker and bounded queue (or a transport with enforceable cancellation):

import queue, threading

results = queue.Queue(maxsize=1)
def worker():
    try:
        results.put((True, call_provider()), block=False)
    except BaseException as exc:
        results.put((False, exc), block=False)

threading.Thread(target=worker, daemon=True).start()
try:
    ok, value = results.get(timeout=1.2)
except queue.Empty:
    return None  # full-surface fallback; do not join the worker
if not ok:
    return None
return value

Test elapsed wall time with a deliberately sleeping worker so a future refactor cannot silently reintroduce shutdown waiting.

str.format() and JSON templates — curly brace escape

When a plugin prompt template uses str.format() and contains JSON examples (common for router/classifier plugins), curly braces in the JSON MUST be escaped by doubling ({{ and }}):

# BROKEN — KeyError: '"toolsets"'
ROUTER_PROMPT = """Example response:
{"toolsets": ["terminal", "web"]}"""

# FIXED — double the braces in JSON examples
ROUTER_PROMPT = """Example response:
{{"toolsets": ["terminal", "web"]}}"""

Python's str.format() interprets ALL {...} as format fields, including those inside JSON literals. This is a silent runtime error (caught by except Exception) that produces no visible output unless you have debug prints inside the except block.

Profile config changes — update .env too

When changing a profile's model or provider, you MUST update both:

  1. config.yaml — model.provider and model.default
  2. .env — HERMES_INFERENCE_PROVIDER and LLM_MODEL

.env values override config.yaml at Hermes startup. Changing only config.yaml leaves the old provider in effect, producing silent connection failures to unreachable endpoints.

Debugging plugin output — use files, not pipes

When debugging plugin print() output via hermes --profile X chat -q "...":

Model command availability drift checks (e.g. `/modelx`)

When a scoped command like /modelx appears in docs or patch trails but is missing in runtime, verify in order:

Pitfall: patch apply logs can be noisy; a successful return code is not proof of semantic parity.

See references/modelx-branch-drift-triage.md for a proven diagnostic flow.

Public distribution prep

When preparing a local/dogfood plugin for GitHub public distribution:

Cross-platform deterministic-prefetch integrations

For a plugin that performs a deterministic read-only lookup before the main model call (calendar, email, Drive, reminders, or similar), treat local dogfood code as a prototype until all of these are true:

Keep the reusable workflow in references/cross-platform-prefetch-publication.md.

Least-privilege OAuth for Workspace prefetch plugins

When adding Gmail or another sensitive Workspace adapter, treat authorization as a separate human gate from implementation:

This keeps implementation evidence separate from live authorization evidence: green tests prove the adapter contract, not that a user's Gmail account has been authorized.

Detailed workflow: references/least-privilege-workspace-oauth.md.

Long-goal handoff and delegated acceptance

For long autonomous coding goals that prepare a public plugin or desktop bridge:

See references/long-goal-public-prep-handoff.md for the compact handoff and acceptance checklist.

When preparing a local/dogfood plugin for GitHub public distribution:

Detailed checklist: references/public-plugin-distribution-checklist.md.

Repo replacement workflow: references/public-plugin-repo-replacement.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.