[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7F657RTE2YX8H8CKXJBAPC8":3,"skill-same:01M7F657RTE2YX8H8CKXJBAPC8":89},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":47,"commitSha":48,"skillDirectory":49,"forksCount":14,"repositoryHtmlUrl":50,"repositoryHomepageUrl":6,"ownerHtmlUrl":51,"ownerBlogUrl":52,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M7F657RTE2YX8H8CKXJBAPC8","hermes-plugin-development",null,"Use when building or extending a Hermes plugin.","chaorenex1\u002Fhermes-home-content","chaorenex1","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F23194925?v=4","01M7F5NA1D1D02R2MEMYQN2NZT","chan chan","01M7F5NA20KTHMTY2015CYM1TZ",0,"MIT","https:\u002F\u002Fgithub.com\u002Fchaorenex1\u002Fhermes-home-content\u002Fblob\u002Fmain\u002Fskills\u002Fautonomous-ai-agents\u002Fhermes-plugin-development\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\r\nname: hermes-plugin-development\r\ndescription: \"Use when building or extending a Hermes plugin.\"\r\nversion: 1.0.0\r\nauthor: Masia\r\nlicense: MIT\r\nplatforms: [linux, macos, windows]\r\nmetadata:\r\n  hermes:\r\n    tags: [hermes, plugins, register, llm, subagents, hooks, middleware, validation]\r\n    related_skills: [hermes-agent, hermes-web-provider-plugin, hermes-secret-source-plugins, lancedb-memory-plugin-development, safe-extension-deployment]\r\n---\r\n\r\n# Hermes Plugin Development\r\n\r\nCross-type knowledge for `plugin.yaml` + `register(ctx)` plugins under `$HERMES_HOME\u002Fplugins\u002F\u003Ccategory>\u002F\u003Cdir>\u002F`: giving a plugin AI capability (LLM calls, child agent sessions), participating in the main agent loop, and the validation loop that proves a registration actually works.\r\n\r\n## When to Use\r\n\r\n- Building or extending any Hermes plugin: tools, hooks, commands, LLM calls (`ctx.llm`), child agent sessions (`ctx.subagent_lifecycle`), or answering \"how do I do X in a plugin\".\r\n- Debugging a plugin registration, hook, or LLM\u002Fsubagent call that does not behave as documented.\r\n- Type-specific plugin kinds load their own skill instead: web-search\u002Fextract provider → `hermes-web-provider-plugin`; secret-source backend → `hermes-secret-source-plugins`; LanceDB memory → `lancedb-memory-plugin-development`. Finished-plugin deployment (atomic swap, rollback, runtime verification) → `safe-extension-deployment`. Recovering another agent's adviser\u002Freviewer mechanism to port into a plugin → `agent-internals-forensics`.\r\n\r\n## Answer from the live install, not memory\r\n\r\nPlugin contracts move between releases. Before answering or writing plugin code:\r\n\r\n1. `hermes --version` — prints the live Install directory (`...\u002Finstalls\u002F\u003Chash>\u002Fenvironments\u002F\u003Chash>\u002Fworkspace`).\r\n2. Read the contract in the live tree: `hermes_cli\u002Fplugins.py` (PluginContext registrars + `VALID_HOOKS`), `agent\u002Fsubagent_lifecycle.py`, `agent\u002Fplugin_llm.py`.\r\n3. Read the in-tree docs — do not guess: `website\u002Fdocs\u002Fdeveloper-guide\u002Fplugins\u002Findex.md` (registrars, hook table, middleware table), `plugin-llm-access.md`, `subagent-lifecycle-api.md`; public hook reference in `website\u002Fdocs\u002Fuser-guide\u002Ffeatures\u002Fhooks.md`.\r\n4. A second source checkout may exist (`$HERMES_HOME\u002Fhermes-agent\u002F`); confirm parity (`diff -q \u003Ca> \u003Cb>`) before citing either tree — the running install is the one that counts.\r\n\r\n## Pick the AI surface (decision table)\r\n\r\n| Need | Surface | Owns an agent loop? |\r\n|---|---|---|\r\n| One LLM call (summarize \u002F classify \u002F rewrite \u002F extract) | `ctx.llm.complete()` \u002F `complete_structured()` (+ async variants) | No — single bounded call, no tool loops |\r\n| Full child agent (LLM + tools, own loop) | `ctx.subagent_lifecycle.launch(SubagentLaunchRequest(...))` | Yes — same host path as `delegate_task` |\r\n| Observe\u002Fsteer the user's running turn | `ctx.register_hook(...)` \u002F `ctx.register_middleware(...)` | No — participates in the main loop |\r\n| Direct in-process `AIAgent` | `from run_agent import AIAgent` | Bundled-plugin escape hatch only — private core import |\r\n\r\nExhaustive request fields, limits, states, methods, routing rules, and pitfalls: `references\u002Fllm-and-agent-loops.md`\r\n(which also carries the working script-probe recipe: import `run_agent` BEFORE any `hermes_cli.*` module).\r\n\r\n## Escalate to async without duplicating the loop\r\n\r\n`AIAgent`'s loop is synchronous — there is no `async def` in `run_agent` or\r\n`agent.conversation_loop` — so an async surface offloads the *whole* run; it never wraps a single\r\ncall in a coroutine. Ship both entries from one implementation:\r\n\r\n```python\r\ndef run(message, *, context=\"\", model=\"\", provider=\"\", toolsets=None) -> AgentRun:\r\n    ...                                   # sync; import run_agent FIRST inside it\r\nasync def run_async(message, **kw) -> AgentRun:\r\n    return await asyncio.to_thread(run, message, **kw)\r\n```\r\n\r\n- Register the coroutine function together with `is_async=True`\r\n  (`ctx.register_tool(..., handler=handle_async, is_async=True)`); `tools.registry.dispatch`\r\n  bridges it for sync callers through `_run_async()` and is safe inside a running loop.\r\n- The pairing is strict and fails at dispatch, not at registration: async handler +\r\n  `is_async=False` hands a coroutine to the result normaliser, sync handler + `is_async=True`\r\n  hands a string to `await`. `validate` compares names, not callable shapes — only an execution\r\n  probe catches the swap.\r\n- Keep the route owner thin: the loop lives in its own module (`run` \u002F `run_async` + a small\r\n  result dataclass), while the aux-task plugin keeps only config, framing, schema and the two\r\n  handlers. Two copies of the constructor drift the moment one gains `reasoning_config` or a\r\n  new guard.\r\n- Keep the loop's EXTERNAL surface to what a caller can actually know — message, context, system\r\n  message, model, provider, toolsets — and resolve model + credentials + reasoning + budget inside the\r\n  runner with the gateway helpers (`gateway.run._load_gateway_config` \u002F `_resolve_gateway_model` \u002F\r\n  `_resolve_runtime_agent_kwargs`, `hermes_constants.resolve_reasoning_config`), the way\r\n  `feishu_comment.py::_resolve_model_and_runtime` does. A caller forced to assemble\r\n  `api_key`\u002F`base_url`\u002F`api_mode`\u002F`credential_pool` is a design error: every call site repeats the\r\n  plumbing and one of them forgets `reasoning_config`. A pinned `provider` re-resolves that\r\n  provider's credentials — never send another provider's model with the main route's key.\r\n- A system message belongs to the TURN (`run_conversation(prompt, system_message=...)`), not to the\r\n  constructor and never merged into the user message. Persona\u002Frubric text prepended to the message\r\n  pollutes the evidence the peer is asked to judge; `ephemeral_system_prompt=` at construction binds\r\n  it for the agent's whole life and hides it from callers who only supply one.\r\n- Isolation of a peer run is explicit: `skip_context_files=True`, `skip_memory=True`,\r\n  `skip_background_review=True`, and a deliberate decision on `load_soul_identity` — that flag LOADS\r\n  the operator's SOUL identity (it is not an isolation switch), so \"all four True\" means isolated\r\n  from project\u002Fmemory\u002Freview but speaking in the configured voice.\r\n- `asyncio.to_thread` copies the contextvars, which is what the gateway's per-profile secret\r\n  scope needs; `close()` then runs in the worker thread that built the agent.\r\n\r\n## Run an agent loop: ctx.subagent_lifecycle\r\n\r\n```python\r\nfrom agent.subagent_lifecycle import SubagentLaunchRequest   # public allowlisted import\r\n\r\ndef run_review(args, **kwargs):          # _ctx captured in register(ctx)\r\n    svc = _ctx.subagent_lifecycle\r\n    handle = svc.launch(SubagentLaunchRequest(\r\n        goal=\"Review this change for regressions.\",\r\n        context=\"Only inspect the supplied repository.\",\r\n        role=\"leaf\",\r\n        allowed_toolsets=(\"file\",),      # registered names; subset of parent's\r\n    ))\r\n    term = svc.wait(handle, timeout_seconds=120)\r\n    if term.timed_out:\r\n        return json.dumps({\"success\": True, \"data\": {\"state\": term.state.value,\r\n                                                     \"handle\": handle.to_dict()}})\r\n    r = svc.result(handle)               # .summary \u002F .terminal_state \u002F .result_hash\r\n    return json.dumps({\"success\": True, \"data\": {\"state\": r.terminal_state.value,\r\n                                                 \"summary\": r.summary}})\r\n```\r\n\r\nRules that cause first-try failures (full list in the reference):\r\n\r\n- Callable only inside an active agent turn — a plugin tool handler or a hook callback. Outside one it raises `SubagentLifecycleError` (\"No active Hermes parent session is available.\"). Works in CLI, gateway, non-interactive, kanban-worker sessions.\r\n- `allowed_toolsets` must be registered names and a subset of the parent's toolsets — it narrows, never broadens.\r\n- `timeout_seconds`, `working_directory`, `blocked_tools` are rejected by launch validation — do not pass them (per-launch timeouts are not supported, children get isolated workdirs, per-tool blocking must be expressed as `allowed_toolsets`). They DO exist as fields on the frozen dataclass, so `dataclasses.fields()` and autocomplete suggest they work; the rejection fires inside `launch()`.\r\n- `provider=` must already be a configured Hermes provider; routing precedence is request.provider > delegation config > parent.\r\n- `agent.subagent_lifecycle` is on the public import allowlist; `run_agent` is not (see the escape hatch in the reference).\r\n- Copy-ready pair that already passed `validate` + `doctor`: `templates\u002Fagentloop_plugin_init.py` + `templates\u002Fagentloop_plugin.yaml`. Register the tool under the plugin's own toolset namespace, not a core one.\r\n\r\n## Mid-turn seams: what a hook or middleware can actually change\r\n\r\nHooks and middleware are not interchangeable; pick by when the effect must land.\r\n\r\n- `pre_llm_call` runs ONCE per turn in the prologue, and its context is stamped into the turn's user\r\n  message and replayed byte-for-byte for every provider attempt that turn. It cannot inject per\r\n  tool-loop iteration.\r\n- `llm_request` middleware runs per provider attempt, returns `{\"request\": {...}}` to replace the\r\n  provider kwargs, and is synchronous with no timeout wrapper: ledger reads only, never a model call.\r\n- A `pre_tool_call` block is visible: the message becomes that tool call's result, so the model may\r\n  retry. Cap it per turn and reserve it for mutating tools.\r\n- `pre_verify` keeps a turn going only when the turn edited files, and only up to\r\n  `agent.verify_hooks.max_verify_nudges` — it is not a general continuation channel.\r\n- `on_interim_message` carries visible assistant text only. `post_auxiliary_call` carries usage per\r\n  auxiliary attempt and is the meter for a plugin's own LLM calls.\r\n- Hooks are bounded by `plugins.hook_callback_timeout` (default 30s; a slow callback is abandoned and\r\n  suppressed for 60s). Model work belongs on a worker thread.\r\n- The system prompt is built once per session and replayed; no plugin rewrites it mid-session.\r\n- `VALID_HOOKS` in the live `hermes_cli\u002Fplugins.py` is the authority; the public hooks page lags.\r\n\r\nUrgency-to-seam mapping, the exact return contracts, and the two-attempt probe that proves which\r\nseam fired: `references\u002Fhook-and-middleware-seams.md`.\r\n\r\n## One ledger, one producer\r\n\r\nA layered plugin that writes the same review table from two places (a cadence-based deeper\r\nreviewer and a per-turn injector) ends up with duplicate advice that dedupe can only hide. Merge\r\nthe production path, not just the output: the deeper layer keeps its own artifact (a correction\r\nnote on the artifact it owns) and the live reviewer is the only writer of advice rows.\r\n\r\n- **Retire a producer in one change.** Grep the removed contract key across the plugin *and*\r\nthe tests before running anything: prompt contract, parser\u002Fnormalizer, store write, artifact\r\nsection heading, the consumer's candidate block, the store's consume\u002Fpromotion branch, and every\r\nfixture helper that builds the old reply. A shared per-file fixture (`_dialectic_json(...)`) makes\r\nthis one edit; hand-rolled payloads scattered per test make it a sweep.\r\n- **Give retired rows an explicit fate.** Pending rows of a source nobody writes any more are a\r\nsilent leak: expire them through the existing TTL path, ignore them on read, or migrate them, and\r\nsay which in the code. Never leave a consumer still reading a source that has no producer.\r\n- **Republish on no-op, or the old artifact stays live.** If the deeper layer's artifact only ships\r\nwhen it changes something, the last advice-bearing artifact survives as the \"latest\" one forever.\r\nPublish a truthful no-change note (`- no change this window`) so the stale text is replaced.\r\n- **Section headings are a contract.** The `## Heading` set is duplicated in the artifact\r\nvalidator, the store's section→conclusion map, and the prefetch\u002Fdigest readers. Rename it in all\r\nof them in the same change; a half-renamed heading silently stops indexing the new artifact while\r\nthe old rows keep serving as current.\r\n- When the layer's only product is a correction of a specific row (a base refresh, a job window),\r\n  skip the model call entirely if that row is absent. A review with nowhere to write its result burns\r\n  tokens and produces nothing.\r\n- **A downstream review validates against its source row, not a blanket non-empty rule.** An\r\n  upstream pass can legitimately publish sparse cards (a window with no identity or summary\r\n  evidence); a review that echoes those empty fields is faithful, not broken. Reject only content\r\n  the source row carried and the reply dropped, plus listed explicit clears. A validator that\r\n  demands every field be non-empty fails every review of a sparse window, retries twice, and keeps\r\n  the content watermark stuck. The artifact docs must state the same rule in every section, or one\r\n  will promise \"empty arrays are valid\" while the validator refuses them.\r\n- **Deliver after the turn ends.** A plugin has no send API of its own: when advice arrives after the\r\n  final answer and must reach a gateway chat, call the host tool in-process —\r\n  `send_message_tool({\"target\": platform, \"action\": \"send\", \"message\": text})` — and treat\r\n  `json.loads(result)[\"success\"]` as the receipt, so a rejected send leaves the row pending instead of\r\n  claiming delivery. Guard on platform (never CLI\u002FTUI) and keep a notified-id set so a retry does not\r\n  repeat the message.\r\n- **Sweep at the terminal hook, not only at publish.** A background review can finish before\r\n  `post_llm_call` marks the turn terminal, so a notify-on-publish check alone misses it. Do both: the\r\n  publish path notifies when the session is already terminal, and the terminal hook sweeps rows nobody\r\n  has sent. The notified-id set makes the double path idempotent.\r\n\r\n## Validation loop (before claiming anything works)\r\n\r\n- `hermes plugins validate \u003Cplugin_dir>` — runs `register(ctx)` with a real context: undeclared tools (`provides_tools`), collisions, import errors; warns on private core imports (catalog rule 9).\r\n- `hermes plugins doctor \u003Cplugin_dir>` — full discovery + import in a temp `HERMES_HOME`; prints the registration count (`registrations: 1 tool(s), 0 hook(s)`) — that line is the cheap proof a handler\u002Ftoolset mismatch did not silently drop the tool.\r\n- Local dev install is a copy, not `hermes plugins install`: that subcommand takes a catalog entry name, a Git URL, or `owner\u002Frepo` shorthand — never a local directory. Place the dir under `$HERMES_HOME\u002Fplugins\u002F\u003Cname>\u002F`, then `hermes plugins enable \u003Cname>` (writes `plugins.entries`; never hand-edit config.yaml).\r\n- Repo vs install: when the plugin is developed in a git checkout while a copy also sits under `$HERMES_HOME\u002Fplugins`, make and verify the change in the repo, then deploy it — the user treats the installed copy as this plugin's deployment target and expects replacement + gateway restart + live verification in the same task, not a fix that only lives in the checkout. Back up the installed tree first and report the path, and put the backup outside `$HERMES_HOME\u002Fplugins\u002F`: that root is the provider discovery root, so a sibling copy left inside it is a candidate second provider. On Windows the running gateway can hold the installed directory: `hermes gateway stop`, replace the tree (`rm -rf` then `cp -a`, which preserves mtimes), `diff -rq --exclude=__pycache__` against the repo, then start the gateway. Replacing under a live process fails or leaves a half-copied tree. After `hermes gateway restart`, prove the new code loaded from `logs\u002Fagent.log` (the manifest parse line names the install path, then the plugin's own hook lines appear); a \"port still accepting connections\" warning during restart is the old process draining, not a failure. A new default in the provider's config defaults applies to every live config that omits the key, so read the deployed config block before shipping a risky default and state the behavior change in the deploy report. Before overwriting, diff it: content the repo lacks is either an older generation (git log shows the removal) or a hand edit that exists nowhere else — a backup alone is not a decision. The ask-first exception is a different plugin owning the same aux key or tool name; report that conflict instead of retiring the other plugin by deleting it.\r\n- Tool handlers must return a JSON **string** (the registry rejects plain dicts; only the multimodal envelope passes).\r\n- Contract-mode test runs: point the suite at the host (`HERMES_WORKSPACE=\u003Cinstall workspace>` + the host venv's python). A bare local interpreter can lack host deps and produce false failures that look like your change; a suite that boots the real `agent.*` \u002F `tools.registry` modules is the only run whose pass means anything. Two `-q` flags (a `pytest.ini` `addopts = -q` plus `-q` on the command line) also suppress the final `N passed` line — read the exit code, and take counts from `--co` (it prints `file.py: N` rows) instead of re-running to find out whether it passed.\r\n- Prove hook **dispatch**, not just registration: `validate` and `doctor` check declared names and that `register(ctx)` runs, but only the agent's own dispatch proves a callback's return value is consumed. Stage the plugin into a temp `HERMES_HOME`, run the host venv python with the workspace on `sys.path`, call `hermes_cli.plugins.discover_plugins()`, then dispatch exactly as the loop does: `invoke_hook(\"pre_tool_call\", tool_name=..., session_id=...)`, `get_pre_verify_continue_message(session_id=..., changed_paths=[...])`, or `invoke_hook(\"pre_llm_call\", user_message=..., parent_session_id=\"\")`. Seed the provider state (a pending row, a bound session) first, and assert the second call no longer fires — one-shot semantics are part of the contract.\r\n- **A plugin scheduler fires in tests too.** With `cadence: 1` the background worker reviews on the first recorded event, so a test that then calls the worker method directly runs it twice and the call counter doubles (N becomes 2N, one per roster member). Give the test config a high cadence and drive the method explicitly, or `wait_idle()` before asserting call counts; assert the *prompt* content rather than the call count when both paths must run.\r\n- Registration metadata (tool\u002Fskill descriptions) is snapshotted at load; a running Gateway needs a plugin reload for changed registration metadata to land — re-`enable` of an already-enabled plugin is a no-op.\r\n\r\n## Diagnose from the host's logs, before touching code\r\n\r\nA \"check the logs and fix the plugin\" request is evidence work: the installed copy can be commits\r\nbehind the repo, so part of what the log shows may already be fixed.\r\n\r\n1. Read `$HERMES_HOME\u002Flogs\u002F`: `agent.log` (plugin lifecycle, per-turn hooks, model calls),\r\n   `errors.log` (WARNING+), `gateway-stdio.log` (the one-line `[gateway-crash] thread \u003Cname> raised ...`),\r\n   `tui_gateway_crash.log` (the full traceback behind that line), `gateway.log` (host startup). Group\r\n   matches by normalized message — one repeating warning is one bug, not N.\r\n2. Prove each candidate is live before patching: grep the source for the exact method\u002Fattribute named\r\n   in the traceback, and `diff -rq --exclude=__pycache__` the installed copy against the repo. A\r\n   stale install replays already-fixed errors; deploying is the whole fix and no code change is owed.\r\n3. Reproduce at the narrowest layer (call the failing store\u002Fworker method directly, or drive the\r\n   tracker with an injected clock), then keep that reproduction as a regression test that fails on\r\n   the old predicate. Prove the test is red on the old code with a path-scoped stash:\r\n   `git stash push -- \u003Cfile>`, run that single test, `git stash pop`; unrelated uncommitted work\r\n   stays put. A test that only asserts \"does not raise\" is vacuous when the old code already\r\n   swallowed the exception — assert on the log record or the returned status instead.\r\n4. Separate model-quality failures from code defects before patching. \"returned invalid JSON\",\r\n   \"empty cards\" and \"no usable JSON after 2 passes\" are not one bug: an \"empty cards\"\r\n   rejection can be a validator contradicting an upstream pass that legitimately emitted empty\r\n   fields (compare the reply with the source row it reviews), while a malformed reply from a small\r\n   aux route is model behaviour (check `auxiliary.\u003Ckey>.model`). Read `agent.log`'s\r\n   `API call #N ... out=\u003Ctokens>` and `Turn ended ... api_calls=N\u002FM response_len=\u003Cchars>` lines: a\r\n   run that spends its tool budget on `tool_search`\u002F`tool_describe` and ends with a long text\r\n   answer is tool-thrash, not JSON incapability. Cap that budget and give it one no-tools repair\r\n   pass; only truncated or invalid JSON with no tool calls is a reason to raise the aux model.\r\n5. Fix, run the full suite, run the repo's host-verification script (often\r\n   `scripts\u002Fverify_against_host.py --host-python \u003Chost venv>\u002Fpython.exe --workspace \u003Cinstall>`;\r\n   auto-detect fails on a non-standard install), deploy, restart the gateway, then re-grep the logs\r\n   for zero new warnings from the plugin. Swap\u002Frollback mechanics: `safe-extension-deployment`.\r\n\r\n## One directory, several surfaces (provider + tools + hooks + aux route)\r\n\r\nA memory-provider plugin is not limited to `register_memory_provider`: the memory loader builds a real\r\n`PluginContext` (`plugins\u002Fmemory\u002F__init__.py`), so `ctx.register_hook`, `ctx.register_tool` and\r\n`ctx.register_auxiliary_task` all work from the same `register()` — one repo can ship the provider, its hooks,\r\na tool and its own `auxiliary.\u003Ckey>` model route.\r\n\r\n- **Aux tasks need no manifest field; ctx-registered tools and hooks do.** List every tool passed to `ctx.register_tool`\r\n  under `provides_tools:`, and every hook passed to `ctx.register_hook` under `provides_hooks:`. `hermes plugins validate`\r\n  FAILS on an undeclared tool (\"undeclared tools registered\") and only warns about a declared-but-unregistered one; the\r\n  manifest-contract test also compares `provides_hooks` against the registered hook set, so adding a hook is a three-file\r\n  change (registration, manifest, that test). Tools a provider returns from `get_tool_schemas()` do\r\n  NOT belong there — they never touch the plugin registry.\r\n- **Collisions are asymmetric, and both are process-wide.** A foreign `auxiliary` key raises `ValueError`\r\n  (\"already registered by plugin X\"); a duplicate tool name is refused with a warning and `register_tool`\r\n  returns `None` instead of raising. So put the optional surface in its own `try\u002Fexcept` inside `register()` and\r\n  keep the primary registration outside it: a refused adviser route must never cost the memory provider.\r\n- **Moving a surface between plugins means retiring the old owner first** (uninstall\u002Fdisable, or the new\r\n  registration is refused\u002Fignored). Keep the toolset name stable when you do — per-platform `toolsets:` lists\r\n  select the toolset, not the plugin.\r\n- Probing the registered surface end-to-end: assert `get_plugin_auxiliary_tasks()` contains the key and\r\n  `tools.registry.registry.get_entry(\u003Ctool>)` returns an entry with the expected `.toolset` and `.is_async`,\r\n  inside a host probe (temp `HERMES_HOME`, repo staged as `plugins\u002F\u003Cname>`). That catches \"registered but not\r\n  callable\" and a handler\u002Fflag mismatch, neither of which manifest validation can see.\r\n\r\n## Memory-provider plugins (`plugins\u002Fmemory\u002F` contract)\r\n\r\nBundled examples to copy from: `plugins\u002Fmemory\u002Fbyterover` (CLI-backed) and\r\n`plugins\u002Fmemory\u002Fretaindb` (cloud + write queue) in the live install tree.\r\n\r\n- `register(ctx)` calls `ctx.register_memory_provider(instance)` — one instance per plugin. Discovery order:\r\n  bundled `plugins\u002Fmemory\u002F\u003Cname>\u002F` → `$HERMES_HOME\u002Fplugins\u002F\u003Cname>\u002F` → `.\u002F.hermes\u002Fplugins\u002F\u003Cname>\u002F`\r\n  (`HERMES_ENABLE_PROJECT_PLUGINS`) → pip entry points `hermes_agent.memory_providers`. The cheap scan\r\n  reads the first 8 KB of `__init__.py` for `register_memory_provider`\u002F`MemoryProvider`; `doctor` then\r\n  auto-detects `kind: exclusive` from the same markers (no `kind:` field needed in plugin.yaml).\r\n- **The INSTALLED DIRECTORY name is the provider name** `memory.provider` selects (`find_provider_dir(name)`\r\n  → `\u003Cplugins>\u002F\u003Cname>`). The `name:` field and the `name` property are labels — a hyphenated repo cloned\r\n  as-is only activates if `memory.provider` equals that directory name; otherwise clone into\r\n  `plugins\u002F\u003Cprovider-name>`. Rename all three together.\r\n- ABC lives at `agent\u002Fmemory_provider.py` (read it live): abstract = `name`, `is_available`, `initialize`,\r\n  `get_tool_schemas`; everything else has no-op defaults. `initialize(session_id, **kwargs)` always carries\r\n  `hermes_home` (profile-scoped — never hardcode) and `agent_context`; subagent\u002Fcron\u002Fflush contexts must not\r\n  write memory. `handle_tool_call` must return a JSON **string** (`tool_error()` from tools.registry).\r\n- Threading model: `sync_turn` and `queue_prefetch` run on the MemoryManager's background worker,\r\n  `prefetch` runs on the critical path under a timeout (a still-running previous prefetch skips the\r\n  provider that turn). So: do I\u002FO in `queue_prefetch`, consume the cached block in `prefetch`, and let\r\n  unexpected failures propagate only from `prefetch` (it is re-raised there); swallow errors in hooks.\r\n- **Every background thread must inherit the caller's contextvars.** Spawn with\r\n  `agent.memory_provider.spawn_context_thread(target, name=...)` (or\r\n  `contextvars.copy_context().run`), never a bare `threading.Thread`. Profile isolation is a\r\n  ContextVar-scoped HERMES_HOME override plus a per-turn secret scope; a bare thread starts empty and\r\n  therefore reads the default profile's secrets or fails closed with `UnscopedSecretError: Hermes\r\n  could not read this profile's \u003CENV_VAR>`, which kills the review\u002Fjob on every run. This covers\r\n  every helper thread, including a run-with-timeout wrapper that calls an LLM and any reviewer\r\n  worker that must not steal the main loop. Probe it: set a ContextVar in the caller and have the\r\n  spawned thread report it back — a bare thread returns the default.\r\n- **A long-lived worker must carry the context per job, not once at thread start.** Capture\r\n  `contextvars.copy_context()` where the job is enqueued (that turn's profile\u002Fsecret scope) and run\r\n  the review inside it. A context captured at thread creation pins whichever profile happened to\r\n  schedule first, and a multiplexed gateway then resolves the wrong profile's scope. Drop the stored\r\n  context on session reset and stop.\r\n- **A bounded `join()` does not make a shared store safe to close.** An LLM-backed job outlives a\r\n  5 s join; its error handler then writes to a closed sqlite connection\r\n  (`AttributeError: 'NoneType' object has no attribute 'execute'`, dumped to\r\n  `logs\u002Ftui_gateway_crash.log`) and the drain thread dies with the row left `running`. Pick one\r\n  invariant-preserving shape: `stop(timeout)` returns whether the thread ended and `shutdown()`\r\n  skips `store.close()` while a drain is in flight; or shutdown closes unconditionally and the\r\n  drain-path store methods (`claim_jobs`, `complete_job`, `fail_job`, the job counts) treat\r\n  `self._conn is None` as gone (`[]` \u002F no-op \u002F `\"closed\"`), with the failure-recording call itself\r\n  wrapped. Nothing may raise into the drain thread; letting one connection die with the process\r\n  beats crashing the handler.\r\n- **Never key job-window uniqueness on an exact wall-clock timestamp.** Windows' `time.time()` has\r\n  ~15 ms granularity on the Python 3.11 host, so two dispatches inside one tick produce the same\r\n  `to_ts`; a store that dedupes `(session, from_ts, to_ts)` then collapses the second job into the\r\n  first and the layer silently misses a window. Make the edge strictly increasing\r\n  (`max(now, last_edge + 1e-6)`) and keep windows edge-to-edge, then test with a fixed clock and\r\n  assert two distinct windows. Same trap for rate-limit buckets and \"new since\" cursors.\r\n- Installed plugins under `$HERMES_HOME\u002Fplugins\u002F\u003Cname>\u002F` are not git repos. When you hand-edit one,\r\n  leave a timestamped backup plus an apply-verified patch under `$HERMES_HOME\u002Flocal-patches\u002F`,\r\n  generated from the pre-change files (`git -c core.autocrlf=false apply` onto a pristine copy must\r\n  reproduce the live bytes). Otherwise the next install\u002Fupdate silently reverts the fix.\r\n- `recall_status()` must reflect only the LAST `prefetch`; count==0 means \"content, no discrete count\".\r\n- Verification ladder (all real, no mocks): `hermes plugins validate \u003Cdir>` (runs `register()` under the\r\n  real contracts) → `hermes plugins doctor \u003Cdir>` (temp-HERMES_HOME discovery+import; prints\r\n  `manifest: \u003Cname> \u003Cver> (exclusive)`) → end-to-end loader probe: copy the plugin to\r\n  `\u003Ctmp>\u002Fplugins\u002F\u003Cname>`, run the host venv python with `HERMES_HOME=\u003Ctmp>` and\r\n  `PYTHONPATH=\u003Cworkspace>`, then `plugins.memory.discover_memory_providers()` \u002F\r\n  `load_memory_provider(\u003Cname>)` + `initialize\u002Fsync_turn\u002Fprefetch` round-trip.\r\n- **pytest pitfall**: the plugin repo root IS the package (`__init__.py`). Pytest treats any ancestor dir\r\n  containing `__init__.py` as a collectable package and imports the plugin module as a test module\r\n  (`CollectError ... ImportError while importing test module '\u003Crepo>\u002F__init__.py'`, relative import\r\n  \"no known parent package\"). `--import-mode=importlib` does NOT fix it. Fix: put the pytest config inside\r\n  `tests\u002Fpytest.ini` so rootdir=tests and the ancestor walk stops before the repo root.\r\n- Test bootstrap that works everywhere: try importing the real host modules per module\r\n  (`agent.memory_provider`, `tools.registry`) and shim only what fails; a shim parent module needs\r\n  `__path__ = []` or `from agent.memory_provider import X` fails with \"'agent' is not a package\".\r\n  Also load the plugin as a synthetic package (`spec_from_file_location(name, root\u002F'__init__.py',\r\n  submodule_search_locations=[root])`) — that mirrors the loader and makes relative imports work.\r\n  An editable host install exposes `agent`\u002F`hermes_cli` through a finder but not the host's\r\n  root-level modules (`hermes_yaml`), so a host-mode test dies mid-run with `ModuleNotFoundError`\r\n  even though `agent` imported. After importing `agent.memory_provider`, insert\r\n  `Path(agent.__file__).resolve().parents[1]` into `sys.path` when that root holds the host's\r\n  top-level modules.\r\n","# Hermes Plugin Development\r\n\r\nCross-type knowledge for `plugin.yaml` + `register(ctx)` plugins under `$HERMES_HOME\u002Fplugins\u002F\u003Ccategory>\u002F\u003Cdir>\u002F`: giving a plugin AI capability (LLM calls, child agent sessions), participating in the main agent loop, and the validation loop that proves a registration actually works.\r\n\r\n## When to Use\r\n\r\n- Building or extending any Hermes plugin: tools, hooks, commands, LLM calls (`ctx.llm`), child agent sessions (`ctx.subagent_lifecycle`), or answering \"how do I do X in a plugin\".\r\n- Debugging a plugin registration, hook, or LLM\u002Fsubagent call that does not behave as documented.\r\n- Type-specific plugin kinds load their own skill instead: web-search\u002Fextract provider → `hermes-web-provider-plugin`; secret-source backend → `hermes-secret-source-plugins`; LanceDB memory → `lancedb-memory-plugin-development`. Finished-plugin deployment (atomic swap, rollback, runtime verification) → `safe-extension-deployment`. Recovering another agent's adviser\u002Freviewer mechanism to port into a plugin → `agent-internals-forensics`.\r\n\r\n## Answer from the live install, not memory\r\n\r\nPlugin contracts move between releases. Before answering or writing plugin code:\r\n\r\n1. `hermes --version` — prints the live Install directory (`...\u002Finstalls\u002F\u003Chash>\u002Fenvironments\u002F\u003Chash>\u002Fworkspace`).\r\n2. Read the contract in the live tree: `hermes_cli\u002Fplugins.py` (PluginContext registrars + `VALID_HOOKS`), `agent\u002Fsubagent_lifecycle.py`, `agent\u002Fplugin_llm.py`.\r\n3. Read the in-tree docs — do not guess: `website\u002Fdocs\u002Fdeveloper-guide\u002Fplugins\u002Findex.md` (registrars, hook table, middleware table), `plugin-llm-access.md`, `subagent-lifecycle-api.md`; public hook reference in `website\u002Fdocs\u002Fuser-guide\u002Ffeatures\u002Fhooks.md`.\r\n4. A second source checkout may exist (`$HERMES_HOME\u002Fhermes-agent\u002F`); confirm parity (`diff -q \u003Ca> \u003Cb>`) before citing either tree — the running install is the one that counts.\r\n\r\n## Pick the AI surface (decision table)\r\n\r\n| Need | Surface | Owns an agent loop? |\r\n|---|---|---|\r\n| One LLM call (summarize \u002F classify \u002F rewrite \u002F extract) | `ctx.llm.complete()` \u002F `complete_structured()` (+ async variants) | No — single bounded call, no tool loops |\r\n| Full child agent (LLM + tools, own loop) | `ctx.subagent_lifecycle.launch(SubagentLaunchRequest(...))` | Yes — same host path as `delegate_task` |\r\n| Observe\u002Fsteer the user's running turn | `ctx.register_hook(...)` \u002F `ctx.register_middleware(...)` | No — participates in the main loop |\r\n| Direct in-process `AIAgent` | `from run_agent import AIAgent` | Bundled-plugin escape hatch only — private core import |\r\n\r\nExhaustive request fields, limits, states, methods, routing rules, and pitfalls: `references\u002Fllm-and-agent-loops.md`\r\n(which also carries the working script-probe recipe: import `run_agent` BEFORE any `hermes_cli.*` module).\r\n\r\n## Escalate to async without duplicating the loop\r\n\r\n`AIAgent`'s loop is synchronous — there is no `async def` in `run_agent` or\r\n`agent.conversation_loop` — so an async surface offloads the *whole* run; it never wraps a single\r\ncall in a coroutine. Ship both entries from one implementation:\r\n\r\n```python\r\ndef run(message, *, context=\"\", model=\"\", provider=\"\", toolsets=None) -> AgentRun:\r\n    ...                                   # sync; import run_agent FIRST inside it\r\nasync def run_async(message, **kw) -> AgentRun:\r\n    return await asyncio.to_thread(run, message, **kw)\r\n```\r\n\r\n- Register the coroutine function together with `is_async=True`\r\n  (`ctx.register_tool(..., handler=handle_async, is_async=True)`); `tools.registry.dispatch`\r\n  bridges it for sync callers through `_run_async()` and is safe inside a running loop.\r\n- The pairing is strict and fails at dispatch, not at registration: async handler +\r\n  `is_async=False` hands a coroutine to the result normaliser, sync handler + `is_async=True`\r\n  hands a string to `await`. `validate` compares names, not callable shapes — only an execution\r\n  probe catches the swap.\r\n- Keep the route owner thin: the loop lives in its own module (`run` \u002F `run_async` + a small\r\n  result dataclass), while the aux-task plugin keeps only config, framing, schema and the two\r\n  handlers. Two copies of the constructor drift the moment one gains `reasoning_config` or a\r\n  new guard.\r\n- Keep the loop's EXTERNAL surface to what a caller can actually know — message, context, system\r\n  message, model, provider, toolsets — and resolve model + credentials + reasoning + budget inside the\r\n  runner with the gateway helpers (`gateway.run._load_gateway_config` \u002F `_resolve_gateway_model` \u002F\r\n  `_resolve_runtime_agent_kwargs`, `hermes_constants.resolve_reasoning_config`), the way\r\n  `feishu_comment.py::_resolve_model_and_runtime` does. A caller forced to assemble\r\n  `api_key`\u002F`base_url`\u002F`api_mode`\u002F`credential_pool` is a design error: every call site repeats the\r\n  plumbing and one of them forgets `reasoning_config`. A pinned `provider` re-resolves that\r\n  provider's credentials — never send another provider's model with the main route's key.\r\n- A system message belongs to the TURN (`run_conversation(prompt, system_message=...)`), not to the\r\n  constructor and never merged into the user message. Persona\u002Frubric text prepended to the message\r\n  pollutes the evidence the peer is asked to judge; `ephemeral_system_prompt=` at construction binds\r\n  it for the agent's whole life and hides it from callers who only supply one.\r\n- Isolation of a peer run is explicit: `skip_context_files=True`, `skip_memory=True`,\r\n  `skip_background_review=True`, and a deliberate decision on `load_soul_identity` — that flag LOADS\r\n  the operator's SOUL identity (it is not an isolation switch), so \"all four True\" means isolated\r\n  from project\u002Fmemory\u002Freview but speaking in the configured voice.\r\n- `asyncio.to_thread` copies the contextvars, which is what the gateway's per-profile secret\r\n  scope needs; `close()` then runs in the worker thread that built the agent.\r\n\r\n## Run an agent loop: ctx.subagent_lifecycle\r\n\r\n```python\r\nfrom agent.subagent_lifecycle import SubagentLaunchRequest   # public allowlisted import\r\n\r\ndef run_review(args, **kwargs):          # _ctx captured in register(ctx)\r\n    svc = _ctx.subagent_lifecycle\r\n    handle = svc.launch(SubagentLaunchRequest(\r\n        goal=\"Review this change for regressions.\",\r\n        context=\"Only inspect the supplied repository.\",\r\n        role=\"leaf\",\r\n        allowed_toolsets=(\"file\",),      # registered names; subset of parent's\r\n    ))\r\n    term = svc.wait(handle, timeout_seconds=120)\r\n    if term.timed_out:\r\n        return json.dumps({\"success\": True, \"data\": {\"state\": term.state.value,\r\n                                                     \"handle\": handle.to_dict()}})\r\n    r = svc.result(handle)               # .summary \u002F .terminal_state \u002F .result_hash\r\n    return json.dumps({\"success\": True, \"data\": {\"state\": r.terminal_state.value,\r\n                                                 \"summary\": r.summary}})\r\n```\r\n\r\nRules that cause first-try failures (full list in the reference):\r\n\r\n- Callable only inside an active agent turn — a plugin tool handler or a hook callback. Outside one it raises `SubagentLifecycleError` (\"No active Hermes parent session is available.\"). Works in CLI, gateway, non-interactive, kanban-worker sessions.\r\n- `allowed_toolsets` must be registered names and a subset of the parent's toolsets — it narrows, never broadens.\r\n- `timeout_seconds`, `working_directory`, `blocked_tools` are rejected by launch validation — do not pass them (per-launch timeouts are not supported, children get isolated workdirs, per-tool blocking must be expressed as `allowed_toolsets`). They DO exist as fields on the frozen dataclass, so `dataclasses.fields()` and autocomplete suggest they work; the rejection fires inside `launch()`.\r\n- `provider=` must already be a configured Hermes provider; routing precedence is request.provider > delegation config > parent.\r\n- `agent.subagent_lifecycle` is on the public import allowlist; `run_agent` is not (see the escape hatch in the reference).\r\n- Copy-ready pair that already passed `validate` + `doctor`: `templates\u002Fagentloop_plugin_init.py` + `templates\u002Fagentloop_plugin.yaml`. Register the tool under the plugin's own toolset namespace, not a core one.\r\n\r\n## Mid-turn seams: what a hook or middleware can actually change\r\n\r\nHooks and middleware are not interchangeable; pick by when the effect must land.\r\n\r\n- `pre_llm_call` runs ONCE per turn in the prologue, and its context is stamped into the turn's user\r\n  message and replayed byte-for-byte for every provider attempt that turn. It cannot inject per\r\n  tool-loop iteration.\r\n- `llm_request` middleware runs per provider attempt, returns `{\"request\": {...}}` to replace the\r\n  provider kwargs, and is synchronous with no timeout wrapper: ledger reads only, never a model call.\r\n- A `pre_tool_call` block is visible: the message becomes that tool call's result, so the model may\r\n  retry. Cap it per turn and reserve it for mutating tools.\r\n- `pre_verify` keeps a turn going only when the turn edited files, and only up to\r\n  `agent.verify_hooks.max_verify_nudges` — it is not a general continuation channel.\r\n- `on_interim_message` carries visible assistant text only. `post_auxiliary_call` carries usage per\r\n  auxiliary attempt and is the meter for a plugin's own LLM calls.\r\n- Hooks are bounded by `plugins.hook_callback_timeout` (default 30s; a slow callback is abandoned and\r\n  suppressed for 60s). Model work belongs on a worker thread.\r\n- The system prompt is built once per session and replayed; no plugin rewrites it mid-session.\r\n- `VALID_HOOKS` in the live `hermes_cli\u002Fplugins.py` is the authority; the public hooks page lags.\r\n\r\nUrgency-to-seam mapping, the exact return contracts, and the two-attempt probe that proves which\r\nseam fired: `references\u002Fhook-and-middleware-seams.md`.\r\n\r\n## One ledger, one producer\r\n\r\nA layered plugin that writes the same review table from two places (a cadence-based deeper\r\nreviewer and a per-turn injector) ends up with duplicate advice that dedupe can only hide. Merge\r\nthe production path, not just the output: the deeper layer keeps its own artifact (a correction\r\nnote on the artifact it owns) and the live reviewer is the only writer of advice rows.\r\n\r\n- **Retire a producer in one change.** Grep the removed contract key across the plugin *and*\r\nthe tests before running anything: prompt contract, parser\u002Fnormalizer, store write, artifact\r\nsection heading, the consumer's candidate block, the store's consume\u002Fpromotion branch, and every\r\nfixture helper that builds the old reply. A shared per-file fixture (`_dialectic_json(...)`) makes\r\nthis one edit; hand-rolled payloads scattered per test make it a sweep.\r\n- **Give retired rows an explicit fate.** Pending rows of a source nobody writes any more are a\r\nsilent leak: expire them through the existing TTL path, ignore them on read, or migrate them, and\r\nsay which in the code. Never leave a consumer still reading a source that has no producer.\r\n- **Republish on no-op, or the old artifact stays live.** If the deeper layer's artifact only ships\r\nwhen it changes something, the last advice-bearing artifact survives as the \"latest\" one forever.\r\nPublish a truthful no-change note (`- no change this window`) so the stale text is replaced.\r\n- **Section headings are a contract.** The `## Heading` set is duplicated in the artifact\r\nvalidator, the store's section→conclusion map, and the prefetch\u002Fdigest readers. Rename it in all\r\nof them in the same change; a half-renamed heading silently stops indexing the new artifact while\r\nthe old rows keep serving as current.\r\n- When the layer's only product is a correction of a specific row (a base refresh, a job window),\r\n  skip the model call entirely if that row is absent. A review with nowhere to write its result burns\r\n  tokens and produces nothing.\r\n- **A downstream review validates against its source row, not a blanket non-empty rule.** An\r\n  upstream pass can legitimately publish sparse cards (a window with no identity or summary\r\n  evidence); a review that echoes those empty fields is faithful, not broken. Reject only content\r\n  the source row carried and the reply dropped, plus listed explicit clears. A validator that\r\n  demands every field be non-empty fails every review of a sparse window, retries twice, and keeps\r\n  the content watermark stuck. The artifact docs must state the same rule in every section, or one\r\n  will promise \"empty arrays are valid\" while the validator refuses them.\r\n- **Deliver after the turn ends.** A plugin has no send API of its own: when advice arrives after the\r\n  final answer and must reach a gateway chat, call the host tool in-process —\r\n  `send_message_tool({\"target\": platform, \"action\": \"send\", \"message\": text})` — and treat\r\n  `json.loads(result)[\"success\"]` as the receipt, so a rejected send leaves the row pending instead of\r\n  claiming delivery. Guard on platform (never CLI\u002FTUI) and keep a notified-id set so a retry does not\r\n  repeat the message.\r\n- **Sweep at the terminal hook, not only at publish.** A background review can finish before\r\n  `post_llm_call` marks the turn terminal, so a notify-on-publish check alone misses it. Do both: the\r\n  publish path notifies when the session is already terminal, and the terminal hook sweeps rows nobody\r\n  has sent. The notified-id set makes the double path idempotent.\r\n\r\n## Validation loop (before claiming anything works)\r\n\r\n- `hermes plugins validate \u003Cplugin_dir>` — runs `register(ctx)` with a real context: undeclared tools (`provides_tools`), collisions, import errors; warns on private core imports (catalog rule 9).\r\n- `hermes plugins doctor \u003Cplugin_dir>` — full discovery + import in a temp `HERMES_HOME`; prints the registration count (`registrations: 1 tool(s), 0 hook(s)`) — that line is the cheap proof a handler\u002Ftoolset mismatch did not silently drop the tool.\r\n- Local dev install is a copy, not `hermes plugins install`: that subcommand takes a catalog entry name, a Git URL, or `owner\u002Frepo` shorthand — never a local directory. Place the dir under `$HERMES_HOME\u002Fplugins\u002F\u003Cname>\u002F`, then `hermes plugins enable \u003Cname>` (writes `plugins.entries`; never hand-edit config.yaml).\r\n- Repo vs install: when the plugin is developed in a git checkout while a copy also sits under `$HERMES_HOME\u002Fplugins`, make and verify the change in the repo, then deploy it — the user treats the installed copy as this plugin's deployment target and expects replacement + gateway restart + live verification in the same task, not a fix that only lives in the checkout. Back up the installed tree first and report the path, and put the backup outside `$HERMES_HOME\u002Fplugins\u002F`: that root is the provider discovery root, so a sibling copy left inside it is a candidate second provider. On Windows the running gateway can hold the installed directory: `hermes gateway stop`, replace the tree (`rm -rf` then `cp -a`, which preserves mtimes), `diff -rq --exclude=__pycache__` against the repo, then start the gateway. Replacing under a live process fails or leaves a half-copied tree. After `hermes gateway restart`, prove the new code loaded from `logs\u002Fagent.log` (the manifest parse line names the install path, then the plugin's own hook lines appear); a \"port still accepting connections\" warning during restart is the old process draining, not a failure. A new default in the provider's config defaults applies to every live config that omits the key, so read the deployed config block before shipping a risky default and state the behavior change in the deploy report. Before overwriting, diff it: content the repo lacks is either an older generation (git log shows the removal) or a hand edit that exists nowhere else — a backup alone is not a decision. The ask-first exception is a different plugin owning the same aux key or tool name; report that conflict instead of retiring the other plugin by deleting it.\r\n- Tool handlers must return a JSON **string** (the registry rejects plain dicts; only the multimodal envelope passes).\r\n- Contract-mode test runs: point the suite at the host (`HERMES_WORKSPACE=\u003Cinstall workspace>` + the host venv's python). A bare local interpreter can lack host deps and produce false failures that look like your change; a suite that boots the real `agent.*` \u002F `tools.registry` modules is the only run whose pass means anything. Two `-q` flags (a `pytest.ini` `addopts = -q` plus `-q` on the command line) also suppress the final `N passed` line — read the exit code, and take counts from `--co` (it prints `file.py: N` rows) instead of re-running to find out whether it passed.\r\n- Prove hook **dispatch**, not just registration: `validate` and `doctor` check declared names and that `register(ctx)` runs, but only the agent's own dispatch proves a callback's return value is consumed. Stage the plugin into a temp `HERMES_HOME`, run the host venv python with the workspace on `sys.path`, call `hermes_cli.plugins.discover_plugins()`, then dispatch exactly as the loop does: `invoke_hook(\"pre_tool_call\", tool_name=..., session_id=...)`, `get_pre_verify_continue_message(session_id=..., changed_paths=[...])`, or `invoke_hook(\"pre_llm_call\", user_message=..., parent_session_id=\"\")`. Seed the provider state (a pending row, a bound session) first, and assert the second call no longer fires — one-shot semantics are part of the contract.\r\n- **A plugin scheduler fires in tests too.** With `cadence: 1` the background worker reviews on the first recorded event, so a test that then calls the worker method directly runs it twice and the call counter doubles (N becomes 2N, one per roster member). Give the test config a high cadence and drive the method explicitly, or `wait_idle()` before asserting call counts; assert the *prompt* content rather than the call count when both paths must run.\r\n- Registration metadata (tool\u002Fskill descriptions) is snapshotted at load; a running Gateway needs a plugin reload for changed registration metadata to land — re-`enable` of an already-enabled plugin is a no-op.\r\n\r\n## Diagnose from the host's logs, before touching code\r\n\r\nA \"check the logs and fix the plugin\" request is evidence work: the installed copy can be commits\r\nbehind the repo, so part of what the log shows may already be fixed.\r\n\r\n1. Read `$HERMES_HOME\u002Flogs\u002F`: `agent.log` (plugin lifecycle, per-turn hooks, model calls),\r\n   `errors.log` (WARNING+), `gateway-stdio.log` (the one-line `[gateway-crash] thread \u003Cname> raised ...`),\r\n   `tui_gateway_crash.log` (the full traceback behind that line), `gateway.log` (host startup). Group\r\n   matches by normalized message — one repeating warning is one bug, not N.\r\n2. Prove each candidate is live before patching: grep the source for the exact method\u002Fattribute named\r\n   in the traceback, and `diff -rq --exclude=__pycache__` the installed copy against the repo. A\r\n   stale install replays already-fixed errors; deploying is the whole fix and no code change is owed.\r\n3. Reproduce at the narrowest layer (call the failing store\u002Fworker method directly, or drive the\r\n   tracker with an injected clock), then keep that reproduction as a regression test that fails on\r\n   the old predicate. Prove the test is red on the old code with a path-scoped stash:\r\n   `git stash push -- \u003Cfile>`, run that single test, `git stash pop`; unrelated uncommitted work\r\n   stays put. A test that only asserts \"does not raise\" is vacuous when the old code already\r\n   swallowed the exception — assert on the log record or the returned status instead.\r\n4. Separate model-quality failures from code defects before patching. \"returned invalid JSON\",\r\n   \"empty cards\" and \"no usable JSON after 2 passes\" are not one bug: an \"empty cards\"\r\n   rejection can be a validator contradicting an upstream pass that legitimately emitted empty\r\n   fields (compare the reply with the source row it reviews), while a malformed reply from a small\r\n   aux route is model behaviour (check `auxiliary.\u003Ckey>.model`). Read `agent.log`'s\r\n   `API call #N ... out=\u003Ctokens>` and `Turn ended ... api_calls=N\u002FM response_len=\u003Cchars>` lines: a\r\n   run that spends its tool budget on `tool_search`\u002F`tool_describe` and ends with a long text\r\n   answer is tool-thrash, not JSON incapability. Cap that budget and give it one no-tools repair\r\n   pass; only truncated or invalid JSON with no tool calls is a reason to raise the aux model.\r\n5. Fix, run the full suite, run the repo's host-verification script (often\r\n   `scripts\u002Fverify_against_host.py --host-python \u003Chost venv>\u002Fpython.exe --workspace \u003Cinstall>`;\r\n   auto-detect fails on a non-standard install), deploy, restart the gateway, then re-grep the logs\r\n   for zero new warnings from the plugin. Swap\u002Frollback mechanics: `safe-extension-deployment`.\r\n\r\n## One directory, several surfaces (provider + tools + hooks + aux route)\r\n\r\nA memory-provider plugin is not limited to `register_memory_provider`: the memory loader builds a real\r\n`PluginContext` (`plugins\u002Fmemory\u002F__init__.py`), so `ctx.register_hook`, `ctx.register_tool` and\r\n`ctx.register_auxiliary_task` all work from the same `register()` — one repo can ship the provider, its hooks,\r\na tool and its own `auxiliary.\u003Ckey>` model route.\r\n\r\n- **Aux tasks need no manifest field; ctx-registered tools and hooks do.** List every tool passed to `ctx.register_tool`\r\n  under `provides_tools:`, and every hook passed to `ctx.register_hook` under `provides_hooks:`. `hermes plugins validate`\r\n  FAILS on an undeclared tool (\"undeclared tools registered\") and only warns about a declared-but-unregistered one; the\r\n  manifest-contract test also compares `provides_hooks` against the registered hook set, so adding a hook is a three-file\r\n  change (registration, manifest, that test). Tools a provider returns from `get_tool_schemas()` do\r\n  NOT belong there — they never touch the plugin registry.\r\n- **Collisions are asymmetric, and both are process-wide.** A foreign `auxiliary` key raises `ValueError`\r\n  (\"already registered by plugin X\"); a duplicate tool name is refused with a warning and `register_tool`\r\n  returns `None` instead of raising. So put the optional surface in its own `try\u002Fexcept` inside `register()` and\r\n  keep the primary registration outside it: a refused adviser route must never cost the memory provider.\r\n- **Moving a surface between plugins means retiring the old owner first** (uninstall\u002Fdisable, or the new\r\n  registration is refused\u002Fignored). Keep the toolset name stable when you do — per-platform `toolsets:` lists\r\n  select the toolset, not the plugin.\r\n- Probing the registered surface end-to-end: assert `get_plugin_auxiliary_tasks()` contains the key and\r\n  `tools.registry.registry.get_entry(\u003Ctool>)` returns an entry with the expected `.toolset` and `.is_async`,\r\n  inside a host probe (temp `HERMES_HOME`, repo staged as `plugins\u002F\u003Cname>`). That catches \"registered but not\r\n  callable\" and a handler\u002Fflag mismatch, neither of which manifest validation can see.\r\n\r\n## Memory-provider plugins (`plugins\u002Fmemory\u002F` contract)\r\n\r\nBundled examples to copy from: `plugins\u002Fmemory\u002Fbyterover` (CLI-backed) and\r\n`plugins\u002Fmemory\u002Fretaindb` (cloud + write queue) in the live install tree.\r\n\r\n- `register(ctx)` calls `ctx.register_memory_provider(instance)` — one instance per plugin. Discovery order:\r\n  bundled `plugins\u002Fmemory\u002F\u003Cname>\u002F` → `$HERMES_HOME\u002Fplugins\u002F\u003Cname>\u002F` → `.\u002F.hermes\u002Fplugins\u002F\u003Cname>\u002F`\r\n  (`HERMES_ENABLE_PROJECT_PLUGINS`) → pip entry points `hermes_agent.memory_providers`. The cheap scan\r\n  reads the first 8 KB of `__init__.py` for `register_memory_provider`\u002F`MemoryProvider`; `doctor` then\r\n  auto-detects `kind: exclusive` from the same markers (no `kind:` field needed in plugin.yaml).\r\n- **The INSTALLED DIRECTORY name is the provider name** `memory.provider` selects (`find_provider_dir(name)`\r\n  → `\u003Cplugins>\u002F\u003Cname>`). The `name:` field and the `name` property are labels — a hyphenated repo cloned\r\n  as-is only activates if `memory.provider` equals that directory name; otherwise clone into\r\n  `plugins\u002F\u003Cprovider-name>`. Rename all three together.\r\n- ABC lives at `agent\u002Fmemory_provider.py` (read it live): abstract = `name`, `is_available`, `initialize`,\r\n  `get_tool_schemas`; everything else has no-op defaults. `initialize(session_id, **kwargs)` always carries\r\n  `hermes_home` (profile-scoped — never hardcode) and `agent_context`; subagent\u002Fcron\u002Fflush contexts must not\r\n  write memory. `handle_tool_call` must return a JSON **string** (`tool_error()` from tools.registry).\r\n- Threading model: `sync_turn` and `queue_prefetch` run on the MemoryManager's background worker,\r\n  `prefetch` runs on the critical path under a timeout (a still-running previous prefetch skips the\r\n  provider that turn). So: do I\u002FO in `queue_prefetch`, consume the cached block in `prefetch`, and let\r\n  unexpected failures propagate only from `prefetch` (it is re-raised there); swallow errors in hooks.\r\n- **Every background thread must inherit the caller's contextvars.** Spawn with\r\n  `agent.memory_provider.spawn_context_thread(target, name=...)` (or\r\n  `contextvars.copy_context().run`), never a bare `threading.Thread`. Profile isolation is a\r\n  ContextVar-scoped HERMES_HOME override plus a per-turn secret scope; a bare thread starts empty and\r\n  therefore reads the default profile's secrets or fails closed with `UnscopedSecretError: Hermes\r\n  could not read this profile's \u003CENV_VAR>`, which kills the review\u002Fjob on every run. This covers\r\n  every helper thread, including a run-with-timeout wrapper that calls an LLM and any reviewer\r\n  worker that must not steal the main loop. Probe it: set a ContextVar in the caller and have the\r\n  spawned thread report it back — a bare thread returns the default.\r\n- **A long-lived worker must carry the context per job, not once at thread start.** Capture\r\n  `contextvars.copy_context()` where the job is enqueued (that turn's profile\u002Fsecret scope) and run\r\n  the review inside it. A context captured at thread creation pins whichever profile happened to\r\n  schedule first, and a multiplexed gateway then resolves the wrong profile's scope. Drop the stored\r\n  context on session reset and stop.\r\n- **A bounded `join()` does not make a shared store safe to close.** An LLM-backed job outlives a\r\n  5 s join; its error handler then writes to a closed sqlite connection\r\n  (`AttributeError: 'NoneType' object has no attribute 'execute'`, dumped to\r\n  `logs\u002Ftui_gateway_crash.log`) and the drain thread dies with the row left `running`. Pick one\r\n  invariant-preserving shape: `stop(timeout)` returns whether the thread ended and `shutdown()`\r\n  skips `store.close()` while a drain is in flight; or shutdown closes unconditionally and the\r\n  drain-path store methods (`claim_jobs`, `complete_job`, `fail_job`, the job counts) treat\r\n  `self._conn is None` as gone (`[]` \u002F no-op \u002F `\"closed\"`), with the failure-recording call itself\r\n  wrapped. Nothing may raise into the drain thread; letting one connection die with the process\r\n  beats crashing the handler.\r\n- **Never key job-window uniqueness on an exact wall-clock timestamp.** Windows' `time.time()` has\r\n  ~15 ms granularity on the Python 3.11 host, so two dispatches inside one tick produce the same\r\n  `to_ts`; a store that dedupes `(session, from_ts, to_ts)` then collapses the second job into the\r\n  first and the layer silently misses a window. Make the edge strictly increasing\r\n  (`max(now, last_edge + 1e-6)`) and keep windows edge-to-edge, then test with a fixed clock and\r\n  assert two distinct windows. Same trap for rate-limit buckets and \"new since\" cursors.\r\n- Installed plugins under `$HERMES_HOME\u002Fplugins\u002F\u003Cname>\u002F` are not git repos. When you hand-edit one,\r\n  leave a timestamped backup plus an apply-verified patch under `$HERMES_HOME\u002Flocal-patches\u002F`,\r\n  generated from the pre-change files (`git -c core.autocrlf=false apply` onto a pristine copy must\r\n  reproduce the live bytes). Otherwise the next install\u002Fupdate silently reverts the fix.\r\n- `recall_status()` must reflect only the LAST `prefetch`; count==0 means \"content, no discrete count\".\r\n- Verification ladder (all real, no mocks): `hermes plugins validate \u003Cdir>` (runs `register()` under the\r\n  real contracts) → `hermes plugins doctor \u003Cdir>` (temp-HERMES_HOME discovery+import; prints\r\n  `manifest: \u003Cname> \u003Cver> (exclusive)`) → end-to-end loader probe: copy the plugin to\r\n  `\u003Ctmp>\u002Fplugins\u002F\u003Cname>`, run the host venv python with `HERMES_HOME=\u003Ctmp>` and\r\n  `PYTHONPATH=\u003Cworkspace>`, then `plugins.memory.discover_memory_providers()` \u002F\r\n  `load_memory_provider(\u003Cname>)` + `initialize\u002Fsync_turn\u002Fprefetch` round-trip.\r\n- **pytest pitfall**: the plugin repo root IS the package (`__init__.py`). Pytest treats any ancestor dir\r\n  containing `__init__.py` as a collectable package and imports the plugin module as a test module\r\n  (`CollectError ... ImportError while importing test module '\u003Crepo>\u002F__init__.py'`, relative import\r\n  \"no known parent package\"). `--import-mode=importlib` does NOT fix it. Fix: put the pytest config inside\r\n  `tests\u002Fpytest.ini` so rootdir=tests and the ancestor walk stops before the repo root.\r\n- Test bootstrap that works everywhere: try importing the real host modules per module\r\n  (`agent.memory_provider`, `tools.registry`) and shim only what fails; a shim parent module needs\r\n  `__path__ = []` or `from agent.memory_provider import X` fails with \"'agent' is not a package\".\r\n  Also load the plugin as a synthetic package (`spec_from_file_location(name, root\u002F'__init__.py',\r\n  submodule_search_locations=[root])`) — that mirrors the loader and makes relative imports work.\r\n  An editable host install exposes `agent`\u002F`hermes_cli` through a finder but not the host's\r\n  root-level modules (`hermes_yaml`), so a host-mode test dies mid-run with `ModuleNotFoundError`\r\n  even though `agent` imported. After importing `agent.memory_provider`, insert\r\n  `Path(agent.__file__).resolve().parents[1]` into `sys.path` when that root holds the host's\r\n  top-level modules.\r\n",{"name":5,"author":24,"license":15,"version":25,"metadata":26,"platforms":43,"description":7},"Masia","1.0.0",{"hermes":27},{"tags":28,"related_skills":37},[29,30,31,32,33,34,35,36],"hermes","plugins","register","llm","subagents","hooks","middleware","validation",[38,39,40,41,42],"hermes-agent","hermes-web-provider-plugin","hermes-secret-source-plugins","lancedb-memory-plugin-development","safe-extension-deployment",[44,45,46],"linux","macos","windows","main","a3f3199bb87ec3c91248f68a39d88527e1847ae9","skills\u002Fautonomous-ai-agents\u002Fhermes-plugin-development","https:\u002F\u002Fgithub.com\u002Fchaorenex1\u002Fhermes-home-content","https:\u002F\u002Fgithub.com\u002Fchaorenex1","https:\u002F\u002Fblog.aduib.com","A programmer whose only hobby in life is coding","2026-10-20 00:34:32",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add chaorenex1\u002Fhermes-home-content --skill hermes-plugin-development",{"tool":61,"command":62},"bunx","bunx skills add chaorenex1\u002Fhermes-home-content --skill hermes-plugin-development",{"tool":64,"command":65},"pnpm","pnpm dlx skills add chaorenex1\u002Fhermes-home-content --skill hermes-plugin-development","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fchaorenex1\u002Fhermes-home-content\u002Fblob\u002Fmain\u002Fskills\u002Fautonomous-ai-agents\u002Fhermes-plugin-development\u002FSKILL.md",true,[69,75,79,85],{"path":70,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":73,"sourceHtmlUrl":74},"references\u002Fhook-and-middleware-seams.md","REFERENCE","参考文档",7119,"https:\u002F\u002Fgithub.com\u002Fchaorenex1\u002Fhermes-home-content\u002Fblob\u002Fmain\u002Fskills\u002Fautonomous-ai-agents\u002Fhermes-plugin-development\u002Freferences\u002Fhook-and-middleware-seams.md",{"path":76,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":77,"sourceHtmlUrl":78},"references\u002Fllm-and-agent-loops.md",18029,"https:\u002F\u002Fgithub.com\u002Fchaorenex1\u002Fhermes-home-content\u002Fblob\u002Fmain\u002Fskills\u002Fautonomous-ai-agents\u002Fhermes-plugin-development\u002Freferences\u002Fllm-and-agent-loops.md",{"path":80,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":83,"sourceHtmlUrl":84},"templates\u002Fagentloop_plugin_init.py","SCRIPT","脚本",3659,"https:\u002F\u002Fgithub.com\u002Fchaorenex1\u002Fhermes-home-content\u002Fblob\u002Fmain\u002Fskills\u002Fautonomous-ai-agents\u002Fhermes-plugin-development\u002Ftemplates\u002Fagentloop_plugin_init.py",{"path":86,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":87,"sourceHtmlUrl":88},"templates\u002Fagentloop_plugin.yaml",397,"https:\u002F\u002Fgithub.com\u002Fchaorenex1\u002Fhermes-home-content\u002Fblob\u002Fmain\u002Fskills\u002Fautonomous-ai-agents\u002Fhermes-plugin-development\u002Ftemplates\u002Fagentloop_plugin.yaml",[90,97,104,111,118,125],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M7F8GF32YD5MBQW2TGSRH1YP","web-retrieval-resilience","Web tools fail or search rules break: repair or fall back.","https:\u002F\u002Fgithub.com\u002Fchaorenex1\u002Fhermes-home-content\u002Fblob\u002Fmain\u002Fskills\u002Fweb\u002Fweb-retrieval-resilience\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M7F8FP46QESQMCZ1KBT3TW3R","blocked-page-recovery","Use when a fetch fails: 403\u002F429, paywall, WAF, bot wall.","https:\u002F\u002Fgithub.com\u002Fchaorenex1\u002Fhermes-home-content\u002Fblob\u002Fmain\u002Fskills\u002Fweb\u002Fblocked-page-recovery\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":19},"01M7F8ER6VXHBNVRQBZS7X08SE","verification-loop","Run a six-phase verification of a Claude Code session's work — build, type check, lint, tests with coverage, security grep, and diff review — then produce a PASS\u002FFAIL verification report. Use when verifying work after completing a feature or refactor, before creating a PR, or when quality gates must pass.","https:\u002F\u002Fgithub.com\u002Fchaorenex1\u002Fhermes-home-content\u002Fblob\u002Fmain\u002Fskills\u002Fverification-loop\u002FSKILL.md",[],[],{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":19},"01M7F8E4BQJ38KVQVM3MT20PYV","unreal-world-builder","开放世界与环境专家——精通 UE5 World Partition、Landscape、程序化植被、HLOD 和大规模关卡流式加载，打造无缝开放世界体验","https:\u002F\u002Fgithub.com\u002Fchaorenex1\u002Fhermes-home-content\u002Fblob\u002Fmain\u002Fskills\u002Funreal-engine\u002Funreal-world-builder\u002FSKILL.md",[],[],{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":19},"01M7F8D747SQW2FTP7GBSX38BR","unreal-technical-artist","Unreal Engine 视觉管线专家——精通材质编辑器、Niagara 特效、程序化内容生成和 UE5 项目的美术到引擎管线","https:\u002F\u002Fgithub.com\u002Fchaorenex1\u002Fhermes-home-content\u002Fblob\u002Fmain\u002Fskills\u002Funreal-engine\u002Funreal-technical-artist\u002FSKILL.md",[],[],{"skillNo":126,"name":127,"nameZh":6,"description":128,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":129,"categories":130,"keywords":131,"publishedAt":19},"01M7F8CKHYJVZVBTN0321J88T2","unreal-systems-engineer","性能与混合架构专家——精通 C++\u002FBlueprint 边界、Nanite 几何体、Lumen GI 和 Gameplay Ability System，面向 AAA 级 Unreal Engine 项目","https:\u002F\u002Fgithub.com\u002Fchaorenex1\u002Fhermes-home-content\u002Fblob\u002Fmain\u002Fskills\u002Funreal-engine\u002Funreal-systems-engineer\u002FSKILL.md",[],[]]