Agent Runtime Architecture: Plugin Graphs and Event Stream Design
This article examines how a production-grade agent runtime can separate composition from history: a runtime plugin graph manages which capabilities exist and how they are wired, while an append-only event stream records what the system has done. It explains dependency injection, scoped resolution, lifecycle cleanup, event sourcing, context compaction, the agent loop between these two structures, and how configuration becomes a runnable plugin tree.
Agent Runtime Architecture: Plugin Graphs and Event Stream Design
Introduction: From a Minimal Loop to a Production Runtime
A working agent demo is not complicated: assemble a prompt, call a model API, parse tool calls, execute tools, send results back to the model, and repeat. This can be done in a few dozen lines of code. Moving from a demo to production, however, sharply increases engineering complexity. How are models and credentials managed? How are sessions restored and compacted? How are tool calls approved and rate-limited? How are sandboxes and remote execution isolated? How do multiple host interfaces observe the same runtime facts? How are sub-agents spawned? How are plugins started and stopped dynamically?
The class of agent runtime frameworks (harnesses) discussed in this article offers an instructive answer: let a runtime plugin graph manage “what the system is made of,” let an append-only event stream record “what the system has done,” and place the agent loop between the two. Understanding these two lines provides a better view of the overall system than reading the loop code line by line.
1. The Runtime Plugin Graph: A Unified Composition Mechanism
1.1 Everything Is a Plugin, but the Key Is Not Quantity
“Everything is a plugin” is a slogan many frameworks use. Model adapters, system prompts, tool catalogs, sessions, storage, sandboxes, agent loops, web interfaces, and even different interaction modes can all be made into plugins. The real distinction is not the number of plugins, but whether the underlying mechanism solves several problems that are usually handled separately:
- Visibility: What capabilities can a plugin see from its current position?
- Dependency readiness: Should a plugin start when a required capability has not yet been registered?
- Scoped isolation: Can services with the same name resolve to different implementations in different sessions or scopes?
- Lifecycle: When a plugin exits, who cleans up the services, event listeners, child processes, and file handles it registered?
- Configuration as runtime: How does static configuration become a runtime plugin tree that can be updated, inspected, and hot-swapped?
Only when these five points are addressed together does a plugin system reach industrial grade, rather than merely requiring every package to implement an apply method.
1.2 Dependency Declaration and Service Injection
In practice, plugins express dependencies declaratively. An illustrative example looks like this:
export const name = 'tool-executor'export const inject = {required: ['model', 'session'],optional: ['sandbox'],}export function apply(ctx: Context, config: Config) {// ctx.model is guaranteed by the runtime to be readyctx.on('tool:call', async (call) => {const result = await ctx.sandbox? ctx.sandbox.exec(call): localExec(call)ctx.session.append({ type: 'tool_result', payload: result })})}
Before mounting a plugin, the runtime resolves the dependency graph. If a required service is not yet available, the plugin delays startup and waits. When a dependency service is replaced because of a configuration change, plugins that depend on it are automatically restarted. In this way, “changing the model” or “changing the sandbox implementation” becomes a configuration-layer operation rather than a code change.
1.3 Scopes and Multi-Instance Resolution
Resolving services with the same name to different implementations in different contexts is essential for multi-session systems. For example, each session can have its own storage backend, approval policy, and tool allowlist. A runtime plugin graph implements this through scopes, using mechanisms such as fork and provide: a parent scope provides global default implementations, while child scopes can override them, and the override affects only that subtree. This makes “temporarily switching to a stricter approval policy for a high-risk task” a configuration injection rather than a global switch.
1.4 Discipline for Cleanup and Unloading
The reliability of a dynamic system depends heavily on whether the unload path is complete. When a plugin exits, the resources it must return include service registrations, event listeners, timers, child processes, network connections, and file handles. A good practice is to register a cleanup function whenever a resource is acquired, so the framework can reclaim resources in order during unload instead of relying on plugin authors’ memory. This discipline directly determines whether “hot-swapping capabilities without restarting the process” is safe.
2. The Event Stream: The Single Source of Truth for a Session
2.1 An Append-Only Log, Not Mutable State
Running in parallel with the plugin graph is an append-only session event stream. Every model request and response, every tool call and result, and every user input and system intervention is appended as an immutable event to the end of the log. The system does not derive history from “current state”; instead, “current state” becomes a projection of the event stream.
This event-sourcing style of design brings several direct benefits:
- Model context is a projection: The message sequence sent to the model is projected from the event stream after filtering, trimming, and compaction. Context strategy can evolve independently.
- Interface traces are projections: A UI displays another view of the same log, naturally making what the interface shows and what the model sees consistent and auditable.
- Recovery and forking are replays: Breakpoint recovery continues replaying from the nearest snapshot; forking copies the event stream to a certain node and then appends a new branch.
2.2 Compaction and Long Sessions
In long sessions, the context window will inevitably overflow. Because the original events are fully retained, compaction can be designed as “generate a summary event + mark the folded interval” rather than overwrite and delete. This makes compaction strategies traceable, comparable, and reversible, and preserves a complete evidence chain for auditing.
3. The Agent Loop Between the Two Lines
The agent loop sits between the plugin graph and the event stream. On each iteration, it first obtains the current model service, tool catalog, prompt templates, and session service from the plugin graph, executes one round of “request—tools—request again,” and writes the entire process back to the event stream. An illustrative structure is:
async function step(ctx: Context) {const view = await ctx.session.projectContext()const reply = await ctx.model.complete(view)ctx.session.append({ type: 'assistant', payload: reply })for (const call of reply.toolCalls) {const result = await ctx.tools.invoke(call)ctx.session.append({ type: 'tool_result', payload: result })}}
Because the loop itself is simplified to “read a projection, call services, write events,” model switching, tool policy changes, and loop-mode changes (such as planning-first, minimal, and creative modes) can all be implemented as changes in plugin composition without modifying the loop core.
4. From Configuration to Runtime Graph
The startup process does not directly construct a fixed application. Instead, it has three steps:
- Read configuration: Load a base configuration file (a Profile/Bundle-style description) that declares which plugins are enabled and what parameters each uses.
- Apply patches: User-level or project-level patches make incremental changes to the configuration—replacing a service implementation, adding tools, or adjusting permissions.
- Mount as a tree: The loader instantiates configuration rows into plugin nodes in dependency order, forming a plugin tree that can run, be inspected, and be hot-updated.
This means “replace capabilities without changing code” is a native capability of the configuration tree: swap one service implementation for another implementation of the same interface, and the runtime handles shutdown, cleanup, and restarting dependents. For enterprise environments, this can also be combined with general cloud capabilities: use object storage to persist event stream snapshots, a logging service to aggregate runtime traces, monitoring and alerting to observe plugin health, and a container platform to isolate sandbox execution.
5. Practical Recommendations and Boundaries
- Draw the two lines first: When evaluating similar frameworks, first ask “who manages composition” and “who records historical facts.” If both answers are clear, the architecture is usually sound.
- Test the unload path: Most hot-swap failures come from incomplete cleanup. Include unload and reload in integration tests.
- Version the event schema: The event stream is a long-term asset, and schema evolution needs a compatibility strategy.
- Be cautious during preview stages: The APIs and design goals of such frameworks are still evolving and should not be treated as stable commitments. Evaluate change risk before production adoption.
Conclusion
The core difficulty of a product-grade agent runtime is not the loop, but composition and continuity: the former is carried by the runtime plugin graph, and the latter by the event stream. Solving these two problems separately and then placing the loop between them is an architectural pattern worth learning from.
