Hermes Agent: The Architecture Behind Real AI Agents
Outline
- 0:00 Rebuild framing
- 1:08 The system map
- 2:22 The minimal agent loop
- 3:28 Provider adapters
- 4:50 Prompt assembly as a snapshot
- 5:48 Tool registry
- 6:55 Tool execution order
- 8:26 Terminal backend abstraction
- 9:56 Background processes
- 11:06 Security as executable design
- 12:40 Session storage
- 14:00 Context compression
- 15:33 Memory and recall
- 16:39 Skills as procedural memory
- 17:57 Hooks, plugins, and MCP
- 19:11 Subagents
- 20:29 Gateway and cron
- 21:36 TUI, dashboard, and ACP
- 22:56 Rebuild order
- 24:06 Failure modes and close
Transcript
0:00 Welcome to Learning Podcasts. Hermes Agent: rebuild the architecture. If you want to replicate Hermes Agent, the trap is starting with the glossy chat UI, the dashboard, the mascot, or the mobile surfaces. That is the shiny hood. It is not the engine. Right. The hood is optional. A chat UI is not an agent runtime. The engine is boring in the best way: one loop, one internal message format, one tool registry, one persistent session store. The sources are the public `NousResearch slash hermes-agent` GitHub repo and the official docs, both linked in the description.
0:39 We read the docs and the current source snapshot. So this is not a feature tour. It is the implementation map you would follow if you wanted to build a small Hermes-like runtime yourself. Because real agent work means tools, long sessions, subprocesses, retries, compression, memory, partial failures, interrupts, and users messaging the agent from somewhere that is not your terminal. The first map to draw is not a UI map. Draw all the ways work can enter the system: terminal, gateway, editor protocol, cron, dashboard, API, and batch jobs.
1:20 In Hermes, those roads eventually feed the same `AIAgent` runtime in run agent dot py. That is the first replication lesson. Do not build one brain for chat, another for terminal, another for scheduled jobs, and another for the IDE. Build one runtime, then let different doors hand it work. Right. The doors differ at the edges. One gets a slash command. One gets a platform event. One gets a scheduled prompt. But underneath, Hermes loads the session, builds the prompt, resolves the model, calls tools when needed, and records the result.
1:57 That is the important shape. The repo looks wide because the entrances are wide, but the core is narrower than it first appears. Exactly. Your first clone milestone is not the dashboard. It is a boring loop that calls one model, runs one tool, and saves one transcript. Once that loop is real, the rest has somewhere to plug in. Let's spell out the loop. Start with messages. Append the user's message. Build or reuse the system prompt. Convert the internal message list into the provider's shape. Send the request with tool schemas. Parse the response. If there are no tool calls, save the assistant message and return the text. If there are tool calls, save the assistant message with those calls, execute each tool, append one tool-result message per call, and send the enlarged history back to the model.
2:49 That is the agent. Not the whole product, but the agent. The model gets to observe tool results and continue. The refinements matter: iteration budgets, interrupts, fallback providers, preflight compression, and special tools that need agent-local state. But those are refinements around the loop, not replacements for it. I used to overbuild this part in my head. Then you look at real agent code and the surprise is how much behavior comes from making that loop reliable. Exactly. If your clone cannot do "model asks for tool, tool returns result, model sees result," no amount of memory or plugins will make it feel like Hermes.
3:27 I love that, because the next failure is, Provider drift. Provider normalization is the next piece. Hermes supports many providers, but the loop should not speak every vendor dialect. Internally, Hermes keeps an OpenAI-style message shape: role, content, tool calls, and tool results. Provider-specific adapters translate at the edge. The docs name three API modes: chat completions for OpenAI-compatible endpoints, Codex Responses for OpenAI's Responses shape, and Anthropic Messages for native Anthropic.
4:06 So a clone needs a runtime resolver. Given provider plus model, produce the API mode, base URL, credential, and provider-specific model name. That sounds like plumbing until it breaks. Then, oh man, it is the whole product. Wrong key to wrong endpoint, wrong message shape, missing reasoning metadata, all of it. The replication rule is to isolate provider weirdness at the boundary. `AIAgent` should talk to a normalized runtime contract. New providers either fit the OpenAI-compatible path, or they get an adapter and a new mode branch.
4:45 Keep the loop boring. Make the edges do the translation. Here's where it gets really interesting. Hermes treats the system prompt as a session snapshot. Meaning it does not rebuild the entire identity every turn? Right. On a fresh session it assembles personality, memory, user profile, skills, context files, tool-use guidance, and model-specific instructions. Then it stores that prompt with the session. So if the agent writes a memory mid-session, disk changes immediately, but the current prompt does not mutate under the model's feet.
5:19 Exactly. The next session sees it. The current session keeps a stable prompt, which protects provider caching and continuity. Hermes can still inject turn-local context through the user message, but the system prompt remains the runtime's territory. I like that. It feels counterintuitive, because you want memory to appear instantly. But instant prompt mutation is a cache nightmare and a debugging nightmare. Rebuild lesson: separate durable prompt identity from turn-local context. Now the tool system. I would build the registry before building any fancy tool.
5:52 Not terminal first? No. Terminal is one tool. Files are tools. Web search is a tool. Memory and session search are presented as tools. If the registry is clean, the rest gets easier. Hermes uses self-registering tool modules. A tool declares its name, toolset, schema, handler, availability check, async flag, description, and display metadata. Then model tools dot py imports modules that register tools, applies toolset filtering, checks availability, patches dynamic schemas, and hands the model only the tools that exist for this session. Wait, really? Availability checks before the model sees the schema?
6:31 Yes, and that matters. Missing API keys should not become hallucinated tool calls. A browser tool should not appear when the browser backend is unavailable. Dispatch is then one path: look up handler, bridge async if needed, catch exceptions, return JSON. So do not hardcode tools in the loop. Build a registry, then make the loop ask the registry what exists. Hmm, and once the registry exists, the scary part is what happens when the model actually calls one. Tool execution has a strict order. Parse arguments. Run pre-tool hooks or blockers.
7:08 Apply guardrails. Check whether the tool needs agent-local state, like todo, memory, session search, or delegate task. Otherwise dispatch through the registry. Then append the result as a tool message with the matching tool-call ID. That ID matching is not decorative. I think of it like a numbered restaurant ticket. The assistant hands the kitchen ticket 42 for a file search. The tool result has to come back on ticket 42. And if the steak shows up with ticket 43 on the plate, the restaurant does not shrug and keep serving. Exactly. In our case the restaurant is the provider history, and it rejects the next request.
7:49 Hermes can also run some batches concurrently, but results are appended back in original order, so concurrency does not change the transcript shape. I have shipped the opposite once: parallel workers returning in completion order. It looked faster for about 10 minutes, then the model started reasoning from the wrong result. Very educational. Not fun. Make sequential tool calls correct first. Add concurrency only when you preserve transcript order and avoid overlapping file mutations. Otherwise you build a deterministic nightmare with better latency.
8:25 The terminal tool is where Hermes becomes more than a chat wrapper. A coding agent without process execution is mostly an explainer. Hermes puts local, Docker, SSH, Singularity, Modal, Daytona, and Vercel Sandbox behind one terminal interface. The loop sees a small contract: run this command, maybe in the background, maybe with a pseudo-terminal, maybe in this working directory, maybe notify when done. Underneath, each backend handles its own reality. Local uses subprocesses. Docker starts or reuses a container. SSH runs remotely. Modal and Daytona use SDK-backed sandboxes.
9:10 Vercel Sandbox has snapshot constraints. The Docker detail is worth pausing on. It is not "new container per command." The docs describe a long-lived container shared across terminal, file, and execute-code calls for the life of the Hermes process. So the sandbox behaves like a small development machine. Install a package once, and later commands see it. Write files once, and later tools can inspect them. Oh, that is the difference between a sandbox and a disposable subprocess. Rebuild rule: define a base environment interface. Every backend must execute, maintain cwd, sync files if needed, clean up, and return the same JSON shape. Background processes deserve their own section because this is where toy agents fall apart. A real coding agent starts dev servers, test watchers, build processes, browser sessions, and long scripts. Think about `npm run dev`.
10:09 That command does not finish. It is supposed to sit there while you use another terminal for tests and logs. Hermes pushes long-lived commands into managed background mode. Start the process, return a session ID, then use a process tool to list, poll, wait, read logs, write input, or kill it. That is cleaner than telling the model to sprinkle ampersands and nohup everywhere. Otherwise the agent starts its own server and then gets trapped by it. The terminal tool even warns when a foreground command looks like a server or watcher. It wants background equals true so Hermes can track lifecycle and output.
10:44 Oh, interesting. That changes the model's behavior, not just the operator's. It can start a server, check readiness, run tests separately, and still recover logs later. For a rebuild, blocking commands are fine for day one. But the first time you ask the agent to build a web app, you need tracked background sessions with status, logs, exit code, and errors. Now the uncomfortable part. If your agent can run terminal commands, the security model is executable code. Hermes has dangerous-command approval modes: manual, smart, and off. Manual asks the user.
11:20 Smart uses an auxiliary model to assess risk. Off disables normal prompts. Hold on. Off is not the floor, right? Correct. A hardline blocklist refuses commands that are too catastrophic even in yolo mode: root wipes, fork bombs, live disk formatting, direct block-device writes. That split is important. Some actions are "ask the human." Some are "never through the agent." Let me put on the security reviewer hat for a second. If Docker is the boundary, why keep command checks at all? If the agent destroys the container, you throw the container away.
11:59 That is the tempting answer, but it is too narrow. A container is still attached to something: network access, injected credentials, mounted source, maybe cloud tokens. If the box has a window into your AWS account, you still need locks on the window. Good. That is the distinction I wanted: containers change the risk model, but they do not delete it. Exactly. And gateways add another gate: who can talk to the agent at all. Hermes uses allowlists, DM pairing, and deny-by-default behavior. A replica needs user authorization, command approval, and environment containment.
12:40 Persistence is the next big piece. Hermes uses SQLite at home dot hermes slash state dot db. Platform engineer objection: why not just write JSONL and grep it later? The docs say SQLite replaced the earlier JSONL approach. The schema has sessions, messages, full-text search tables, metadata, and schema versioning. Sessions store source, user ID, model, system prompt, parent session ID, token counts, costs, title, and timing. That sounds heavier than a transcript file, but it buys resume, search, lineage, platform filtering, and analytics. Exactly. FTS5 is doing real work.
13:27 Session search is not just searching old text files. Messages are indexed, including a trigram search table for substring and CJK cases. And writes need discipline: WAL mode, short timeouts, jittered retries, begin-immediate transactions, and passive checkpoints. My first instinct for a clone would be "just write JSONL." I would resist that now. Start with SQLite sessions and messages. Add full-text search before your logs become a migration project. Context compression is the part every long-running agent eventually has to confront.
14:06 Hermes has two layers. Gateway session hygiene is the safety net around 85 percent context usage. The agent compressor is the normal in-loop system, around 50 percent by default. The dual layer makes sense. Gateways receive messages across time, platforms, restarts, and stale sessions. They need a guardrail before the model call starts. Inside the agent, compression has four jobs. Prune old large tool results. Choose boundaries. Summarize the middle with an auxiliary model. Reassemble the transcript while keeping tool-call pairs valid.
14:42 The tool-pair repair is the detail you appreciate after an API rejects your beautiful summary because a tool result no longer has a parent tool call. Exactly. Compression is transcript surgery under provider constraints, not just summarization. So, not a chainsaw summary. Right. More like pruning a bonsai tree. You can cut old growth, but you cannot cut the structural branch that holds a tool call and its result together. And the docs warn that the summary model needs enough context to see the middle being summarized.
15:20 Replication rule: compression must preserve active task, recent exact messages, tool-call validity, and critical context. Smaller alone is not enough. Hermes separates small curated memory from larger session recall. The small memory is two files: memory dot md and user dot md, under home dot hermes slash memories. Memory is operational notes. User is the profile. Those files are injected as a frozen prompt block at session start. The agent can update them through the memory tool, but the current session prompt does not mutate.
15:55 Then session search handles the long tail. If the agent needs something from weeks ago, it searches SQLite history and summarizes relevant sessions. That split is the key. Always-on memory stays tiny because it taxes every prompt. Session recall can be larger because it is on demand. So the mistake is treating memory like one bucket instead of two budgets. Hermes also wraps external providers through `MemoryManager`: built-in provider plus at most one external provider, fenced recalled context, streaming scrubbers, and lifecycle hooks.
16:26 Recalled memory should inform the answer, not leak as internal markup. For a replica: tiny prompt memory first, session search second, external providers only after the manager interface is clean. Skills are the other half of learning. Memory remembers facts. Skills remember procedures. Hermes skills are markdown documents under home dot hermes slash skills. The docs describe progressive disclosure: list skills first, load the full skill only when needed, then load specific reference files only when asked.
17:00 That is token discipline. A skill library can be huge, but the model should not carry every skill body in every prompt. Skills also become slash commands. And `skill_manage` lets the agent create, patch, edit, delete, and add supporting files for skills. So a successful workflow can become procedural memory. But I would not start with a marketplace. Start with the format and loader first. What needs to be in that loader? Name, trigger description, instructions, references, templates, scripts, assets, and required environment declarations.
17:41 Then add agent-written skills once provenance and validation are visible. Letting an agent write future instructions is powerful, but it is also how you create a very polite self-inflicted mess. Hermes has several extension surfaces, and they are easy to blur together. Let's separate them. MCP connects external tool servers. Plugins add Python extension points. Hooks run custom code at lifecycle moments. Skills add instruction and procedure. MCP is "there is a server exposing tools." The agent discovers those tools and calls them through the normal surface.
18:22 Kind of like a USB port for tools, except the runtime still has to decide which plugged-in thing gets authority. Plugins are more intimate. They can register tools, hooks, CLI commands, memory providers, context engines, and model providers. Wait, so which one is allowed to actually change runtime behavior? That is the useful lens: blast radius. A skill can guide the model. A tool can do work. A plugin can register runtime pieces. A hook can intercept pre-tool call, post-tool call, pre-model context, output transform, session events, gateway events, or shell scripts from config.
19:03 If a mechanism can execute code before a tool call, name it separately from a mechanism that only loads instructions. Delegation is where the implementation is more concrete than the marketing. Hermes implements delegate task as child AI agent instances. A child gets a fresh conversation, no parent history, a focused prompt from goal and context, a separate task ID, and a restricted toolset. The parent sees the delegation call and the summary result, not the child's whole messy transcript. Exactly. Think of a QA tester finding a bug.
19:37 The lead does not need a video of 50 failed test runs. They need the final bug report and the patch context. Exactly, and the parent should not pay context rent for every failed test run. Right. That is the point of hiding the child transcript. It is not secrecy. It is context control. The defaults also block recursive delegation, clarify, shared memory writes, cross-platform messages, and execute code. Concurrency is capped. There is a child timeout, spawn depth control, active-subagent status, and interruption support.
20:07 So subagents are not just parallel prompts. They are context isolation, tool restriction, lifecycle tracking, and result summarization. If you replicate only parallel API calls, you miss the point. The useful primitive is "run a bounded worker with a bounded tool surface and return a bounded summary." The gateway makes Hermes feel like it lives outside the terminal. The implementation pattern matters more than the platform list. Platform event becomes normalized message event. Gateway authorizes the user, resolves the session key, creates or resumes `AIAgent` with history, then delivers the response back.
20:43 So the gateway is not a second agent. It is a router, authorizer, session manager, delivery layer, and lifecycle supervisor. It handles realities the CLI does not: second messages during active work, restarts, chunking, unknown senders, slash commands, model switches, and thread routing. So what happens when the user sends message two while message one is still running? The gateway has to serialize, interrupt, or route that on purpose. Cron is similar: create a fresh agent, attach skills, run a prompt, deliver to a platform, and update job state.
21:17 Recent releases also add script-only watchdog mode when no agent is needed. For a rebuild, gateway and cron come after the core loop is solid. Otherwise every platform bug looks like an agent bug. First make the runtime trustworthy. Then let other systems invoke it. The visible interfaces sit on top of the same runtime. The terminal user interface gives multiline editing, slash commands, history, streaming output, tool previews, interrupts, and session controls. The dashboard manages models, sessions, skills, plugins, analytics, and chat.
21:53 ACP exposes Hermes to editors. The key is that these are control surfaces, not separate brains. Right. A good control surface shows current model, active session, token usage, subagent status, process state, skills, plugins, and logs. It should not fork semantics. I have seen the opposite happen, and we have all debugged some version of it: web UI behavior, terminal behavior, editor behavior, all slightly different. Nobody knows which one is canonical. Every bug report starts with, wait, which UI did you use?
22:32 Hermes centralizes canonical behavior in the runtime. If a background process is stuck, fix process registry. If a transcript is malformed, fix the loop. If a model setting is stale, fix session and runtime resolution. UI should expose runtime state clearly, not invent a parallel path around it. Let's hear it as a rebuild order. First, build the loop: internal messages, provider call, tool-call parsing, tool-result append, final response. One provider, one tool. Second, build the registry: self-registering tools, schemas, handlers, checks, dispatch, and uniform JSON errors.
23:13 3rd, build terminal execution as a backend interface. Start local. Add Docker or SSH. Make background processes managed. 4th, persist sessions in SQLite. Add resume, then full-text search. 5th, add compression. Preserve head and tail. Summarize the middle. Keep tool pairs valid. Where would you stop before adding gateways? After memory, skills, extension surfaces, and bounded subagents. Gateways multiply whatever semantics the runtime already has, so shaky internals become public bugs. Then add gateway, cron, dashboard, and editor protocol surfaces.
23:51 And through all of it, security is behavior: authorization, approval, blocklists, container boundaries, secret redaction, context scanning, and write validation. The failure modes are predictable. Tool schemas drift from handlers. Provider adapters leak dialect assumptions into the loop. Prompt snapshots mutate mid-session. Tool outputs explode context. Compression drops the only useful error. Background servers become orphaned. Subagents inherit too much authority. Gateways let strangers in. And the subtle one: every feature works alone, but the transcript shape becomes invalid when they compose. A tool call gets dropped.
24:30 A result loses its ID. Two assistant messages land back to back. The provider says no. Oh, that's the whole lesson. The feature is not the feature. The composition is the feature. That is why Hermes is useful source material. It is not just a pile of features. It is survival mechanisms around the loop. So copy the discipline, not the surface area: preserve transcript shape while you add providers, tools, sessions, compression, memory, skills, extensions, subagents, and gateways. And read the sources.
25:03 The GitHub repo and official docs are linked in the description. Hermes is large because real agents touch the real world. The way to rebuild it is not to copy every feature. It is to copy the layering discipline. Build the small loop first. Then make every new surface prove where it plugs in. Thanks for listening to Learning Podcasts.